From 4177146acdd8666a549274ed502b8b2425e70955 Mon Sep 17 00:00:00 2001 From: Brett Zamir Date: Fri, 24 May 2019 20:17:17 +0800 Subject: [PATCH] - Linting (ESLint): Remove now unneeded config and add per new update - Refactoring: Prefer for-of, event.key (newly enforced linting) - Refactoring: Better var. names - npm: Update devDeps and update local copies --- .eslintrc.js | 46 +- .npmignore | 1 - CHANGES.md | 1 + dist/canvg.js | 2 +- dist/extensions/ext-mathjax.js | 2 +- dist/extensions/ext-server_moinsave.js | 2 +- dist/extensions/ext-server_opensave.js | 2 +- dist/extensions/imagelib/openclipart.js | 919 ++++++++++------- dist/index-es.js | 265 +++-- dist/index-es.min.js | 2 +- dist/index-es.min.js.map | 2 +- dist/index-umd.js | 265 +++-- dist/index-umd.min.js | 2 +- dist/index-umd.min.js.map | 2 +- dist/svgcanvas-iife.js | 159 ++- dist/svgcanvas-iife.min.js | 2 +- dist/svgcanvas-iife.min.js.map | 2 +- docs/ReleaseInstructions.md | 8 - editor/canvg/canvg.js | 2 - editor/contextmenu/jQuery.contextMenu.js | 8 +- editor/dbox.js | 12 +- editor/embedapi.js | 12 +- editor/external/core-js-bundle/minified.js | 12 +- .../dynamic-import-polyfill/importModule.js | 13 +- editor/external/jamilih/jml-es.js | 951 +++++++++++------- editor/external/load-stylesheets/index-es.js | 223 ++-- editor/jQuery.attr.js | 2 +- editor/layer.js | 4 +- editor/path.js | 2 +- editor/svg-editor.js | 2 +- editor/svgcanvas.js | 20 +- editor/svgicons/jQuery.svgIcons.js | 6 +- editor/utilities.js | 4 +- editor/xdomain-svgedit-config-iife.js | 265 +++-- jsdoc-check-overly-generic-types.js | 104 -- package-lock.json | 315 +++--- package.json | 20 +- svgedit-config-iife.js | 265 +++-- 38 files changed, 2450 insertions(+), 1476 deletions(-) delete mode 100644 jsdoc-check-overly-generic-types.js diff --git a/.eslintrc.js b/.eslintrc.js index 43093357..e9d3bc39 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -50,12 +50,7 @@ module.exports = { // In case we need to extend customTags: [] }, - allowOverrideWithoutParam: true, - allowImplementsWithoutParam: true, - allowAugmentsExtendsWithoutParam: true, - // For `jsdoc/check-examples` in `ash-nazg` - matchingFileName: "dummy.md", - rejectExampleCodeRegex: "^`", + augmentsExtendsReplacesDocs: true, // Todo: Figure out why this is not working and why seem to have to // disable for all Markdown: /* @@ -65,34 +60,6 @@ module.exports = { } } */ - // Todo: Remove after ash-nazg update - forceRequireReturn: true, - // Todo: Remove if ash-nazg has sufficiently merged - preferredTypes: { - "*": { - message: "Use a more precise type or if necessary use `{{preferredType}}` or `ArbitraryCallbackResult`", - replacement: "Any" - }, - any: { - message: "Use a more precise type or if necessary use `{{preferredType}}` or `ArbitraryCallbackResult`", - replacement: "Any" - }, - number: { - message: "Use `Integer` or `Float`" - }, - Function: { - message: "Point to a `@callback` namepath or `{{preferredType}}` if truly arbitrary in form", - replacement: "GenericCallback" - }, - object: { - message: "Use the specific object type or `{{preferredType}}` (or `ArbitraryObject` or `ArbitraryModule`) if truly arbitrary", - replacement: "PlainObject" - }, - Array: { - message: "Use `{{preferredType}}` (or `ArgumentsArray`) if it is truly arbitrary.", - replacement: "GenericArray" - } - } } }, overrides: [ @@ -173,7 +140,7 @@ module.exports = { // Node files files: [ "docs/jsdoc-config.js", - "build-html.js", "jsdoc-check-overly-generic-types.js", + "build-html.js", "rollup.config.js", "rollup-config.config.js" ], env: { @@ -216,13 +183,6 @@ module.exports = { }], "unicorn/prefer-query-selector": "off", "unicorn/prefer-node-append": "off", - "unicorn/no-zero-fractions": "off", - - // Todo: Remove when ash-nazg removes - "valid-jsdoc": "off", - // Todo: Remove when ash-nazg adds (then also remove - // jsdoc-check-overly-generic-types.js file and npm script) - "jsdoc/require-returns-check": ["error"], - "jsdoc/match-description": ["error"], + "unicorn/no-zero-fractions": "off" } }; diff --git a/.npmignore b/.npmignore index cdd46ea7..77a92f98 100644 --- a/.npmignore +++ b/.npmignore @@ -4,5 +4,4 @@ test .github/ISSUE_TEMPLATE/bug_report.md build -jsdoc-check-overly-generic-types.js lgtm.yml diff --git a/CHANGES.md b/CHANGES.md index 51ea819f..6d2adf7e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -7,6 +7,7 @@ - Enhancement: Added `avoidClientSideOpen` config for `ext-server_opensave.js` - Refactoring: Use `static` keyword for classes +- Build: Remove `types-docs` script as being handled in ESLint - npm: Update devDeps (including switching from deprecate opn-cli package to open-cli) diff --git a/dist/canvg.js b/dist/canvg.js index 9d30ceb7..e151b560 100644 --- a/dist/canvg.js +++ b/dist/canvg.js @@ -924,7 +924,7 @@ var canvg = (function (exports) { * @param {HTMLCanvasElement|string} target canvas element or the id of a canvas element * @param {string|XMLDocument} s - svg string, url to svg file, or xml document * @param {module:canvg.CanvgOptions} [opts] Optional hash of options - * @returns {Promise} All the function after the first render is completed with dom + * @returns {Promise} All the function after the first render is completed with dom */ diff --git a/dist/extensions/ext-mathjax.js b/dist/extensions/ext-mathjax.js index 0dcce512..72926763 100644 --- a/dist/extensions/ext-mathjax.js +++ b/dist/extensions/ext-mathjax.js @@ -40,7 +40,7 @@ var svgEditorExtension_mathjax = (function () { /** * Add any of the whitelisted attributes to the script tag. * @param {HTMLScriptElement} script - * @param {PlainObject.} atts + * @param {PlainObject} atts * @returns {void} */ diff --git a/dist/extensions/ext-server_moinsave.js b/dist/extensions/ext-server_moinsave.js index cb415360..5e4dd602 100644 --- a/dist/extensions/ext-server_moinsave.js +++ b/dist/extensions/ext-server_moinsave.js @@ -924,7 +924,7 @@ var svgEditorExtension_server_moinsave = (function () { * @param {HTMLCanvasElement|string} target canvas element or the id of a canvas element * @param {string|XMLDocument} s - svg string, url to svg file, or xml document * @param {module:canvg.CanvgOptions} [opts] Optional hash of options - * @returns {Promise} All the function after the first render is completed with dom + * @returns {Promise} All the function after the first render is completed with dom */ diff --git a/dist/extensions/ext-server_opensave.js b/dist/extensions/ext-server_opensave.js index 5b8360fb..799833ab 100644 --- a/dist/extensions/ext-server_opensave.js +++ b/dist/extensions/ext-server_opensave.js @@ -924,7 +924,7 @@ var svgEditorExtension_server_opensave = (function () { * @param {HTMLCanvasElement|string} target canvas element or the id of a canvas element * @param {string|XMLDocument} s - svg string, url to svg file, or xml document * @param {module:canvg.CanvgOptions} [opts] Optional hash of options - * @returns {Promise} All the function after the first render is completed with dom + * @returns {Promise} All the function after the first render is completed with dom */ diff --git a/dist/extensions/imagelib/openclipart.js b/dist/extensions/imagelib/openclipart.js index 0d13fc72..874dc008 100644 --- a/dist/extensions/imagelib/openclipart.js +++ b/dist/extensions/imagelib/openclipart.js @@ -284,6 +284,40 @@ return Constructor; } + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + var ownKeys = Object.keys(source); + + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + + ownKeys.forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } + + return target; + } + function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); @@ -523,20 +557,22 @@ var doc = typeof document !== 'undefined' && document; var XmlSerializer = typeof XMLSerializer !== 'undefined' && XMLSerializer; // STATIC PROPERTIES - var possibleOptions = ['$plugins', '$map' // Add any other options here + var possibleOptions = ['$plugins', // '$mode', // Todo (SVG/XML) + // 'state', // Used internally + '$map' // Add any other options here ]; var NS_HTML = 'http://www.w3.org/1999/xhtml', - hyphenForCamelCase = /-([a-z])/g; + hyphenForCamelCase = /\x2D([a-z])/g; var ATTR_MAP = { - 'readonly': 'readOnly' + readonly: 'readOnly' }; // We define separately from ATTR_DOM for clarity (and parity with JsonML) but no current need // We don't set attribute esp. for boolean atts as we want to allow setting of `undefined` // (e.g., from an empty variable) on templates to have no effect var BOOL_ATTS = ['checked', 'defaultChecked', 'defaultSelected', 'disabled', 'indeterminate', 'open', // Dialog elements - 'readOnly', 'selected']; - var ATTR_DOM = BOOL_ATTS.concat([// From JsonML - 'accessKey', // HTMLElement + 'readOnly', 'selected']; // From JsonML + + var ATTR_DOM = BOOL_ATTS.concat(['accessKey', // HTMLElement 'async', 'autocapitalize', // HTMLElement 'autofocus', 'contentEditable', // HTMLElement through ElementContentEditable 'defaultValue', 'defer', 'draggable', // HTMLElement @@ -557,10 +593,10 @@ return doc.querySelector(sel); }; /** - * Retrieve the (lower-cased) HTML name of a node + * Retrieve the (lower-cased) HTML name of a node. * @static * @param {Node} node The HTML node - * @returns {String} The lower-cased node name + * @returns {string} The lower-cased node name */ @@ -568,9 +604,10 @@ return node.nodeName && node.nodeName.toLowerCase(); } /** - * Apply styles if this is a style tag + * Apply styles if this is a style tag. * @static * @param {Node} node The element to check whether it is a style tag + * @returns {void} */ @@ -587,11 +624,12 @@ } } /** - * Need this function for IE since options weren't otherwise getting added + * Need this function for IE since options weren't otherwise getting added. * @private * @static - * @param {DOMElement} parent The parent to which to append the element - * @param {DOMNode} child The element or other node to append to the parent + * @param {Element} parent The parent to which to append the element + * @param {Node} child The element or other node to append to the parent + * @returns {void} */ @@ -614,12 +652,12 @@ } if (parentName === 'template') { - parent.content.appendChild(child); + parent.content.append(child); return; } try { - parent.appendChild(child); // IE9 is now ok with this + parent.append(child); // IE9 is now ok with this } catch (e) { if (parentName === 'select' && childName === 'option') { try { @@ -637,31 +675,32 @@ } } /** - * Attach event in a cross-browser fashion + * Attach event in a cross-browser fashion. * @static - * @param {DOMElement} el DOM element to which to attach the event - * @param {String} type The DOM event (without 'on') to attach to the element + * @param {Element} el DOM element to which to attach the event + * @param {string} type The DOM event (without 'on') to attach to the element * @param {Function} handler The event handler to attach to the element - * @param {Boolean} [capturing] Whether or not the event should be - * capturing (W3C-browsers only); default is false; NOT IN USE + * @param {boolean} [capturing] Whether or not the event should be + * capturing (W3C-browsers only); default is false; NOT IN USE + * @returns {void} */ function _addEvent(el, type, handler, capturing) { - el.addEventListener(type, handler, !!capturing); + el.addEventListener(type, handler, Boolean(capturing)); } /** - * Creates a text node of the result of resolving an entity or character reference + * Creates a text node of the result of resolving an entity or character reference. * @param {'entity'|'decimal'|'hexadecimal'} type Type of reference - * @param {String} prefix Text to prefix immediately after the "&" - * @param {String} arg The body of the reference + * @param {string} prefix Text to prefix immediately after the "&" + * @param {string} arg The body of the reference * @returns {Text} The text node of the resolved reference */ function _createSafeReference(type, prefix, arg) { // For security reasons related to innerHTML, we ensure this string only contains potential entity characters - if (!arg.match(/^\w+$/)) { + if (!arg.match(/^[0-9A-Z_a-z]+$/)) { throw new TypeError('Bad ' + type); } @@ -671,18 +710,31 @@ return doc.createTextNode(elContainer.innerHTML); } /** - * @param {String} n0 Whole expression match (including "-") - * @param {String} n1 Lower-case letter match - * @returns {String} Uppercased letter + * @param {string} n0 Whole expression match (including "-") + * @param {string} n1 Lower-case letter match + * @returns {string} Uppercased letter */ function _upperCase(n0, n1) { return n1.toUpperCase(); - } + } // Todo: Make as public utility + + /** + * @param {*} o + * @returns {boolean} + */ + + + function _isNullish(o) { + return o === null || o === undefined; + } // Todo: Make as public utility, but also return types for undefined, boolean, number, document, etc. + /** * @private * @static + * @param {string|object|Array|Element|DocumentFragment} item + * @returns {"string"|"null"|"array"|"element"|"fragment"|"object"} */ @@ -718,16 +770,21 @@ /** * @private * @static + * @param {DocumentFragment} frag + * @param {Node} node + * @returns {DocumentFragment} */ function _fragReducer(frag, node) { - frag.appendChild(node); + frag.append(node); return frag; } /** * @private * @static + * @param {Object<{string:string}>} xmlnsObj + * @returns {string} */ @@ -736,7 +793,7 @@ var retStr = xmlnsObj[''] ? ' xmlns="' + xmlnsObj[''] + '"' : n0 || ''; // Preserve XHTML for (var ns in xmlnsObj) { - if (xmlnsObj.hasOwnProperty(ns)) { + if ({}.hasOwnProperty.call(xmlnsObj, ns)) { if (ns !== '') { retStr += ' xmlns:' + ns + '="' + xmlnsObj[ns] + '"'; } @@ -746,6 +803,12 @@ return retStr; }; } + /** + * + * @param {JamilihArray} args + * @returns {Element} + */ + function _optsOrUndefinedJML() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { @@ -757,15 +820,26 @@ /** * @private * @static + * @param {string} arg + * @returns {Element} */ function _jmlSingleArg(arg) { return jml(arg); } + /** + * @typedef {Array} AttributeArray + * @property {string} 0 The key + * @property {string} 1 The value + */ + /** * @private * @static + * @todo Deprecate as now there is predictable iteration order? + * @param {AttributeArray} attArr + * @returns {PlainObject} */ @@ -776,9 +850,17 @@ return obj; } + /** + * @callback ChildrenToJMLCallback + * @param {JamilihArray|Jamilih} childNodeJML + * @param {Integer} i + */ + /** * @private * @static + * @param {Node} node + * @returns {ChildrenToJMLCallback} */ @@ -789,29 +871,45 @@ cn.parentNode.replaceChild(j, cn); }; } + /** + * @callback JamilihAppender + * @param {JamilihArray} childJML + * @returns {void} + */ + /** * @private * @static + * @param {Node} node + * @returns {JamilihAppender} */ function _appendJML(node) { return function (childJML) { - node.appendChild(jml.apply(void 0, _toConsumableArray$1(childJML))); + node.append(jml.apply(void 0, _toConsumableArray$1(childJML))); }; } + /** + * @callback appender + * @param {string|JamilihArray} childJML + * @returns {void} + */ + /** * @private * @static + * @param {Node} node + * @returns {appender} */ function _appendJMLOrText(node) { return function (childJML) { if (typeof childJML === 'string') { - node.appendChild(doc.createTextNode(childJML)); + node.append(childJML); } else { - node.appendChild(jml.apply(void 0, _toConsumableArray$1(childJML))); + node.append(jml.apply(void 0, _toConsumableArray$1(childJML))); } }; } @@ -827,22 +925,32 @@ */ /** - * Creates an XHTML or HTML element (XHTML is preferred, but only in browsers that support); - * Any element after element can be omitted, and any subsequent type or types added afterwards - * @requires polyfill: Array.isArray - * @requires polyfill: Array.prototype.reduce For returning a document fragment - * @requires polyfill: Element.prototype.dataset For dataset functionality (Will not work in IE <= 7) - * @param {String} el The element to create (by lower-case name) - * @param {Object} [atts] Attributes to add with the key as the attribute name and value as the - * attribute value; important for IE where the input element's type cannot - * be added later after already added to the page - * @param {DOMElement[]} [children] The optional children of this element (but raw DOM elements - * required to be specified within arrays since - * could not otherwise be distinguished from siblings being added) - * @param {DOMElement} [parent] The optional parent to which to attach the element (always the last - * unless followed by null, in which case it is the second-to-last) - * @param {null} [returning] Can use null to indicate an array of elements should be returned - * @returns {DOMElement} The newly created (and possibly already appended) element or array of elements + * @typedef {Element|DocumentFragment} JamilihReturn + */ + + /** + * @typedef {GenericArray} JamilihArray + * @property {string} 0 The element to create (by lower-case name) + * @property {Object} [1] Attributes to add with the key as the attribute name + * and value as the attribute value; important for IE where the input + * element's type cannot be added later after already added to the page + * @param {Element[]} [children] The optional children of this element + * (but raw DOM elements required to be specified within arrays since + * could not otherwise be distinguished from siblings being added) + * @param {Element} [parent] The optional parent to which to attach the element + * (always the last unless followed by null, in which case it is the + * second-to-last) + * @param {null} [returning] Can use null to indicate an array of elements + * should be returned + */ + + /** + * Creates an XHTML or HTML element (XHTML is preferred, but only in browsers + * that support); any element after element can be omitted, and any subsequent + * type or types added afterwards. + * @param {JamilihArray} args + * @returns {JamilihReturn} The newly created (and possibly already appended) + * element or array of elements */ @@ -852,12 +960,17 @@ } var elem = doc.createDocumentFragment(); + /** + * + * @param {Object<{string: string}>} atts + * @returns {void} + */ function _checkAtts(atts) { var att; for (att in atts) { - if (!atts.hasOwnProperty(att)) { + if (!{}.hasOwnProperty.call(atts, att)) { continue; } @@ -865,7 +978,7 @@ att = att in ATTR_MAP ? ATTR_MAP[att] : att; if (NULLABLES.includes(att)) { - if (attVal != null) { + if (!_isNullish(attVal)) { elem[att] = attVal; } @@ -961,9 +1074,9 @@ return "break"; } - var getConstructor = function getConstructor(cb) { + var getConstructor = function getConstructor(cnstrct) { var baseClass = options && options["extends"] ? doc.createElement(options["extends"]).constructor : customizedBuiltIn ? doc.createElement(localName).constructor : HTMLElement; - return cb ? + return cnstrct ? /*#__PURE__*/ function (_baseClass) { _inherits$1(_class, _baseClass); @@ -974,7 +1087,7 @@ _classCallCheck$1(this, _class); _this = _possibleConstructorReturn$1(this, _getPrototypeOf$1(_class).call(this)); - cb.call(_assertThisInitialized$1(_assertThisInitialized$1(_this))); + cnstrct.call(_assertThisInitialized$1(_this)); return _this; } @@ -994,7 +1107,7 @@ }(baseClass); }; - var constructor = void 0, + var cnstrctr = void 0, options = void 0, prototype = void 0; @@ -1002,25 +1115,25 @@ if (attVal.length <= 2) { var _attVal = _slicedToArray$1(attVal, 2); - constructor = _attVal[0]; + cnstrctr = _attVal[0]; options = _attVal[1]; if (typeof options === 'string') { options = { "extends": options }; - } else if (!options.hasOwnProperty('extends')) { + } else if (!{}.hasOwnProperty.call(options, 'extends')) { prototype = options; } - if (_typeof$1(constructor) === 'object') { - prototype = constructor; - constructor = getConstructor(); + if (_typeof$1(cnstrctr) === 'object') { + prototype = cnstrctr; + cnstrctr = getConstructor(); } } else { var _attVal2 = _slicedToArray$1(attVal, 3); - constructor = _attVal2[0]; + cnstrctr = _attVal2[0]; prototype = _attVal2[1]; options = _attVal2[2]; @@ -1031,14 +1144,14 @@ } } } else if (typeof attVal === 'function') { - constructor = attVal; + cnstrctr = attVal; } else { prototype = attVal; - constructor = getConstructor(); + cnstrctr = getConstructor(); } - if (!constructor.toString().startsWith('class')) { - constructor = getConstructor(constructor); + if (!cnstrctr.toString().startsWith('class')) { + cnstrctr = getConstructor(cnstrctr); } if (!options && customizedBuiltIn) { @@ -1048,10 +1161,10 @@ } if (prototype) { - Object.assign(constructor.prototype, prototype); + Object.assign(cnstrctr.prototype, prototype); } - customElements.define(def, constructor, customizedBuiltIn ? options : undefined); + customElements.define(def, cnstrctr, customizedBuiltIn ? options : undefined); return "break"; }(); @@ -1116,13 +1229,14 @@ var _node2 = doc.implementation.createHTMLDocument(); if (attVal.childNodes) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator attVal.childNodes.forEach(_childrenToJML(_node2)); // Remove any extra nodes created by createHTMLDocument(). var j = attVal.childNodes.length; while (_node2.childNodes[j]) { var cn = _node2.childNodes[j]; - cn.parentNode.removeChild(cn); + cn.remove(); j++; } } else { @@ -1142,7 +1256,7 @@ if (attVal.title || attVal.head) { var meta = doc.createElement('meta'); meta.setAttribute('charset', 'utf-8'); - head.appendChild(meta); + head.append(meta); } if (attVal.title) { @@ -1150,10 +1264,12 @@ } if (attVal.head) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator attVal.head.forEach(_appendJML(head)); } if (attVal.body) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator attVal.body.forEach(_appendJMLOrText(_body)); } } @@ -1179,7 +1295,9 @@ nodeName: attVal.name, nodeValue: null, nodeType: 10, + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator entities: attVal.entities.map(_jmlSingleArg), + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator notations: attVal.notations.map(_jmlSingleArg), publicId: attVal.publicId, systemId: attVal.systemId // internalSubset: // Todo @@ -1228,7 +1346,7 @@ { // Events for (var p2 in attVal) { - if (attVal.hasOwnProperty(p2)) { + if ({}.hasOwnProperty.call(attVal, p2)) { var val = attVal[p2]; if (typeof val === 'function') { @@ -1247,7 +1365,7 @@ case 'className': case 'class': - if (attVal != null) { + if (!_isNullish(attVal)) { elem.className = attVal; } @@ -1257,11 +1375,11 @@ { var _ret2 = function () { // Map can be keyed with hyphenated or camel-cased properties - var recurse = function recurse(attVal, startProp) { + var recurse = function recurse(atVal, startProp) { var prop = ''; var pastInitialProp = startProp !== ''; - Object.keys(attVal).forEach(function (key) { - var value = attVal[key]; + Object.keys(atVal).forEach(function (key) { + var value = atVal[key]; if (pastInitialProp) { prop = startProp + key.replace(hyphenForCamelCase, _upperCase).replace(/^([a-z])/, _upperCase); @@ -1270,7 +1388,7 @@ } if (value === null || _typeof$1(value) !== 'object') { - if (value != null) { + if (!_isNullish(value)) { elem.dataset[prop] = value; } @@ -1286,13 +1404,13 @@ return "break"; // Todo: Disable this by default unless configuration explicitly allows (for security) }(); - break; + if (_ret2 === "break") break; } // #if IS_REMOVE // Don't remove this `if` block (for sake of no-innerHTML build) case 'innerHTML': - if (attVal != null) { + if (!_isNullish(attVal)) { elem.innerHTML = attVal; } @@ -1302,7 +1420,7 @@ case 'htmlFor': case 'for': if (elStr === 'label') { - if (attVal != null) { + if (!_isNullish(attVal)) { elem.htmlFor = attVal; } @@ -1317,64 +1435,66 @@ break; default: - if (att.match(/^on/)) { - elem[att] = attVal; // _addEvent(elem, att.slice(2), attVal, false); // This worked, but perhaps the user wishes only one event + { + if (att.startsWith('on')) { + elem[att] = attVal; // _addEvent(elem, att.slice(2), attVal, false); // This worked, but perhaps the user wishes only one event - break; - } - - if (att === 'style') { - if (attVal == null) { break; } - if (_typeof$1(attVal) === 'object') { - for (var _p in attVal) { - if (attVal.hasOwnProperty(_p) && attVal[_p] != null) { - // Todo: Handle aggregate properties like "border" - if (_p === 'float') { - elem.style.cssFloat = attVal[_p]; - elem.style.styleFloat = attVal[_p]; // Harmless though we could make conditional on older IE instead - } else { - elem.style[_p.replace(hyphenForCamelCase, _upperCase)] = attVal[_p]; + if (att === 'style') { + if (_isNullish(attVal)) { + break; + } + + if (_typeof$1(attVal) === 'object') { + for (var _p in attVal) { + if ({}.hasOwnProperty.call(attVal, _p) && !_isNullish(attVal[_p])) { + // Todo: Handle aggregate properties like "border" + if (_p === 'float') { + elem.style.cssFloat = attVal[_p]; + elem.style.styleFloat = attVal[_p]; // Harmless though we could make conditional on older IE instead + } else { + elem.style[_p.replace(hyphenForCamelCase, _upperCase)] = attVal[_p]; + } } } + + break; + } // setAttribute unfortunately erases any existing styles + + + elem.setAttribute(att, attVal); + /* + // The following reorders which is troublesome for serialization, e.g., as used in our testing + if (elem.style.cssText !== undefined) { + elem.style.cssText += attVal; + } else { // Opera + elem.style += attVal; } + */ break; - } // setAttribute unfortunately erases any existing styles + } + var matchingPlugin = opts && opts.$plugins && opts.$plugins.find(function (p) { + return p.name === att; + }); + + if (matchingPlugin) { + matchingPlugin.set({ + element: elem, + attribute: { + name: att, + value: attVal + } + }); + break; + } elem.setAttribute(att, attVal); - /* - // The following reorders which is troublesome for serialization, e.g., as used in our testing - if (elem.style.cssText !== undefined) { - elem.style.cssText += attVal; - } else { // Opera - elem.style += attVal; - } - */ - break; } - - var matchingPlugin = opts && opts.$plugins && opts.$plugins.find(function (p) { - return p.name === att; - }); - - if (matchingPlugin) { - matchingPlugin.set({ - element: elem, - attribute: { - name: att, - value: attVal - } - }); - break; - } - - elem.setAttribute(att, attVal); - break; } } } @@ -1402,7 +1522,7 @@ if ('$plugins' in opts) { if (!Array.isArray(opts.$plugins)) { - throw new Error('$plugins must be an array'); + throw new TypeError('$plugins must be an array'); } opts.$plugins.forEach(function (pluginObj) { @@ -1445,6 +1565,8 @@ obj = dataVal[1] || defaultMap[1]; } // Map + /* eslint-disable-next-line unicorn/no-unsafe-regex */ + } else if (/^\[object (?:Weak)?Map\]$/.test([].toString.call(dataVal))) { map = dataVal; obj = defaultMap[1]; // Non-map data object @@ -1460,6 +1582,10 @@ var arg = args[i]; switch (_getType(arg)) { + default: + // Todo: Throw here instead? + break; + case 'null': // null always indicates a place-holder (only needed for last argument if want array returned) if (i === argc - 1) { @@ -1467,7 +1593,8 @@ // Todo: Fix to allow application of stylesheets of style tags within fragments? - return nodes.length <= 1 ? nodes[0] : nodes.reduce(_fragReducer, doc.createDocumentFragment()); // nodes; + return nodes.length <= 1 ? nodes[0] // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + : nodes.reduce(_fragReducer, doc.createDocumentFragment()); // nodes; } break; @@ -1480,39 +1607,40 @@ break; case '?': - arg = args[++i]; - var procValue = args[++i]; - var val = procValue; + { + arg = args[++i]; + var procValue = args[++i]; + var val = procValue; - if (_typeof$1(val) === 'object') { - procValue = []; + if (_typeof$1(val) === 'object') { + procValue = []; - for (var p in val) { - if (val.hasOwnProperty(p)) { - procValue.push(p + '=' + '"' + // https://www.w3.org/TR/xml-stylesheet/#NT-PseudoAttValue - val[p].replace(/"/g, '"') + '"'); + for (var p in val) { + if ({}.hasOwnProperty.call(val, p)) { + procValue.push(p + '=' + '"' + // https://www.w3.org/TR/xml-stylesheet/#NT-PseudoAttValue + val[p].replace(/"/g, '"') + '"'); + } } + + procValue = procValue.join(' '); + } // Firefox allows instructions with ">" in this method, but not if placed directly! + + + try { + nodes[nodes.length] = doc.createProcessingInstruction(arg, procValue); + } catch (e) { + // Getting NotSupportedError in IE, so we try to imitate a processing instruction with a comment + // innerHTML didn't work + // var elContainer = doc.createElement('div'); + // elContainer.innerHTML = ''; + // nodes[nodes.length] = elContainer.innerHTML; + // Todo: any other way to resolve? Just use XML? + nodes[nodes.length] = doc.createComment('?' + arg + ' ' + procValue + '?'); } - procValue = procValue.join(' '); - } // Firefox allows instructions with ">" in this method, but not if placed directly! - - - try { - nodes[nodes.length] = doc.createProcessingInstruction(arg, procValue); - } catch (e) { - // Getting NotSupportedError in IE, so we try to imitate a processing instruction with a comment - // innerHTML didn't work - // var elContainer = doc.createElement('div'); - // elContainer.innerHTML = ''; - // nodes[nodes.length] = elContainer.innerHTML; - // Todo: any other way to resolve? Just use XML? - nodes[nodes.length] = doc.createComment('?' + arg + ' ' + procValue + '?'); + break; // Browsers don't support doc.createEntityReference, so we just use this as a convenience } - break; - // Browsers don't support doc.createEntityReference, so we just use this as a convenience - case '&': nodes[nodes.length] = _createSafeReference('entity', '', args[++i]); break; @@ -1547,10 +1675,10 @@ { // An element elStr = arg; - var _atts = args[i + 1]; // Todo: Fix this to depend on XML/config, not availability of methods + var atts = args[i + 1]; // Todo: Fix this to depend on XML/config, not availability of methods - if (_getType(_atts) === 'object' && _atts.is) { - var is = _atts.is; + if (_getType(atts) === 'object' && atts.is) { + var is = atts.is; if (doc.createElementNS) { elem = doc.createElementNS(NS_HTML, elStr, { @@ -1561,12 +1689,10 @@ is: is }); } + } else if (doc.createElementNS) { + elem = doc.createElementNS(NS_HTML, elStr); } else { - if (doc.createElementNS) { - elem = doc.createElementNS(NS_HTML, elStr); - } else { - elem = doc.createElement(elStr); - } + elem = doc.createElement(elStr); } nodes[nodes.length] = elem; // Add to parent @@ -1578,32 +1704,36 @@ break; case 'object': - // Non-DOM-element objects indicate attribute-value pairs - var atts = arg; + { + // Non-DOM-element objects indicate attribute-value pairs + var _atts = arg; - if (atts.xmlns !== undefined) { - // We handle this here, as otherwise may lose events, etc. - // As namespace of element already set as XHTML, we need to change the namespace - // elem.setAttribute('xmlns', atts.xmlns); // Doesn't work - // Can't set namespaceURI dynamically, renameNode() is not supported, and setAttribute() doesn't work to change the namespace, so we resort to this hack - var replacer = void 0; + if (_atts.xmlns !== undefined) { + // We handle this here, as otherwise may lose events, etc. + // As namespace of element already set as XHTML, we need to change the namespace + // elem.setAttribute('xmlns', atts.xmlns); // Doesn't work + // Can't set namespaceURI dynamically, renameNode() is not supported, and setAttribute() doesn't work to change the namespace, so we resort to this hack + var replacer = void 0; - if (_typeof$1(atts.xmlns) === 'object') { - replacer = _replaceDefiner(atts.xmlns); - } else { - replacer = ' xmlns="' + atts.xmlns + '"'; - } // try { - // Also fix DOMParser to work with text/html + if (_typeof$1(_atts.xmlns) === 'object') { + replacer = _replaceDefiner(_atts.xmlns); + } else { + replacer = ' xmlns="' + _atts.xmlns + '"'; + } // try { + // Also fix DOMParser to work with text/html - elem = nodes[nodes.length - 1] = new DOMParser().parseFromString(new XmlSerializer().serializeToString(elem) // Mozilla adds XHTML namespace - .replace(' xmlns="' + NS_HTML + '"', replacer), 'application/xml').documentElement; // }catch(e) {alert(elem.outerHTML);throw e;} + elem = nodes[nodes.length - 1] = new DOMParser().parseFromString(new XmlSerializer().serializeToString(elem) // Mozilla adds XHTML namespace + .replace(' xmlns="' + NS_HTML + '"', replacer), 'application/xml').documentElement; // }catch(e) {alert(elem.outerHTML);throw e;} + } // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + + + var orderedArr = _atts.$a ? _atts.$a.map(_copyOrderedAtts) : [_atts]; // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + + orderedArr.forEach(_checkAtts); + break; } - var orderedArr = atts.$a ? atts.$a.map(_copyOrderedAtts) : [atts]; - orderedArr.forEach(_checkAtts); - break; - case 'fragment': case 'element': /* @@ -1633,46 +1763,48 @@ break; case 'array': - // Arrays or arrays of arrays indicate child nodes - var child = arg; - var cl = child.length; + { + // Arrays or arrays of arrays indicate child nodes + var child = arg; + var cl = child.length; - for (var j = 0; j < cl; j++) { - // Go through children array container to handle elements - var childContent = child[j]; + for (var j = 0; j < cl; j++) { + // Go through children array container to handle elements + var childContent = child[j]; - var childContentType = _typeof$1(childContent); + var childContentType = _typeof$1(childContent); - if (childContent === undefined) { - throw String('Parent array:' + JSON.stringify(args) + '; child: ' + child + '; index:' + j); + if (childContent === undefined) { + throw String('Parent array:' + JSON.stringify(args) + '; child: ' + child + '; index:' + j); + } + + switch (childContentType) { + // Todo: determine whether null or function should have special handling or be converted to text + case 'string': + case 'number': + case 'boolean': + _appendNode(elem, doc.createTextNode(childContent)); + + break; + + default: + if (Array.isArray(childContent)) { + // Arrays representing child elements + _appendNode(elem, _optsOrUndefinedJML.apply(void 0, [opts].concat(_toConsumableArray$1(childContent)))); + } else if (childContent['#']) { + // Fragment + _appendNode(elem, _optsOrUndefinedJML(opts, childContent['#'])); + } else { + // Single DOM element children + _appendNode(elem, childContent); + } + + break; + } } - switch (childContentType) { - // Todo: determine whether null or function should have special handling or be converted to text - case 'string': - case 'number': - case 'boolean': - _appendNode(elem, doc.createTextNode(childContent)); - - break; - - default: - if (Array.isArray(childContent)) { - // Arrays representing child elements - _appendNode(elem, _optsOrUndefinedJML.apply(void 0, [opts].concat(_toConsumableArray$1(childContent)))); - } else if (childContent['#']) { - // Fragment - _appendNode(elem, _optsOrUndefinedJML(opts, childContent['#'])); - } else { - // Single DOM element children - _appendNode(elem, childContent); - } - - break; - } + break; } - - break; } } @@ -1685,11 +1817,11 @@ return ret; }; /** - * Converts a DOM object or a string of HTML into a Jamilih object (or string) + * Converts a DOM object or a string of HTML into a Jamilih object (or string). * @param {string|HTMLElement} [dom=document.documentElement] Defaults to converting the current document. * @param {object} [config={stringOutput:false}] Configuration object * @param {boolean} [config.stringOutput=false] Whether to output the Jamilih object as a string. - * @returns {array|string} Array containing the elements which represent a Jamilih object, or, + * @returns {Array|string} Array containing the elements which represent a Jamilih object, or, if `stringOutput` is true, it will be the stringified version of such an object */ @@ -1707,12 +1839,18 @@ var ret = []; var parent = ret; var parentIdx = 0; + /** + * + * @throws {DOMException} + * @returns {void} + */ function invalidStateError() { // These are probably only necessary if working with text/html - function DOMException() { - return this; - } + // eslint-disable-next-line no-shadow + var DOMException = function DOMException() { + _classCallCheck$1(this, DOMException); + }; { // INVALID_STATE_ERR per section 9.3 XHTML 5: http://www.w3.org/TR/html5/the-xhtml-syntax.html @@ -1722,14 +1860,21 @@ throw e; } } + /** + * + * @param {DocumentType|Entity|Notation} obj + * @param {Node} node + * @returns {void} + */ + function addExternalID(obj, node) { if (node.systemId.includes('"') && node.systemId.includes("'")) { invalidStateError(); } - var publicId = node.publicId; - var systemId = node.systemId; + var publicId = node.publicId, + systemId = node.systemId; if (systemId) { obj.systemId = systemId; @@ -1739,17 +1884,34 @@ obj.publicId = publicId; } } + /** + * + * @param {*} val + * @returns {void} + */ + function set(val) { parent[parentIdx] = val; parentIdx++; } + /** + * @returns {void} + */ + function setChildren() { set([]); parent = parent[parentIdx - 1]; parentIdx = 0; } + /** + * + * @param {string} prop1 + * @param {string} prop2 + * @returns {void} + */ + function setObj(prop1, prop2) { parent = parent[parentIdx - 1][prop1]; @@ -1759,6 +1921,13 @@ parent = parent[prop2]; } } + /** + * + * @param {Node} node + * @param {object<{string: string}>} namespaces + * @returns {void} + */ + function parseDOM(node, namespaces) { // namespaces = clone(namespaces) || {}; // Ensure we're working with a copy, so different levels in the hierarchy can treat it differently @@ -1769,19 +1938,26 @@ } */ var type = 'nodeType' in node ? node.nodeType : null; - namespaces = Object.assign({}, namespaces); - var xmlChars = /([\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]|[\uD800-\uDBFF][\uDC00-\uDFFF])*$/; // eslint-disable-line no-control-regex + namespaces = _objectSpread({}, namespaces); + var xmlChars = /([\t\n\r -\uD7FF\uE000-\uFFFD]|(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))(?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))*$/; // eslint-disable-line no-control-regex if ([2, 3, 4, 7, 8].includes(type) && !xmlChars.test(node.nodeValue)) { invalidStateError(); } var children, start, tmpParent, tmpParentIdx; + /** + * @returns {void} + */ function setTemp() { tmpParent = parent; tmpParentIdx = parentIdx; } + /** + * @returns {void} + */ + function resetTemp() { parent = tmpParent; @@ -1791,51 +1967,53 @@ switch (type) { case 1: - // ELEMENT - setTemp(); - var nodeName = node.nodeName.toLowerCase(); // Todo: for XML, should not lower-case + { + // ELEMENT + setTemp(); + var nodeName = node.nodeName.toLowerCase(); // Todo: for XML, should not lower-case - setChildren(); // Build child array since elements are, except at the top level, encapsulated in arrays + setChildren(); // Build child array since elements are, except at the top level, encapsulated in arrays - set(nodeName); - start = {}; - var hasNamespaceDeclaration = false; + set(nodeName); + start = {}; + var hasNamespaceDeclaration = false; - if (namespaces[node.prefix || ''] !== node.namespaceURI) { - namespaces[node.prefix || ''] = node.namespaceURI; + if (namespaces[node.prefix || ''] !== node.namespaceURI) { + namespaces[node.prefix || ''] = node.namespaceURI; - if (node.prefix) { - start['xmlns:' + node.prefix] = node.namespaceURI; - } else if (node.namespaceURI) { - start.xmlns = node.namespaceURI; + if (node.prefix) { + start['xmlns:' + node.prefix] = node.namespaceURI; + } else if (node.namespaceURI) { + start.xmlns = node.namespaceURI; + } + + hasNamespaceDeclaration = true; } - hasNamespaceDeclaration = true; + if (node.attributes.length) { + set(_toConsumableArray$1(node.attributes).reduce(function (obj, att) { + obj[att.name] = att.value; // Attr.nodeName and Attr.nodeValue are deprecated as of DOM4 as Attr no longer inherits from Node, so we can safely use name and value + + return obj; + }, start)); + } else if (hasNamespaceDeclaration) { + set(start); + } + + children = node.childNodes; + + if (children.length) { + setChildren(); // Element children array container + + _toConsumableArray$1(children).forEach(function (childNode) { + parseDOM(childNode, namespaces); + }); + } + + resetTemp(); + break; } - if (node.attributes.length) { - set(Array.from(node.attributes).reduce(function (obj, att) { - obj[att.name] = att.value; // Attr.nodeName and Attr.nodeValue are deprecated as of DOM4 as Attr no longer inherits from Node, so we can safely use name and value - - return obj; - }, start)); - } else if (hasNamespaceDeclaration) { - set(start); - } - - children = node.childNodes; - - if (children.length) { - setChildren(); // Element children array container - - Array.from(children).forEach(function (childNode) { - parseDOM(childNode, namespaces); - }); - } - - resetTemp(); - break; - case undefined: // Treat as attribute node until this is fixed: https://github.com/tmpvar/jsdom/issues/1641 / https://github.com/tmpvar/jsdom/pull/1822 case 2: @@ -1847,7 +2025,7 @@ case 3: // TEXT - if (config.stripWhitespace && /^\s+$/.test(node.nodeValue)) { + if (config.stripWhitespace && /^[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+$/.test(node.nodeValue)) { return; } @@ -1902,7 +2080,8 @@ start.$ENTITY.childNodes = []; // Set position to $ENTITY's childNodes array children setObj('$ENTITY', 'childNodes'); - Array.from(children).forEach(function (childNode) { + + _toConsumableArray$1(children).forEach(function (childNode) { parseDOM(childNode, namespaces); }); } @@ -1942,91 +2121,99 @@ break; case 9: - // DOCUMENT - setTemp(); - var docObj = { - $document: { - childNodes: [] - } - }; - - if (config.xmlDeclaration) { - docObj.$document.xmlDeclaration = { - version: doc.xmlVersion, - encoding: doc.xmlEncoding, - standAlone: doc.xmlStandalone + { + // DOCUMENT + setTemp(); + var docObj = { + $document: { + childNodes: [] + } }; + + if (config.xmlDeclaration) { + docObj.$document.xmlDeclaration = { + version: doc.xmlVersion, + encoding: doc.xmlEncoding, + standAlone: doc.xmlStandalone + }; + } + + set(docObj); // doc.implementation.createHTMLDocument + // Set position to fragment's array children + + setObj('$document', 'childNodes'); + children = node.childNodes; + + if (!children.length) { + invalidStateError(); + } // set({$xmlDocument: []}); // doc.implementation.createDocument // Todo: use this conditionally + + + _toConsumableArray$1(children).forEach(function (childNode) { + // Can't just do documentElement as there may be doctype, comments, etc. + // No need for setChildren, as we have already built the container array + parseDOM(childNode, namespaces); + }); + + resetTemp(); + break; } - set(docObj); // doc.implementation.createHTMLDocument - // Set position to fragment's array children - - setObj('$document', 'childNodes'); - children = node.childNodes; - - if (!children.length) { - invalidStateError(); - } // set({$xmlDocument: []}); // doc.implementation.createDocument // Todo: use this conditionally - - - Array.from(children).forEach(function (childNode) { - // Can't just do documentElement as there may be doctype, comments, etc. - // No need for setChildren, as we have already built the container array - parseDOM(childNode, namespaces); - }); - resetTemp(); - break; - case 10: - // DOCUMENT TYPE - setTemp(); // Can create directly by doc.implementation.createDocumentType + { + // DOCUMENT TYPE + setTemp(); // Can create directly by doc.implementation.createDocumentType - start = { - $DOCTYPE: { - name: node.name + start = { + $DOCTYPE: { + name: node.name + } + }; + + if (node.internalSubset) { + start.internalSubset = node.internalSubset; } - }; - if (node.internalSubset) { - start.internalSubset = node.internalSubset; + var pubIdChar = /^( |\r|\n|[0-9A-Za-z]|[!#-%'-\/:;=\?@_])*$/; // eslint-disable-line no-control-regex + + if (!pubIdChar.test(node.publicId)) { + invalidStateError(); + } + + addExternalID(start.$DOCTYPE, node); // Fit in internal subset along with entities?: probably don't need as these would only differ if from DTD, and we're not rebuilding the DTD + + set(start); // Auto-generate the internalSubset instead? Avoid entities/notations in favor of array to preserve order? + + var entities = node.entities; // Currently deprecated + + if (entities && entities.length) { + start.$DOCTYPE.entities = []; + setObj('$DOCTYPE', 'entities'); + + _toConsumableArray$1(entities).forEach(function (entity) { + parseDOM(entity, namespaces); + }); // Reset for notations + + + parent = tmpParent; + parentIdx = tmpParentIdx + 1; + } + + var notations = node.notations; // Currently deprecated + + if (notations && notations.length) { + start.$DOCTYPE.notations = []; + setObj('$DOCTYPE', 'notations'); + + _toConsumableArray$1(notations).forEach(function (notation) { + parseDOM(notation, namespaces); + }); + } + + resetTemp(); + break; } - var pubIdChar = /^(\u0020|\u000D|\u000A|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%])*$/; // eslint-disable-line no-control-regex - - if (!pubIdChar.test(node.publicId)) { - invalidStateError(); - } - - addExternalID(start.$DOCTYPE, node); // Fit in internal subset along with entities?: probably don't need as these would only differ if from DTD, and we're not rebuilding the DTD - - set(start); // Auto-generate the internalSubset instead? Avoid entities/notations in favor of array to preserve order? - - var entities = node.entities; // Currently deprecated - - if (entities && entities.length) { - start.$DOCTYPE.entities = []; - setObj('$DOCTYPE', 'entities'); - Array.from(entities).forEach(function (entity) { - parseDOM(entity, namespaces); - }); // Reset for notations - - parent = tmpParent; - parentIdx = tmpParentIdx + 1; - } - - var notations = node.notations; // Currently deprecated - - if (notations && notations.length) { - start.$DOCTYPE.notations = []; - setObj('$DOCTYPE', 'notations'); - Array.from(notations).forEach(function (notation) { - parseDOM(notation, namespaces); - }); - } - - resetTemp(); - break; - case 11: // DOCUMENT FRAGMENT setTemp(); @@ -2036,10 +2223,12 @@ setObj('#'); children = node.childNodes; - Array.from(children).forEach(function (childNode) { + + _toConsumableArray$1(children).forEach(function (childNode) { // No need for setChildren, as we have already built the container array parseDOM(childNode, namespaces); }); + resetTemp(); break; @@ -2073,11 +2262,23 @@ stringOutput: true })); }; + /** + * + * @param {JamilihArray} args + * @returns {JamilihReturn} + */ + jml.toDOM = function () { // Alias for jml() return jml.apply(void 0, arguments); }; + /** + * + * @param {JamilihArray} args + * @returns {string} + */ + jml.toHTML = function () { // Todo: Replace this with version of jml() that directly builds a string @@ -2085,16 +2286,34 @@ return ret.outerHTML; }; + /** + * + * @param {JamilihArray} args + * @returns {string} + */ + jml.toDOMString = function () { // Alias for jml.toHTML for parity with jml.toJMLString return jml.toHTML.apply(jml, arguments); }; + /** + * + * @param {JamilihArray} args + * @returns {string} + */ + jml.toXML = function () { var ret = jml.apply(void 0, arguments); return new XmlSerializer().serializeToString(ret); }; + /** + * + * @param {JamilihArray} args + * @returns {string} + */ + jml.toXMLDOMString = function () { // Alias for jml.toXML for parity with jml.toJMLString @@ -2114,7 +2333,7 @@ _createClass(JamilihMap, [{ key: "get", - value: function get$$1(elem) { + value: function get(elem) { elem = typeof elem === 'string' ? $(elem) : elem; return _get(_getPrototypeOf$1(JamilihMap.prototype), "get", this).call(this, elem); } @@ -2155,7 +2374,7 @@ _createClass(JamilihWeakMap, [{ key: "get", - value: function get$$1(elem) { + value: function get(elem) { elem = typeof elem === 'string' ? $(elem) : elem; return _get(_getPrototypeOf$1(JamilihWeakMap.prototype), "get", this).call(this, elem); } @@ -2218,6 +2437,8 @@ }; jml.command = function (elem, symOrMap, methodName) { + var _func3; + elem = typeof elem === 'string' ? $(elem) : elem; var func; @@ -2235,20 +2456,17 @@ } return (_func = func)[methodName].apply(_func, args); - } else { - var _func3; + } - func = symOrMap.get(elem); + func = symOrMap.get(elem); - if (typeof func === 'function') { - var _func2; + if (typeof func === 'function') { + var _func2; - return (_func2 = func).call.apply(_func2, [elem, methodName].concat(args)); - } - - return (_func3 = func)[methodName].apply(_func3, [elem].concat(args)); - } // return func[methodName].call(elem, ...args); + return (_func2 = func).call.apply(_func2, [elem, methodName].concat(args)); + } + return (_func3 = func)[methodName].apply(_func3, [elem].concat(args)); // return func[methodName].call(elem, ...args); }; jml.setWindow = function (wind) { @@ -2279,7 +2497,8 @@ return XmlSerializer; }; - var body = doc && doc.body; + var body = doc && doc.body; // eslint-disable-line import/no-mutable-exports + var nbsp = "\xA0"; // Very commonly needed in templates /** diff --git a/dist/index-es.js b/dist/index-es.js index 81943341..c64a167a 100644 --- a/dist/index-es.js +++ b/dist/index-es.js @@ -2927,7 +2927,7 @@ function jQueryPluginSVG($) { /** * @function external:jQuery.fn.attr - * @param {string|string[]|PlainObject.} key + * @param {string|string[]|PlainObject} key * @param {string} value * @returns {external:jQuery|module:jQueryAttr.Attributes} */ @@ -3134,6 +3134,7 @@ function () { /** * @param {Element} elem + * @returns {SVGTransformList} */ function SVGTransformList(elem) { _classCallCheck(this, SVGTransformList); @@ -3242,7 +3243,7 @@ function () { } /** * @param {SVGTransform} newItem - * @returns {SVGTransform} + * @returns {void} */ }, { @@ -5379,7 +5380,7 @@ var getPointGrip = function getPointGrip(seg, update) { /** * @function module:path.getControlPoints * @param {Segment} seg -* @returns {PlainObject.} +* @returns {PlainObject} */ var getControlPoints = function getControlPoints(seg) { @@ -7124,7 +7125,7 @@ var pathActions = function () { width: 0, height: 0, display: 'inline' - }, 100); + }); } return undefined; @@ -8682,7 +8683,7 @@ var getPathDFromElement = function getPathDFromElement(elem) { * Get a set of attributes from an element that is useful for convertToPath. * @function module:utilities.getExtraAttributesForConvertToPath * @param {Element} elem - The element to be probed -* @returns {PlainObject.<"marker-start"|"marker-end"|"marker-mid"|"filter"|"clip-path", string>} An object with attributes. +* @returns {PlainObject<"marker-start"|"marker-end"|"marker-mid"|"filter"|"clip-path", string>} An object with attributes. */ var getExtraAttributesForConvertToPath = function getExtraAttributesForConvertToPath(elem) { @@ -9107,7 +9108,7 @@ var getElem = supportsSelectors() ? function (id) { * Assigns multiple attributes to an element. * @function module:utilities.assignAttributes * @param {Element} elem - DOM element to apply new attribute values to -* @param {PlainObject.} attrs - Object with attribute keys/values +* @param {PlainObject} attrs - Object with attribute keys/values * @param {Integer} [suspendLength] - Milliseconds to suspend redraw * @param {boolean} [unitCheck=false] - Boolean to indicate the need to use units.setUnitAttr * @returns {void} @@ -9357,7 +9358,7 @@ function toAbsoluteURL(url) { /** * Add any of the whitelisted attributes to the script tag. * @param {HTMLScriptElement} script - * @param {PlainObject.} atts + * @param {PlainObject} atts * @returns {void} */ @@ -9378,9 +9379,9 @@ function addScriptAtts(script, atts) { /** * @function module:importModule.importSetGlobalDefault -* @param {string|string[]} url +* @param {string|GenericArray} url * @param {module:importModule.ImportConfig} config -* @returns {Promise<*>} The value to which it resolves depends on the export of the targeted module. +* @returns {Promise} The value to which it resolves depends on the export of the targeted module. */ @@ -9501,7 +9502,7 @@ function importScript(url) { * @param {PlainObject} [atts={}] * @param {PlainObject} opts * @param {boolean} [opts.returnDefault=false} = {}] -* @returns {Promise<*>} Resolves to value of loading module or rejects with +* @returns {Promise} Resolves to value of loading module or rejects with * `Error` upon a script loading error. */ @@ -9607,7 +9608,7 @@ function jQueryPluginDBox($) { * types without checkboxes, it resolves to `true`. For checkboxes, it resolves * to an object with the `response` key containing the same value as the previous * mentioned (string or `true`) and a `checked` (boolean) property. - * @typedef {Promise} module:jQueryPluginDBox.PromiseResult + * @typedef {Promise} module:jQueryPluginDBox.ResultPromise */ /** @@ -9641,7 +9642,7 @@ function jQueryPluginDBox($) { * @param {module:jQueryPluginDBox.SelectOption[]} [opts] * @param {module:jQueryPluginDBox.SelectChangeListener} [changeListener] * @param {module:jQueryPluginDBox.CheckboxInfo} [checkbox] - * @returns {jQueryPluginDBox.PromiseResult} + * @returns {jQueryPluginDBox.ResultPromise} */ function dbox(type, msg, defaultVal, opts, changeListener, checkbox) { @@ -9729,7 +9730,7 @@ function jQueryPluginDBox($) { } /** * @param {string} msg Message to alert - * @returns {jQueryPluginDBox.PromiseResult} + * @returns {jQueryPluginDBox.ResultPromise} */ @@ -9738,7 +9739,7 @@ function jQueryPluginDBox($) { }; /** * @param {string} msg Message for which to ask confirmation - * @returns {jQueryPluginDBox.PromiseResult} + * @returns {jQueryPluginDBox.ResultPromise} */ @@ -9747,7 +9748,7 @@ function jQueryPluginDBox($) { }; /** * @param {string} msg Message to indicate upon cancelable indicator - * @returns {jQueryPluginDBox.PromiseResult} + * @returns {jQueryPluginDBox.ResultPromise} */ @@ -9757,7 +9758,7 @@ function jQueryPluginDBox($) { /** * @param {string} msg Message to accompany the prompt * @param {string} [defaultText=''] The default text to show for the prompt - * @returns {jQueryPluginDBox.PromiseResult} + * @returns {jQueryPluginDBox.ResultPromise} */ @@ -9930,8 +9931,28 @@ function () { }, { key: "appendChildren", value: function appendChildren(children) { - for (var i = 0; i < children.length; ++i) { - this.group_.append(children[i]); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var child = _step.value; + this.group_.append(child); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } } } /** @@ -13778,10 +13799,10 @@ function SvgCanvas(container, config) { 'fill-opacity': curShape.fill_opacity, opacity: curShape.opacity / 2, style: 'pointer-events:inherit' - }, 100); + }); } - assignAttributes(shape, data.attr, 100); + assignAttributes(shape, data.attr); cleanupElement(shape); // Children if (data.children) { @@ -14510,7 +14531,7 @@ function SvgCanvas(container, config) { * @param {module:svgcanvas.SvgCanvas#event:ext_mouseDown|module:svgcanvas.SvgCanvas#event:ext_mouseMove|module:svgcanvas.SvgCanvas#event:ext_mouseUp|module:svgcanvas.SvgCanvas#event:ext_zoomChanged|module:svgcanvas.SvgCanvas#event:ext_IDsUpdated|module:svgcanvas.SvgCanvas#event:ext_canvasUpdated|module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate|module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementTransition|module:svgcanvas.SvgCanvas#event:ext_elementChanged|module:svgcanvas.SvgCanvas#event:ext_langReady|module:svgcanvas.SvgCanvas#event:ext_langChanged|module:svgcanvas.SvgCanvas#event:ext_addLangData|module:svgcanvas.SvgCanvas#event:ext_onNewDocument|module:svgcanvas.SvgCanvas#event:ext_workareaResized|module:svgcanvas.ExtensionVarBuilder} [vars] * @param {boolean} [returnArray] * @param {module:svgcanvas.ExtensionNameFilter} nameFilter - * @returns {GenericArray.|module:svgcanvas.ExtensionStatus|false} See {@tutorial ExtensionDocs} on the ExtensionStatus. + * @returns {GenericArray|module:svgcanvas.ExtensionStatus|false} See {@tutorial ExtensionDocs} on the ExtensionStatus. */ @@ -15435,12 +15456,14 @@ function SvgCanvas(container, config) { if (!rightClick) { // insert a dummy transform so if the element(s) are moved it will have // a transform to use for its translate - for (var i = 0; i < selectedElements.length; ++i) { - if (isNullish(selectedElements[i])) { + for (var _i2 = 0, _selectedElements = selectedElements; _i2 < _selectedElements.length; _i2++) { + var selectedElement = _selectedElements[_i2]; + + if (isNullish(selectedElement)) { continue; } - var slist = getTransformList(selectedElements[i]); + var slist = getTransformList(selectedElement); if (slist.numberOfItems) { slist.insertItemBefore(svgroot.createSVGTransform(), 0); @@ -15469,7 +15492,7 @@ function SvgCanvas(container, config) { width: 0, height: 0, display: 'inline' - }, 100); + }); } break; @@ -15487,7 +15510,7 @@ function SvgCanvas(container, config) { width: 0, height: 0, display: 'inline' - }, 100); + }); break; case 'resize': @@ -15544,16 +15567,16 @@ function SvgCanvas(container, config) { var all = mouseTarget.getElementsByTagName('*'), len = all.length; - for (var _i2 = 0; _i2 < len; _i2++) { - if (!all[_i2].style) { + for (var i = 0; i < len; i++) { + if (!all[i].style) { // mathML continue; } - all[_i2].style.vectorEffect = 'non-scaling-stroke'; + all[i].style.vectorEffect = 'non-scaling-stroke'; if (iswebkit) { - delayedStroke(all[_i2]); + delayedStroke(all[i]); } } } @@ -15884,7 +15907,7 @@ function SvgCanvas(container, config) { y: Math.min(rStartY, realY), width: Math.abs(realX - rStartX), height: Math.abs(realY - rStartY) - }, 100); // for each selected: + }); // for each selected: // - if newList contains selected, do nothing // - if newList doesn't contain selected, remove it from selected // - for any newList that was not in selectedElements, add it to selected @@ -16032,7 +16055,7 @@ function SvgCanvas(container, config) { y: Math.min(rStartY * currentZoom, realY), width: Math.abs(realX - rStartX * currentZoom), height: Math.abs(realY - rStartY * currentZoom) - }, 100); + }); break; } @@ -16041,7 +16064,7 @@ function SvgCanvas(container, config) { assignAttributes(shape, { x: x, y: y - }, 1000); + }); break; } @@ -16100,7 +16123,7 @@ function SvgCanvas(container, config) { height: h, x: newX, y: newY - }, 1000); + }); break; } @@ -16232,7 +16255,7 @@ function SvgCanvas(container, config) { y: Math.min(rStartY * currentZoom, realY), width: Math.abs(realX - rStartX * currentZoom), height: Math.abs(realY - rStartY * currentZoom) - }, 100); + }); } pathActions$1.mouseMove(x, y); @@ -19006,10 +19029,30 @@ function SvgCanvas(container, config) { elem = $$9(elem).data('gsvg') || $$9(elem).data('symbol') || elem; var childs = elem.childNodes; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - for (var i = 0; i < childs.length; i++) { - if (childs[i].nodeName === 'title') { - return childs[i].textContent; + try { + for (var _iterator2 = childs[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var child = _step2.value; + + if (child.nodeName === 'title') { + return child.textContent; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { + _iterator2["return"](); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } } } @@ -19076,12 +19119,32 @@ function SvgCanvas(container, config) { var docTitle = false, oldTitle = ''; var batchCmd = new BatchCommand$1('Change Image Title'); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; - for (var i = 0; i < childs.length; i++) { - if (childs[i].nodeName === 'title') { - docTitle = childs[i]; - oldTitle = docTitle.textContent; - break; + try { + for (var _iterator3 = childs[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var child = _step3.value; + + if (child.nodeName === 'title') { + docTitle = child; + oldTitle = docTitle.textContent; + break; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { + _iterator3["return"](); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } } } @@ -19922,7 +19985,7 @@ function SvgCanvas(container, config) { y: '-50%', width: '200%', height: '200%' - }, 100); // Removing these attributes hides text in Chrome (see Issue 579) + }); // Removing these attributes hides text in Chrome (see Issue 579) } else if (!isWebkit()) { filterElem.removeAttribute('x'); filterElem.removeAttribute('y'); @@ -21068,9 +21131,9 @@ function SvgCanvas(container, config) { this.moveToTopSelectedElement = function () { - var _selectedElements = selectedElements, - _selectedElements2 = _slicedToArray(_selectedElements, 1), - selected = _selectedElements2[0]; + var _selectedElements2 = selectedElements, + _selectedElements3 = _slicedToArray(_selectedElements2, 1), + selected = _selectedElements3[0]; if (!isNullish(selected)) { var t = selected; @@ -21095,9 +21158,9 @@ function SvgCanvas(container, config) { this.moveToBottomSelectedElement = function () { - var _selectedElements3 = selectedElements, - _selectedElements4 = _slicedToArray(_selectedElements3, 1), - selected = _selectedElements4[0]; + var _selectedElements4 = selectedElements, + _selectedElements5 = _slicedToArray(_selectedElements4, 1), + selected = _selectedElements5[0]; if (!isNullish(selected)) { var t = selected; @@ -22352,10 +22415,10 @@ function jQueryPluginSVGIcons($) { * listed under "fallback" * @param {boolean} [opts.replace] If set to `true`, HTML elements will * be replaced by, rather than include the SVG icon. - * @param {PlainObject.} [opts.placement] Map with selectors + * @param {PlainObject} [opts.placement] Map with selectors * for keys and SVG icon ids as values. This provides a custom method of * adding icons. - * @param {PlainObject.} [opts.resize] Map + * @param {PlainObject} [opts.resize] Map * with selectors for keys and numbers as values. This allows an easy way to * resize specific icons. * @param {module:jQuerySVGIcons.SVGIconsLoadedCallback} [opts.callback] A @@ -22777,7 +22840,7 @@ function jQueryPluginSVGIcons($) { /** * @function external:jQuery.resizeSvgIcons - * @param {PlainObject.} obj Object with + * @param {PlainObject} obj Object with * selectors as keys. The values are sizes. * @returns {void} */ @@ -24682,9 +24745,28 @@ function jQueryContextMenu($) { $(this).each(function () { if (o !== undefined) { var d = o.split(','); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - for (var i = 0; i < d.length; i++) { - $(this).find('A[href="' + d[i] + '"]').parent().addClass('disabled'); + try { + for (var _iterator = d[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var href = _step.value; + $(this).find('A[href="' + href + '"]').parent().addClass('disabled'); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } } } }); @@ -24707,9 +24789,28 @@ function jQueryContextMenu($) { $(this).each(function () { if (o !== undefined) { var d = o.split(','); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - for (var i = 0; i < d.length; i++) { - $(this).find('A[href="' + d[i] + '"]').parent().removeClass('disabled'); + try { + for (var _iterator2 = d[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var href = _step2.value; + $(this).find('A[href="' + href + '"]').parent().removeClass('disabled'); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { + _iterator2["return"](); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } } } }); @@ -28518,6 +28619,44 @@ function () { }; }(); +function _slicedToArray$1(arr, i) { + return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _nonIterableRest$1(); +} + +function _arrayWithHoles$1(arr) { + if (Array.isArray(arr)) return arr; +} + +function _iterableToArrayLimit$1(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +function _nonIterableRest$1() { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); +} + function loadStylesheets(stylesheets) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, beforeDefault = _ref.before, @@ -28536,7 +28675,7 @@ function loadStylesheets(stylesheets) { if (Array.isArray(stylesheetURL)) { var _stylesheetURL = stylesheetURL; - var _stylesheetURL2 = _slicedToArray(_stylesheetURL, 2); + var _stylesheetURL2 = _slicedToArray$1(_stylesheetURL, 2); stylesheetURL = _stylesheetURL2[0]; var _stylesheetURL2$ = _stylesheetURL2[1]; @@ -29998,7 +30137,7 @@ editor.init = function () { setFlyoutPositions(); }; /** - * Setup SVG icons + * Setup SVG icons. * @returns {void} */ @@ -30381,7 +30520,7 @@ editor.init = function () { } /** * This function highlights the layer passed in (by fading out the other layers). - * If no layer is passed in, this function restores the other layers + * If no layer is passed in, this function restores the other layers. * @param {string} [layerNameToHighlight] * @returns {void} */ @@ -31757,7 +31896,7 @@ editor.init = function () { var allHolders = {}; /** - * @param {PlainObject.} holders Key is a selector + * @param {PlainObject} holders Key is a selector * @returns {void} */ @@ -35826,7 +35965,7 @@ editor.init = function () { } }); /** - * Implements {@see module:jQueryContextMenu.jQueryContextMenuListener} + * Implements {@see module:jQueryContextMenu.jQueryContextMenuListener}. * @param {"dupe"|"delete"|"merge_down"|"merge_all"} action * @param {external:jQuery} el * @param {{x: Float, y: Float, docX: Float, docY: Float}} pos @@ -36024,7 +36163,7 @@ editor.init = function () { var result = _ref27.target.result; /** - * Insert the new image until we know its dimensions + * Insert the new image until we know its dimensions. * @param {Float} width * @param {Float} height * @returns {void} diff --git a/dist/index-es.min.js b/dist/index-es.min.js index c1cae6d0..8579fe79 100644 --- a/dist/index-es.min.js +++ b/dist/index-es.min.js @@ -1,2 +1,2 @@ -function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function n(e){return function(){var n=this,r=arguments;return new Promise(function(a,i){var o=e.apply(n,r);function s(e){t(o,a,i,s,l,"next",e)}function l(e){t(o,a,i,s,l,"throw",e)}s(void 0)})}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;nt.getTotalLength())break;n--}while(n>0);return n}),window.SVGPathSeg=e,window.SVGPathSegClosePath=t,window.SVGPathSegMovetoAbs=n,window.SVGPathSegMovetoRel=a,window.SVGPathSegLinetoAbs=o,window.SVGPathSegLinetoRel=c,window.SVGPathSegCurvetoCubicAbs=d,window.SVGPathSegCurvetoCubicRel=h,window.SVGPathSegCurvetoQuadraticAbs=p,window.SVGPathSegCurvetoQuadraticRel=f,window.SVGPathSegArcAbs=g,window.SVGPathSegArcRel=m,window.SVGPathSegLinetoHorizontalAbs=v,window.SVGPathSegLinetoHorizontalRel=_,window.SVGPathSegLinetoVerticalAbs=y,window.SVGPathSegLinetoVerticalRel=b,window.SVGPathSegCurvetoCubicSmoothAbs=x,window.SVGPathSegCurvetoCubicSmoothRel=w,window.SVGPathSegCurvetoQuadraticSmoothAbs=S,window.SVGPathSegCurvetoQuadraticSmoothRel=k}if(!("SVGPathSegList"in window&&"appendItem"in window.SVGPathSegList.prototype)){var C=function(){function e(t){r(this,e),this._pathElement=t,this._list=this._parsePath(this._pathElement.getAttribute("d")),this._mutationObserverConfig={attributes:!0,attributeFilter:["d"]},this._pathElementMutationObserver=new MutationObserver(this._updateListFromPathMutations.bind(this)),this._pathElementMutationObserver.observe(this._pathElement,this._mutationObserverConfig)}return i(e,[{key:"_checkPathSynchronizedToList",value:function(){this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords())}},{key:"_updateListFromPathMutations",value:function(e){if(this._pathElement){var t=!1;e.forEach(function(e){"d"===e.attributeName&&(t=!0)}),t&&(this._list=this._parsePath(this._pathElement.getAttribute("d")))}}},{key:"_writeListToPath",value:function(){this._pathElementMutationObserver.disconnect(),this._pathElement.setAttribute("d",e._pathSegArrayAsString(this._list)),this._pathElementMutationObserver.observe(this._pathElement,this._mutationObserverConfig)}},{key:"segmentChanged",value:function(e){this._writeListToPath()}},{key:"clear",value:function(){this._checkPathSynchronizedToList(),this._list.forEach(function(e){e._owningPathSegList=null}),this._list=[],this._writeListToPath()}},{key:"initialize",value:function(e){return this._checkPathSynchronizedToList(),this._list=[e],e._owningPathSegList=this,this._writeListToPath(),e}},{key:"_checkValidIndex",value:function(e){if(isNaN(e)||e<0||e>=this.numberOfItems)throw new Error("INDEX_SIZE_ERR")}},{key:"getItem",value:function(e){return this._checkPathSynchronizedToList(),this._checkValidIndex(e),this._list[e]}},{key:"insertItemBefore",value:function(e,t){return this._checkPathSynchronizedToList(),t>this.numberOfItems&&(t=this.numberOfItems),e._owningPathSegList&&(e=e.clone()),this._list.splice(t,0,e),e._owningPathSegList=this,this._writeListToPath(),e}},{key:"replaceItem",value:function(e,t){return this._checkPathSynchronizedToList(),e._owningPathSegList&&(e=e.clone()),this._checkValidIndex(t),this._list[t]=e,e._owningPathSegList=this,this._writeListToPath(),e}},{key:"removeItem",value:function(e){this._checkPathSynchronizedToList(),this._checkValidIndex(e);var t=this._list[e];return this._list.splice(e,1),this._writeListToPath(),t}},{key:"appendItem",value:function(e){return this._checkPathSynchronizedToList(),e._owningPathSegList&&(e=e.clone()),this._list.push(e),e._owningPathSegList=this,this._writeListToPath(),e}},{key:"_parsePath",value:function(e){if(!e||!e.length)return[];var t=this,n=function(){function e(){r(this,e),this.pathSegList=[]}return i(e,[{key:"appendSegment",value:function(e){this.pathSegList.push(e)}}]),e}(),a=function(){function e(t){r(this,e),this._string=t,this._currentIndex=0,this._endIndex=this._string.length,this._previousCommand=SVGPathSeg.PATHSEG_UNKNOWN,this._skipOptionalSpaces()}return i(e,[{key:"_isCurrentSpace",value:function(){var e=this._string[this._currentIndex];return e<=" "&&(" "===e||"\n"===e||"\t"===e||"\r"===e||"\f"===e)}},{key:"_skipOptionalSpaces",value:function(){for(;this._currentIndex="0"&&e<="9")&&t!==SVGPathSeg.PATHSEG_CLOSEPATH?t===SVGPathSeg.PATHSEG_MOVETO_ABS?SVGPathSeg.PATHSEG_LINETO_ABS:t===SVGPathSeg.PATHSEG_MOVETO_REL?SVGPathSeg.PATHSEG_LINETO_REL:t:SVGPathSeg.PATHSEG_UNKNOWN}},{key:"initialCommandIsMoveTo",value:function(){if(!this.hasMoreData())return!0;var e=this.peekSegmentType();return e===SVGPathSeg.PATHSEG_MOVETO_ABS||e===SVGPathSeg.PATHSEG_MOVETO_REL}},{key:"_parseNumber",value:function(){var e=0,t=0,n=1,r=0,a=1,i=1,o=this._currentIndex;if(this._skipOptionalSpaces(),this._currentIndex"9")&&"."!==this._string.charAt(this._currentIndex))){for(var s=this._currentIndex;this._currentIndex="0"&&this._string.charAt(this._currentIndex)<="9";)this._currentIndex++;if(this._currentIndex!==s)for(var l=this._currentIndex-1,c=1;l>=s;)t+=c*(this._string.charAt(l--)-"0"),c*=10;if(this._currentIndex=this._endIndex||this._string.charAt(this._currentIndex)<"0"||this._string.charAt(this._currentIndex)>"9")return;for(;this._currentIndex="0"&&this._string.charAt(this._currentIndex)<="9";)n*=10,r+=(this._string.charAt(this._currentIndex)-"0")/n,this._currentIndex+=1}if(this._currentIndex!==o&&this._currentIndex+1=this._endIndex||this._string.charAt(this._currentIndex)<"0"||this._string.charAt(this._currentIndex)>"9")return;for(;this._currentIndex="0"&&this._string.charAt(this._currentIndex)<="9";)e*=10,e+=this._string.charAt(this._currentIndex)-"0",this._currentIndex++}var u=t+r;if(u*=a,e&&(u*=Math.pow(10,i*e)),o!==this._currentIndex)return this._skipOptionalSpacesOrDelimiter(),u}}},{key:"_parseArcFlag",value:function(){if(!(this._currentIndex>=this._endIndex)){var e=!1,t=this._string.charAt(this._currentIndex++);if("0"===t)e=!1;else{if("1"!==t)return;e=!0}return this._skipOptionalSpacesOrDelimiter(),e}}},{key:"parseSegment",value:function(){var e=this._string[this._currentIndex],n=this._pathSegTypeFromChar(e);if(n===SVGPathSeg.PATHSEG_UNKNOWN){if(this._previousCommand===SVGPathSeg.PATHSEG_UNKNOWN)return null;if((n=this._nextCommandHelper(e,this._previousCommand))===SVGPathSeg.PATHSEG_UNKNOWN)return null}else this._currentIndex++;switch(this._previousCommand=n,n){case SVGPathSeg.PATHSEG_MOVETO_REL:return new SVGPathSegMovetoRel(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_MOVETO_ABS:return new SVGPathSegMovetoAbs(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_REL:return new SVGPathSegLinetoRel(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_ABS:return new SVGPathSegLinetoAbs(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:return new SVGPathSegLinetoHorizontalRel(t,this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:return new SVGPathSegLinetoHorizontalAbs(t,this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:return new SVGPathSegLinetoVerticalRel(t,this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:return new SVGPathSegLinetoVerticalAbs(t,this._parseNumber());case SVGPathSeg.PATHSEG_CLOSEPATH:return this._skipOptionalSpaces(),new SVGPathSegClosePath(t);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL:var r={x1:this._parseNumber(),y1:this._parseNumber(),x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicRel(t,r.x,r.y,r.x1,r.y1,r.x2,r.y2);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS:var a={x1:this._parseNumber(),y1:this._parseNumber(),x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicAbs(t,a.x,a.y,a.x1,a.y1,a.x2,a.y2);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:var i={x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicSmoothRel(t,i.x,i.y,i.x2,i.y2);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:var o={x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicSmoothAbs(t,o.x,o.y,o.x2,o.y2);case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:var s={x1:this._parseNumber(),y1:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoQuadraticRel(t,s.x,s.y,s.x1,s.y1);case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:var l={x1:this._parseNumber(),y1:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoQuadraticAbs(t,l.x,l.y,l.x1,l.y1);case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:return new SVGPathSegCurvetoQuadraticSmoothRel(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:return new SVGPathSegCurvetoQuadraticSmoothAbs(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_ARC_REL:var c={x1:this._parseNumber(),y1:this._parseNumber(),arcAngle:this._parseNumber(),arcLarge:this._parseArcFlag(),arcSweep:this._parseArcFlag(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegArcRel(t,c.x,c.y,c.x1,c.y1,c.arcAngle,c.arcLarge,c.arcSweep);case SVGPathSeg.PATHSEG_ARC_ABS:var u={x1:this._parseNumber(),y1:this._parseNumber(),arcAngle:this._parseNumber(),arcLarge:this._parseArcFlag(),arcSweep:this._parseArcFlag(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegArcAbs(t,u.x,u.y,u.x1,u.y1,u.arcAngle,u.arcLarge,u.arcSweep);default:throw new Error("Unknown path seg type.")}}}]),e}(),o=new n,s=new a(e);if(!s.initialCommandIsMoveTo())return[];for(;s.hasMoreData();){var l=s.parseSegment();if(!l)return[];o.appendSegment(l)}return o.pathSegList}}],[{key:"_pathSegArrayAsString",value:function(e){var t="",n=!0;return e.forEach(function(e){n?(n=!1,t+=e._asPathString()):t+=" "+e._asPathString()}),t}}]),e}();C.prototype.classname="SVGPathSegList",Object.defineProperty(C.prototype,"numberOfItems",{get:function(){return this._checkPathSynchronizedToList(),this._list.length},enumerable:!0}),Object.defineProperties(SVGPathElement.prototype,{pathSegList:{get:function(){return this._pathSegList||(this._pathSegList=new C(this)),this._pathSegList},enumerable:!0},normalizedPathSegList:{get:function(){return this.pathSegList},enumerable:!0},animatedPathSegList:{get:function(){return this.pathSegList},enumerable:!0},animatedNormalizedPathSegList:{get:function(){return this.pathSegList},enumerable:!0}}),window.SVGPathSegList=C}}();var m,v=jQuery,_=(Boolean(document.createElementNS&&document.createElementNS(f.SVG,"svg").createSVGRect),navigator.userAgent),y=document.createElementNS(f.SVG,"svg"),b=Boolean(window.opera),x=_.includes("AppleWebKit"),w=_.includes("Gecko/"),S=_.includes("MSIE"),k=_.includes("Chrome/"),C=(_.includes("Windows"),_.includes("Macintosh")),A="ontouchstart"in window,E=Boolean(y.querySelector),G=Boolean(document.evaluate),P=function(){var e=document.createElementNS(f.SVG,"path");e.setAttribute("d","M0,0 10,10");var t=e.pathSegList,n=e.createSVGPathSegLinetoAbs(5,5);try{return t.replaceItem(n,1),!0}catch(e){}return!1}(),I=function(){var e=document.createElementNS(f.SVG,"path");e.setAttribute("d","M0,0 10,10");var t=e.pathSegList,n=e.createSVGPathSegLinetoAbs(5,5);try{return t.insertItemBefore(n,1),!0}catch(e){}return!1}(),N=function(){var e=document.createElementNS(f.SVG,"svg"),t=document.createElementNS(f.SVG,"svg");document.documentElement.append(e),t.setAttribute("x",5),e.append(t);var n=document.createElementNS(f.SVG,"text");n.textContent="a",t.append(n);try{return 0===n.getStartPositionOfChar(0).x}catch(e){return!1}finally{e.remove()}}(),T=function(){var e=document.createElementNS(f.SVG,"svg");document.documentElement.append(e);var t=document.createElementNS(f.SVG,"path");t.setAttribute("d","M0,0 C0,0 10,10 10,0"),e.append(t);var n=t.getBBox();return e.remove(),n.height>4&&n.height<5}(),L=function(){var e=document.createElementNS(f.SVG,"svg");document.documentElement.append(e);var t=document.createElementNS(f.SVG,"path");t.setAttribute("d","M0,0 10,0");var n=document.createElementNS(f.SVG,"path");n.setAttribute("d","M5,0 15,0");var r=document.createElementNS(f.SVG,"g");r.append(t,n),e.append(r);var a=r.getBBox();return e.remove(),15===a.width}(),M=(function(){var e=document.createElementNS(f.SVG,"rect");e.setAttribute("x",.1);var t=!e.cloneNode(!1).getAttribute("x").includes(",");t||v.alert('NOTE: This version of Opera is known to contain bugs in SVG-edit.\nPlease upgrade to the latest version in which the problems have been fixed.')}(),(m=document.createElementNS(f.SVG,"rect")).setAttribute("style","vector-effect:non-scaling-stroke"),"non-scaling-stroke"===m.style.vectorEffect),O=function(){var t=document.createElementNS(f.SVG,"rect").transform.baseVal,n=y.createSVGTransform();t.appendItem(n);var r=t.getItem(0),a=function(t){return t&&"object"===e(t)&&"function"==typeof t.setMatrix&&"angle"in t};return a(r)&&a(n)&&r.type===n.type&&r.angle===n.angle&&r.matrix.a===n.matrix.a&&r.matrix.b===n.matrix.b&&r.matrix.c===n.matrix.c&&r.matrix.d===n.matrix.d&&r.matrix.e===n.matrix.e&&r.matrix.f===n.matrix.f}(),j=function(){return b},V=function(){return x},R=function(){return w},B=function(){return S},D=function(){return k},U=function(){return C},F=function(){return A},H=function(){return L},z=function(){return M};function q(t){var n=t.fn.attr;return t.fn.attr=function(t,r){var a=this.length;if(!a)return n.call(this,t,r);for(var i=0;i=0)return this._xforms[e];var t=new Error("DOMException with code=INDEX_SIZE_ERR");throw t.code=1,t}},{key:"insertItemBefore",value:function(e,t){var n=null;if(t>=0)if(t=0&&(this._removeFromOtherLists(e),this._xforms[t]=e,n=e,this._list._update()),n}},{key:"removeItem",value:function(e){if(e=0){var t,n=this._xforms[e],r=new Array(this.numberOfItems-1);for(t=0;t=0;t--)this.stack[t].unapply(e);e&&e.handleHistoryEvent(ce.AFTER_UNAPPLY,this)}},{key:"elements",value:function(){for(var e=[],t=this.stack.length;t--;)for(var n=this.stack[t].elements(),r=n.length;r--;)e.includes(n[r])||e.push(n[r]);return e}},{key:"addSubCommand",value:function(e){this.stack.push(e)}},{key:"isEmpty",value:function(){return!this.stack.length}}]),t}();ge.type=ge.prototype.type;var me,ve,_e,ye,be,xe=function(){function e(t){r(this,e),this.handler_=t||null,this.undoStackPointer=0,this.undoStack=[],this.undoChangeStackPointer=-1,this.undoableChangeStack=[]}return i(e,[{key:"resetUndoStack",value:function(){this.undoStack=[],this.undoStackPointer=0}},{key:"getUndoStackSize",value:function(){return this.undoStackPointer}},{key:"getRedoStackSize",value:function(){return this.undoStack.length-this.undoStackPointer}},{key:"getNextUndoCommandText",value:function(){return this.undoStackPointer>0?this.undoStack[this.undoStackPointer-1].getText():""}},{key:"getNextRedoCommandText",value:function(){return this.undoStackPointer0&&this.undoStack[--this.undoStackPointer].unapply(this.handler_)}},{key:"redo",value:function(){this.undoStackPointer0&&this.undoStack[this.undoStackPointer++].apply(this.handler_)}},{key:"addCommandToHistory",value:function(e){this.undoStackPointer0&&(this.undoStack=this.undoStack.splice(0,this.undoStackPointer)),this.undoStack.push(e),this.undoStackPointer=this.undoStack.length}},{key:"beginUndoableChange",value:function(e,t){for(var n=++this.undoChangeStackPointer,r=t.length,a=new Array(r),i=new Array(r);r--;){var o=t[r];an(o)||(i[r]=o,a[r]=o.getAttribute(e))}this.undoableChangeStack[n]={attrName:e,oldValues:a,elements:i}}},{key:"finishUndoableChange",value:function(){for(var e=this.undoChangeStackPointer--,t=this.undoableChangeStack[e],n=t.attrName,r=new ge("Change "+n),a=t.elements.length;a--;){var i=t.elements[a];if(!an(i)){var o={};o[n]=t.oldValues[a],o[n]!==i.getAttribute(n)&&r.addSubCommand(new fe(i,o,n))}}return this.undoableChangeStack[e]=null,r}}]),e}(),we=Object.freeze({HistoryEventTypes:ce,MoveElementCommand:de,InsertElementCommand:he,RemoveElementCommand:pe,ChangeElementCommand:fe,BatchCommand:ge,UndoManager:xe}),Se=document.createElementNS(f.SVG,"svg"),ke=function(e,t,n){return{x:n.a*e+n.c*t+n.e,y:n.b*e+n.d*t+n.f}},Ce=function(e){return 1===e.a&&0===e.b&&0===e.c&&1===e.d&&0===e.e&&0===e.f},Ae=function(){for(var e=arguments.length,t=new Array(e),n=0;n(n=parseInt(n))){var r=n;n=t,t=r}for(var a=Se.createSVGMatrix(),i=t;i<=n;++i){var o=i>=0&&ie.x&&t.ye.y},Le=jQuery,Me={2:["x","y"],4:["x","y"],6:["x","y","x1","y1","x2","y2"],8:["x","y","x1","y1"],10:["x","y","r1","r2","angle","largeArcFlag","sweepFlag"],12:["x"],14:["y"],16:["x","y","x2","y2"],18:["x","y"]},Oe={},je=function(e){Object.assign(Oe,e.ui)},Ve=[],Re=!0,Be={},De=null,Ue=null,Fe=function(e){Ue=e,Ve=[0,"ClosePath"];Le.each(["Moveto","Lineto","CurvetoCubic","CurvetoQuadratic","Arc","LinetoHorizontal","LinetoVertical","CurvetoCubicSmooth","CurvetoQuadraticSmooth"],function(e,t){Ve.push(t+"Abs"),Ve.push(t+"Rel")})},He=function(e,t,n){var r=e.pathSegList;if(I)r.insertItemBefore(t,n);else{for(var a=r.numberOfItems,i=[],o=0;o0?(p=g element");this.elem=t,this.segs=[],this.selected_pts=[],De=this,this.init()}return i(e,[{key:"init",value:function(){Le(Xe()).find("*").each(function(){Le(this).attr("display","none")});var e=this.elem.pathSegList,t=e.numberOfItems;this.segs=[],this.selected_pts=[],this.first_seg=null;for(var n=0;n=t?null:i[s+1],u=s-1<0?null:i[s-1];if(2===l.type){if(u&&1!==u.type){var d=i[o];d.next=i[o+1],d.next.prev=d,d.addGrip()}o=s}else if(c&&1===c.type)l.next=i[o+1],l.next.prev=l,l.mate=i[o],l.addGrip(),an(this.first_seg)&&(this.first_seg=l);else if(c)1!==l.type&&(l.addGrip(),c&&2!==c.type&&(l.next=c,l.next.prev=l));else if(1!==l.type){var h=i[o];h.next=i[o+1],h.next.prev=h,h.addGrip(),l.addGrip(),this.first_seg||(this.first_seg=i[o])}}return this}},{key:"eachSeg",value:function(e){for(var t=this.segs.length,n=0;n=0&&n.selected_pts.push(e)}),this.selected_pts.sort();var r=this.selected_pts.length,a=[];for(a.length=r;r--;){var i=this.selected_pts[r],o=this.segs[i];o.select(!0),a[r]=o.ptgrip}var s=e.subpathIsClosed(this.selected_pts[0]);Ue.addPtsToSelection({grips:a,closedSubpath:s})}}],[{key:"subpathIsClosed",value:function(e){var t=!1;return De.eachSeg(function(n){return n<=e||2!==this.type&&(1!==this.type||(t=!0,!1))}),t}}]),e}(),rt=function(e){var t=Be[e.id];return t||(t=Be[e.id]=new nt(e)),t},at=function(e){e in Be&&delete Be[e]},it=function(e,t){var n=e-_e,r=t-ye,a=Math.sqrt(n*n+r*r),i=Math.atan2(r,n)+be;return n=a*Math.cos(i)+_e,r=a*Math.sin(i)+ye,n-=me,r-=ve,a=Math.sqrt(n*n+r*r),i=Math.atan2(r,n)-be,{x:a*Math.cos(i)+me,y:a*Math.sin(i)+ve}},ot=function(){var e=De.elem;if(be=Zt(e,!0)){var t=De.oldbbox;_e=t.x+t.width/2,ye=t.y+t.height/2;var n=Dt(e);me=n.x+n.width/2,ve=n.y+n.height/2;var r=me-_e,a=ve-ye,i=Math.sqrt(r*r+a*a),o=Math.atan2(a,r)+be;me=i*Math.cos(o)+_e,ve=i*Math.sin(o)+ye;for(var s=e.pathSegList,l=s.numberOfItems;l;){l-=1;var c=s.getItem(l),u=c.pathSegType;if(1!==u){var d=it(c.x,c.y),h=[d.x,d.y];if(!an(c.x1)&&!an(c.x2)){var p=it(c.x1,c.y1),f=it(c.x2,c.y2);h.splice(h.length,0,p.x,p.y,f.x,f.y)}$e(u,l,h)}}Dt(e);var g=Ue.getSVGRoot().createSVGTransform(),m=$(e);g.setRotate(180*be/Math.PI,me,ve),m.replaceItem(g,0)}},st=[0,"z","M","m","L","l","C","c","Q","q","A","a","H","h","V","v","S","s","T","t"],lt=function(e,t){for(var n=e.pathSegList,r=n.numberOfItems,a=0,i=0,o="",s=null,l=0;l=C-w&&g<=C+w&&m>=A-w&&m<=A+w){S=!0;break}}a=Ue.getId(),at(a);var E,G,P=Jt(a),I=b.numberOfItems;if(S){if(x<=1&&I>=2){var N=b.getItem(0).x,T=b.getItem(0).y;E=4===(G=v.pathSegList.getItem(1)).pathSegType?y.createSVGPathSegLinetoAbs(N,T):y.createSVGPathSegCurvetoCubicAbs(N,T,G.x1/p,G.y1/p,N,T);var L=y.createSVGPathSegClosePath();b.appendItem(E),b.appendItem(L)}else if(I<3)return!1;if(Le(v).remove(),Ue.setDrawnPath(null),Ue.setStarted(!1),ht){De.matrix&&Ue.remapElement(P,{},De.matrix.inverse());var M=P.getAttribute("d"),O=Le(De.elem).attr("d");return Le(De.elem).attr("d",O+M),Le(P).remove(),De.matrix&&ot(),Fe(),gt.toEditMode(De.elem),De.selectPt(),!1}}else{if(!Le.contains(Ue.getContainer(),Ue.getMouseTarget(e)))return!1;var j=y.pathSegList.numberOfItems,V=y.pathSegList.getItem(j-1),R=V.x,B=V.y;if(e.shiftKey){var D=Ne(R,B,g,m);g=D.x,m=D.y}E=4===(G=v.pathSegList.getItem(1)).pathSegType?y.createSVGPathSegLinetoAbs(Ue.round(g),Ue.round(m)):y.createSVGPathSegCurvetoCubicAbs(Ue.round(g),Ue.round(m),G.x1/p,G.y1/p,G.x2/p,G.y2/p),y.pathSegList.appendItem(E),g*=p,m*=p,v.setAttribute("d",["M",g,m,g,m].join(" ")),_=j,ht&&(_+=De.segs.length),We(_,g,m)}}else{var U="M"+g+","+m+" ";Ue.setDrawnPath(Ue.addSVGElementFromJson({element:"path",curStyles:!0,attr:{d:U,id:Ue.getNextId(),opacity:Ue.getOpacity()/2}})),v.setAttribute("d",["M",d,h,d,h].join(" ")),_=ht?De.segs.length:0,We(_,d,h)}}},mouseMove:function(e,t){var n=Ue.getCurrentZoom();ft=!0;var r=Ue.getDrawnPath();if("path"!==Ue.getCurrentMode())if(De.dragging){var a=Ye({x:De.dragging[0],y:De.dragging[1]},De),i=Ye({x:e,y:t},De),o=i.x-a.x,s=i.y-a.y;De.dragging=[e,t],De.dragctrl?De.moveCtrl(o,s):De.movePts(o,s)}else De.selected_pts=[],De.eachSeg(function(e){if(this.next||this.prev){var t=Ue.getRubberBox().getBBox(),n=qe(this),r={x:n.x,y:n.y,width:0,height:0},a=Te(t,r);this.select(a),a&&De.selected_pts.push(this.index)}});else{if(!r)return;var l=r.pathSegList,c=l.numberOfItems-1;if(ut){var u=Qe("1c1"),d=Qe("0c2");u.setAttribute("cx",e),u.setAttribute("cy",t),u.setAttribute("display","inline");var h=ut[0],p=ut[1],f=h+(h-e/n),g=p+(p-t/n);d.setAttribute("cx",f*n),d.setAttribute("cy",g*n),d.setAttribute("display","inline");var m=Ke(1);if(en(m,{x1:e,y1:t,x2:f*n,y2:g*n,display:"inline"}),0===c)dt=[e,t];else{var v=l.getItem(c-1),_=v.x,y=v.y;6===v.pathSegType?(_+=_-v.x2,y+=y-v.y2):dt&&(_=dt[0]/n,y=dt[1]/n),$e(6,c,[h,p,_,y,f,g],r)}}else{var b=Jt("path_stretch_line");if(b){var x=l.getItem(c);if(6===x.pathSegType){var w=x.x+(x.x-x.x2),S=x.y+(x.y-x.y2);$e(6,1,[e,t,w*n,S*n,e,t],b)}else dt?$e(6,1,[e,t,dt[0],dt[1],e,t],b):$e(4,1,[e,t],b)}}}},mouseUp:function(e,t,n,r){var a=Ue.getDrawnPath();if("path"===Ue.getCurrentMode())return ut=null,a||(t=Jt(Ue.getId()),Ue.setStarted(!1),dt=null),{keep:!0,element:t};var i=Ue.getRubberBox();if(De.dragging){var o=De.cur_pt;De.dragging=!1,De.dragctrl=!1,De.update(),ft&&De.endChanges("Move path point(s)"),e.shiftKey||ft||De.selectPt(o)}else i&&"none"!==i.getAttribute("display")?(i.setAttribute("display","none"),i.getAttribute("width")<=2&&i.getAttribute("height")<=2&>.toSelectMode(e.target)):gt.toSelectMode(e.target);ft=!1},toEditMode:function(e){De=rt(e),Ue.setCurrentMode("pathedit"),Ue.clearSelection(),De.show(!0).update(),De.oldbbox=Dt(De.elem),ht=!1},toSelectMode:function(e){var t=e===De.elem;Ue.setCurrentMode("select"),De.show(!1),pt=!1,Ue.clearSelection(),De.matrix&&ot(),t&&(Ue.call("selected",[e]),Ue.addToSelection([e],!0))},addSubPath:function(e){e?(Ue.setCurrentMode("path"),ht=!0):(gt.clear(!0),gt.toEditMode(De.elem))},select:function(e){pt===e?(gt.toEditMode(e),Ue.setCurrentMode("pathedit")):pt=e},reorient:function(){var e=Ue.getSelectedElements()[0];if(e&&0!==Zt(e)){var t=new ge("Reorient path"),n={d:e.getAttribute("d"),transform:e.getAttribute("transform")};t.addSubCommand(new fe(e,n)),Ue.clearSelection(),this.resetOrientation(e),Ue.addCommandToHistory(t),rt(e).show(!1).matrix=null,this.clear(),Ue.addToSelection([e],!0),Ue.call("changed",Ue.getSelectedElements())}},clear:function(e){var t=Ue.getDrawnPath();if(pt=null,t){var n=Jt(Ue.getId());Le(Jt("path_stretch_line")).remove(),Le(n).remove(),Le(Jt("pathpointgrip_container")).find("*").attr("display","none"),dt=null,Ue.setDrawnPath(null),Ue.setStarted(!1)}else"pathedit"===Ue.getCurrentMode()&&this.toSelectMode();De&&De.init().show(!1)},resetOrientation:function(e){if(an(e)||"path"!==e.nodeName)return!1;var t=$(e),n=Pe(t).matrix;t.clear(),e.removeAttribute("transform");for(var r=e.pathSegList,a=r.numberOfItems,i=function(t){var a=r.getItem(t),i=a.pathSegType;if(1===i)return"continue";var o=[];Le.each(["",1,2],function(e,t){var r=a["x"+t],i=a["y"+t];if(void 0!==r&&void 0!==i){var s=ke(r,i,n);o.splice(o.length,0,s.x,s.y)}}),$e(i,t,o,e)},o=0;o0){var s=t.getItem(n-1).pathSegType;if(2===s){r(n-1,1),e();break}if(1===s&&t.numberOfItems-1===n){r(n,1),e();break}}}return!1}(),De.elem.pathSegList.numberOfItems<=1)return gt.toSelectMode(De.elem),void Ue.canvas.deleteSelectedElements();if(De.init(),De.clearSelection(),window.opera){var r=Le(De.elem);r.attr("d",r.attr("d"))}De.endChanges("Delete path node(s)")}},smoothPolylineIntoPath:function(e){var t,n=e.points,r=n.numberOfItems;if(r>=4){var a=n.getItem(0),i=null,o=[];for(o.push(["M",a.x,",",a.y," C"].join("")),t=1;t<=r-4;t+=3){var s=n.getItem(t),l=n.getItem(t+1),c=n.getItem(t+2);if(i){var u=et(i,s,a);if(u&&2===u.length){var d=o[o.length-1].split(",");d[2]=u[0].x,d[3]=u[0].y,o[o.length-1]=d.join(","),s=u[1]}}o.push([s.x,s.y,l.x,l.y,c.x,c.y].join(",")),a=c,i=l}for(o.push("L");t)/,"$1$2")},kt=function(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")};function Ct(e){if(e=Gt(e),window.btoa)return window.btoa(e);var t=new Array(4*Math.floor((e.length+2)/3)),n=0,r=0;do{var a=e.charCodeAt(n++),i=e.charCodeAt(n++),o=e.charCodeAt(n++),s=a>>2,l=(3&a)<<4|i>>4,c=(15&i)<<2|o>>6,u=63&o;isNaN(i)?(c=64,u=64):isNaN(o)&&(u=64),t[r++]=vt.charAt(s),t[r++]=vt.charAt(l),t[r++]=vt.charAt(c),t[r++]=vt.charAt(u)}while(n>4,l=(15&a)<<4|i>>2,c=(3&i)<<6|o;t+=String.fromCharCode(s),64!==i&&(t+=String.fromCharCode(l)),64!==o&&(t+=String.fromCharCode(c))}while(nSVG-edit "],{type:"text/html"});return It(e)}(),Tt=function(e){var t,n;e.includes("0?t=t[0]:(t=e.ownerDocument.createElementNS(f.SVG,"defs"),e.firstChild?e.insertBefore(t,e.firstChild.nextSibling):e.append(t)),t},Rt=function(e){for(var t=e.pathSegList,n=t.numberOfItems,r=[[],[]],a=t.getItem(0),i=[a.x,a.y],o=function(e,t,n,r){return function(a){return 1-Math.pow(a,3)*i[e]+3-Math.pow(a,2)*a*t[e]+3*(1-a)*Math.pow(a,2)*n[e]+Math.pow(a,3)*r[e]}},s=0;s0&&_<1&&r[h].push(p(_));var y=(-f-Math.sqrt(v))/(2*g);y>0&&y<1&&r[h].push(p(y))}}else{if(0===f)continue;var b=-m/f;b>0&&b<1&&r[h].push(p(b))}}i=d}else r[0].push(l.x),r[1].push(l.y)}var x=Math.min.apply(null,r[0]),w=Math.max.apply(null,r[0])-x,S=Math.min.apply(null,r[1]);return{x:x,y:S,width:w,height:Math.max.apply(null,r[1])-S}};function Bt(e){if(H())try{return e.getBBox()}catch(e){}var t,n,r=mt.data(e,"ref"),a=null;r?(n=mt(r).children().clone().attr("visibility","hidden"),mt(wt).append(n),a=n.filter("line, path")):a=mt(e).find("line, path");var i=!1;if(a.length)if(a.each(function(){var e=this.getBBox();e.width&&e.height||(i=!0)}),i){var o=r?n:mt(e).children();t=Wt(o)}else t=e.getBBox();else t=e.getBBox();return r&&n.remove(),t}var Dt=function(e){var t=e||yt.geSelectedElements()[0];if(1!==e.nodeType)return null;var n,r=t.nodeName,a=null;switch(r){case"text":""===t.textContent?(t.textContent="a",a=t.getBBox(),t.textContent=""):t.getBBox&&(a=t.getBBox());break;case"path":T?t.getBBox&&(a=t.getBBox()):a=Rt(t);break;case"g":case"a":a=Bt(t);break;default:if("use"===r&&(a=Bt(t)),"use"===r||"foreignObject"===r&&V()){if(a||(a=t.getBBox()),!V()){var i={};i.width=a.width,i.height=a.height,i.x=a.x+parseFloat(t.getAttribute("x")||0),i.y=a.y+parseFloat(t.getAttribute("y")||0),a=i}}else if(_t.includes(r))if(t)try{a=t.getBBox()}catch(e){var o=t.getExtentOfChar(0),s=t.getComputedTextLength();a={x:o.x,y:o.y,width:s,height:o.height}}else{var l=mt(t).closest("foreignObject");l.length&&l[0].getBBox&&(a=l[0].getBBox())}}return a&&(a={x:(n=a).x,y:n.y,width:n.width,height:n.height}),a},Ut=function(e){var t="";return mt.each(e,function(e,n){var r=d(n,2),a=r[0],i=r[1];t+=a;for(var o=0;o-.001&&n<.001||n<-89.99||n>89.99)}(i,o)){if(["ellipse","path","line","polyline","polygon"].includes(e.tagName))r=s=zt(e,t,n);else if("rect"===e.tagName){var l=e.getAttribute("rx"),c=e.getAttribute("ry");(l||c)&&(r=s=zt(e,t,n))}}if(!s){var u=Pe(a).matrix;r=Ge(r.x,r.y,r.width,r.height,u).aabox}}return r};function Yt(e){var t=e.getAttribute("stroke-width");return isNaN(t)||"none"===e.getAttribute("stroke")?0:t/2}var Wt=function(e,t,n){if(!e||!e.length)return!1;var r;if(mt.each(e,function(){r||this.parentNode&&(r=qt(this,t,n))}),void 0===r)return null;var a=r.x+r.width,i=r.y+r.height,o=r.x,s=r.y;if(1===e.length){var l=Yt(e[0]);o-=l,s-=l,a+=l,i+=l}else mt.each(e,function(e,r){var l=qt(r,t,n);if(l){var c=Yt(r);o=Math.min(o,l.x-c),s=Math.min(s,l.y-c),1===r.nodeType&&(a=Math.max(a,l.x+l.width+c),i=Math.max(i,l.y+l.height+c))}});return r.x=o,r.y=s,r.width=a-o,r.height=i-s,r},Xt=function(e){e||(e=mt(yt.getSVGContent()).children());var t=[];return mt(e).children().each(function(e,n){n.getBBox&&t.push(n)}),t.reverse()},Qt=function(e){return e||(e=Xt()),Wt(e,yt.addSVGElementFromJson,yt.pathActions)},Kt=function(e,t){if(!e)return 0;for(var n=e.numberOfItems,r=0;r");var t=e.shortcut||"";on("#cmenu_canvas").append("
  • "+e.label+""+t+"
  • ")}(e)})};function cn(e,t){["id","class","type"].forEach(function(n){n in t&&(e[n]=t[n])})}function un(e,t){return dn(e,o({},t,{returnDefault:!0}))}function dn(e,t){return hn.apply(this,arguments)}function hn(){return(hn=n(regeneratorRuntime.mark(function e(t,n){var r,a;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.global,a=n.returnDefault,!!("svgEditor"in window&&window.svgEditor&&!1===window.svgEditor.modules)){e.next=4;break}return e.abrupt("return",fn(t,void 0,{returnDefault:a}));case 4:return e.next=6,pn(t);case 6:return e.abrupt("return",window[r]);case 7:case"end":return e.stop()}},e)}))).apply(this,arguments)}function pn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Array.isArray(e)?Promise.all(e.map(function(e){return pn(e,t)})):new Promise(function(n,r){var a=document.createElement("script");function i(){r(new Error("Failed to import: ".concat(e))),s()}function o(){n(),s()}var s=function(){a.removeEventListener("error",i),a.removeEventListener("load",o),a.remove(),a.src=""};a.defer="defer",cn(a,t),a.addEventListener("error",i),a.addEventListener("load",o),a.src=e,document.head.append(a)})}function fn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).returnDefault,r=void 0!==n&&n;return Array.isArray(e)?Promise.all(e.map(function(e){return fn(e,t)})):new Promise(function(n,a){var i="$importModule$"+Math.random().toString(32).slice(2),o=document.createElement("script");function s(){a(new Error("Failed to import: ".concat(e))),c()}function l(){n(window[i]),c()}var c=function(){delete window[i],o.removeEventListener("error",s),o.removeEventListener("load",l),o.remove(),URL.revokeObjectURL(o.src),o.src=""};cn(o,t),o.defer="defer",o.type="module",o.addEventListener("error",s),o.addEventListener("load",l);var u=function(e){var t=document.createElement("a");return t.setAttribute("href",e),t.cloneNode(!1).href}(e),d="import * as m from '".concat(u.replace(/'/g,"\\'"),"'; window.").concat(i," = ").concat(r?"m.default || ":"","m;"),h=new Blob([d],{type:"text/javascript"});o.src=URL.createObjectURL(h),document.head.append(o)})}function gn(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ok:"Ok",cancel:"Cancel"};t("#dialog_container").draggable({cancel:"#dialog_content, #dialog_buttons *",containment:"window"}).css("position","absolute");var r=t("#dialog_box"),a=t("#dialog_buttons"),i=t("#dialog_content");function o(o,s,l,c,u,d){i.html("

    "+s.replace(/\n/g,"

    ")+"

    ").toggleClass("prompt","prompt"===o),a.empty();var h=t('').appendTo(a);return new Promise(function(p,f){var g,m;if("alert"!==o&&t('').appendTo(a).click(function(){r.hide(),p(!1)}),"prompt"===o)(g=t('').prependTo(a)).val(l||""),g.bind("keydown","return",function(){h.click()});else if("select"===o){var v=t('
    ');if(g=t('').appendTo(_)).val(d.value),d.tooltip&&_.attr("title",d.tooltip),m.prop("checked",Boolean(d.checked)),v.append(t("
    ").append(_))}t.each(c||[],function(n,r){"object"===e(r)?g.append(t("