From 2e5c7557a98ae4378f9fc6922262748bcc2815dc Mon Sep 17 00:00:00 2001 From: Brett Zamir Date: Thu, 8 Nov 2018 14:48:01 +0800 Subject: [PATCH] - Breaking change: `loadSvgString` now returns a `Promise` rather than accepting a callback - Breaking change: Treat callbacks to `editor.ready` as Promises, only resolving after all resolve - Breaking change: Make `editor.runCallbacks` return a `Promise` which resolves upon all callbacks resolving - Breaking change: Require `npx` (used with `babel-node`) to allow Node files for HTML building and JSDoc type checking to be expressed as ESM. - Breaking change: `addExtension` now throws upon a repeated attempt to add an already-added extension - Breaking change (storage preference cookies): Namespace the cookie as "svgeditstore" instead of just "store" - Breaking change (API): Remove `svgCanvas.rasterExport` fourth (callback) argument, collapsing fifth (options) to fourth - Breaking change (API): Remove `svgCanvas.exportPDF` third (callback) argument - Breaking change (API): `editor/contextmenu.js` `add` now throws instead of giving a console error only upon detecting a bad menuitem or preexisting context menu - Breaking change (API): Remove `svgCanvas.embedImage` second (callback) argument - Breaking change (API): Make `getHelpXML` a class instead of instance method of `RGBColor` - Breaking change (internal API): Refactor `dbox` (and `alert`/`confirm`/`process`/`prompt`/`select`) to avoid a callback argument in favor of return a Promise - Fix: Avoid running in extension `langReady` multiple times or serially - Enhancement (API): Add svgCanvas.runExtension to run just one extension and add `nameFilter` callback to `runExtensions` - Enhancement (API): Supply `$` (our wrapped jQuery) to extensions so can use its plugins, e.g., dbox with its `alert` - Enhancement: Use alert dialog in place of `alert` in webappfind - Enhancement: `editor.ready` now returns a Promise resolving when all callbacks have resolved - Enhancement: Allow `noAlert` option as part of second argument to `loadSvgString` (and `loadFromURL` and `loadFromDataURI`) to avoid UI alert (and trigger promise rejection) - Enhancement: Make `dbox` as a separate module for alert, prompt, etc. dialogs - Refactoring: Internal `PaintBox` as class; other misc. tweaks; no bitwise in canvg - Linting (ESLint): Further linting changes (for editor); rename `.eslintrc` -> `.eslintrc.json` per recommendation - Optimization: Recompress images (imageoptim-cli updated) - npm: Update devDeps - npm: Bump to 4.0.0 --- .eslintrc | 368 - .eslintrc.js | 154 + CHANGES.md | 61 +- README.md | 1 + build-html.js | 21 +- dist/canvg.js | 656 +- dist/dom-polyfill.js | 17 + dist/extensions/ext-arrows.js | 59 +- dist/extensions/ext-closepath.js | 9 +- dist/extensions/ext-connector.js | 106 +- dist/extensions/ext-eyedropper.js | 13 +- dist/extensions/ext-foreignobject.js | 194 +- dist/extensions/ext-grid.js | 15 +- dist/extensions/ext-helloworld.js | 11 +- dist/extensions/ext-imagelib.js | 486 +- dist/extensions/ext-markers.js | 169 +- dist/extensions/ext-mathjax.js | 179 +- dist/extensions/ext-overview_window.js | 10 +- dist/extensions/ext-panning.js | 4 + dist/extensions/ext-php_savefile.js | 9 +- dist/extensions/ext-polygon.js | 152 +- dist/extensions/ext-server_moinsave.js | 654 +- dist/extensions/ext-server_opensave.js | 816 +- dist/extensions/ext-shapes.js | 83 +- dist/extensions/ext-star.js | 21 +- dist/extensions/ext-storage.js | 343 +- dist/extensions/ext-webappfind.js | 7 +- dist/extensions/ext-xdomain-messaging.js | 5 +- dist/extensions/imagelib/index.js | 4 +- dist/extensions/imagelib/openclipart.js | 54 +- dist/index-es.js | 7557 +++++++++++------ dist/index-es.min.js | 2 +- dist/index-es.min.js.map | 2 +- dist/index-umd.js | 7557 +++++++++++------ dist/index-umd.min.js | 2 +- dist/index-umd.min.js.map | 2 +- dist/jspdf.plugin.svgToPdf.js | 299 +- dist/locale/lang.af.js | 2 +- dist/locale/lang.ar.js | 2 +- dist/locale/lang.az.js | 2 +- dist/locale/lang.be.js | 2 +- dist/locale/lang.bg.js | 2 +- dist/locale/lang.ca.js | 2 +- dist/locale/lang.cs.js | 2 +- dist/locale/lang.cy.js | 2 +- dist/locale/lang.da.js | 2 +- dist/locale/lang.de.js | 2 +- dist/locale/lang.el.js | 2 +- dist/locale/lang.en.js | 2 +- dist/locale/lang.es.js | 2 +- dist/locale/lang.et.js | 2 +- dist/locale/lang.fa.js | 2 +- dist/locale/lang.fi.js | 2 +- dist/locale/lang.fr.js | 2 +- dist/locale/lang.fy.js | 2 +- dist/locale/lang.ga.js | 2 +- dist/locale/lang.gl.js | 2 +- dist/locale/lang.he.js | 2 +- dist/locale/lang.hi.js | 2 +- dist/locale/lang.hr.js | 2 +- dist/locale/lang.hu.js | 2 +- dist/locale/lang.hy.js | 2 +- dist/locale/lang.id.js | 2 +- dist/locale/lang.is.js | 2 +- dist/locale/lang.it.js | 2 +- dist/locale/lang.ja.js | 2 +- dist/locale/lang.ko.js | 2 +- dist/locale/lang.lt.js | 2 +- dist/locale/lang.lv.js | 2 +- dist/locale/lang.mk.js | 2 +- dist/locale/lang.ms.js | 2 +- dist/locale/lang.mt.js | 2 +- dist/locale/lang.nl.js | 2 +- dist/locale/lang.no.js | 2 +- dist/locale/lang.pl.js | 2 +- dist/locale/lang.pt-BR.js | 2 +- dist/locale/lang.pt-PT.js | 2 +- dist/locale/lang.ro.js | 2 +- dist/locale/lang.ru.js | 2 +- dist/locale/lang.sk.js | 2 +- dist/locale/lang.sl.js | 2 +- dist/locale/lang.sq.js | 2 +- dist/locale/lang.sr.js | 2 +- dist/locale/lang.sv.js | 2 +- dist/locale/lang.sw.js | 2 +- dist/locale/lang.test.js | 2 +- dist/locale/lang.th.js | 2 +- dist/locale/lang.tl.js | 2 +- dist/locale/lang.tr.js | 2 +- dist/locale/lang.uk.js | 2 +- dist/locale/lang.vi.js | 2 +- dist/locale/lang.yi.js | 2 +- dist/locale/lang.zh-CN.js | 2 +- dist/locale/lang.zh-HK.js | 2 +- dist/locale/lang.zh-TW.js | 2 +- dist/redirect-on-lacking-support.js | 73 +- docs/jsdoc-config.js | 2 +- docs/versions/4.0.0.md | 51 + editor/canvg/canvg.js | 171 +- editor/canvg/rgbcolor.js | 90 +- editor/contextmenu.js | 9 +- editor/contextmenu/jQuery.contextMenu.js | 158 +- editor/dbox.js | 165 + editor/embedapi-dom.js | 29 +- editor/embedapi.js | 4 +- editor/extensions/ext-arrows.js | 57 +- editor/extensions/ext-closepath.js | 4 +- editor/extensions/ext-connector.js | 57 +- editor/extensions/ext-eyedropper.js | 9 +- editor/extensions/ext-foreignobject.js | 112 +- editor/extensions/ext-grid.js | 13 +- editor/extensions/ext-helloworld.js | 5 +- editor/extensions/ext-imagelib.js | 60 +- editor/extensions/ext-markers.js | 100 +- editor/extensions/ext-mathjax.js | 37 +- editor/extensions/ext-overview_window.js | 6 +- editor/extensions/ext-panning.js | 2 + editor/extensions/ext-php_savefile.js | 8 +- editor/extensions/ext-polygon.js | 156 +- editor/extensions/ext-server_moinsave.js | 6 +- editor/extensions/ext-server_opensave.js | 65 +- editor/extensions/ext-shapes.js | 102 +- editor/extensions/ext-star.js | 21 +- editor/extensions/ext-storage.js | 186 +- editor/extensions/ext-webappfind.js | 4 +- editor/extensions/ext-xdomain-messaging.js | 4 +- editor/extensions/imagelib/index.js | 3 +- editor/extensions/imagelib/openclipart.js | 29 +- editor/external/dom-polyfill/dom-polyfill.js | 15 + .../dynamic-import-polyfill/importModule.js | 8 +- editor/history.js | 52 +- editor/images/angle.png | Bin 557 -> 487 bytes editor/images/bold.png | Bin 219 -> 195 bytes editor/images/c_radius.png | Bin 364 -> 308 bytes editor/images/fill.png | Bin 891 -> 644 bytes editor/images/fontsize.png | Bin 534 -> 474 bytes editor/images/italic.png | Bin 192 -> 157 bytes editor/images/select.png | Bin 566 -> 392 bytes editor/images/sep.png | Bin 74 -> 71 bytes editor/images/wireframe.png | Bin 308 -> 268 bytes editor/jgraduate/images/map-opacity.png | Bin 85 -> 81 bytes editor/jgraduate/images/mappoint_c.png | Bin 150 -> 143 bytes editor/jgraduate/images/mappoint_f.png | Bin 155 -> 147 bytes editor/jgraduate/jQuery.jGraduate.js | 151 +- editor/jgraduate/jQuery.jPicker.js | 875 +- editor/jspdf/jspdf.plugin.svgToPdf.js | 27 +- editor/locale/locale.js | 11 +- editor/spinbtn/jQuery.SpinButton.js | 22 +- editor/svg-editor.js | 1362 +-- editor/svgcanvas.js | 458 +- editor/utilities.js | 4 +- editor/xdomain-svgedit-config-iife.js | 7557 +++++++++++------ jsdoc-check-overly-generic-types.js | 4 +- package-lock.json | 977 ++- package.json | 31 +- svgedit-config-iife.js | 7557 +++++++++++------ test/contextmenu_test.js | 25 +- test/history_test.js | 2 +- test/qunit/qunit-assert-close.js | 6 +- 159 files changed, 25502 insertions(+), 15658 deletions(-) delete mode 100644 .eslintrc create mode 100644 .eslintrc.js create mode 100644 docs/versions/4.0.0.md create mode 100644 editor/dbox.js diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index fd6d4a88..00000000 --- a/.eslintrc +++ /dev/null @@ -1,368 +0,0 @@ -{ - "extends": [ - "standard", "plugin:compat/recommended", - "plugin:qunit/recommended", "plugin:testcafe/recommended" - ], - "parserOptions": { - "sourceType": "module" - }, - "plugins": ["compat", "qunit", "testcafe", "jsdoc", "markdown", "import", "node", "promise"], - "env": { - "node": false, - "browser": true - }, - "settings": { - "polyfills": ["url", "promises", "fetch", "queryselector"], - "jsdoc": { - "additionalTagNames": { - "customTags": [] - }, - "tagNamePreference": { - "arg": "param", - "return": "returns" - }, - "allowOverrideWithoutParam": true, - "allowImplementsWithoutParam": true, - "allowAugmentsExtendsWithoutParam": true - } - }, - "overrides": [ - { - "files": ["editor/locale/lang.*.js"], - "rules": { - "import/no-anonymous-default-export": ["off"] - } - }, - { - "files": ["editor/extensions/ext-locale/**"], - "rules": { - "import/no-anonymous-default-export": ["off"] - } - }, - { - "files": ["editor/extensions/**/ext-*.js"], - "rules": { - "consistent-this": ["error", "svgEditor"], - "import/no-anonymous-default-export": ["off"] - } - }, - { - "files": [ - "editor/svgpathseg.js", "editor/touch.js", "editor/typedefs.js", - "editor/redirect-on-no-module-support.js", - "test/all_tests.js", "screencasts/svgopen2010/script.js", - "opera-widget/handlers.js", - "firefox-extension/handlers.js", - "firefox-extension/content/svg-edit-overlay.js" - ], - "rules": { - "import/unambiguous": ["off"] - } - }, - { - "files": ["**/*.md"], - "rules": { - "no-undef": ["off"], - "no-unused-vars": ["warn"], - "padded-blocks": ["off"], - "import/unambiguous": ["off"] - } - }, - { - "files": ["test/**"], - "rules": { - "no-console": ["off"] - } - }, - { - "files": [ - "docs/jsdoc-config.js", "build-html.js", "jsdoc-check-overly-generic-types.js", - "rollup.config.js", "rollup-config.config.js" - ], - "rules": { - "node/no-extraneous-import": ["error"], - "node/no-extraneous-require": ["error"], - "node/no-missing-import": ["error"], - "node/no-missing-require": ["error"], - "node/no-unpublished-bin": ["error"], - "node/no-unpublished-import": ["error"], - "node/no-unpublished-require": ["error"], - "node/no-unsupported-features/es-builtins": ["error"], - "node/no-unsupported-features/es-syntax": ["error"], - "node/no-unsupported-features/node-builtins": ["error"], - "node/process-exit-as-throw": ["error"], - "node/shebang": ["error"], - - "node/exports-style": ["error", "module.exports"], - "node/prefer-global/buffer": ["error", "always"], - "node/prefer-global/console": ["error", "always"], - "node/prefer-global/process": ["error", "always"], - "node/prefer-global/text-decoder": ["error", "always"], - "node/prefer-global/text-encoder": ["error", "always"], - "node/prefer-global/url-search-params": ["error", "always"], - "node/prefer-global/url": ["error", "always"] - } - }, - { - "files": ["rollup.config.js", "rollup-config.config.js"], - "rules": { - "node/no-unsupported-features/es-syntax": "off", - "node/no-unpublished-import": "off" - } - }, - { - "files": ["jsdoc-check-overly-generic-types.js", "build-html.js"], - "rules": { - "import/unambiguous": "off", - "import/no-commonjs": "off" - } - } - ], - "rules": { - "array-bracket-newline": ["error", "consistent"], - "array-bracket-spacing": ["error"], - "array-callback-return": ["error"], - "array-element-newline": ["off"], - "arrow-body-style": ["off"], - "arrow-parens": ["error"], - "block-scoped-var": ["error"], - "callback-return": ["error"], - "class-methods-use-this": ["warn"], - "computed-property-spacing": ["error"], - "consistent-return": ["error"], - "consistent-this": ["warn"], - "dot-notation": ["error"], - "for-direction": ["error"], - "func-name-matching": ["error"], - "func-names": ["off"], - "func-style": ["off"], - "function-paren-newline": ["error", "consistent"], - "getter-return": ["error"], - "global-require": ["error"], - "guard-for-in": ["error"], - "id-blacklist": ["off"], - "id-length": ["off"], - "id-match": ["off"], - "implicit-arrow-linebreak": ["error"], - "init-declarations": ["off"], - "jsx-quotes": ["error"], - "line-comment-position": ["off"], - "linebreak-style": ["error"], - "lines-around-comment": ["off"], - "lines-between-class-members": ["off"], - "max-classes-per-file": ["off"], - "max-depth": ["off"], - "max-lines-per-function": ["off"], - "max-lines": ["off"], - "max-nested-callbacks": ["error"], - "max-params": ["off"], - "max-statements-per-line": ["off"], - "max-statements": ["off"], - "multiline-comment-style": ["off"], - "multiline-ternary": ["error", "always-multiline"], - "newline-after-var": ["off"], - "newline-before-return": ["off"], - "newline-per-chained-call": ["off"], - "no-alert": ["warn"], - "no-async-promise-executor": ["error"], - "no-await-in-loop": ["error"], - "no-bitwise": ["error"], - "no-buffer-constructor": ["error"], - "no-case-declarations": ["error"], - "no-confusing-arrow": ["error"], - "no-console": ["warn"], - "no-continue": ["off"], - "no-div-regex": ["error"], - "no-duplicate-imports": ["error"], - "no-else-return": ["error"], - "no-empty-function": ["warn"], - "no-empty": ["error", {"allowEmptyCatch": true}], - "no-eq-null": ["error"], - "no-extra-label": ["error"], - "no-extra-semi": ["error"], - "no-implicit-coercion": ["error"], - "no-implicit-globals": ["error"], - "no-inline-comments": ["off"], - "no-invalid-this": ["off"], - "no-lonely-if": ["error"], - "no-loop-func": ["error"], - "no-misleading-character-class": ["error"], - "no-mixed-requires": ["error", {"grouping": true, "allowCall": true}], - "no-multi-assign": ["off"], - "no-negated-condition": ["off"], - "no-nested-ternary": ["off"], - "no-param-reassign": ["off"], - "no-plusplus": ["off"], - "no-process-env": ["error"], - "no-process-exit": ["error"], - "no-prototype-builtins": ["error"], - "no-restricted-globals": ["error", { - "name": "event", - "message": "Use local event parameter instead (preferably as \"e\" or \"ev\")." - }, { - "name": "fdescribe", - "message": "Do not commit fdescribe. Use describe instead." - }], - "no-restricted-imports": ["off"], - "no-restricted-modules": ["off"], - "no-restricted-properties": ["error", { - "property": "__defineGetter__", - "message": "Please use `Object.defineProperty` instead." - }], - "no-restricted-syntax": ["off"], - "no-script-url": ["error"], - "no-shadow": ["error", {"builtinGlobals": true, "hoist": "functions", "allow": ["parent", "top", "open", "name", "closed", "start"]}], - "no-spaced-func": ["error"], - "no-sync": ["error"], - "no-ternary": ["off"], - "no-undefined": ["off"], - "no-underscore-dangle": ["off"], - "no-unused-labels": ["error"], - "no-useless-concat": ["off"], - "no-var": ["error"], - "no-void": ["error"], - "nonblock-statement-body-position": ["error"], - "object-curly-newline": ["off"], - "object-shorthand": ["error", "always", {"avoidExplicitReturnArrows": true}], - "one-var-declaration-per-line": ["off"], - "operator-assignment": ["error"], - "padding-line-between-statements": ["off"], - "prefer-arrow-callback": ["off"], - "prefer-const": ["error"], - "prefer-destructuring": ["error", {"object": true}], - "prefer-numeric-literals": ["warn"], - "prefer-object-spread": ["error"], - "prefer-rest-params": ["error"], - "prefer-spread": ["error"], - "prefer-template": ["off"], - "quote-props": ["error", "as-needed"], - "radix": ["error", "as-needed"], - "require-atomic-updates": ["error"], - "require-await": ["error"], - "require-jsdoc": ["warn"], - "require-yield": ["error"], - "semi-style": ["error"], - "sort-imports": ["off"], - "sort-keys": ["off"], - "sort-vars": ["off"], - "strict": ["error"], - "switch-colon-spacing": ["error"], - "vars-on-top": ["warn"], - "wrap-regex": ["error"], - - "semi": ["error", "always"], - "indent": ["error", 2, {"outerIIFEBody": 0}], - "object-property-newline": ["off"], - "one-var": ["off"], - "object-curly-spacing": ["error", "never"], - - "promise/catch-or-return": "error", - "promise/no-return-wrap": "error", - "promise/param-names": "error", - "promise/always-return": "error", - "promise/no-native": "off", - "promise/no-nesting": "warn", - "promise/no-promise-in-callback": "warn", - "promise/no-callback-in-promise": "warn", - "promise/avoid-new": "warn", - "promise/no-new-statics": "error", - "promise/no-return-in-finally": "warn", - "promise/valid-params": "warn", - "promise/prefer-await-to-then": "error", - "promise/prefer-await-to-callbacks": "warn", - - "import/no-unresolved": "error", - "import/named": "error", - "import/default": "error", - "import/namespace": "error", - "import/no-restricted-paths": "off", - "import/no-absolute-path": "error", - "import/no-dynamic-require": "error", - "import/no-internal-modules": "off", - "import/no-webpack-loader-syntax": "error", - "import/no-self-import": "error", - "import/no-cycle": "off", - "import/no-useless-path-segments": "error", - "import/no-relative-parent-imports": "off", - "import/export": "error", - "import/no-named-as-default": "error", - "import/no-named-as-default-member": "error", - "import/no-deprecated": "error", - "import/no-extraneous-dependencies": "error", - "import/no-mutable-exports": "error", - "import/unambiguous": "warn", - "import/no-commonjs": "error", - "import/no-amd": "error", - "import/no-nodejs-modules": "off", - "import/first": "error", - "import/exports-last": "off", - "import/no-duplicates": "error", - "import/no-namespace": "off", - "import/extensions": ["error", "always", {"ignorePackages": true}], - "import/order": ["error", {"groups": [ - "builtin", - "external", - "internal", - ["parent", "sibling", "index"] - ]}], - "import/newline-after-import": "error", - "import/prefer-default-export": "off", - "import/max-dependencies": "off", - "import/no-unassigned-import": "off", - "import/no-named-default": "error", - "import/no-default-export": "off", - "import/no-named-export": "off", - "import/no-anonymous-default-export": "error", - "import/group-exports": "off", - "import/dynamic-import-chunkname": "off", - - "jsdoc/check-param-names": 1, - "jsdoc/check-tag-names": 1, - "jsdoc/check-types": 1, - "jsdoc/newline-after-description": 0, - "jsdoc/require-description": 0, - "jsdoc/require-description-complete-sentence": 0, - "jsdoc/require-example": 0, - "jsdoc/require-hyphen-before-param-description": 0, - "jsdoc/require-param-description": 0, - "jsdoc/require-param": 1, - "jsdoc/require-param-name": 1, - "jsdoc/require-param-type": 1, - "jsdoc/require-returns-description": 0, - "jsdoc/require-returns-type": 1, - - "jsdoc/no-undefined-types": ["off"], - "jsdoc/valid-types": ["error"], - "valid-jsdoc": ["error", { - "prefer": { - "arg": "param", - "argument": "param", - "return": "returns", - "virtual": "abstract" - }, - "preferType": { - "Boolean": "boolean", - "Number": "number", - "String": "string", - "object": "Object", - "array": "Array" - }, - "requireReturn": true, - "requireReturnType": true, - "requireParamType": true, - "matchDescription": "^([A-Z][\\s\\S]*[.`?!])?$", - "requireParamDescription": false, - "requireReturnDescription": false - }], - "no-warning-comments": ["off"], - "default-case": ["off"], - "complexity": ["off"], - "require-unicode-regexp": ["off"], - "capitalized-comments": ["off"], - "no-magic-numbers": ["off"], - "max-len": ["off", { - "ignoreUrls": true, - "ignoreRegExpLiterals": true - }] - } -} diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 00000000..e5e73a9e --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,154 @@ +module.exports = { + "extends": [ + "ash-nazg/sauron-node", + "plugin:qunit/recommended", "plugin:testcafe/recommended" + ], + "parserOptions": { + "sourceType": "module" + }, + // Need to make explicit here for processing by jsdoc/check-examples + "plugins": ["qunit"], + "env": { + "browser": true + }, + "settings": { + "polyfills": ["url", "promises", "fetch", "queryselector"], + "jsdoc": { + "additionalTagNames": { + // In case we need to extend + "customTags": [] + }, + "tagNamePreference": { + "arg": "param", + "return": "returns" + }, + "allowOverrideWithoutParam": true, + "allowImplementsWithoutParam": true, + "allowAugmentsExtendsWithoutParam": true, + // For `jsdoc/check-examples` in `ash-nazg` + "matchingFileName": "dummy.md", + "rejectExampleCodeRegex": "^`", + } + }, + "overrides": [ + // These would otherwise currently break because of these issues: + // 1. `event:` https://github.com/eslint/doctrine/issues/221 and https://github.com/Kuniwak/jsdoctypeparser/pull/49 with https://github.com/Kuniwak/jsdoctypeparser/issues/47 + // 1. `@implements`/`@augments`/`@extends`/`@override`: https://github.com/eslint/doctrine/issues/222 + { + "files": [ + "test/utilities_test.js", "editor/svg-editor.js", "editor/svgcanvas.js", + "editor/coords.js", + "editor/extensions/ext-eyedropper.js", "editor/extensions/ext-webappfind.js" + ], + "rules": { + "jsdoc/valid-types": "off", + "valid-jsdoc": "off" + } + }, + // Locales have no need for importing outside of SVG-Edit + { + "files": [ + "editor/locale/lang.*.js", "editor/extensions/ext-locale/**", + "docs/tutorials/ExtensionDocs.md" + ], + "rules": { + "import/no-anonymous-default-export": ["off"] + } + }, + // For extensions, `this` is generally assigned to be the more + // descriptive `svgEditor`; they also have no need for importing outside + // of SVG-Edit + { + "files": ["editor/extensions/**/ext-*.js"], + "rules": { + "consistent-this": ["error", "svgEditor"], + "import/no-anonymous-default-export": ["off"] + } + }, + // These browser files don't do importing or requiring + { + "files": [ + "editor/svgpathseg.js", "editor/touch.js", "editor/typedefs.js", + "editor/redirect-on-no-module-support.js", + "editor/extensions/imagelib/index.js", + "editor/external/dom-polyfill/dom-polyfill.js", + "test/all_tests.js", "screencasts/svgopen2010/script.js", + "opera-widget/handlers.js", + "firefox-extension/handlers.js", + "firefox-extension/content/svg-edit-overlay.js" + ], + "rules": { + "import/unambiguous": ["off"] + } + }, + // Our Markdown rules (and used for JSDoc examples as well, by way of + // our use of `matchingFileName` in conjunction with + // `jsdoc/check-examples` within `ash-nazg`) + { + "files": ["**/*.md"], + "rules": { + "eol-last": ["off"], + "no-console": ["off"], + "no-undef": ["off"], + "no-unused-vars": ["warn"], + "padded-blocks": ["off"], + "import/unambiguous": ["off"], + "import/no-unresolved": ["off"], + "node/no-missing-import": ["off"] + } + }, + // Dis-apply Node rules mistakenly giving errors with browser files + { + "files": ["editor/**", "test/**"], + "rules": { + "node/no-unsupported-features/node-builtins": ["off"] + } + }, + // We want console in tests! + { + "files": ["test/**"], + "rules": { + "no-console": ["off"] + } + }, + { + // Node files + "files": [ + "docs/jsdoc-config.js", + "build-html.js", "jsdoc-check-overly-generic-types.js", + "rollup.config.js", "rollup-config.config.js" + ], + "env": { + "node": true, + }, + "rules": { + "node/no-unpublished-import": ["off"], + "node/no-unsupported-features/es-syntax": ["off"] + } + }, + { + // As consumed by jsdoc, cannot be expressed as ESM + "files": ["docs/jsdoc-config.js"], + "parserOptions": { + "sourceType": "script" + }, + "rules": { + "import/no-commonjs": "off" + } + } + ], + "rules": { + // Override these `ash-nazg/sauron` rules which are difficult for us + // to apply at this time + "capitalized-comments": ["off"], + "complexity": ["off"], + "default-case": ["off"], + "require-unicode-regexp": ["off"], + "no-magic-numbers": ["off"], + "no-warning-comments": ["off"], + "max-len": ["off", { + "ignoreUrls": true, + "ignoreRegExpLiterals": true + }] + } +}; diff --git a/CHANGES.md b/CHANGES.md index 29bc81f8..ef4100e2 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,62 @@ # SVG-Edit CHANGES +# 4.0.0 + +- Breaking change (storage preference cookies): Namespace the cookie as + "svgeditstore" instead of just "store" +- Breaking change: `loadSvgString` now returns a `Promise` rather than + accepting a callback. +- Breaking change: Treat callbacks to `editor.ready` as Promises, only + resolving after all resolve. May require no changes unless for timing. +- Breaking change: Make `editor.runCallbacks` return a `Promise` which + resolves upon all callbacks resolving. +- Breaking change: Require `npx` (used with `babel-node`) to allow Node files + for HTML building and JSDoc type checking to be expressed as ESM. +- Breaking change: `addExtension` now throws upon a repeated attempt to + add an already-added extension +- Breaking change (API): Remove `svgCanvas.rasterExport` fourth (callback) + argument, collapsing fifth (options) to fourth +- Breaking change (API): Remove `svgCanvas.exportPDF` third (callback) + argument +- Breaking change (API): `editor/contextmenu.js` `add` now throws instead + of giving a console error only upon detecting a bad menuitem or + preexisting context menu +- Breaking change (API): Remove `svgCanvas.embedImage` second (callback) + argument +- Breaking change (API): Make `getHelpXML` a class instead of instance method + of `RGBColor` +- Breaking change (internal API): Refactor `dbox` (and + `alert`/`confirm`/`process`/`prompt`/`select`) to avoid a callback argument + in favor of returning a Promise +- Breaking internal API change: `updateGripCursor` moved to be class method + of Selector rather than instance method +- Breaking internal API change: `subpathIsClosed` moved to be class method + of `Path` rather than instance method +- Fix: Avoid running in extension `langReady` multiple times or serially +- Enhancement (API): Add `svgCanvas.runExtension` to run just one extension and + add `nameFilter` callback to `runExtensions` +- Enhancement (API): Supply `$` (our wrapped jQuery) to extensions so can use + its plugins, e.g., dbox with its `alert` +- Enhancement: Use alert dialog in place of `alert` in webappfind +- Enhancement: `editor.ready` now returns a Promise resolving when all + callbacks have resolved +- Enhancement: Allow `noAlert` option as part of second argument to + `loadSvgString` (and `loadFromURL` and `loadFromDataURI`) to avoid UI + alert (and trigger promise rejection) +- Enhancement: Make `dbox` as a separate module for alert, prompt, etc. dialogs +- Optimization: Recompress images (imageoptim-cli updated) +- Refactoring: Internal `PaintBox` as class; other misc. tweaks; no bitwise + in canvg +- Refactoring: Reuse utilities base64 encoder for SVG icons plugin +- Linting (ESLint): Further linting changes (for editor); rename + `.eslintrc` -> `.eslintrc.js` per recommendation and to more transparently + allow comments; apply new strict `eslint-config-ash-nazg` rules. +- Linting (ESLint): Stricter rules (or switch to warning) +- Docs (JSDoc): Fix return of the `mouseUp` (can also be an object) and + `mouseDown` (may also be a boolean) of `pathActions`; other JSDoc + additions/improvements +- npm: Update devDeps + ## 3.2.0 - Refactoring: Avoid unnecessary `addEventListener` `false`; change internal @@ -21,7 +78,9 @@ , , , - + ; NOTE: + if we need to tap into Markdown within JSDoc, see + for commit not present in npm. - Docs (README): Indicate minimal polyfills needed for older browsers (IE <= 11, IE Mobile, Opera Mini, Blackberry Browser <= 10, Android Browser 4.4.3-4.4.4) diff --git a/README.md b/README.md index d41f9e91..065d5868 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,7 @@ incorporating SVGEdit. ## Recent news +- 2018-11-16 Published 4.0.0 (Move to Promise-based APIs) - 2018-11-01 Published 3.2.0 (Update qunit to resolve security vulnerability of a dependency) - 2018-10-25 Published 3.1.1 (Fix for saving SVG on Firefox) - 2018-10-24 Published 3.1.0 (Redirect on modular page for non-module-support; diff --git a/build-html.js b/build-html.js index 5b899756..6898f823 100644 --- a/build-html.js +++ b/build-html.js @@ -1,5 +1,5 @@ /* eslint-env node */ -const fs = require('promise-fs'); +import fs from 'promise-fs'; const filesAndReplacements = [ { @@ -122,26 +122,27 @@ const filesAndReplacements = [ } ]; -filesAndReplacements.reduce(async (p, {input, output, replacements}) => { +(async () => { +await filesAndReplacements.reduce(async (p, {input, output, replacements}) => { await p; let data; try { data = await fs.readFile(input, 'utf8'); } catch (err) { - console.log(`Error reading ${input} file`, err); + console.log(`Error reading ${input} file`, err); // eslint-disable-line no-console } - data = replacements.reduce((s, [find, replacement]) => { - return s.replace(find, replacement); + data = replacements.reduce((s, [fnd, replacement]) => { + return s.replace(fnd, replacement); }, data); try { await fs.writeFile(output, data); } catch (err) { - console.log(`Error writing file: ${err}`, err); + console.log(`Error writing file: ${err}`, err); // eslint-disable-line no-console return; } - console.log(`Completed file ${input} rewriting!`); -}, Promise.resolve()).then(() => { - console.log('Finished!'); -}); + console.log(`Completed file ${input} rewriting!`); // eslint-disable-line no-console +}, Promise.resolve()); +console.log('Finished!'); // eslint-disable-line no-console +})(); diff --git a/dist/canvg.js b/dist/canvg.js index 5c8cf931..4689ed54 100644 --- a/dist/canvg.js +++ b/dist/canvg.js @@ -380,20 +380,38 @@ var canvg = (function (exports) { var colorDefs = [{ re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], - process: function process(bits) { - return [parseInt(bits[1], 10), parseInt(bits[2], 10), parseInt(bits[3], 10)]; + process: function process(_) { + for (var _len = arguments.length, bits = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + bits[_key - 1] = arguments[_key]; + } + + return bits.map(function (b) { + return parseInt(b); + }); } }, { re: /^(\w{2})(\w{2})(\w{2})$/, example: ['#00ff00', '336699'], - process: function process(bits) { - return [parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16)]; + process: function process(_) { + for (var _len2 = arguments.length, bits = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + bits[_key2 - 1] = arguments[_key2]; + } + + return bits.map(function (b) { + return parseInt(b, 16); + }); } }, { re: /^(\w{1})(\w{1})(\w{1})$/, example: ['#fb0', 'f0f'], - process: function process(bits) { - return [parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16)]; + process: function process(_) { + for (var _len3 = arguments.length, bits = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + bits[_key3 - 1] = arguments[_key3]; + } + + return bits.map(function (b) { + return parseInt(b + b, 16); + }); } }]; /** @@ -407,6 +425,8 @@ var canvg = (function (exports) { * @param {string} colorString */ function RGBColor(colorString) { + var _this = this; + _classCallCheck(this, RGBColor); this.ok = false; // strip any leading # @@ -426,9 +446,9 @@ var canvg = (function (exports) { // search through the definitions to find a match - for (var i = 0; i < colorDefs.length; i++) { - var re = colorDefs[i].re; - var processor = colorDefs[i].process; + colorDefs.forEach(function (_ref) { + var re = _ref.re, + processor = _ref.process; var bits = re.exec(colorString); if (bits) { @@ -438,15 +458,14 @@ var canvg = (function (exports) { g = _processor2[1], b = _processor2[2]; - Object.assign(this, { + Object.assign(_this, { r: r, g: g, b: b }); - this.ok = true; + _this.ok = true; } - } // validate/cleanup values - + }, this); // validate/cleanup values this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r; this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g; @@ -488,88 +507,74 @@ var canvg = (function (exports) { return '#' + r + g + b; } - /** - * Offers a bulleted list of help. - * @returns {HTMLUListElement} - */ - - }, { - key: "getHelpXML", - value: function getHelpXML() { - var examples = []; // add regexps - - for (var i = 0; i < colorDefs.length; i++) { - var example = colorDefs[i].example; - - for (var j = 0; j < example.length; j++) { - examples[examples.length] = example[j]; - } - } // add type-in colors - - - examples.push.apply(examples, _toConsumableArray(Object.keys(simpleColors))); - var xml = document.createElement('ul'); - xml.setAttribute('id', 'rgbcolor-examples'); - - for (var _i = 0; _i < examples.length; _i++) { - try { - var listItem = document.createElement('li'); - var listColor = new RGBColor(examples[_i]); - var exampleDiv = document.createElement('div'); - exampleDiv.style.cssText = "\nmargin: 3px;\nborder: 1px solid black;\nbackground: ".concat(listColor.toHex(), ";\ncolor: ").concat(listColor.toHex(), ";"); - exampleDiv.append('test'); - var listItemValue = " ".concat(examples[_i], " -> ").concat(listColor.toRGB(), " -> ").concat(listColor.toHex()); - listItem.append(exampleDiv, listItemValue); - xml.append(listItem); - } catch (e) {} - } - - return xml; - } }]); return RGBColor; }(); + RGBColor.getHelpXML = function () { + var examples = _toConsumableArray(colorDefs.flatMap(function (_ref2) { + var example = _ref2.example; + return example; + })).concat(_toConsumableArray(Object.keys(simpleColors))); + + var xml = document.createElement('ul'); + xml.setAttribute('id', 'rgbcolor-examples'); + xml.append.apply(xml, _toConsumableArray(examples.map(function (example) { + try { + var listItem = document.createElement('li'); + var listColor = new RGBColor(example); + var exampleDiv = document.createElement('div'); + exampleDiv.style.cssText = "\nmargin: 3px;\nborder: 1px solid black;\nbackground: ".concat(listColor.toHex(), ";\ncolor: ").concat(listColor.toHex(), ";"); + exampleDiv.append('test'); + var listItemValue = " ".concat(example, " -> ").concat(listColor.toRGB(), " -> ").concat(listColor.toHex()); + listItem.append(exampleDiv, listItemValue); + return listItem; + } catch (e) { + return ''; + } + }))); + return xml; + }; + /** * StackBlur - a fast almost Gaussian Blur For Canvas - - In case you find this class useful - especially in commercial projects - - I am not totally unhappy for a small donation to my PayPal account - mario@quasimondo.de - - Or support me on flattr: - https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript - + * + * In case you find this class useful - especially in commercial projects - + * I am not totally unhappy for a small donation to my PayPal account + * mario@quasimondo.de + * + * Or support me on flattr: + * {@link https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript} * @module StackBlur * @version 0.5 * @author Mario Klingemann - Contact: mario@quasimondo.com - Website: http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html - Twitter: @quasimondo - + * Contact: mario@quasimondo.com + * Website: {@link http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html} + * Twitter: @quasimondo + * * @copyright (c) 2010 Mario Klingemann - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation - files (the "Software"), to deal in the Software without - restriction, including without limitation the rights to use, - copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following - conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. */ var mulTable = [512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456, 437, 420, 404, 388, 374, 360, 347, 335, 323, 312, 302, 292, 282, 273, 265, 512, 497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328, 320, 312, 305, 298, 291, 284, 278, 271, 265, 259, 507, 496, 485, 475, 465, 456, 446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335, 329, 323, 318, 312, 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512, 505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405, 399, 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328, 324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278, 274, 271, 268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456, 451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408, 404, 400, 396, 392, 388, 385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323, 320, 318, 315, 312, 310, 307, 304, 302, 299, 297, 294, 292, 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259]; var shgTable = [9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24]; @@ -843,31 +848,20 @@ var canvg = (function (exports) { this.next = null; }; - var canvasRGBA_ = processCanvasRGBA; /** - * @callback module:canvg.StackBlurCanvasRGBA - * @param {string} id - * @param {Float} x - * @param {Float} y - * @param {Float} width - * @param {Float} height - * @param {Float} blurRadius - */ + * Whether a value is `null` or `undefined`. + * @param {Any} val + * @returns {boolean} + */ + var isNullish = function isNullish(val) { + return val === null || val === undefined; + }; /** * @callback module:canvg.ForceRedraw * @returns {boolean} */ - /** - * @function module:canvg.setStackBlurCanvasRGBA - * @param {module:canvg.StackBlurCanvasRGBA} cb Will be passed the canvas ID, x, y, width, height, blurRadius - * @returns {undefined} - */ - - var setStackBlurCanvasRGBA = function setStackBlurCanvasRGBA(cb) { - canvasRGBA_ = cb; - }; /** * @typedef {PlainObject} module:canvg.CanvgOptions * @property {boolean} opts.ignoreMouse true => ignore mouse events @@ -888,14 +882,15 @@ var canvg = (function (exports) { * with `` elements. * @function module:canvg.canvg * @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 {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 */ + var canvg = function canvg(target, s, opts) { // no parameters - if (target == null && s == null && opts == null) { + if (isNullish(target) && isNullish(s) && isNullish(opts)) { var svgTags = document.querySelectorAll('svg'); return Promise.all(_toConsumableArray(svgTags).map(function (svgTag) { var c = document.createElement('canvas'); @@ -914,7 +909,7 @@ var canvg = (function (exports) { } // store class on canvas - if (target.svg != null) target.svg.stop(); + if (!isNullish(target.svg)) target.svg.stop(); var svg = build(opts || {}); // on i.e. 8 for flash canvas, we can't assign the property so check for it if (!(target.childNodes.length === 1 && target.childNodes[0].nodeName === 'OBJECT')) { @@ -949,12 +944,15 @@ var canvg = (function (exports) { svg.FRAMERATE = 30; svg.MAX_VIRTUAL_PIXELS = 30000; - svg.log = function (msg) {}; + svg.log = function (msg) { + /* */ + }; if (svg.opts.log === true && typeof console !== 'undefined') { svg.log = function (msg) { console.log(msg); - }; + }; // eslint-disable-line no-console + } // globals @@ -995,7 +993,7 @@ var canvg = (function (exports) { return this.Current().height; }, ComputeSize: function ComputeSize(d) { - if (d != null && typeof d === 'number') return d; + if (!isNullish(d) && typeof d === 'number') return d; if (d === 'x') return this.width(); if (d === 'y') return this.height(); return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2); @@ -1020,6 +1018,7 @@ var canvg = (function (exports) { svg.compressSpaces = function (s) { return s.replace(/[\s\r\t\n]+/gm, ' '); }; // ajax + // Todo: Replace with `fetch` and polyfill svg.ajax = function (url, asynch) { @@ -1027,6 +1026,7 @@ var canvg = (function (exports) { if (asynch) { return new Promise(function (resolve, reject) { + // eslint-disable-line promise/avoid-new var req = AJAX.open('GET', url, true); req.addEventListener('load', function () { resolve(AJAX.responseText); @@ -1045,13 +1045,13 @@ var canvg = (function (exports) { if (window.DOMParser) { var parser = new DOMParser(); return parser.parseFromString(xml, 'text/xml'); - } else { - xml = xml.replace(/]*>/, ''); - var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM'); - xmlDoc.async = 'false'; - xmlDoc.loadXML(xml); - return xmlDoc; } + + xml = xml.replace(/]*>/, ''); + var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM'); + xmlDoc.async = 'false'; + xmlDoc.loadXML(xml); + return xmlDoc; }; // text extensions // get the text baseline @@ -1088,7 +1088,7 @@ var canvg = (function (exports) { }, { key: "hasValue", value: function hasValue() { - return this.value != null && this.value !== ''; + return !isNullish(this.value) && this.value !== ''; } // return the numerical value of the property }, { @@ -1097,8 +1097,8 @@ var canvg = (function (exports) { if (!this.hasValue()) return 0; var n = parseFloat(this.value); - if ((this.value + '').match(/%$/)) { - n = n / 100.0; + if (String(this.value).match(/%$/)) { + n /= 100.0; } return n; @@ -1122,7 +1122,7 @@ var canvg = (function (exports) { value: function addOpacity(opacityProp) { var newValue = this.value; - if (opacityProp.value != null && opacityProp.value !== '' && typeof this.value === 'string') { + if (!isNullish(opacityProp.value) && opacityProp.value !== '' && typeof this.value === 'string') { // can only add opacity to colors, not patterns var color = new RGBColor(this.value); @@ -1160,12 +1160,12 @@ var canvg = (function (exports) { value: function getFillStyleDefinition(e, opacityProp) { var def = this.getDefinition(); // gradient - if (def != null && def.createGradient) { + if (!isNullish(def) && def.createGradient) { return def.createGradient(svg.ctx, e, opacityProp); } // pattern - if (def != null && def.createPattern) { + if (!isNullish(def) && def.createPattern) { if (def.getHrefAttribute().hasValue()) { var pt = def.attribute('patternTransform'); def = def.getHrefAttribute().getDefinition(); @@ -1197,15 +1197,14 @@ var canvg = (function (exports) { }, { key: "getUnits", value: function getUnits() { - var s = this.value + ''; - return s.replace(/[0-9.-]/g, ''); + return String(this.value).replace(/[0-9.-]/g, ''); } // get the length as pixels }, { key: "toPixels", value: function toPixels(viewPort, processPercent) { if (!this.hasValue()) return 0; - var s = this.value + ''; + var s = String(this.value); if (s.match(/em$/)) return this.numValue() * this.getEM(viewPort); if (s.match(/ex$/)) return this.numValue() * this.getEM(viewPort) / 2.0; if (s.match(/px$/)) return this.numValue(); @@ -1225,7 +1224,7 @@ var canvg = (function (exports) { key: "toMilliseconds", value: function toMilliseconds() { if (!this.hasValue()) return 0; - var s = this.value + ''; + var s = String(this.value); if (s.match(/s$/)) return this.numValue() * 1000; if (s.match(/ms$/)) return this.numValue(); return this.numValue(); @@ -1236,7 +1235,7 @@ var canvg = (function (exports) { key: "toRadians", value: function toRadians() { if (!this.hasValue()) return 0; - var s = this.value + ''; + var s = String(this.value); if (s.match(/deg$/)) return this.numValue() * (Math.PI / 180.0); if (s.match(/grad$/)) return this.numValue() * (Math.PI / 200.0); if (s.match(/rad$/)) return this.numValue(); @@ -1259,7 +1258,7 @@ var canvg = (function (exports) { Variants: 'normal|small-caps|inherit', Weights: 'normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit', CreateFont: function CreateFont(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) { - var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); + var f = !isNullish(inherit) ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); return { fontFamily: fontFamily || f.fontFamily, fontSize: fontSize || f.fontSize, @@ -1275,7 +1274,7 @@ var canvg = (function (exports) { var _this = this; var f = {}; - var d = svg.trim(svg.compressSpaces(s || '')).split(' '); + var ds = svg.trim(svg.compressSpaces(s || '')).split(' '); var set = { fontSize: false, fontStyle: false, @@ -1283,7 +1282,7 @@ var canvg = (function (exports) { fontVariant: false }; var ff = ''; - d.forEach(function (d) { + ds.forEach(function (d) { if (!set.fontStyle && _this.Styles.includes(d)) { if (d !== 'inherit') { f.fontStyle = d; @@ -1308,10 +1307,8 @@ var canvg = (function (exports) { } set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; - } else { - if (d !== 'inherit') { - ff += d; - } + } else if (d !== 'inherit') { + ff += d; } }); @@ -1325,8 +1322,8 @@ var canvg = (function (exports) { svg.ToNumberArray = function (s) { var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); - return a.map(function (a) { - return parseFloat(a); + return a.map(function (_a) { + return parseFloat(_a); }); }; @@ -1413,7 +1410,7 @@ var canvg = (function (exports) { }, { key: "addPoint", value: function addPoint(x, y) { - if (x != null) { + if (!isNullish(x)) { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; @@ -1423,7 +1420,7 @@ var canvg = (function (exports) { if (x > this.x2) this.x2 = x; } - if (y != null) { + if (!isNullish(y)) { if (isNaN(this.y1) || isNaN(this.y2)) { this.y1 = y; this.y2 = y; @@ -1577,9 +1574,10 @@ var canvg = (function (exports) { }; this.applyToPoint = function (p) { - var a = this.angle.toRadians(); + var _a = this.angle.toRadians(); + p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); - p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); + p.applyTransform([Math.cos(_a), Math.sin(_a), -Math.sin(_a), Math.cos(_a), 0, 0]); p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); }; }, @@ -1745,7 +1743,7 @@ var canvg = (function (exports) { if (align === 'none') ctx.scale(scaleX, scaleY);else if (meetOrSlice === 'meet') ctx.scale(scaleMin, scaleMin);else if (meetOrSlice === 'slice') ctx.scale(scaleMax, scaleMax); // translate - ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY); + ctx.translate(isNullish(minX) ? 0 : -minX, isNullish(minY) ? 0 : -minY); }; // elements @@ -1760,13 +1758,14 @@ var canvg = (function (exports) { _classCallCheck(this, _class4); - this.captureTextNodes = arguments[1]; // Argument from inheriting class + // Argument from inheriting class + this.captureTextNodes = arguments[1]; // eslint-disable-line prefer-rest-params this.attributes = {}; this.styles = {}; this.children = []; - if (node != null && node.nodeType === 1) { + if (!isNullish(node) && node.nodeType === 1) { // ELEMENT_NODE // add children _toConsumableArray(node.childNodes).forEach(function (childNode) { @@ -1795,10 +1794,14 @@ var canvg = (function (exports) { var styles = svg.Styles[node.nodeName]; - if (styles != null) { - for (var name in styles) { - this.styles[name] = styles[name]; - } + if (!isNullish(styles)) { + Object.entries(styles).forEach(function (_ref2) { + var _ref3 = _slicedToArray(_ref2, 2), + name = _ref3[0], + styleValue = _ref3[1]; + + _this7.styles[name] = styleValue; + }); } // add class styles @@ -1807,18 +1810,26 @@ var canvg = (function (exports) { classes.forEach(function (clss) { styles = svg.Styles['.' + clss]; - if (styles != null) { - for (var _name in styles) { - _this7.styles[_name] = styles[_name]; - } + if (!isNullish(styles)) { + Object.entries(styles).forEach(function (_ref4) { + var _ref5 = _slicedToArray(_ref4, 2), + name = _ref5[0], + styleValue = _ref5[1]; + + _this7.styles[name] = styleValue; + }); } styles = svg.Styles[node.nodeName + '.' + clss]; - if (styles != null) { - for (var _name2 in styles) { - _this7.styles[_name2] = styles[_name2]; - } + if (!isNullish(styles)) { + Object.entries(styles).forEach(function (_ref6) { + var _ref7 = _slicedToArray(_ref6, 2), + name = _ref7[0], + styleValue = _ref7[1]; + + _this7.styles[name] = styleValue; + }); } }); } // add id styles @@ -1827,10 +1838,14 @@ var canvg = (function (exports) { if (this.attribute('id').hasValue()) { var _styles = svg.Styles['#' + this.attribute('id').value]; - if (_styles != null) { - for (var _name3 in _styles) { - this.styles[_name3] = _styles[_name3]; - } + if (!isNullish(_styles)) { + Object.entries(_styles).forEach(function (_ref8) { + var _ref9 = _slicedToArray(_ref8, 2), + name = _ref9[0], + styleValue = _ref9[1]; + + _this7.styles[name] = styleValue; + }); } } // add inline styles @@ -1841,19 +1856,19 @@ var canvg = (function (exports) { _styles2.forEach(function (style) { if (svg.trim(style) !== '') { var _style$split = style.split(':'), - _name4 = _style$split.name, + name = _style$split.name, value = _style$split.value; - _name4 = svg.trim(_name4); + name = svg.trim(name); value = svg.trim(value); - _this7.styles[_name4] = new svg.Property(_name4, value); + _this7.styles[name] = new svg.Property(name, value); } }); } // add id if (this.attribute('id').hasValue()) { - if (svg.Definitions[this.attribute('id').value] == null) { + if (isNullish(svg.Definitions[this.attribute('id').value])) { svg.Definitions[this.attribute('id').value] = this; } } @@ -1865,7 +1880,7 @@ var canvg = (function (exports) { key: "attribute", value: function attribute(name, createIfNotExists) { var a = this.attributes[name]; - if (a != null) return a; + if (!isNullish(a)) return a; if (createIfNotExists === true) { a = new svg.Property(name, ''); @@ -1890,10 +1905,10 @@ var canvg = (function (exports) { key: "style", value: function style(name, createIfNotExists, skipAncestors) { var s = this.styles[name]; - if (s != null) return s; + if (!isNullish(s)) return s; var a = this.attribute(name); - if (a != null && a.hasValue()) { + if (!isNullish(a) && a.hasValue()) { this.styles[name] = a; // move up to me to cache return a; @@ -1902,10 +1917,10 @@ var canvg = (function (exports) { if (skipAncestors !== true) { var p = this.parent; - if (p != null) { + if (!isNullish(p)) { var ps = p.style(name); - if (ps != null && ps.hasValue()) { + if (!isNullish(ps) && ps.hasValue()) { return ps; } } @@ -1931,11 +1946,11 @@ var canvg = (function (exports) { if (this.attribute('mask').hasValue()) { // mask var mask = this.attribute('mask').getDefinition(); - if (mask != null) mask.apply(ctx, this); + if (!isNullish(mask)) mask.apply(ctx, this); } else if (this.style('filter').hasValue()) { // filter var filter = this.style('filter').getDefinition(); - if (filter != null) filter.apply(ctx, this); + if (!isNullish(filter)) filter.apply(ctx, this); } else { this.setContext(ctx); this.renderChildren(ctx); @@ -1994,7 +2009,7 @@ var canvg = (function (exports) { // fill if (this.style('fill').isUrlDefinition()) { var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity')); - if (fs != null) ctx.fillStyle = fs; + if (!isNullish(fs)) ctx.fillStyle = fs; } else if (this.style('fill').hasValue()) { var fillStyle = this.style('fill'); if (fillStyle.value === 'currentColor') fillStyle.value = this.style('color').value; @@ -2012,7 +2027,7 @@ var canvg = (function (exports) { if (this.style('stroke').isUrlDefinition()) { var _fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity')); - if (_fs != null) ctx.strokeStyle = _fs; + if (!isNullish(_fs)) ctx.strokeStyle = _fs; } else if (this.style('stroke').hasValue()) { var strokeStyle = this.style('stroke'); if (strokeStyle.value === 'currentColor') strokeStyle.value = this.style('color').value; @@ -2071,7 +2086,7 @@ var canvg = (function (exports) { if (this.style('clip-path', false, true).hasValue()) { var clip = this.style('clip-path', false, true).getDefinition(); - if (clip != null) clip.apply(ctx); + if (!isNullish(clip)) clip.apply(ctx); } // opacity @@ -2098,7 +2113,7 @@ var canvg = (function (exports) { _createClass(_class6, [{ key: "path", value: function path(ctx) { - if (ctx != null) ctx.beginPath(); + if (!isNullish(ctx)) ctx.beginPath(); return new svg.BoundingBox(); } }, { @@ -2118,7 +2133,7 @@ var canvg = (function (exports) { if (ctx.strokeStyle !== '') ctx.stroke(); var markers = this.getMarkers(); - if (markers != null) { + if (!isNullish(markers)) { if (this.style('marker-start').isUrlDefinition()) { var marker = this.style('marker-start').getDefinition(); marker.render(ctx, markers[0][0], markers[0][1]); @@ -2263,7 +2278,7 @@ var canvg = (function (exports) { rx = Math.min(rx, width / 2.0); ry = Math.min(ry, height / 2.0); - if (ctx != null) { + if (!isNullish(ctx)) { ctx.beginPath(); ctx.moveTo(x + rx, y); ctx.lineTo(x + width - rx, y); @@ -2303,7 +2318,7 @@ var canvg = (function (exports) { var cy = this.attribute('cy').toPixels('y'); var r = this.attribute('r').toPixels(); - if (ctx != null) { + if (!isNullish(ctx)) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, true); ctx.closePath(); @@ -2338,7 +2353,7 @@ var canvg = (function (exports) { var cx = this.attribute('cx').toPixels('x'); var cy = this.attribute('cy').toPixels('y'); - if (ctx != null) { + if (!isNullish(ctx)) { ctx.beginPath(); ctx.moveTo(cx, cy - ry); ctx.bezierCurveTo(cx + KAPPA * rx, cy - ry, cx + rx, cy - KAPPA * ry, cx + rx, cy); @@ -2377,7 +2392,7 @@ var canvg = (function (exports) { value: function path(ctx) { var points = this.getPoints(); - if (ctx != null) { + if (!isNullish(ctx)) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); ctx.lineTo(points[1].x, points[1].y); @@ -2421,7 +2436,7 @@ var canvg = (function (exports) { y = _this$points$.y; var bb = new svg.BoundingBox(x, y); - if (ctx != null) { + if (!isNullish(ctx)) { ctx.beginPath(); ctx.moveTo(x, y); } @@ -2431,7 +2446,7 @@ var canvg = (function (exports) { _x = _this$points$i.x, _y = _this$points$i.y; bb.addPoint(_x, _y); - if (ctx != null) ctx.lineTo(_x, _y); + if (!isNullish(ctx)) ctx.lineTo(_x, _y); } return bb; @@ -2470,7 +2485,7 @@ var canvg = (function (exports) { value: function path(ctx) { var bb = _get(_getPrototypeOf(_class13.prototype), "path", this).call(this, ctx); - if (ctx != null) { + if (!isNullish(ctx)) { ctx.lineTo(this.points[0].x, this.points[0].y); ctx.closePath(); } @@ -2526,7 +2541,7 @@ var canvg = (function (exports) { }, isCommandOrEnd: function isCommandOrEnd() { if (this.isEnd()) return true; - return this.tokens[this.i + 1].match(/^[A-Za-z]$/) != null; + return !isNullish(this.tokens[this.i + 1].match(/^[A-Za-z]$/)); }, isRelativeCommand: function isRelativeCommand() { switch (this.command) { @@ -2589,11 +2604,11 @@ var canvg = (function (exports) { }, addMarker: function addMarker(p, from, priorTo) { // if the last angle isn't filled in because we didn't have this point yet ... - if (priorTo != null && this.angles.length > 0 && this.angles[this.angles.length - 1] == null) { + if (!isNullish(priorTo) && this.angles.length > 0 && isNullish(this.angles[this.angles.length - 1])) { this.angles[this.angles.length - 1] = this.points[this.points.length - 1].angleTo(priorTo); } - this.addMarkerAngle(p, from == null ? null : from.angleTo(p)); + this.addMarkerAngle(p, isNullish(from) ? null : from.angleTo(p)); }, addMarkerAngle: function addMarkerAngle(p, a) { this.points.push(p); @@ -2604,9 +2619,9 @@ var canvg = (function (exports) { }, getMarkerAngles: function getMarkerAngles() { for (var i = 0; i < this.angles.length; i++) { - if (this.angles[i] == null) { + if (isNullish(this.angles[i])) { for (var j = i + 1; j < this.angles.length; j++) { - if (this.angles[j] != null) { + if (!isNullish(this.angles[j])) { this.angles[i] = this.angles[j]; break; } @@ -2626,7 +2641,7 @@ var canvg = (function (exports) { var pp = this.PathParser; pp.reset(); var bb = new svg.BoundingBox(); - if (ctx != null) ctx.beginPath(); + if (!isNullish(ctx)) ctx.beginPath(); while (!pp.isEnd()) { pp.nextCommand(); @@ -2634,22 +2649,24 @@ var canvg = (function (exports) { switch (pp.command) { case 'M': case 'm': - var p = pp.getAsCurrentPoint(); - pp.addMarker(p); - bb.addPoint(p.x, p.y); - if (ctx != null) ctx.moveTo(p.x, p.y); - pp.start = pp.current; + { + var p = pp.getAsCurrentPoint(); + pp.addMarker(p); + bb.addPoint(p.x, p.y); + if (!isNullish(ctx)) ctx.moveTo(p.x, p.y); + pp.start = pp.current; - while (!pp.isCommandOrEnd()) { - var _p = pp.getAsCurrentPoint(); + while (!pp.isCommandOrEnd()) { + var _p = pp.getAsCurrentPoint(); - pp.addMarker(_p, pp.start); - bb.addPoint(_p.x, _p.y); - if (ctx != null) ctx.lineTo(_p.x, _p.y); + pp.addMarker(_p, pp.start); + bb.addPoint(_p.x, _p.y); + if (!isNullish(ctx)) ctx.lineTo(_p.x, _p.y); + } + + break; } - break; - case 'L': case 'l': while (!pp.isCommandOrEnd()) { @@ -2659,7 +2676,7 @@ var canvg = (function (exports) { pp.addMarker(_p2, c); bb.addPoint(_p2.x, _p2.y); - if (ctx != null) ctx.lineTo(_p2.x, _p2.y); + if (!isNullish(ctx)) ctx.lineTo(_p2.x, _p2.y); } break; @@ -2671,7 +2688,7 @@ var canvg = (function (exports) { pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); - if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); + if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); } break; @@ -2684,7 +2701,7 @@ var canvg = (function (exports) { pp.addMarker(_newP, pp.current); pp.current = _newP; bb.addPoint(pp.current.x, pp.current.y); - if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); + if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); } break; @@ -2698,7 +2715,7 @@ var canvg = (function (exports) { var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl, p1); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); - if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); + if (!isNullish(ctx)) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; @@ -2716,7 +2733,7 @@ var canvg = (function (exports) { pp.addMarker(_cp, _cntrl, _p3); bb.addBezierCurve(_curr.x, _curr.y, _p3.x, _p3.y, _cntrl.x, _cntrl.y, _cp.x, _cp.y); - if (ctx != null) ctx.bezierCurveTo(_p3.x, _p3.y, _cntrl.x, _cntrl.y, _cp.x, _cp.y); + if (!isNullish(ctx)) ctx.bezierCurveTo(_p3.x, _p3.y, _cntrl.x, _cntrl.y, _cp.x, _cp.y); } break; @@ -2732,7 +2749,7 @@ var canvg = (function (exports) { pp.addMarker(_cp2, _cntrl2, _cntrl2); bb.addQuadraticCurve(_curr2.x, _curr2.y, _cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); - if (ctx != null) ctx.quadraticCurveTo(_cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); + if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); } break; @@ -2750,7 +2767,7 @@ var canvg = (function (exports) { pp.addMarker(_cp3, _cntrl3, _cntrl3); bb.addQuadraticCurve(_curr3.x, _curr3.y, _cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); - if (ctx != null) ctx.quadraticCurveTo(_cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); + if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); } break; @@ -2814,7 +2831,7 @@ var canvg = (function (exports) { pp.addMarkerAngle(cp, ah - dir * Math.PI); bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better - if (ctx != null) { + if (!isNullish(ctx)) { var _r = rx > ry ? rx : ry; var sx = rx > ry ? 1 : rx / ry; @@ -2837,7 +2854,7 @@ var canvg = (function (exports) { case 'Z': case 'z': - if (ctx != null) ctx.closePath(); + if (!isNullish(ctx)) ctx.closePath(); pp.current = pp.start; } } @@ -2878,10 +2895,10 @@ var canvg = (function (exports) { var height = this.attribute('height').toPixels('y', true); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); - tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); - tempSvg.attributes['width'] = new svg.Property('width', width + 'px'); - tempSvg.attributes['height'] = new svg.Property('height', height + 'px'); - tempSvg.attributes['transform'] = new svg.Property('transform', this.attribute('patternTransform').value); + tempSvg.attributes.viewBox = new svg.Property('viewBox', this.attribute('viewBox').value); + tempSvg.attributes.width = new svg.Property('width', width + 'px'); + tempSvg.attributes.height = new svg.Property('height', height + 'px'); + tempSvg.attributes.transform = new svg.Property('transform', this.attribute('patternTransform').value); tempSvg.children = this.children; var c = document.createElement('canvas'); c.width = width; @@ -2931,13 +2948,13 @@ var canvg = (function (exports) { ctx.save(); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); - tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); - tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value); - tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value); - tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value); - tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value); - tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black')); - tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none')); + tempSvg.attributes.viewBox = new svg.Property('viewBox', this.attribute('viewBox').value); + tempSvg.attributes.refX = new svg.Property('refX', this.attribute('refX').value); + tempSvg.attributes.refY = new svg.Property('refY', this.attribute('refY').value); + tempSvg.attributes.width = new svg.Property('width', this.attribute('markerWidth').value); + tempSvg.attributes.height = new svg.Property('height', this.attribute('markerHeight').value); + tempSvg.attributes.fill = new svg.Property('fill', this.attribute('fill').valueOrDefault('black')); + tempSvg.attributes.stroke = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none')); tempSvg.children = this.children; tempSvg.render(ctx); ctx.restore(); @@ -3014,10 +3031,10 @@ var canvg = (function (exports) { }; var g = this.getGradient(ctx, element); - if (g == null) return addParentOpacity(stopsContainer.stops[stopsContainer.stops.length - 1].color); - stopsContainer.stops.forEach(function (_ref2) { - var offset = _ref2.offset, - color = _ref2.color; + if (isNullish(g)) return addParentOpacity(stopsContainer.stops[stopsContainer.stops.length - 1].color); + stopsContainer.stops.forEach(function (_ref10) { + var offset = _ref10.offset, + color = _ref10.color; g.addColorStop(offset, addParentOpacity(color)); }); @@ -3025,18 +3042,18 @@ var canvg = (function (exports) { // render as transformed pattern on temporary canvas var rootView = svg.ViewPort.viewPorts[0]; var rect = new svg.Element.rect(); - rect.attributes['x'] = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS / 3.0); - rect.attributes['y'] = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS / 3.0); - rect.attributes['width'] = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS); - rect.attributes['height'] = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS); + rect.attributes.x = new svg.Property('x', -svg.MAX_VIRTUAL_PIXELS / 3.0); + rect.attributes.y = new svg.Property('y', -svg.MAX_VIRTUAL_PIXELS / 3.0); + rect.attributes.width = new svg.Property('width', svg.MAX_VIRTUAL_PIXELS); + rect.attributes.height = new svg.Property('height', svg.MAX_VIRTUAL_PIXELS); var group = new svg.Element.g(); - group.attributes['transform'] = new svg.Property('transform', this.attribute('gradientTransform').value); + group.attributes.transform = new svg.Property('transform', this.attribute('gradientTransform').value); group.children = [rect]; var tempSvg = new svg.Element.svg(); - tempSvg.attributes['x'] = new svg.Property('x', 0); - tempSvg.attributes['y'] = new svg.Property('y', 0); - tempSvg.attributes['width'] = new svg.Property('width', rootView.width); - tempSvg.attributes['height'] = new svg.Property('height', rootView.height); + tempSvg.attributes.x = new svg.Property('x', 0); + tempSvg.attributes.y = new svg.Property('y', 0); + tempSvg.attributes.width = new svg.Property('width', rootView.width); + tempSvg.attributes.height = new svg.Property('height', rootView.height); tempSvg.children = [group]; var c = document.createElement('canvas'); c.width = rootView.width; @@ -3209,7 +3226,7 @@ var canvg = (function (exports) { key: "update", value: function update(delta) { // set initial value - if (this.initialValue == null) { + if (isNullish(this.initialValue)) { this.initialValue = this.getProperty().value; this.initialUnits = this.getProperty().getUnits(); } // if we're past the end time @@ -3327,7 +3344,7 @@ var canvg = (function (exports) { var r = from.r + (to.r - from.r) * p.progress; var g = from.g + (to.g - from.g) * p.progress; var b = from.b + (to.b - from.b) * p.progress; - return 'rgb(' + parseInt(r, 10) + ',' + parseInt(g, 10) + ',' + parseInt(b, 10) + ')'; + return 'rgb(' + parseInt(r) + ',' + parseInt(g) + ',' + parseInt(b) + ')'; } return this.attribute('from').value; @@ -3496,8 +3513,8 @@ var canvg = (function (exports) { _get(_getPrototypeOf(_class30.prototype), "setContext", this).call(this, ctx); var textBaseline = this.style('dominant-baseline').toTextBaseline(); - if (textBaseline == null) textBaseline = this.style('alignment-baseline').toTextBaseline(); - if (textBaseline != null) ctx.textBaseline = textBaseline; + if (isNullish(textBaseline)) textBaseline = this.style('alignment-baseline').toTextBaseline(); + if (!isNullish(textBaseline)) ctx.textBaseline = textBaseline; } }, { key: "getBoundingBox", @@ -3567,8 +3584,8 @@ var canvg = (function (exports) { this.y = child.y; child.render(ctx); - for (var _i = 0; _i < child.children.length; _i++) { - this.renderChild(ctx, child, _i); + for (var j = 0; j < child.children.length; j++) { + this.renderChild(ctx, child, j); } } }]); @@ -3602,13 +3619,13 @@ var canvg = (function (exports) { if (typeof font.glyphs[c] !== 'undefined') { glyph = font.glyphs[c][arabicForm]; - if (glyph == null && font.glyphs[c].type === 'glyph') glyph = font.glyphs[c]; + if (isNullish(glyph) && font.glyphs[c].type === 'glyph') glyph = font.glyphs[c]; } } else { glyph = font.glyphs[c]; } - if (glyph == null) glyph = font.missingGlyph; + if (isNullish(glyph)) glyph = font.missingGlyph; return glyph; } }, { @@ -3616,7 +3633,7 @@ var canvg = (function (exports) { value: function renderChildren(ctx) { var customFont = this.parent.style('font-family').getDefinition(); - if (customFont != null) { + if (!isNullish(customFont)) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var fontStyle = this.parent.style('font-style').valueOrDefault(svg.Font.Parse(svg.ctx.font).fontStyle); var text = this.getText(); @@ -3667,7 +3684,7 @@ var canvg = (function (exports) { value: function measureText(ctx) { var customFont = this.parent.style('font-family').getDefinition(); - if (customFont != null) { + if (!isNullish(customFont)) { var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); var measure = 0; var text = this.getText(); @@ -3744,7 +3761,8 @@ var canvg = (function (exports) { key: "getText", value: function getText() { var element = this.getHrefAttribute().getDefinition(); - if (element != null) return element.children[0].getText(); + if (!isNullish(element)) return element.children[0].getText(); + return undefined; } }]); @@ -3843,22 +3861,25 @@ var canvg = (function (exports) { _this20.img.crossOrigin = 'Anonymous'; } - var self = _assertThisInitialized(_assertThisInitialized(_this20)); - _this20.img.onload = function () { - self.loaded = true; + _this20.loaded = true; }; _this20.img.onerror = function () { svg.log('ERROR: image "' + href + '" not found'); - self.loaded = true; + _this20.loaded = true; }; _this20.img.src = href; } else { svg.ajax(href, true).then(function (img) { + // eslint-disable-line promise/prefer-await-to-then, promise/always-return _this20.img = img; _this20.loaded = true; + }).catch(function (err) { + // eslint-disable-line promise/prefer-await-to-callbacks + _this20.erred = true; + console.error('Ajax error for canvg', err); // eslint-disable-line no-console }); } @@ -3961,8 +3982,8 @@ var canvg = (function (exports) { var css = ''; - _toConsumableArray(node.childNodes).forEach(function (_ref3) { - var nodeValue = _ref3.nodeValue; + _toConsumableArray(node.childNodes).forEach(function (_ref11) { + var nodeValue = _ref11.nodeValue; css += nodeValue; }); @@ -3990,7 +4011,7 @@ var canvg = (function (exports) { var name = cssProp.substr(0, prop); var value = cssProp.substr(prop + 1, cssProp.length - prop); - if (name != null && value != null) { + if (!isNullish(name) && !isNullish(value)) { props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value)); } }); @@ -3998,7 +4019,7 @@ var canvg = (function (exports) { if (cssClass === '@font-face') { var fontFamily = props['font-family'].value.replace(/"/g, ''); - var srcs = props['src'].value.split(','); + var srcs = props.src.value.split(','); srcs.forEach(function (src) { if (src.includes('format("svg")')) { var urlStart = src.indexOf('url'); @@ -4053,36 +4074,37 @@ var canvg = (function (exports) { key: "path", value: function path(ctx) { var element = this._el; - if (element != null) element.path(ctx); + if (!isNullish(element)) element.path(ctx); } }, { key: "getBoundingBox", value: function getBoundingBox() { var element = this._el; - if (element != null) return element.getBoundingBox(); + if (!isNullish(element)) return element.getBoundingBox(); + return undefined; } }, { key: "renderChildren", value: function renderChildren(ctx) { var element = this._el; - if (element != null) { + if (!isNullish(element)) { var tempSvg = element; if (element.type === 'symbol') { // render me using a temporary svg element in symbol cases (https://www.w3.org/TR/SVG/struct.html#UseElement) tempSvg = new svg.Element.svg(); tempSvg.type = 'svg'; - tempSvg.attributes['viewBox'] = new svg.Property('viewBox', element.attribute('viewBox').value); - tempSvg.attributes['preserveAspectRatio'] = new svg.Property('preserveAspectRatio', element.attribute('preserveAspectRatio').value); - tempSvg.attributes['overflow'] = new svg.Property('overflow', element.attribute('overflow').value); + tempSvg.attributes.viewBox = new svg.Property('viewBox', element.attribute('viewBox').value); + tempSvg.attributes.preserveAspectRatio = new svg.Property('preserveAspectRatio', element.attribute('preserveAspectRatio').value); + tempSvg.attributes.overflow = new svg.Property('overflow', element.attribute('overflow').value); tempSvg.children = element.children; } if (tempSvg.type === 'svg') { // if symbol or svg, inherit width/height from me - if (this.attribute('width').hasValue()) tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value); - if (this.attribute('height').hasValue()) tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value); + if (this.attribute('width').hasValue()) tempSvg.attributes.width = new svg.Property('width', this.attribute('width').value); + if (this.attribute('height').hasValue()) tempSvg.attributes.height = new svg.Property('height', this.attribute('height').value); } var oldParent = tempSvg.parent; @@ -4294,10 +4316,31 @@ var canvg = (function (exports) { return _class44; }(svg.Element.ElementBase); + /** + * @param {Uint8ClampedArray} img + * @param {Integer} x + * @param {Integer} y + * @param {Float} width + * @param {Float} height + * @param {Integer} rgba + * @returns {undefined} + */ + function imGet(img, x, y, width, height, rgba) { return img[y * width * 4 + x * 4 + rgba]; } + /** + * @param {Uint8ClampedArray} img + * @param {Integer} x + * @param {Integer} y + * @param {Float} width + * @param {Float} height + * @param {Integer} rgba + * @param {Float} val + * @returns {undefined} + */ + function imSet(img, x, y, width, height, rgba, val) { img[y * width * 4 + x * 4 + rgba] = val; @@ -4319,19 +4362,23 @@ var canvg = (function (exports) { switch (_this23.attribute('type').valueOrDefault('matrix')) { // https://www.w3.org/TR/SVG/filters.html#feColorMatrixElement case 'saturate': - var s = matrix[0]; - matrix = [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]; - break; + { + var s = matrix[0]; + matrix = [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s, 0, 0, 0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]; + break; + } case 'hueRotate': - var a = matrix[0] * Math.PI / 180.0; + { + var a = matrix[0] * Math.PI / 180.0; - var c = function c(m1, m2, m3) { - return m1 + Math.cos(a) * m2 + Math.sin(a) * m3; - }; + var c = function c(m1, m2, m3) { + return m1 + Math.cos(a) * m2 + Math.sin(a) * m3; + }; - matrix = [c(0.213, 0.787, -0.213), c(0.715, -0.715, -0.715), c(0.072, -0.072, 0.928), 0, 0, c(0.213, -0.213, 0.143), c(0.715, 0.285, 0.140), c(0.072, -0.072, -0.283), 0, 0, c(0.213, -0.213, -0.787), c(0.715, -0.715, 0.715), c(0.072, 0.928, 0.072), 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]; - break; + matrix = [c(0.213, 0.787, -0.213), c(0.715, -0.715, -0.715), c(0.072, -0.072, 0.928), 0, 0, c(0.213, -0.213, 0.143), c(0.715, 0.285, 0.140), c(0.072, -0.072, -0.283), 0, 0, c(0.213, -0.213, -0.787), c(0.715, -0.715, 0.715), c(0.072, 0.928, 0.072), 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]; + break; + } case 'luminanceToAlpha': matrix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.2125, 0.7154, 0.0721, 0, 0, 0, 0, 0, 0, 1]; @@ -4355,16 +4402,16 @@ var canvg = (function (exports) { var srcData = ctx.getImageData(0, 0, width, height); - for (var _y2 = 0; _y2 < height; _y2++) { - for (var _x2 = 0; _x2 < width; _x2++) { - var r = imGet(srcData.data, _x2, _y2, width, height, 0); - var g = imGet(srcData.data, _x2, _y2, width, height, 1); - var b = imGet(srcData.data, _x2, _y2, width, height, 2); - var a = imGet(srcData.data, _x2, _y2, width, height, 3); - imSet(srcData.data, _x2, _y2, width, height, 0, m(0, r) + m(1, g) + m(2, b) + m(3, a) + m(4, 1)); - imSet(srcData.data, _x2, _y2, width, height, 1, m(5, r) + m(6, g) + m(7, b) + m(8, a) + m(9, 1)); - imSet(srcData.data, _x2, _y2, width, height, 2, m(10, r) + m(11, g) + m(12, b) + m(13, a) + m(14, 1)); - imSet(srcData.data, _x2, _y2, width, height, 3, m(15, r) + m(16, g) + m(17, b) + m(18, a) + m(19, 1)); + for (var _y = 0; _y < height; _y++) { + for (var _x = 0; _x < width; _x++) { + var r = imGet(srcData.data, _x, _y, width, height, 0); + var g = imGet(srcData.data, _x, _y, width, height, 1); + var b = imGet(srcData.data, _x, _y, width, height, 2); + var a = imGet(srcData.data, _x, _y, width, height, 3); + imSet(srcData.data, _x, _y, width, height, 0, m(0, r) + m(1, g) + m(2, b) + m(3, a) + m(4, 1)); + imSet(srcData.data, _x, _y, width, height, 1, m(5, r) + m(6, g) + m(7, b) + m(8, a) + m(9, 1)); + imSet(srcData.data, _x, _y, width, height, 2, m(10, r) + m(11, g) + m(12, b) + m(13, a) + m(14, 1)); + imSet(srcData.data, _x, _y, width, height, 3, m(15, r) + m(16, g) + m(17, b) + m(18, a) + m(19, 1)); } } @@ -4395,17 +4442,12 @@ var canvg = (function (exports) { _createClass(_class46, [{ key: "apply", value: function apply(ctx, x, y, width, height) { - if (typeof canvasRGBA_ !== 'function') { - svg.log('ERROR: The function `setStackBlurCanvasRGBA` must be present for blur to work'); - return; - } // Todo: This might not be a problem anymore with out `instanceof` fix + // Todo: This might not be a problem anymore with out `instanceof` fix // StackBlur requires canvas be on document - - ctx.canvas.id = svg.UniqueId(); ctx.canvas.style.display = 'none'; document.body.append(ctx.canvas); - canvasRGBA_(ctx.canvas, x, y, width, height, this.blurRadius); + processCanvasRGBA(ctx.canvas, x, y, width, height, this.blurRadius); ctx.canvas.remove(); } }]); @@ -4482,7 +4524,7 @@ var canvg = (function (exports) { svg.load = /*#__PURE__*/ function () { - var _ref4 = _asyncToGenerator( + var _ref12 = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(ctx, url) { var dom; @@ -4505,8 +4547,8 @@ var canvg = (function (exports) { }, _callee, this); })); - return function (_x3, _x4) { - return _ref4.apply(this, arguments); + return function (_x2, _x3) { + return _ref12.apply(this, arguments); }; }(); // load from xml @@ -4536,7 +4578,7 @@ var canvg = (function (exports) { if (svg.opts.ignoreMouse !== true) { ctx.canvas.onclick = function (e) { - var args = e != null ? [e.clientX, e.clientY] : [event.clientX, event.clientY]; + var args = !isNullish(e) ? [e.clientX, e.clientY] : [event.clientX, event.clientY]; // eslint-disable-line no-restricted-globals var _mapXY = mapXY(_construct(svg.Point, args)), x = _mapXY.x, @@ -4546,7 +4588,7 @@ var canvg = (function (exports) { }; ctx.canvas.onmousemove = function (e) { - var args = e != null ? [e.clientX, e.clientY] : [event.clientX, event.clientY]; + var args = !isNullish(e) ? [e.clientX, e.clientY] : [event.clientX, event.clientY]; // eslint-disable-line no-restricted-globals var _mapXY2 = mapXY(_construct(svg.Point, args)), x = _mapXY2.x, @@ -4591,20 +4633,20 @@ var canvg = (function (exports) { svg.ViewPort.SetCurrent(cWidth, cHeight); - if (svg.opts.offsetX != null) { + if (!isNullish(svg.opts.offsetX)) { e.attribute('x', true).value = svg.opts.offsetX; } - if (svg.opts.offsetY != null) { + if (!isNullish(svg.opts.offsetY)) { e.attribute('y', true).value = svg.opts.offsetY; } - if (svg.opts.scaleWidth != null || svg.opts.scaleHeight != null) { + if (!isNullish(svg.opts.scaleWidth) || !isNullish(svg.opts.scaleHeight)) { var viewBox = svg.ToNumberArray(e.attribute('viewBox').value); var xRatio = null, yRatio = null; - if (svg.opts.scaleWidth != null) { + if (!isNullish(svg.opts.scaleWidth)) { if (e.attribute('width').hasValue()) { xRatio = e.attribute('width').toPixels('x') / svg.opts.scaleWidth; } else if (!isNaN(viewBox[2])) { @@ -4612,7 +4654,7 @@ var canvg = (function (exports) { } } - if (svg.opts.scaleHeight != null) { + if (!isNullish(svg.opts.scaleHeight)) { if (e.attribute('height').hasValue()) { yRatio = e.attribute('height').toPixels('y') / svg.opts.scaleHeight; } else if (!isNaN(viewBox[3])) { @@ -4620,11 +4662,11 @@ var canvg = (function (exports) { } } - if (xRatio == null) { + if (isNullish(xRatio)) { xRatio = yRatio; } - if (yRatio == null) { + if (isNullish(yRatio)) { yRatio = xRatio; } @@ -4658,13 +4700,14 @@ var canvg = (function (exports) { if (svg.opts.ignoreMouse !== true) { - needUpdate = needUpdate | svg.Mouse.hasEvents(); + needUpdate = needUpdate || svg.Mouse.hasEvents(); } // need update from animations? if (svg.opts.ignoreAnimation !== true) { svg.Animations.forEach(function (animation) { - needUpdate = needUpdate | animation.update(1000 / svg.FRAMERATE); + var needAnimationUpdate = animation.update(1000 / svg.FRAMERATE); + needUpdate = needUpdate || needAnimationUpdate; }); } // need update from redraw? @@ -4680,8 +4723,10 @@ var canvg = (function (exports) { draw(res); svg.Mouse.runEvents(); // run and clear our events } - }, 1000 / svg.FRAMERATE); + }, 1000 / svg.FRAMERATE); // Todo: Replace with an image loading Promise utility? + return new Promise(function (resolve, reject) { + // eslint-disable-line promise/avoid-new if (svg.ImagesLoaded()) { waitingForImages = false; draw(resolve); @@ -4727,9 +4772,9 @@ var canvg = (function (exports) { checkPath: function checkPath(element, ctx) { var _this26 = this; - this.events.forEach(function (_ref5, i) { - var x = _ref5.x, - y = _ref5.y; + this.events.forEach(function (_ref13, i) { + var x = _ref13.x, + y = _ref13.y; if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { _this26.eventElements[i] = element; @@ -4739,9 +4784,9 @@ var canvg = (function (exports) { checkBoundingBox: function checkBoundingBox(element, bb) { var _this27 = this; - this.events.forEach(function (_ref6, i) { - var x = _ref6.x, - y = _ref6.y; + this.events.forEach(function (_ref14, i) { + var x = _ref14.x, + y = _ref14.y; if (bb.isPointInBox(x, y)) { _this27.eventElements[i] = element; @@ -4783,7 +4828,6 @@ var canvg = (function (exports) { }; } - exports.setStackBlurCanvasRGBA = setStackBlurCanvasRGBA; exports.canvg = canvg; return exports; diff --git a/dist/dom-polyfill.js b/dist/dom-polyfill.js index 3ace743b..ddcfed73 100644 --- a/dist/dom-polyfill.js +++ b/dist/dom-polyfill.js @@ -2,6 +2,17 @@ 'use strict'; // From https://github.com/inexorabletash/polyfill/blob/master/dom.js + + /** + * @module DOMPolyfill + */ + + /** + * + * @param {Node} o + * @param {module:DOMPolyfill~ParentNode|module:DOMPolyfill~ChildNode} ps + * @returns {undefined} + */ function mixin(o, ps) { if (!o) return; Object.keys(ps).forEach(function (p) { @@ -17,6 +28,12 @@ } }); } + /** + * + * @param {Node[]} nodes + * @returns {Node} + */ + function convertNodesIntoANode(nodes) { nodes = nodes.map(function (node) { diff --git a/dist/extensions/ext-arrows.js b/dist/extensions/ext-arrows.js index 90ff8a20..94908b34 100644 --- a/dist/extensions/ext-arrows.js +++ b/dist/extensions/ext-arrows.js @@ -37,8 +37,6 @@ var svgEditorExtension_arrows = (function () { }; } - /* globals jQuery */ - /** * ext-arrows.js * @@ -53,12 +51,12 @@ var svgEditorExtension_arrows = (function () { var _init = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee2(S) { - var strings, svgEditor, svgCanvas, $, addElem, nonce, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; + var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: - colorChanged = function _ref9(elem) { + colorChanged = function _ref10(elem) { var color = elem.getAttribute('stroke'); var mtypes = ['start', 'mid', 'end']; var defs = svgCanvas.findDefs(); @@ -84,7 +82,7 @@ var svgEditorExtension_arrows = (function () { if (attrs.fill === color && attrs.d === curD) { // Found another marker with this color and this path - newMarker = this; + newMarker = this; // eslint-disable-line consistent-this } }); @@ -100,17 +98,22 @@ var svgEditorExtension_arrows = (function () { var remove = true; $(S.svgcontent).find('line, polyline, path, polygon').each(function () { - var elem = this; + var element = this; // eslint-disable-line consistent-this + $.each(mtypes, function (j, mtype) { - if ($(elem).attr('marker-' + mtype) === 'url(#' + marker.id + ')') { + if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') { remove = false; return remove; } + + return undefined; }); if (!remove) { return false; } + + return undefined; }); // Not found, so can safely remove if (remove) { @@ -119,7 +122,7 @@ var svgEditorExtension_arrows = (function () { }); }; - setArrow = function _ref8() { + setArrow = function _ref9() { resetMarker(); var type = this.value; @@ -147,7 +150,7 @@ var svgEditorExtension_arrows = (function () { svgCanvas.call('changed', selElems); }; - addMarker = function _ref7(dir, type, id) { + addMarker = function _ref8(dir, type, id) { // TODO: Make marker (or use?) per arrow type, since refX can be different id = id || arrowprefix + dir; var data = pathdata[dir]; @@ -188,14 +191,14 @@ var svgEditorExtension_arrows = (function () { return marker; }; - resetMarker = function _ref6() { + resetMarker = function _ref7() { var el = selElems[0]; el.removeAttribute('marker-start'); el.removeAttribute('marker-mid'); el.removeAttribute('marker-end'); }; - showPanel = function _ref5(on) { + showPanel = function _ref6(on) { $('#arrow_panel').toggle(on); if (on) { @@ -227,7 +230,7 @@ var svgEditorExtension_arrows = (function () { } }; - getLinked = function _ref4(elem, attr) { + getLinked = function _ref5(elem, attr) { var str = elem.getAttribute(attr); if (!str) { @@ -243,14 +246,14 @@ var svgEditorExtension_arrows = (function () { return svgCanvas.getElem(m[1]); }; - unsetArrowNonce = function _ref3(window) { + unsetArrowNonce = function _ref4(win) { randomizeIds = false; arrowprefix = prefix; pathdata.fw.id = arrowprefix + 'fw'; pathdata.bk.id = arrowprefix + 'bk'; }; - setArrowNonce = function _ref2(window, n) { + setArrowNonce = function _ref3(win, n) { randomizeIds = true; arrowprefix = prefix + n + '_'; pathdata.fw.id = arrowprefix + 'fw'; @@ -264,10 +267,15 @@ var svgEditorExtension_arrows = (function () { strings = _context2.sent; svgEditor = this; svgCanvas = svgEditor.canvas; - $ = jQuery; // {svgcontent} = S, - addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, prefix = 'se_arrow_'; + addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, $ = S.$, prefix = 'se_arrow_'; randomizeIds = S.randomize_ids; + /** + * @param {Window} win + * @param {!(string|Integer)} n + * @returns {undefined} + */ + svgCanvas.bind('setnonce', setArrowNonce); svgCanvas.bind('unsetnonce', unsetArrowNonce); @@ -289,6 +297,13 @@ var svgEditorExtension_arrows = (function () { id: arrowprefix + 'bk' } }; + /** + * Gets linked element. + * @param {Element} elem + * @param {string} attr + * @returns {Element} + */ + contextTools = [{ type: 'select', panel: 'arrow_panel', @@ -312,7 +327,8 @@ var svgEditorExtension_arrows = (function () { var _addLangData = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(_ref) { - var lang, importLocale, strings; + var lang, importLocale, _ref2, langList; + return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { @@ -322,12 +338,13 @@ var svgEditorExtension_arrows = (function () { return importLocale(); case 3: - strings = _context.sent; + _ref2 = _context.sent; + langList = _ref2.langList; return _context.abrupt("return", { - data: strings.langList + data: langList }); - case 5: + case 6: case "end": return _context.stop(); } @@ -372,7 +389,7 @@ var svgEditorExtension_arrows = (function () { } }); - case 22: + case 21: case "end": return _context2.stop(); } diff --git a/dist/extensions/ext-closepath.js b/dist/extensions/ext-closepath.js index fe4fad06..39a84fd7 100644 --- a/dist/extensions/ext-closepath.js +++ b/dist/extensions/ext-closepath.js @@ -37,8 +37,6 @@ var svgEditorExtension_closepath = (function () { }; } - /* globals jQuery */ - /** * ext-closepath.js * @@ -55,18 +53,17 @@ var svgEditorExtension_closepath = (function () { var _init = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(_ref) { - var importLocale, strings, $, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; + var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: - importLocale = _ref.importLocale; + importLocale = _ref.importLocale, $ = _ref.$; _context.next = 3; return importLocale(); case 3: strings = _context.sent; - $ = jQuery; svgEditor = this; updateButton = function updateButton(path) { @@ -157,7 +154,7 @@ var svgEditorExtension_closepath = (function () { } }); - case 11: + case 10: case "end": return _context.stop(); } diff --git a/dist/extensions/ext-connector.js b/dist/extensions/ext-connector.js index d2821767..ce0a73ff 100644 --- a/dist/extensions/ext-connector.js +++ b/dist/extensions/ext-connector.js @@ -37,8 +37,6 @@ var svgEditorExtension_connector = (function () { }; } - /* globals jQuery */ - /** * ext-connector.js * @@ -52,11 +50,11 @@ var svgEditorExtension_connector = (function () { init: function () { var _init = _asyncToGenerator( /*#__PURE__*/ - regeneratorRuntime.mark(function _callee2(S) { - var $, svgEditor, svgCanvas, getElem, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons; - return regeneratorRuntime.wrap(function _callee2$(_context2) { + regeneratorRuntime.mark(function _callee(S) { + var svgEditor, svgCanvas, getElem, $, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons; + return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context.prev = _context.next) { case 0: init = function _ref9() { // Make sure all connectors have data set @@ -133,6 +131,10 @@ var svgEditorExtension_connector = (function () { connectors.each(function () { var addThis; + /** + * + * @returns {undefined} + */ function add() { if (elems.includes(this)) { @@ -147,14 +149,15 @@ var svgEditorExtension_connector = (function () { var key = 'c_' + pos; var part = elData(this, key); - if (part == null) { + if (part === null || part === undefined) { + // Does this ever return nullish values? part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]); elData(this, 'c_' + pos, part.id); elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part])); } else part = document.getElementById(part); parts.push(part); - }.bind(this)); + }, this); for (var i = 0; i < 2; i++) { var cElem = parts[i]; @@ -257,7 +260,7 @@ var svgEditorExtension_connector = (function () { }; getOffset = function _ref3(side, line) { - var giveOffset = !!line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off'); + var giveOffset = line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off'); // TODO: Make this number (5) be based on marker width/height var size = line.getAttribute('stroke-width') * 5; @@ -293,17 +296,24 @@ var svgEditorExtension_connector = (function () { }; }; - $ = jQuery; svgEditor = this; svgCanvas = svgEditor.canvas; getElem = svgCanvas.getElem; - svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data; - _context2.next = 15; + $ = S.$, svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data; + _context.next = 14; return importLocale(); - case 15: - strings = _context2.sent; + case 14: + strings = _context.sent; svgcontent = S.svgcontent, started = false, connections = [], selElems = []; + /** + * + * @param {Float} x + * @param {Float} y + * @param {module:utilities.BBoxObject} bb + * @param {Float} offset + * @returns {module:math.XYObject} + */ // Do once (function () { @@ -311,19 +321,32 @@ var svgEditorExtension_connector = (function () { svgCanvas.groupSelectedElements = function () { svgCanvas.removeFromSelection($(connSel).toArray()); - return gse.apply(this, arguments); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return gse.apply(this, args); }; var mse = svgCanvas.moveSelectedElements; svgCanvas.moveSelectedElements = function () { - var cmd = mse.apply(this, arguments); + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + var cmd = mse.apply(this, args); updateConnectors(); return cmd; }; seNs = svgCanvas.getEditorNS(); - })(); // Do on reset + })(); + /** + * Do on reset. + * @returns {undefined} + */ // $(svgroot).parent().mousemove(function (e) { @@ -351,38 +374,21 @@ var svgEditorExtension_connector = (function () { } } }]; - return _context2.abrupt("return", { + return _context.abrupt("return", { name: strings.name, svgicons: svgEditor.curConfig.imgPath + 'conn.svg', buttons: strings.buttons.map(function (button, i) { return Object.assign(buttons[i], button); }), - addLangData: function () { - var _addLangData = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var lang, importLocale; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - lang = _ref.lang, importLocale = _ref.importLocale; - return _context.abrupt("return", { - data: strings.langList - }); - case 2: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - return function addLangData(_x2) { - return _addLangData.apply(this, arguments); + /* async */ + addLangData: function addLangData(_ref) { + var lang = _ref.lang; + // , importLocale: importLoc + return { + data: strings.langList }; - }(), + }, mouseDown: function mouseDown(opts) { var e = opts.event; startX = opts.start_x; @@ -392,7 +398,7 @@ var svgEditorExtension_connector = (function () { if (mode === 'connector') { if (started) { - return; + return undefined; } var mouseTarget = e.target; @@ -431,6 +437,8 @@ var svgEditorExtension_connector = (function () { if (mode === 'select') { findConnectors(); } + + return undefined; }, mouseMove: function mouseMove(opts) { var zoom = svgCanvas.getZoom(); // const e = opts.event; @@ -476,7 +484,7 @@ var svgEditorExtension_connector = (function () { var mouseTarget = e.target; if (svgCanvas.getMode() !== 'connector') { - return; + return undefined; } var fo = $(mouseTarget).closest('foreignObject'); @@ -521,6 +529,8 @@ var svgEditorExtension_connector = (function () { if (conn === connStr || conn === altStr) { return true; } + + return false; }); if (dupe.length) { @@ -598,7 +608,7 @@ var svgEditorExtension_connector = (function () { var mid = elem.getAttribute('marker-mid'); var end = elem.getAttribute('marker-end'); curLine = elem; - $(elem).data('start_off', !!start).data('end_off', !!end); + $(elem).data('start_off', Boolean(start)).data('end_off', Boolean(end)); if (elem.tagName === 'line' && mid) { // Convert to polyline to accept mid-arrow @@ -666,12 +676,12 @@ var svgEditorExtension_connector = (function () { } }); - case 20: + case 19: case "end": - return _context2.stop(); + return _context.stop(); } } - }, _callee2, this); + }, _callee, this); })); return function init(_x) { diff --git a/dist/extensions/ext-eyedropper.js b/dist/extensions/ext-eyedropper.js index d8a007e2..54c3f314 100644 --- a/dist/extensions/ext-eyedropper.js +++ b/dist/extensions/ext-eyedropper.js @@ -37,8 +37,6 @@ var svgEditorExtension_eyedropper = (function () { }; } - /* globals jQuery */ - /** * ext-eyedropper.js * @@ -94,8 +92,7 @@ var svgEditorExtension_eyedropper = (function () { case 3: strings = _context.sent; svgEditor = this; - $ = jQuery; - ChangeElementCommand = S.ChangeElementCommand, svgCanvas = svgEditor.canvas, addToHistory = function addToHistory(cmd) { + $ = S.$, ChangeElementCommand = S.ChangeElementCommand, svgCanvas = svgEditor.canvas, addToHistory = function addToHistory(cmd) { svgCanvas.undoMgr.addCommandToHistory(cmd); }, currentStyle = { fillPaint: 'red', @@ -108,6 +105,12 @@ var svgEditorExtension_eyedropper = (function () { strokeLinecap: 'butt', strokeLinejoin: 'miter' }; + /** + * + * @param {module:svgcanvas.SvgCanvas#event:ext-selectedChanged|module:svgcanvas.SvgCanvas#event:ext-elementChanged} opts + * @returns {undefined} + */ + buttons = [{ id: 'tool_eyedropper', icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png', @@ -184,7 +187,7 @@ var svgEditorExtension_eyedropper = (function () { } }); - case 9: + case 8: case "end": return _context.stop(); } diff --git a/dist/extensions/ext-foreignobject.js b/dist/extensions/ext-foreignobject.js index 81db9f8c..702acb74 100644 --- a/dist/extensions/ext-foreignobject.js +++ b/dist/extensions/ext-foreignobject.js @@ -37,8 +37,6 @@ var svgEditorExtension_foreignobject = (function () { }; } - /* globals jQuery */ - /** * ext-foreignobject.js * @@ -52,18 +50,18 @@ var svgEditorExtension_foreignobject = (function () { init: function () { var _init = _asyncToGenerator( /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(S) { - var svgEditor, text2xml, NS, importLocale, $, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; - return regeneratorRuntime.wrap(function _callee$(_context) { + regeneratorRuntime.mark(function _callee2(S) { + var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; + return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { - switch (_context.prev = _context.next) { + switch (_context2.prev = _context2.next) { case 0: - setAttr = function _ref5(attr, val) { + setAttr = function _ref6(attr, val) { svgCanvas.changeSelectedAttribute(attr, val); svgCanvas.call('changed', selElems); }; - showForeignEditor = function _ref4() { + showForeignEditor = function _ref5() { var elt = selElems[0]; if (!elt || editingforeign) { @@ -80,8 +78,8 @@ var svgEditorExtension_foreignobject = (function () { $('#svg_source_textarea').focus(); }; - setForeignString = function _ref3(xmlString) { - var elt = selElems[0]; + setForeignString = function _ref4(xmlString) { + var elt = selElems[0]; // The parent `Element` to append to try { // convert string into XML document @@ -92,19 +90,21 @@ var svgEditorExtension_foreignobject = (function () { svgCanvas.call('changed', [elt]); svgCanvas.clearSelection(); } catch (e) { - console.log(e); + // Todo: Surface error to user + console.log(e); // eslint-disable-line no-console + return false; } return true; }; - toggleSourceButtons = function _ref2(on) { + toggleSourceButtons = function _ref3(on) { $('#tool_source_save, #tool_source_cancel').toggle(!on); $('#foreign_save, #foreign_cancel').toggle(on); }; - showPanel = function _ref(on) { + showPanel = function _ref2(on) { var fcRules = $('#fc_rules'); if (!fcRules.length) { @@ -116,27 +116,30 @@ var svgEditorExtension_foreignobject = (function () { }; svgEditor = this; - text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale; - $ = jQuery; + $ = S.$, text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale; svgCanvas = svgEditor.canvas; svgdoc = S.svgroot.parentNode.ownerDocument; - _context.next = 12; + _context2.next = 11; return importLocale(); - case 12: - strings = _context.sent; + case 11: + strings = _context2.sent; properlySourceSizeTextArea = function properlySourceSizeTextArea() { // TODO: remove magic numbers here and get values from CSS var height = $('#svg_source_container').height() - 80; $('#svg_source_textarea').css('height', height); }; + /** + * @param {boolean} on + * @returns {undefined} + */ + editingforeign = false; /** * This function sets the content of element elt to the input XML. * @param {string} xmlString - The XML text - * @param {Element} elt - the parent element to append to * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise. */ @@ -191,7 +194,7 @@ var svgEditorExtension_foreignobject = (function () { } } }]; - return _context.abrupt("return", { + return _context2.abrupt("return", { name: strings.name, svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml', buttons: strings.buttons.map(function (button, i) { @@ -215,24 +218,57 @@ var svgEditorExtension_foreignobject = (function () { // Create source save/cancel buttons /* const save = */ - $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click(function () { - if (!editingforeign) { - return; - } + $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click( + /*#__PURE__*/ + _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee() { + var ok; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (editingforeign) { + _context.next = 2; + break; + } - if (!setForeignString($('#svg_source_textarea').val())) { - $.confirm('Errors found. Revert to original?', function (ok) { - if (!ok) { - return false; + return _context.abrupt("return"); + + case 2: + if (setForeignString($('#svg_source_textarea').val())) { + _context.next = 11; + break; + } + + _context.next = 5; + return $.confirm('Errors found. Revert to original?'); + + case 5: + ok = _context.sent; + + if (ok) { + _context.next = 8; + break; + } + + return _context.abrupt("return"); + + case 8: + endChanges(); + _context.next = 12; + break; + + case 11: + endChanges(); + + case 12: + case "end": + return _context.stop(); } - - endChanges(); - }); - } else { - endChanges(); - } // setSelectMode(); - - }); + } + }, _callee, this); + }))); /* const cancel = */ $('#tool_source_cancel').clone().hide().attr('id', 'foreign_cancel').unbind().appendTo('#tool_source_back').click(function () { @@ -242,49 +278,53 @@ var svgEditorExtension_foreignobject = (function () { }, mouseDown: function mouseDown(opts) { // const e = opts.event; - if (svgCanvas.getMode() === 'foreign') { - started = true; - newFO = svgCanvas.addSVGElementFromJson({ - element: 'foreignObject', - attr: { - x: opts.start_x, - y: opts.start_y, - id: svgCanvas.getNextId(), - 'font-size': 16, - // cur_text.font_size, - width: '48', - height: '20', - style: 'pointer-events:inherit' - } - }); - var m = svgdoc.createElementNS(NS.MATH, 'math'); - m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH); - m.setAttribute('display', 'inline'); - var mi = svgdoc.createElementNS(NS.MATH, 'mi'); - mi.setAttribute('mathvariant', 'normal'); - mi.textContent = "\u03A6"; - var mo = svgdoc.createElementNS(NS.MATH, 'mo'); - mo.textContent = "\u222A"; - var mi2 = svgdoc.createElementNS(NS.MATH, 'mi'); - mi2.textContent = "\u2133"; - m.append(mi, mo, mi2); - newFO.append(m); - return { - started: true - }; + if (svgCanvas.getMode() !== 'foreign') { + return undefined; } + + started = true; + newFO = svgCanvas.addSVGElementFromJson({ + element: 'foreignObject', + attr: { + x: opts.start_x, + y: opts.start_y, + id: svgCanvas.getNextId(), + 'font-size': 16, + // cur_text.font_size, + width: '48', + height: '20', + style: 'pointer-events:inherit' + } + }); + var m = svgdoc.createElementNS(NS.MATH, 'math'); + m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH); + m.setAttribute('display', 'inline'); + var mi = svgdoc.createElementNS(NS.MATH, 'mi'); + mi.setAttribute('mathvariant', 'normal'); + mi.textContent = "\u03A6"; + var mo = svgdoc.createElementNS(NS.MATH, 'mo'); + mo.textContent = "\u222A"; + var mi2 = svgdoc.createElementNS(NS.MATH, 'mi'); + mi2.textContent = "\u2133"; + m.append(mi, mo, mi2); + newFO.append(m); + return { + started: true + }; }, mouseUp: function mouseUp(opts) { // const e = opts.event; - if (svgCanvas.getMode() === 'foreign' && started) { - var attrs = $(newFO).attr(['width', 'height']); - var keep = attrs.width !== '0' || attrs.height !== '0'; - svgCanvas.addToSelection([newFO], true); - return { - keep: keep, - element: newFO - }; + if (svgCanvas.getMode() !== 'foreign' || !started) { + return undefined; } + + var attrs = $(newFO).attr(['width', 'height']); + var keep = attrs.width !== '0' || attrs.height !== '0'; + svgCanvas.addToSelection([newFO], true); + return { + keep: keep, + element: newFO + }; }, selectedChanged: function selectedChanged(opts) { // Use this to update the current selected elements @@ -311,12 +351,12 @@ var svgEditorExtension_foreignobject = (function () { elementChanged: function elementChanged(opts) {} }); - case 18: + case 17: case "end": - return _context.stop(); + return _context2.stop(); } } - }, _callee, this); + }, _callee2, this); })); return function init(_x) { diff --git a/dist/extensions/ext-grid.js b/dist/extensions/ext-grid.js index 9eb33479..35d3568c 100644 --- a/dist/extensions/ext-grid.js +++ b/dist/extensions/ext-grid.js @@ -37,8 +37,6 @@ var svgEditorExtension_grid = (function () { }; } - /* globals jQuery */ - /** * ext-grid.js * @@ -53,7 +51,7 @@ var svgEditorExtension_grid = (function () { var _init = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(_ref) { - var NS, getTypeMap, importLocale, strings, svgEditor, $, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons; + var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { @@ -121,14 +119,13 @@ var svgEditorExtension_grid = (function () { svgCanvas.setHref(gridimg, datauri); }; - NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale; + $ = _ref.$, NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale; _context.next = 5; return importLocale(); case 5: strings = _context.sent; svgEditor = this; - $ = jQuery; svgCanvas = svgEditor.canvas; svgdoc = document.getElementById('svgcanvas').ownerDocument, assignAttributes = svgCanvas.assignAttributes, hcanvas = document.createElement('canvas'), canvBG = $('#canvasBackground'), units = getTypeMap(), intervals = [0.01, 0.1, 1, 10, 100, 1000]; showGrid = svgEditor.curConfig.showGrid || false; @@ -178,6 +175,12 @@ var svgEditorExtension_grid = (function () { style: 'pointer-events: none; display:visible;' }); $('#canvasGrid').append(gridBox); + /** + * + * @param {Float} zoom + * @returns {undefined} + */ + buttons = [{ id: 'view_grid', icon: svgEditor.curConfig.extIconsPath + 'grid.png', @@ -208,7 +211,7 @@ var svgEditorExtension_grid = (function () { }) }); - case 26: + case 25: case "end": return _context.stop(); } diff --git a/dist/extensions/ext-helloworld.js b/dist/extensions/ext-helloworld.js index 9f3257dd..72146cc7 100644 --- a/dist/extensions/ext-helloworld.js +++ b/dist/extensions/ext-helloworld.js @@ -75,8 +75,6 @@ var svgEditorExtension_helloworld = (function () { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - /* globals jQuery */ - /** * ext-helloworld.js * @@ -97,19 +95,18 @@ var svgEditorExtension_helloworld = (function () { var _init = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(_ref) { - var importLocale, strings, svgEditor, $, svgCanvas; + var $, importLocale, strings, svgEditor, svgCanvas; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: - importLocale = _ref.importLocale; + $ = _ref.$, importLocale = _ref.importLocale; _context.next = 3; return importLocale(); case 3: strings = _context.sent; svgEditor = this; - $ = jQuery; svgCanvas = svgEditor.canvas; return _context.abrupt("return", { name: strings.name, @@ -148,6 +145,8 @@ var svgEditorExtension_helloworld = (function () { started: true }; } + + return undefined; }, // This is triggered from anywhere, but "started" must have been set // to true (see above). Note that "opts" is an object with event info @@ -173,7 +172,7 @@ var svgEditorExtension_helloworld = (function () { } }); - case 8: + case 7: case "end": return _context.stop(); } diff --git a/dist/extensions/ext-imagelib.js b/dist/extensions/ext-imagelib.js index 7ce2c824..b3ac4657 100644 --- a/dist/extensions/ext-imagelib.js +++ b/dist/extensions/ext-imagelib.js @@ -51,8 +51,6 @@ var svgEditorExtension_imagelib = (function () { }; } - /* globals jQuery */ - /** * ext-imagelib.js * @@ -66,13 +64,13 @@ var svgEditorExtension_imagelib = (function () { init: function () { var _init = _asyncToGenerator( /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, $, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { + regeneratorRuntime.mark(function _callee2(_ref) { + var $, decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons; + return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { - switch (_context.prev = _context.next) { + switch (_context2.prev = _context2.next) { case 0: - showBrowser = function _ref9() { + showBrowser = function _ref10() { var browser = $('#imgbrowse'); if (!browser.length) { @@ -128,10 +126,10 @@ var svgEditorExtension_imagelib = (function () { }); cancel.prepend($.getSvgIcon('cancel', true)); back.prepend($.getSvgIcon('tool_imagelib', true)); - imagelibStrings.imgLibs.forEach(function (_ref5) { - var name = _ref5.name, - url = _ref5.url, - description = _ref5.description; + imagelibStrings.imgLibs.forEach(function (_ref6) { + var name = _ref6.name, + url = _ref6.url, + description = _ref6.description; $('
  • ').appendTo(libOpts).text(name).on('click touchend', function () { frame.attr('src', url).show(); header.text(name); @@ -144,7 +142,7 @@ var svgEditorExtension_imagelib = (function () { } }; - toggleMulti = function _ref8(show) { + toggleMulti = function _ref9(show) { $('#lib_framewrap, #imglib_opts').css({ right: show ? 200 : 10 }); @@ -186,7 +184,7 @@ var svgEditorExtension_imagelib = (function () { submit.toggle(show); }; - importImage = function _ref7(url) { + importImage = function _ref8(url) { var newImage = svgCanvas.addSVGElementFromJson({ element: 'image', attr: { @@ -203,19 +201,18 @@ var svgEditorExtension_imagelib = (function () { svgCanvas.setImageURL(url); }; - closeBrowser = function _ref6() { + closeBrowser = function _ref7() { $('#imgbrowse_holder').hide(); }; - decode64 = _ref.decode64, importLocale = _ref.importLocale, dropXMLInternalSubset = _ref.dropXMLInternalSubset; - _context.next = 7; + $ = _ref.$, decode64 = _ref.decode64, importLocale = _ref.importLocale, dropXMLInternalSubset = _ref.dropXMLInternalSubset; + _context2.next = 7; return importLocale(); case 7: - imagelibStrings = _context.sent; + imagelibStrings = _context2.sent; modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false; svgEditor = this; - $ = jQuery; uiStrings = svgEditor.uiStrings, svgCanvas = svgEditor.canvas, extIconsPath = svgEditor.curConfig.extIconsPath; imagelibStrings.imgLibs = imagelibStrings.imgLibs.map(function (_ref2) { var name = _ref2.name, @@ -238,233 +235,316 @@ var svgEditorExtension_imagelib = (function () { return location.origin; } }); + /** + * + * @returns {undefined} + */ + pending = {}; mode = 's'; multiArr = []; transferStopped = false; // Receive `postMessage` data - window.addEventListener('message', function (_ref4) { - var origin = _ref4.origin, - response = _ref4.data; + window.addEventListener('message', + /*#__PURE__*/ + function () { + var _ref5 = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(_ref4) { + var origin, response, id, type, hasName, hasHref, char1, secondpos, entry, curMeta, svgStr, imgStr, name, message, pre, src, title, xml, ok; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + origin = _ref4.origin, response = _ref4.data; - if (!response || !['string', 'object'].includes(_typeof(response))) { - // Do nothing - return; - } + if (!(!response || !['string', 'object'].includes(_typeof(response)))) { + _context.next = 3; + break; + } - var id; - var type; + return _context.abrupt("return"); - try { - // Todo: This block can be removed (and the above check changed to - // insist on an object) if embedAPI moves away from a string to - // an object (if IE9 support not needed) - response = _typeof(response) === 'object' ? response : JSON.parse(response); + case 3: + _context.prev = 3; + // Todo: This block can be removed (and the above check changed to + // insist on an object) if embedAPI moves away from a string to + // an object (if IE9 support not needed) + response = _typeof(response) === 'object' ? response : JSON.parse(response); - if (response.namespace !== 'imagelib') { - return; - } + if (!(response.namespace !== 'imagelib')) { + _context.next = 7; + break; + } - if (!allowedImageLibOrigins.includes('*') && !allowedImageLibOrigins.includes(origin)) { - console.log("Origin ".concat(origin, " not whitelisted for posting to ").concat(window.origin)); - return; - } + return _context.abrupt("return"); - var hasName = 'name' in response; - var hasHref = 'href' in response; + case 7: + if (!(!allowedImageLibOrigins.includes('*') && !allowedImageLibOrigins.includes(origin))) { + _context.next = 10; + break; + } - if (!hasName && transferStopped) { - transferStopped = false; - return; - } + // Todo: Surface this error to user? + console.log("Origin ".concat(origin, " not whitelisted for posting to ").concat(window.origin)); // eslint-disable-line no-console - if (hasHref) { - id = response.href; - response = response.data; - } // Hide possible transfer dialog box + return _context.abrupt("return"); + + case 10: + hasName = 'name' in response; + hasHref = 'href' in response; + + if (!(!hasName && transferStopped)) { + _context.next = 15; + break; + } + + transferStopped = false; + return _context.abrupt("return"); + + case 15: + if (hasHref) { + id = response.href; + response = response.data; + } // Hide possible transfer dialog box - $('#dialog_box').hide(); - type = hasName ? 'meta' : response.charAt(0); - } catch (e) { - // This block is for backward compatibility (for IAN and Openclipart); - // should otherwise return - if (typeof response === 'string') { - var char1 = response.charAt(0); + $('#dialog_box').hide(); + type = hasName ? 'meta' : response.charAt(0); + _context.next = 28; + break; - if (char1 !== '{' && transferStopped) { - transferStopped = false; - return; - } + case 20: + _context.prev = 20; + _context.t0 = _context["catch"](3); - if (char1 === '|') { - var secondpos = response.indexOf('|', 1); - id = response.substr(1, secondpos - 1); - response = response.substr(secondpos + 1); - type = response.charAt(0); - } - } - } + if (!(typeof response === 'string')) { + _context.next = 28; + break; + } - var entry, curMeta, svgStr, imgStr; + char1 = response.charAt(0); - switch (type) { - case 'meta': - { - // Metadata - transferStopped = false; - curMeta = response; // Should be safe to add dynamic property as passed metadata + if (!(char1 !== '{' && transferStopped)) { + _context.next = 27; + break; + } - pending[curMeta.id] = curMeta; // lgtm [js/remote-property-injection] + transferStopped = false; + return _context.abrupt("return"); - var name = curMeta.name || 'file'; - var message = uiStrings.notification.retrieving.replace('%s', name); + case 27: + if (char1 === '|') { + secondpos = response.indexOf('|', 1); + id = response.substr(1, secondpos - 1); + response = response.substr(secondpos + 1); + type = response.charAt(0); + } - if (mode !== 'm') { - $.process_cancel(message, function () { + case 28: + _context.t1 = type; + _context.next = _context.t1 === 'meta' ? 31 : _context.t1 === '<' ? 47 : _context.t1 === 'd' ? 49 : 60; + break; + + case 31: + // Metadata + transferStopped = false; + curMeta = response; // Should be safe to add dynamic property as passed metadata + + pending[curMeta.id] = curMeta; // lgtm [js/remote-property-injection] + + name = curMeta.name || 'file'; + message = uiStrings.notification.retrieving.replace('%s', name); + + if (!(mode !== 'm')) { + _context.next = 43; + break; + } + + _context.next = 39; + return $.process_cancel(message); + + case 39: transferStopped = true; // Should a message be sent back to the frame? $('#dialog_box').hide(); - }); - } else { - entry = $('
    ').text(message).data('id', curMeta.id); - preview.append(entry); - curMeta.entry = entry; - } + _context.next = 46; + break; - return; - } + case 43: + entry = $('
    ').text(message).data('id', curMeta.id); + preview.append(entry); + curMeta.entry = entry; - case '<': - svgStr = true; - break; + case 46: + return _context.abrupt("return"); - case 'd': - { - if (response.startsWith('data:image/svg+xml')) { - var pre = 'data:image/svg+xml;base64,'; - var src = response.substring(pre.length); - response = decode64(src); - svgStr = true; - break; - } else if (response.startsWith('data:image/')) { - imgStr = true; - break; - } - } - // Else fall through + case 47: + svgStr = true; + return _context.abrupt("break", 62); - default: - // TODO: See if there's a way to base64 encode the binary data stream - // const str = 'data:;base64,' + svgedit.utilities.encode64(response, true); - // Assume it's raw image data - // importImage(str); - // Don't give warning as postMessage may have been used by something else - if (mode !== 'm') { - closeBrowser(); - } else { - pending[id].entry.remove(); - } // $.alert('Unexpected data was returned: ' + response, function() { - // if (mode !== 'm') { - // closeBrowser(); - // } else { - // pending[id].entry.remove(); - // } - // }); + case 49: + if (!response.startsWith('data:image/svg+xml')) { + _context.next = 57; + break; + } + + pre = 'data:image/svg+xml;base64,'; + src = response.substring(pre.length); + response = decode64(src); + svgStr = true; + return _context.abrupt("break", 62); + + case 57: + if (!response.startsWith('data:image/')) { + _context.next = 60; + break; + } + + imgStr = true; + return _context.abrupt("break", 62); + + case 60: + // TODO: See if there's a way to base64 encode the binary data stream + // const str = 'data:;base64,' + svgedit.utilities.encode64(response, true); + // Assume it's raw image data + // importImage(str); + // Don't give warning as postMessage may have been used by something else + if (mode !== 'm') { + closeBrowser(); + } else { + pending[id].entry.remove(); + } // await $.alert('Unexpected data was returned: ' + response, function() { + // if (mode !== 'm') { + // closeBrowser(); + // } else { + // pending[id].entry.remove(); + // } + // }); - return; - } + return _context.abrupt("return"); - switch (mode) { - case 's': - // Import one - if (svgStr) { - svgCanvas.importSvgString(response); - } else if (imgStr) { - importImage(response); - } + case 62: + _context.t2 = mode; + _context.next = _context.t2 === 's' ? 65 : _context.t2 === 'm' ? 68 : _context.t2 === 'o' ? 72 : 83; + break; - closeBrowser(); - break; + case 65: + // Import one + if (svgStr) { + svgCanvas.importSvgString(response); + } else if (imgStr) { + importImage(response); + } - case 'm': - // Import multiple - multiArr.push([svgStr ? 'svg' : 'img', response]); - curMeta = pending[id]; - var title; + closeBrowser(); + return _context.abrupt("break", 83); - if (svgStr) { - if (curMeta && curMeta.name) { - title = curMeta.name; - } else { - // Try to find a title - // `dropXMLInternalSubset` is to help prevent the billion laughs attack - var xml = new DOMParser().parseFromString(dropXMLInternalSubset(response), 'text/xml').documentElement; // lgtm [js/xml-bomb] + case 68: + // Import multiple + multiArr.push([svgStr ? 'svg' : 'img', response]); + curMeta = pending[id]; - title = $(xml).children('title').first().text() || '(SVG #' + response.length + ')'; - } - - if (curMeta) { - preview.children().each(function () { - if ($(this).data('id') === id) { - if (curMeta.preview_url) { - $(this).html($('').append($('').attr('src', curMeta.preview_url), document.createTextNode(title))); + if (svgStr) { + if (curMeta && curMeta.name) { + title = curMeta.name; } else { - $(this).text(title); + // Try to find a title + // `dropXMLInternalSubset` is to help prevent the billion laughs attack + xml = new DOMParser().parseFromString(dropXMLInternalSubset(response), 'text/xml').documentElement; // lgtm [js/xml-bomb] + + title = $(xml).children('title').first().text() || '(SVG #' + response.length + ')'; } - submit.removeAttr('disabled'); - } - }); - } else { - preview.append($('
    ').text(title)); - submit.removeAttr('disabled'); - } - } else { - if (curMeta && curMeta.preview_url) { - title = curMeta.name || ''; - } + if (curMeta) { + preview.children().each(function () { + if ($(this).data('id') === id) { + if (curMeta.preview_url) { + $(this).html($('').append($('').attr('src', curMeta.preview_url), document.createTextNode(title))); + } else { + $(this).text(title); + } - if (curMeta && curMeta.preview_url) { - entry = $('').append($('').attr('src', curMeta.preview_url), document.createTextNode(title)); - } else { - entry = $('').attr('src', response); - } + submit.removeAttr('disabled'); + } + }); + } else { + preview.append($('
    ').text(title)); + submit.removeAttr('disabled'); + } + } else { + if (curMeta && curMeta.preview_url) { + title = curMeta.name || ''; + } - if (curMeta) { - preview.children().each(function () { - if ($(this).data('id') === id) { - $(this).html(entry); - submit.removeAttr('disabled'); + if (curMeta && curMeta.preview_url) { + entry = $('').append($('').attr('src', curMeta.preview_url), document.createTextNode(title)); + } else { + entry = $('').attr('src', response); + } + + if (curMeta) { + preview.children().each(function () { + if ($(this).data('id') === id) { + $(this).html(entry); + submit.removeAttr('disabled'); + } + }); + } else { + preview.append($('
    ').append(entry)); + submit.removeAttr('disabled'); + } } - }); - } else { - preview.append($('
    ').append(entry)); - submit.removeAttr('disabled'); + + return _context.abrupt("break", 83); + + case 72: + if (svgStr) { + _context.next = 74; + break; + } + + return _context.abrupt("break", 83); + + case 74: + closeBrowser(); + _context.next = 77; + return svgEditor.openPrep(); + + case 77: + ok = _context.sent; + + if (ok) { + _context.next = 80; + break; + } + + return _context.abrupt("return"); + + case 80: + svgCanvas.clear(); + svgCanvas.setSvgString(response); // updateCanvas(); + + return _context.abrupt("break", 83); + + case 83: + case "end": + return _context.stop(); } } + }, _callee, this, [[3, 20]]); + })); - break; + return function (_x2) { + return _ref5.apply(this, arguments); + }; + }(), true); + /** + * @param {boolean} show + * @returns {undefined} + */ - case 'o': - // Open - if (!svgStr) { - break; - } - - svgEditor.openPrep(function (ok) { - if (!ok) { - return; - } - - svgCanvas.clear(); - svgCanvas.setSvgString(response); // updateCanvas(); - }); - closeBrowser(); - break; - } - }, true); buttons = [{ id: 'tool_imagelib', type: 'app_menu', @@ -475,7 +555,7 @@ var svgEditorExtension_imagelib = (function () { mouseup: showBrowser } }]; - return _context.abrupt("return", { + return _context2.abrupt("return", { svgicons: extIconsPath + 'ext-imagelib.xml', buttons: imagelibStrings.buttons.map(function (button, i) { return Object.assign(buttons[i], button); @@ -485,12 +565,12 @@ var svgEditorExtension_imagelib = (function () { } }); - case 21: + case 20: case "end": - return _context.stop(); + return _context2.stop(); } } - }, _callee, this); + }, _callee2, this); })); return function init(_x) { diff --git a/dist/extensions/ext-markers.js b/dist/extensions/ext-markers.js index e4651bd3..50537c7a 100644 --- a/dist/extensions/ext-markers.js +++ b/dist/extensions/ext-markers.js @@ -37,8 +37,6 @@ var svgEditorExtension_markers = (function () { }; } - /* globals jQuery */ - /** * ext-markers.js * @@ -74,13 +72,14 @@ var svgEditorExtension_markers = (function () { init: function () { var _init = _asyncToGenerator( /*#__PURE__*/ - regeneratorRuntime.mark(function _callee2(S) { - var strings, svgEditor, $, svgCanvas, addElem, mtypes, markerPrefix, idPrefix, markerTypes, getLinked, setIcon, selElems, showPanel, addMarker, convertline, setMarker, colorChanged, updateReferences, triggerTextEntry, showTextPrompt, setArrowFromButton, getTitle, buildButtonList, contextTools; - return regeneratorRuntime.wrap(function _callee2$(_context2) { + regeneratorRuntime.mark(function _callee3(S) { + var strings, svgEditor, $, svgCanvas, addElem, mtypes, markerPrefix, idPrefix, markerTypes, getLinked, setIcon, selElems, showPanel, addMarker, convertline, setMarker, colorChanged, updateReferences, triggerTextEntry, showTextPrompt, _showTextPrompt, setArrowFromButton, _setArrowFromButton, getTitle, buildButtonList, contextTools; + + return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { - switch (_context2.prev = _context2.next) { + switch (_context3.prev = _context3.next) { case 0: - buildButtonList = function _ref14(lang) { + buildButtonList = function _ref16() { var buttons = []; // const i = 0; /* @@ -131,42 +130,95 @@ var svgEditorExtension_markers = (function () { return buttons; }; - getTitle = function _ref13(id) { + getTitle = function _ref15(id) { var langList = strings.langList; - var item = langList.find(function (item) { - return item.id === id; + var item = langList.find(function (itm) { + return itm.id === id; }); return item ? item.title : id; }; - setArrowFromButton = function _ref12(obj) { - var parts = this.id.split('_'); - var pos = parts[1]; - var val = parts[2]; + _setArrowFromButton = function _ref14() { + _setArrowFromButton = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee2(ev) { + var parts, pos, val; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + parts = this.id.split('_'); + pos = parts[1]; + val = parts[2]; - if (parts[3]) { - val += '_' + parts[3]; - } + if (parts[3]) { + val += '_' + parts[3]; + } - if (val !== 'textmarker') { - triggerTextEntry(pos, '\\' + val); - } else { - showTextPrompt(pos); - } + if (!(val !== 'textmarker')) { + _context2.next = 8; + break; + } + + triggerTextEntry(pos, '\\' + val); + _context2.next = 10; + break; + + case 8: + _context2.next = 10; + return showTextPrompt(pos); + + case 10: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + return _setArrowFromButton.apply(this, arguments); }; - showTextPrompt = function _ref11(pos) { - var def = $('#' + pos + '_marker').val(); + setArrowFromButton = function _ref13(_x3) { + return _setArrowFromButton.apply(this, arguments); + }; - if (def.substr(0, 1) === '\\') { - def = ''; - } + _showTextPrompt = function _ref12() { + _showTextPrompt = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(pos) { + var def, txt; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + def = $('#' + pos + '_marker').val(); - $.prompt('Enter text for ' + pos + ' marker', def, function (txt) { - if (txt) { - triggerTextEntry(pos, txt); - } - }); + if (def.substr(0, 1) === '\\') { + def = ''; + } + + _context.next = 4; + return $.prompt('Enter text for ' + pos + ' marker', def); + + case 4: + txt = _context.sent; + + if (txt) { + triggerTextEntry(pos, txt); + } + + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + return _showTextPrompt.apply(this, arguments); + }; + + showTextPrompt = function _ref11(_x2) { + return _showTextPrompt.apply(this, arguments); }; triggerTextEntry = function _ref10(pos, val) { @@ -333,11 +385,11 @@ var svgEditorExtension_markers = (function () { var marker = svgCanvas.getElem(id); if (marker) { - return; + return undefined; } if (val === '' || val === '\\nomarker') { - return; + return undefined; } var el = selElems[0]; @@ -360,7 +412,7 @@ var svgEditorExtension_markers = (function () { } if (!markerTypes[seType]) { - return; + return undefined; } // an unknown type! // create a generic marker @@ -492,13 +544,13 @@ var svgEditorExtension_markers = (function () { return svgCanvas.getElem(m[1]); }; - _context2.next = 15; + _context3.next = 17; return S.importLocale(); - case 15: - strings = _context2.sent; + case 17: + strings = _context3.sent; svgEditor = this; - $ = jQuery; + $ = S.$; svgCanvas = svgEditor.canvas; addElem = svgCanvas.addSVGElementFromJson; mtypes = ['start', 'mid', 'end']; @@ -647,38 +699,21 @@ var svgEditorExtension_markers = (function () { change: setArrowFromButton } }]; - return _context2.abrupt("return", { + return _context3.abrupt("return", { name: strings.name, svgicons: svgEditor.curConfig.extIconsPath + 'markers-icons.xml', callback: function callback() { $('#marker_panel').addClass('toolset').hide(); }, - addLangData: function () { - var _addLangData = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var importLocale, lang; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - importLocale = _ref.importLocale, lang = _ref.lang; - return _context.abrupt("return", { - data: strings.langList - }); - case 2: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - return function addLangData(_x2) { - return _addLangData.apply(this, arguments); + /* async */ + addLangData: function addLangData(_ref) { + var importLocale = _ref.importLocale, + lang = _ref.lang; + return { + data: strings.langList }; - }(), + }, selectedChanged: function selectedChanged(opts) { // Use this to update the current selected elements // console.log('selectChanged',opts); @@ -716,12 +751,12 @@ var svgEditorExtension_markers = (function () { }) }); - case 27: + case 29: case "end": - return _context2.stop(); + return _context3.stop(); } } - }, _callee2, this); + }, _callee3, this); })); return function init(_x) { diff --git a/dist/extensions/ext-mathjax.js b/dist/extensions/ext-mathjax.js index d0d86ef5..9ad9ae6d 100644 --- a/dist/extensions/ext-mathjax.js +++ b/dist/extensions/ext-mathjax.js @@ -37,6 +37,14 @@ var svgEditorExtension_mathjax = (function () { }; } + /** + * Add any of the whitelisted attributes to the script tag. + * @param {HTMLScriptElement} script + * @param {PlainObject.} atts + * @returns {undefined} + */ + + function addScriptAtts(script, atts) { ['id', 'class', 'type'].forEach(function (prop) { if (prop in atts) { @@ -55,6 +63,7 @@ var svgEditorExtension_mathjax = (function () { } return new Promise(function (resolve, reject) { + // eslint-disable-line promise/avoid-new var script = document.createElement('script'); var destructor = function destructor() { @@ -87,11 +96,11 @@ var svgEditorExtension_mathjax = (function () { init: function () { var _init = _asyncToGenerator( /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var importLocale, strings, svgEditor, $, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { + regeneratorRuntime.mark(function _callee2(_ref) { + var $, importLocale, strings, svgEditor, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons; + return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { - switch (_context.prev = _context.next) { + switch (_context2.prev = _context2.next) { case 0: saveMath = function _ref2() { var code = $('#mathjax_code_textarea').val(); // displaystyle to force MathJax NOT to use the inline style. Because it is @@ -145,14 +154,13 @@ var svgEditorExtension_mathjax = (function () { }); }; - importLocale = _ref.importLocale; - _context.next = 4; + $ = _ref.$, importLocale = _ref.importLocale; + _context2.next = 4; return importLocale(); case 4: - strings = _context.sent; + strings = _context2.sent; svgEditor = this; - $ = jQuery; svgCanvas = svgEditor.canvas; // Configuration of the MathJax extention. // This will be added to the head tag before MathJax is loaded. @@ -182,7 +190,8 @@ var svgEditorExtension_mathjax = (function () { // Had been on https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG.js // Obtained Text-AMS-MML_SVG.js from https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.3/config/TeX-AMS-MML_SVG.js mathjaxSrcSecure = 'mathjax/MathJax.min.js?config=TeX-AMS-MML_SVG.js', uiStrings = svgEditor.uiStrings; - mathjaxLoaded = false; // TODO: Implement language support. Move these uiStrings to the locale files and the code to the langReady callback. + mathjaxLoaded = false; // TODO: Implement language support. Move these uiStrings to the locale files and + // the code to the langReady callback. Also i18nize alert and HTML below $.extend(uiStrings, { mathjax: { @@ -193,74 +202,110 @@ var svgEditorExtension_mathjax = (function () { title: 'Mathematics code editor' } }); + /** + * + * @returns {undefined} + */ + buttons = [{ id: 'tool_mathjax', type: 'mode', icon: svgEditor.curConfig.extIconsPath + 'mathjax.png', events: { - click: function click() { - // Only load Mathjax when needed, we don't want to strain Svg-Edit any more. - // From this point on it is very probable that it will be needed, so load it. - if (mathjaxLoaded === false) { - $('
    ' + '' + '' + '
    ' + '
    ' + '
    ' + '' + '' + '
    ' + '
    ' + 'Mathematics Editor' + '' + '' + '
    ' + '
    ' + '
    ').insertAfter('#svg_prefs').hide(); // Make the MathEditor draggable. + click: function () { + var _click = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee() { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + // Set the mode. + svgCanvas.setMode('mathjax'); // Only load Mathjax when needed, we don't want to strain Svg-Edit any more. + // From this point on it is very probable that it will be needed, so load it. - $('#mathjax_container').draggable({ - cancel: 'button,fieldset', - containment: 'window' - }); // Add functionality and picture to cancel button. + if (!(mathjaxLoaded === false)) { + _context.next = 17; + break; + } - $('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () { - $('#mathjax').hide(); - }); // Add functionality and picture to the save button. + $('
    ' + '' + '' + '
    ' + '
    ' + '
    ' + '' + '' + '
    ' + '
    ' + 'Mathematics Editor' + '' + '' + '
    ' + '
    ' + '
    ').insertAfter('#svg_prefs').hide(); // Make the MathEditor draggable. - $('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () { - saveMath(); - $('#mathjax').hide(); - }); // MathJax preprocessing has to ignore most of the page. + $('#mathjax_container').draggable({ + cancel: 'button,fieldset', + containment: 'window' + }); // Add functionality and picture to cancel button. - $('body').addClass('tex2jax_ignore'); // Now get (and run) the MathJax Library. - // Todo: insert script with modules once widely supported - // and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up - // providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998 + $('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () { + $('#mathjax').hide(); + }); // Add functionality and picture to the save button. - /* - const modularVersion = !('svgEditor' in window) || - !window.svgEditor || - window.svgEditor.modules !== false; - // Add as second argument to `importScript` - { - type: modularVersion - ? 'module' // Make this the default when widely supported - : 'text/javascript' - } - // If only using modules, just use this: - const {default: MathJax} = await importModule( // or `import()` when widely supported - svgEditor.curConfig.extIconsPath + mathjaxSrcSecure - ); - */ - // We use `extIconsPath` here for now as it does not vary with - // the modular type as does `extPath` + $('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () { + saveMath(); + $('#mathjax').hide(); + }); // MathJax preprocessing has to ignore most of the page. - importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure).then(function () { - // When MathJax is loaded get the div where the math will be rendered. - MathJax.Hub.queue.Push(function () { - math = MathJax.Hub.getAllJax('#mathjax_creator')[0]; - console.log(math); - mathjaxLoaded = true; - console.log('MathJax Loaded'); - }); - }).catch(function () { - console.log('Failed loadeing MathJax.'); - $.alert('Failed loading MathJax. You will not be able to change the mathematics.'); - }); - } // Set the mode. + $('body').addClass('tex2jax_ignore'); // Now get (and run) the MathJax Library. + // Todo: insert script with modules once widely supported + // and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up + // providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998 + /* + const modularVersion = !('svgEditor' in window) || + !window.svgEditor || + window.svgEditor.modules !== false; + // Add as second argument to `importScript` + { + type: modularVersion + ? 'module' // Make this the default when widely supported + : 'text/javascript' + } + // If only using modules, just use this: + const {default: MathJax} = await importModule( // or `import()` when widely supported + svgEditor.curConfig.extIconsPath + mathjaxSrcSecure + ); + */ + // We use `extIconsPath` here for now as it does not vary with + // the modular type as does `extPath` - svgCanvas.setMode('mathjax'); - } + _context.prev = 7; + _context.next = 10; + return importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure); + + case 10: + // When MathJax is loaded get the div where the math will be rendered. + MathJax.Hub.queue.Push(function () { + math = MathJax.Hub.getAllJax('#mathjax_creator')[0]; + console.log(math); // eslint-disable-line no-console + + mathjaxLoaded = true; + console.log('MathJax Loaded'); // eslint-disable-line no-console + }); + _context.next = 17; + break; + + case 13: + _context.prev = 13; + _context.t0 = _context["catch"](7); + console.log('Failed loading MathJax.'); // eslint-disable-line no-console + + $.alert('Failed loading MathJax. You will not be able to change the mathematics.'); + + case 17: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[7, 13]]); + })); + + return function click() { + return _click.apply(this, arguments); + }; + }() } }]; - return _context.abrupt("return", { + return _context2.abrupt("return", { name: strings.name, svgicons: svgEditor.curConfig.extIconsPath + 'mathjax-icons.xml', buttons: strings.buttons.map(function (button, i) { @@ -272,6 +317,8 @@ var svgEditorExtension_mathjax = (function () { started: true }; } + + return undefined; }, mouseUp: function mouseUp(opts) { if (svgCanvas.getMode() === 'mathjax') { @@ -285,6 +332,8 @@ var svgEditorExtension_mathjax = (function () { started: false }; // Otherwise the last selected object dissapears. } + + return undefined; }, callback: function callback() { $('').appendTo("head"),"m"!==e){var u="";$$b.each(l,function(t,n){t="#svg_editor "+t.replace(/,/g,", #svg_editor"),u+=t+"{",$$b.each(n,function(t,n){var r;"number"==typeof n?r=n*a+"px":(n[e]||n.all)&&(r=n[e]||n.all),u+=t+":"+r+";"}),u+="}"});var d="-"+o.toLowerCase()+"-";u+=t+"{"+d+"transform: scale("+a+");} #svg_editor div.toolset .toolset {"+d+"transform: scale(1); margin: 1px !important;} #svg_editor .ui-slider {"+d+"transform: scale("+1/a+");}",c.text(u)}i()};$$b.svgIcons(curConfig.imgPath+"svg_edit_icons.svg",{w:24,h:24,id_match:!1,no_img:!isWebkit(),fallback_path:curConfig.imgPath,fallback:{logo:"logo.png",select:"select.png",select_node:"select_node.png",square:"square.png",rect:"rect.png",fh_rect:"freehand-square.png",circle:"circle.png",ellipse:"ellipse.png",fh_ellipse:"freehand-circle.png",pencil:"fhpath.png",pen:"line.png",text:"text.png",path:"path.png",add_subpath:"add_subpath.png",close_path:"closepath.png",open_path:"openpath.png",image:"image.png",zoom:"zoom.png",arrow_right:"flyouth.png",arrow_right_big:"arrow_right_big.png",arrow_down:"dropdown.gif",fill:"fill.png",stroke:"stroke.png",opacity:"opacity.png",new_image:"clear.png",save:"save.png",export:"export.png",open:"open.png",import:"import.png",docprops:"document-properties.png",source:"source.png",wireframe:"wireframe.png",undo:"undo.png",redo:"redo.png",clone:"clone.png",delete:"delete.png",go_up:"go-up.png",go_down:"go-down.png",context_menu:"context_menu.png",move_bottom:"move_bottom.png",move_top:"move_top.png",to_path:"to_path.png",link_controls:"link_controls.png",reorient:"reorient.png",group_elements:"shape_group_elements.png",ungroup:"shape_ungroup.png",unlink_use:"unlink_use.png",width:"width.png",height:"height.png",c_radius:"c_radius.png",angle:"angle.png",blur:"blur.png",fontsize:"fontsize.png",align:"align.png",align_left:"align-left.png",align_center:"align-center.png",align_right:"align-right.png",align_top:"align-top.png",align_middle:"align-middle.png",align_bottom:"align-bottom.png",linecap_butt:"linecap_butt.png",linecap_square:"linecap_square.png",linecap_round:"linecap_round.png",linejoin_miter:"linejoin_miter.png",linejoin_bevel:"linejoin_bevel.png",linejoin_round:"linejoin_round.png",eye:"eye.png",no_color:"no_color.png",ok:"save.png",cancel:"cancel.png",warning:"warning.png",node_delete:"node_delete.png",node_clone:"node_clone.png",globe_link:"globe_link.png"},placement:{"#logo":"logo","#tool_clear div,#layer_new":"new_image","#tool_save div":"save","#tool_export div":"export","#tool_open div div":"open","#tool_import div div":"import","#tool_source":"source","#tool_docprops > div":"docprops","#tool_wireframe":"wireframe","#tool_undo":"undo","#tool_redo":"redo","#tool_select":"select","#tool_fhpath":"pencil","#tool_line":"pen","#tool_rect,#tools_rect_show":"rect","#tool_square":"square","#tool_fhrect":"fh_rect","#tool_ellipse,#tools_ellipse_show":"ellipse","#tool_circle":"circle","#tool_fhellipse":"fh_ellipse","#tool_path":"path","#tool_text,#layer_rename":"text","#tool_image":"image","#tool_zoom":"zoom","#tool_clone,#tool_clone_multi":"clone","#tool_node_clone":"node_clone","#layer_delete,#tool_delete,#tool_delete_multi":"delete","#tool_node_delete":"node_delete","#tool_add_subpath":"add_subpath","#tool_openclose_path":"open_path","#tool_move_top":"move_top","#tool_move_bottom":"move_bottom","#tool_topath":"to_path","#tool_node_link":"link_controls","#tool_reorient":"reorient","#tool_group_elements":"group_elements","#tool_ungroup":"ungroup","#tool_unlink_use":"unlink_use","#tool_alignleft, #tool_posleft":"align_left","#tool_aligncenter, #tool_poscenter":"align_center","#tool_alignright, #tool_posright":"align_right","#tool_aligntop, #tool_postop":"align_top","#tool_alignmiddle, #tool_posmiddle":"align_middle","#tool_alignbottom, #tool_posbottom":"align_bottom","#cur_position":"align","#linecap_butt,#cur_linecap":"linecap_butt","#linecap_round":"linecap_round","#linecap_square":"linecap_square","#linejoin_miter,#cur_linejoin":"linejoin_miter","#linejoin_round":"linejoin_round","#linejoin_bevel":"linejoin_bevel","#url_notice":"warning","#layer_up":"go_up","#layer_down":"go_down","#layer_moreopts":"context_menu","#layerlist td.layervis":"eye","#tool_source_save,#tool_docprops_save,#tool_prefs_save":"ok","#tool_source_cancel,#tool_docprops_cancel,#tool_prefs_cancel":"cancel","#rwidthLabel, #iwidthLabel":"width","#rheightLabel, #iheightLabel":"height","#cornerRadiusLabel span":"c_radius","#angleLabel":"angle","#linkLabel,#tool_make_link,#tool_make_link_multi":"globe_link","#zoomLabel":"zoom","#tool_fill label":"fill","#tool_stroke .icon_label":"stroke","#group_opacityLabel":"opacity","#blurLabel":"blur","#font_sizeLabel":"fontsize",".flyout_arrow_horiz":"arrow_right",".dropdown button, #main_button .dropdown":"arrow_down","#palette .palette_item:first, #fill_bg, #stroke_bg":"no_color"},resize:{"#logo .svg_icon":28,".flyout_arrow_horiz .svg_icon":5,".layer_button .svg_icon, #layerlist td.layervis .svg_icon":14,".dropdown button .svg_icon":7,"#main_button .dropdown .svg_icon":9,".palette_item:first .svg_icon":15,"#fill_bg .svg_icon, #stroke_bg .svg_icon":16,".toolbar_button button .svg_icon":16,".stroke_tool div div .svg_icon":20,"#tools_bottom label .svg_icon":18},callback:function(e){$$b(".toolbar_button button > svg, .toolbar_button button > img").each(function(){$$b(this).parent().prepend(this)});var t,n=$$b("#tools_left");n.length&&(t=n.offset().top+n.outerHeight());var a=$$b.pref("iconsize");function r(e){switch(e){case"jgraduate/css/jPicker.css":return 1;case"jgraduate/css/jGraduate.css":return 2;case"svg-editor.css":return 3;case"spinbtn/jQuery.SpinButton.css":return 4;default:return 1/0}}editor.setIconSize(a||($$b(window).height()a});if(curConfig.stylesheets.length){var o,s=(i=_toConsumableArray(new Set(curConfig.stylesheets))).indexOf("@default");if(s>-1)(o=i).splice.apply(o,[s,1].concat(_toConsumableArray($$b.loadingStylesheets)))}loadStylesheets(i,{acceptErrors:function(e){var t=e.stylesheetURL,n=e.reject,a=e.resolve;$$b.loadingStylesheets.includes(t)?n(new Error("Missing expected stylesheet: ".concat(t))):a()}}).then(function(){$$b("#svg_container")[0].style.visibility="visible",editor.runCallbacks()})}}),editor.canvas=svgCanvas=new SvgCanvas(document.getElementById("svgcanvas"),curConfig);var l,c,u=isMac()?"meta+":"ctrl+",d=svgCanvas.pathActions,h=svgCanvas.undoMgr,p=$$b("#workarea"),g=$$b("#cmenu_canvas"),f={fill:null,stroke:null},m=null,v=curConfig.imgPath+"logo.png",_="crosshair",b="crosshair",y="toolbars";!function(){var e=window.opener||window.parent;if(e)try{var t=new e.CustomEvent("svgEditorReady",{bubbles:!0,cancelable:!0});e.document.documentElement.dispatchEvent(t)}catch(e){}}(),function(){$$b("#dialog_container").draggable({cancel:"#dialog_content, #dialog_buttons *",containment:"window"}).css("position","absolute");var e=$$b("#dialog_box"),t=$$b("#dialog_buttons"),n=$$b("#dialog_content"),a=function(a,r,i,o,s,l,c){n.html("

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

    ")+"

    ").toggleClass("prompt","prompt"===a),t.empty();var u,d,h=$$b('').appendTo(t);if("alert"!==a&&$$b('').appendTo(t).click(function(){e.hide(),i&&i(!1)}),"prompt"===a)(u=$$b('').prependTo(t)).val(o||""),u.bind("keydown","return",function(){h.click()});else if("select"===a){var p=$$b('
    ');if(u=$$b("').appendTo(g)).val(c.value),c.tooltip&&g.attr("title",c.tooltip),d.prop("checked",!!c.checked),p.append($$b("
    ").append(g))}$$b.each(s||[],function(e,t){"object"===_typeof(t)?u.append($$b("
  • ":"
    ").attr("id",c).attr("title",t.title).addClass(a);if(t.includeWith||t.list){if(t.list){if(v.addClass("push_button"),$$b("#"+t.list+"_opts").append(v),t.isDefault){$$b("#cur_"+t.list).append(v.children().clone());var _=t.svgicon||t.id;p["#cur_"+t.list]=_}}else if(t.includeWith){var b,y=t.includeWith;i=(l=$$b(y.button)).parent(),l.parent().hasClass("tools_flyout")||(b=l[0].id.replace("tool_","tools_"),o=l.clone().attr("id",b+"_show").append($$b("
    ",{class:"flyout_arrow_horiz"})),l.before(o),i=te(b,l)),s=Wt.getButtonData(y.button),y.isDefault&&(p["#"+b+"_show"]=t.id);var x=g["#"+i[0].id]=[{sel:"#"+c,fn:t.events.click,icon:t.id,key:t.key,isDefault:Boolean(t.includeWith&&t.includeWith.isDefault)},s],C="position"in y?y.position:"last",S=i.children().length;!isNaN(C)&&C>=0&&C",{class:"flyout_arrow_horiz"})),l.before(o),(i=te(m,l)).data("isLibrary",!0),o.data("isLibrary",!0)),p["#"+m+"_show"]=t.id,g["#"+i[0].id]=[{sel:"#"+c,fn:t.events.click,icon:t.id,isDefault:!0}]):"app_menu"===t.type&&v.append("
    ").append(t.title);d||v.append(n),t.list||$$b.each(t.events,function(e,n){"click"===e&&"mode"===t.type?(isTouch()&&"click"===e&&(e="mousedown"),t.includeWith?v.bind(e,n):v.bind(e,function(){I(v)&&n()}),t.key&&($$b(document).bind("keydown",t.key,n),t.title&&v.attr("title",t.title+" ["+t.key+"]"))):v.bind(e,n)}),ee(g)}),$$b.each(u,function(){ne(this.elem,this.list,this.callback,{seticon:!0})}),!d){e.next=24;break}return e.abrupt("return",new Promise(function(e,t){$$b.svgIcons(d,{w:24,h:24,id_match:!1,no_img:!isWebkit(),fallback:h,placement:p,callback:function(t){"m"!==$$b.pref("iconsize")&&o(),c(),e()}})}));case 24:return e.abrupt("return",c());case 25:case"end":return e.stop()}},e,this)}));return function(t,n){return e.apply(this,arguments)}}();svgCanvas.bind("selected",function(e,t){var a=svgCanvas.getMode();"select"===a&&x();var r="pathedit"===a;T=1===t.length||null==t[1]?t[0]:null,G=t.length>=2&&null!=t[1],null!=T&&(r||function(){var e,t;if(null!=T)switch(T.tagName){case"use":case"image":case"foreignObject":break;case"g":case"a":var n=T.getElementsByTagName("*"),a=null;for(e=0,t=n.length;e=2&&null!=t[1]))switch(n){case"rotate":var r=svgCanvas.getRotationAngle(a);$$b("#angle").val(r),$$b("#tool_reorient").toggleClass("disabled",0===r)}svgCanvas.runExtensions("elementTransition",{elems:t})}}),svgCanvas.bind("changed",function(e,t){var n=svgCanvas.getMode();"select"===n&&x();for(var a=0;a\n'+t,isIE())P(0,!0);else{var n=document.createElement("a");n.href="data:image/svg+xml;base64,"+encode64(t),n.download="icon.svg",n.style="display: none;",document.body.append(n),n.click();var a=$$b.pref("save_notice_done");if("all"!==a){var r=uiStrings$1.notification.saveFromBrowser.replace("%s","SVG");isGecko()?t.includes("",$$b(t).parentsUntil("#svgcontent > g").andSelf().each(function(){this.id&&(a+=" > "+this.id,n+=this!==t?' > '+this.id+"":" > "+this.id)}),H=a}else H=null;$$b("#cur_context_panel").toggle(!!t).html(n),z()}),svgCanvas.bind("extension_added",re),svgCanvas.textActions.setInputElem($$b("#text")[0]);var ie='
    ';$$b.each(["#000000","#3f3f3f","#7f7f7f","#bfbfbf","#ffffff","#ff0000","#ff7f00","#ffff00","#7fff00","#00ff00","#00ff7f","#00ffff","#007fff","#0000ff","#7f00ff","#ff00ff","#ff007f","#7f0000","#7f3f00","#7f7f00","#3f7f00","#007f00","#007f3f","#007f7f","#003f7f","#00007f","#3f007f","#7f007f","#7f003f","#ffaaaa","#ffd4aa","#ffffaa","#d4ffaa","#aaffaa","#aaffd4","#aaffff","#aad4ff","#aaaaff","#d4aaff","#ffaaff","#ffaad4"],function(e,t){ie+='
    '}),$$b("#palette").append(ie);ie="",$$b.each(["#FFF","#888","#000"],function(){ie+='
    '}),$$b("#bg_blocks").append(ie);var oe=$$b("#bg_blocks div");oe.each(function(){$$b(this).click(function(){oe.removeClass("cur_background"),$$b(this).addClass("cur_background")})}),O($$b.pref("bkgd_color"),$$b.pref("bkgd_url")),$$b("#image_save_opts input").val([$$b.pref("img_save")]);var se=function(e,t){null==t&&(t=e.value),$$b("#group_opacity").val(t),e&&e.handle||$$b("#opac_slider").slider("option","value",t),svgCanvas.setOpacity(t/100)},le=function(e,t,n){null==t&&(t=e.value),$$b("#blur").val(t);var a=!1;e&&e.handle||($$b("#blur_slider").slider("option","value",t),a=!0),n?svgCanvas.setBlurNoUndo(t):svgCanvas.setBlur(t,a)};$$b("#stroke_style").change(function(){svgCanvas.setStrokeAttr("stroke-dasharray",$$b(this).val()),N()}),$$b("#stroke_linejoin").change(function(){svgCanvas.setStrokeAttr("stroke-linejoin",$$b(this).val()),N()}),$$b("select").change(function(){$$b(this).blur()});var ce,ue,de,he,pe,ge=!1;$$b("#selLayerNames").change(function(){var e=this.options[this.selectedIndex].value,t=uiStrings$1.notification.QmoveElemsToLayer.replace("%s",e),n=function(t){t&&(ge=!0,svgCanvas.moveSelectedToLayer(e),svgCanvas.clearSelection(),k())};e&&(ge?n(!0):$$b.confirm(t,n))}),$$b("#font_family").change(function(){svgCanvas.setFontFamily(this.value)}),$$b("#seg_type").change(function(){svgCanvas.setSegType($$b(this).val())}),$$b("#text").bind("keyup input",function(){svgCanvas.setTextContent(this.value)}),$$b("#image_url").change(function(){R(this.value)}),$$b("#link_url").change(function(){this.value.length?svgCanvas.setLinkURL(this.value):svgCanvas.removeHyperlink()}),$$b("#g_title").change(function(){svgCanvas.setGroupTitle(this.value)}),$$b(".attr_changer").change(function(){var e=this.getAttribute("data-attr"),t=this.value;if(!isValidUnit(e,t,T))return $$b.alert(uiStrings$1.notification.invalidAttrValGiven),this.value=T.getAttribute(e),!1;if("id"!==e&&"class"!==e)if(isNaN(t))t=svgCanvas.convertToNum(e,t);else if("px"!==curConfig.baseUnit){var n=getTypeMap();(T[e]||"pathedit"===svgCanvas.getMode()||"x"===e||"y"===e)&&(t*=n[curConfig.baseUnit])}if("id"===e){var a=T;svgCanvas.clearSelection(),a.id=t,svgCanvas.addToSelection([a],!0)}else svgCanvas.changeSelectedAttribute(e,t);this.blur()}),$$b("#palette").mouseover(function(){var e=$$b('');$$b(this).append(e),e.focus().remove()}),$$b(".palette_item").mousedown(function(e){var t,n=e.shiftKey||2===e.button?"stroke":"fill",a=$$b(this).data("rgb");"none"===a||"transparent"===a||"initial"===a?(a="none",t=new $$b.jGraduate.Paint):t=new $$b.jGraduate.Paint({alpha:100,solidColor:a.substr(1)}),f[n].setPaint(t),svgCanvas.setColor(n,a),"none"!==a&&1!==svgCanvas.getPaintOpacity(n)&&svgCanvas.setPaintOpacity(n,1),D()}).bind("contextmenu",function(e){e.preventDefault()}),$$b("#toggle_stroke_tools").on("click",function(){$$b("#tools_bottom").toggleClass("expanded")}),ce=p[0],ue=null,de=null,he=!1,pe=!1,$$b("#svgcanvas").bind("mousemove mouseup",function(e){if(!1!==he)return ce.scrollLeft-=e.clientX-ue,ce.scrollTop-=e.clientY-de,ue=e.clientX,de=e.clientY,"mouseup"===e.type&&(he=!1),!1}).mousedown(function(e){if(1===e.button||!0===pe)return he=!0,ue=e.clientX,de=e.clientY,!1}),$$b(window).mouseup(function(){he=!1}),$$b(document).bind("keydown","space",function(e){svgCanvas.spaceKey=pe=!0,e.preventDefault()}).bind("keyup","space",function(e){e.preventDefault(),svgCanvas.spaceKey=pe=!1}).bind("keydown","shift",function(e){"zoom"===svgCanvas.getMode()&&p.css("cursor",b)}).bind("keyup","shift",function(e){"zoom"===svgCanvas.getMode()&&p.css("cursor",_)}),editor.setPanning=function(e){svgCanvas.spaceKey=pe=e},function(){var e=$$b("#main_icon"),t=$$b("#main_icon span"),n=$$b("#main_menu"),a=!1,r=0,i=!0,o=!1;$$b(window).mouseup(function(t){a||(e.removeClass("buttondown"),"INPUT"!==t.target.tagName?n.fadeOut(200):o||(o=!0,$$b(t.target).click(function(){n.css("margin-left","-9999px").show()}))),a=!1}).mousedown(function(e){$$b(e.target).closest("div.tools_flyout, .contextMenu").length||$$b(".tools_flyout:visible,.contextMenu").fadeOut(250)}),t.bind("mousedown",function(){e.hasClass("buttondown")?n.fadeOut(200):(n.css("margin-left",0).show(),r||(r=n.height()),n.css("height",0).animate({height:r},200),a=!0),e.toggleClass("buttondown buttonup")}).hover(function(){a=!0}).mouseout(function(){a=!1});var s=$$b("#main_menu li");s.mouseover(function(){i="rgba(0, 0, 0, 0)"===$$b(this).css("background-color"),s.unbind("mouseover"),i&&s.mouseover(function(){this.style.backgroundColor="#FFC"}).mouseout(function(){return this.style.backgroundColor="transparent",!0})})}(),editor.addDropDown=function(e,t,n){if($$b(e).length){var a=$$b(e).find("button"),r=$$b(e).find("ul").attr("id",$$b(e)[0].id+"-list");n?$$b(e).addClass("dropup"):$$b("#option_lists").append(r),r.find("li").bind("mouseup",t);var i=!1;$$b(window).mouseup(function(e){i||(a.removeClass("down"),r.hide()),i=!1}),a.bind("mousedown",function(){if(a.hasClass("down"))r.hide();else{if(!n){var t=$$b(e).position();r.css({top:t.top+24,left:t.left-10})}r.show(),i=!0}a.toggleClass("down")}).hover(function(){i=!0}).mouseout(function(){i=!1})}},editor.addDropDown("#font_family_dropdown",function(){$$b("#font_family").val($$b(this).text()).change()}),editor.addDropDown("#opacity_dropdown",function(){if(!$$b(this).find("div").length){var e=parseInt($$b(this).text().split("%")[0],10);se(!1,e)}},!0),$$b("#opac_slider").slider({start:function(){$$b("#opacity_dropdown li:not(.special)").hide()},stop:function(){$$b("#opacity_dropdown li").show(),$$b(window).mouseup()},slide:function(e,t){se(t)}}),editor.addDropDown("#blur_dropdown",$$b.noop);var fe,me,ve=!1;$$b("#blur_slider").slider({max:10,step:.1,stop:function(e,t){ve=!1,le(t),$$b("#blur_dropdown li").show(),$$b(window).mouseup()},start:function(){ve=!0},slide:function(e,t){le(t,null,ve)}}),editor.addDropDown("#zoom_dropdown",function(){var e=$$b(this),t=e.data("val");t?Y(window,t):X({value:parseFloat(e.text())})},!0),ne("#stroke_linecap","#linecap_opts",function(){L(this,!0)},{dropUp:!0}),ne("#stroke_linejoin","#linejoin_opts",function(){L(this,!0)},{dropUp:!0}),ne("#tool_position","#position_opts",function(){var e=this.id.replace("tool_pos","").charAt(0);svgCanvas.alignSelectedElements(e,"page")},{multiclick:!0}),me=function(){$$b(fe).blur()},$$b("#svg_editor").find("button, select, input:not(#text)").focus(function(){fe=this,y="toolbars",p.mousedown(me)}).blur(function(){y="canvas",p.unbind("mousedown",me),"textedit"===svgCanvas.getMode()&&$$b("#text").focus()});var _e,be=function(){I("#tool_fhpath")&&svgCanvas.setMode("fhpath")},ye=function(){I("#tool_line")&&svgCanvas.setMode("line")},xe=function(){I("#tool_square")&&svgCanvas.setMode("square")},Ce=function(){I("#tool_rect")&&svgCanvas.setMode("rect")},Se=function(){I("#tool_fhrect")&&svgCanvas.setMode("fhrect")},we=function(){I("#tool_circle")&&svgCanvas.setMode("circle")},$e=function(){I("#tool_ellipse")&&svgCanvas.setMode("ellipse")},ke=function(){I("#tool_fhellipse")&&svgCanvas.setMode("fhellipse")},Ae=function(){I("#tool_image")&&svgCanvas.setMode("image")},Ee=function(){I("#tool_zoom")&&(svgCanvas.setMode("zoom"),p.css("cursor",_))},Pe=function(e){var t=svgCanvas.getResolution();e=e?t.zoom*e:1,$$b("#zoom").val(100*e),svgCanvas.setZoom(e),W(),j(!0)},Te=function(){I("#tool_zoom")&&(Pe(),x())},Ge=function(){I("#tool_text")&&svgCanvas.setMode("text")},Ne=function(){I("#tool_path")&&svgCanvas.setMode("path")},Le=function(){(null!=T||G)&&svgCanvas.deleteSelectedElements()},Ie=function(){(null!=T||G)&&svgCanvas.cutSelectedElements()},Me=function(){(null!=T||G)&&svgCanvas.copySelectedElements()},Re=function(){var e=svgCanvas.getZoom(),t=(p[0].scrollLeft+p.width()/2)/e-svgCanvas.contentW,n=(p[0].scrollTop+p.height()/2)/e-svgCanvas.contentH;svgCanvas.pasteElements("point",t,n)},Oe=function(){null!=T&&svgCanvas.moveToTopSelectedElement()},Be=function(){null!=T&&svgCanvas.moveToBottomSelectedElement()},Ve=function(e){null!=T&&svgCanvas.moveUpDownSelected(e)},je=function(){null!=T&&svgCanvas.convertToPath()},De=function(){null!=T&&d.reorient()},Fe=function(){(null!=T||G)&&$$b.prompt(uiStrings$1.notification.enterNewLinkURL,"http://",function(e){e&&svgCanvas.makeHyperlink(e)})},Ue=function(e,t){if(null!=T||G){if(curConfig.gridSnapping){var n=svgCanvas.getZoom()*curConfig.snappingStep;e*=n,t*=n}svgCanvas.moveSelectedElements(e,t)}},He=function(){$$b("#tool_node_link").toggleClass("push_button_pressed tool_button");var e=$$b("#tool_node_link").hasClass("push_button_pressed");d.linkControlPoints(e)},ze=function(){d.getNodePoint()&&d.clonePathNode()},qe=function(){d.getNodePoint()&&d.deletePathNode()},We=function(){var e=$$b("#tool_add_subpath"),t=!e.hasClass("push_button_pressed");e.toggleClass("push_button_pressed tool_button"),d.addSubPath(t)},Ye=function(){d.opencloseSubPath()},Xe=function(){svgCanvas.cycleElement(1)},Qe=function(){svgCanvas.cycleElement(0)},Ke=function(e,t){if(null!=T&&!G){e||(t*=-1);var n=parseFloat($$b("#angle").val())+t;svgCanvas.setRotationAngle(n),F()}},Ze=function(){var e=_slicedToArray(curConfig.dimensions,2),t=e[0],n=e[1];$$b.confirm(uiStrings$1.notification.QwantToClear,function(e){e&&(x(),svgCanvas.clear(),svgCanvas.setResolution(t,n),j(!0),Pe(),k(),F(),Q(),svgCanvas.runExtensions("onNewDocument"))})},Je=function(){return svgCanvas.setBold(!svgCanvas.getBold()),F(),!1},et=function(){return svgCanvas.setItalic(!svgCanvas.getItalic()),F(),!1},tt=function(){$$b.select("Select an image type for export: ",["PNG","JPEG","BMP","WEBP","PDF"],function(){var e=_asyncToGenerator(regeneratorRuntime.mark(function e(t){var n,a,r,i;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(a=function(){var e,t,a=uiStrings$1.notification.loadingImage;if("new"===curConfig.exportWindowType&&editor.exportWindowCt++,n=curConfig.canvasName+editor.exportWindowCt,_e)t=_e;else{if(e='\n \n \n '.concat(a,"\n \n

    ").concat(a,"

    \n "),"undefined"!=typeof URL&&URL.createObjectURL){var r=new Blob([e],{type:"text/html"});t=URL.createObjectURL(r)}else t="data:text/html;base64;charset=utf-8,"+encode64(e);_e=t}m=window.open(t,n)},t){e.next=3;break}return e.abrupt("return");case 3:if(r=isChrome(),"PDF"!==t){e.next=9;break}customExportPDF||r||a(),svgCanvas.exportPDF(n),e.next=13;break;case 9:return customExportImage||a(),i=parseInt($$b("#image-slider").val(),10)/100,e.next=13,svgCanvas.rasterExport(t,i,n);case 13:case"end":return e.stop()}},e,this)}));return function(t){return e.apply(this,arguments)}}(),function(){var e=$$b(this);"JPEG"===e.val()||"WEBP"===e.val()?$$b("#image-slider").length||$$b("
    ')).appendTo(e.parent()):$$b("#image-slider").parent().remove()})},nt=function(){svgCanvas.open()},at=function(){},rt=function(){h.getUndoStackSize()>0&&(h.undo(),k())},it=function(){h.getRedoStackSize()>0&&(h.redo(),k())},ot=function(){G?svgCanvas.groupSelectedElements():T&&svgCanvas.ungroupSelectedElement()},st=function(){svgCanvas.cloneSelectedElements(20,20)},lt=function(){var e=this.id.replace("tool_align","").charAt(0);svgCanvas.alignSelectedElements(e,$$b("#align_relative_to").val())},ct=function(){if($$b("#tool_wireframe").toggleClass("push_button_pressed tool_button"),p.toggleClass("wireframe"),!Nt){var e=$$b("#wireframe_rules");e.length?e.empty():$$b('').appendTo("head"),U()}};$$b("#svg_docprops_container, #svg_prefs_container").draggable({cancel:"button,fieldset",containment:"window"}).css("position","absolute");var ut,dt,ht=!1,pt=!1,gt=function(){if(!ht){ht=!0,$$b("#image_save_opts input").val([$$b.pref("img_save")]);var e=svgCanvas.getResolution();"px"!==curConfig.baseUnit&&(e.w=convertUnit(e.w)+curConfig.baseUnit,e.h=convertUnit(e.h)+curConfig.baseUnit),$$b("#canvas_width").val(e.w),$$b("#canvas_height").val(e.h),$$b("#canvas_title").val(svgCanvas.getDocumentTitle()),$$b("#svg_docprops").show()}},ft=function(){$$b("#svg_source_editor").hide(),A=!1,$$b("#svg_source_textarea").blur()},mt=function(){if(A){var e=function(){svgCanvas.clearSelection(),ft(),Pe(),k(),z(),Q()};svgCanvas.setSvgString($$b("#svg_source_textarea").val())?e():$$b.confirm(uiStrings$1.notification.QerrorsRevertToSource,function(t){if(!t)return!1;e()}),x()}},vt=function(){$$b("#svg_docprops").hide(),$$b("#canvas_width,#canvas_height").removeAttr("disabled"),$$b("#resolution")[0].selectedIndex=0,$$b("#image_save_opts input").val([$$b.pref("img_save")]),ht=!1},_t=function(){$$b("#svg_prefs").hide(),pt=!1},bt=function(){var e=$$b("#canvas_title").val();z(e),svgCanvas.setDocumentTitle(e);var t=$$b("#canvas_width"),n=t.val(),a=$$b("#canvas_height"),r=a.val();return"fit"===n||isValidUnit("width",n)?(t.parent().removeClass("error"),"fit"===r||isValidUnit("height",r)?(a.parent().removeClass("error"),svgCanvas.setResolution(n,r)?($$b.pref("img_save",$$b("#image_save_opts :checked").val()),j(),void vt()):($$b.alert(uiStrings$1.notification.noContentToFitTo),!1)):($$b.alert(uiStrings$1.notification.invalidAttrValGiven),a.parent().addClass("error"),!1)):($$b.alert(uiStrings$1.notification.invalidAttrValGiven),t.parent().addClass("error"),!1)},yt=editor.savePreferences=_asyncToGenerator(regeneratorRuntime.mark(function t(){var n,a,r,i;return regeneratorRuntime.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(O($$b("#bg_blocks div.cur_background").css("background-color")||"#FFF",$$b("#canvas_bg_url").val()),(n=$$b("#lang_select").val())===$$b.pref("lang")){t.next=11;break}return t.next=6,editor.putLocale(n,e,curConfig);case 6:return a=t.sent,r=a.langParam,i=a.langData,t.next=11,en(r,i);case 11:s($$b("#iconsize").val()),curConfig.gridSnapping=$$b("#grid_snapping_on")[0].checked,curConfig.snappingStep=$$b("#grid_snapping_step").val(),curConfig.gridColor=$$b("#grid_color").val(),curConfig.showRulers=$$b("#show_rulers")[0].checked,$$b("#rulers").toggle(curConfig.showRulers),curConfig.showRulers&&V(),curConfig.baseUnit=$$b("#base_unit").val(),svgCanvas.setConfig(curConfig),j(),_t();case 22:case"end":return t.stop()}},t,this)})),xt=$$b.noop,Ct=function(){$$b("#dialog_box").hide(),A||ht||pt?(A?E!==$$b("#svg_source_textarea").val()?$$b.confirm(uiStrings$1.notification.QignoreSourceChanges,function(e){e&&ft()}):ft():ht?vt():pt&&_t(),xt()):H&&svgCanvas.leaveContext()},St={width:$$b(window).width(),height:$$b(window).height()};if(isIE()&&(xt=function(){0===p[0].scrollLeft&&0===p[0].scrollTop&&(p[0].scrollLeft=c.left,p[0].scrollTop=c.top)},c={left:p[0].scrollLeft,top:p[0].scrollTop},$$b(window).resize(xt),editor.ready(function(){setTimeout(function(){xt()},500)}),p.scroll(function(){c={left:p[0].scrollLeft,top:p[0].scrollTop}})),$$b(window).resize(function(e){$$b.each(St,function(e,t){var n=$$b(window)[e]();p[0]["scroll"+("width"===e?"Left":"Top")]-=(n-t)/2,St[e]=n}),i()}),p.scroll(function(){$$b("#ruler_x").length&&($$b("#ruler_x")[0].scrollLeft=p[0].scrollLeft),$$b("#ruler_y").length&&($$b("#ruler_y")[0].scrollTop=p[0].scrollTop)}),$$b("#url_notice").click(function(){$$b.alert(this.title)}),$$b("#change_image_url").click(B),ut="tool_button_current",dt="",$$b.each(["clear","open","save","source","delete","delete_multi","paste","clone","clone_multi","move_top","move_bottom"],function(e,t){dt+=(e?",":"")+"#tool_"+t}),$$b(dt).mousedown(function(){$$b(this).addClass(ut)}).bind("mousedown mouseout",function(){$$b(this).removeClass(ut)}),$$b("#tool_undo, #tool_redo").mousedown(function(){$$b(this).hasClass("disabled")||$$b(this).addClass(ut)}).bind("mousedown mouseout",function(){$$b(this).removeClass(ut)}),isMac()&&!window.opera)for(var wt=["tool_clear","tool_save","tool_source","tool_undo","tool_redo","tool_clone"],$t=wt.length;$t--;){var kt=document.getElementById(wt[$t]);if(kt){var At=kt.title,Et=At.indexOf("Ctrl+");kt.title=[At.substr(0,Et),"Cmd+",At.substr(Et+5)].join("")}}var Pt=function(e){var t="stroke_color"===e.attr("id")?"stroke":"fill",n="stroke"===t?uiStrings$1.ui.pick_stroke_paint_opacity:uiStrings$1.ui.pick_fill_paint_opacity,a=e.offset(),r=f[t].paint;$$b("#color_picker").draggable({cancel:".jGraduate_tabs, .jGraduate_colPick, .jGraduate_gradPick, .jPicker",containment:"window"}).css(curConfig.colorPickerCSS||{left:a.left-140,bottom:40}).jGraduate({paint:r,window:{pickerTitle:n},images:{clientPath:curConfig.jGraduatePath},newstop:"inverse"},function(e){r=new $$b.jGraduate.Paint(e),f[t].setPaint(r),svgCanvas.setPaint(t,r),$$b("#color_picker").hide()},function(){$$b("#color_picker").hide()})},Tt=function(e,t){var n,a,r=curConfig["fill"===t?"initFill":"initStroke"],i=(new DOMParser).parseFromString('\n \n \n '),"text/xml").documentElement;(i=$$b(e)[0].appendChild(document.importNode(i,!0))).setAttribute("width",16.5),this.rect=i.firstElementChild,this.defs=i.getElementsByTagName("defs")[0],this.grad=this.defs.firstElementChild,this.paint=new $$b.jGraduate.Paint({solidColor:r.color}),this.type=t,this.setPaint=function(e,t){this.paint=e;var r=e.type,i=e.alpha/100,o="none";switch(r){case"solidColor":o="none"!==e[r]?"#"+e[r]:e[r];break;case"linearGradient":case"radialGradient":this.grad.remove(),this.grad=this.defs.appendChild(e[r]),o="url(#"+(this.grad.id="gradbox_"+this.type)+")"}this.rect.setAttribute("fill",o),this.rect.setAttribute("opacity",i),t&&(svgCanvas.setColor(this.type,n,!0),svgCanvas.setPaintOpacity(this.type,a,!0))},this.update=function(e){if(T){var t=this.type;switch(T.tagName){case"use":case"image":case"foreignObject":return;case"g":case"a":for(var r=T.getElementsByTagName("*"),i=null,o=0,s=r.length;o0||n300?t=300-n:n+t<2&&(t=2-n),0!==t&&(Bt-=t,Dt(t))}},Ut=function(e){var t=$$b("#sidepanels").width();Dt((t>2||e?2:150)-t)};$$b("#sidepanel_handle").mousedown(function(e){Bt=e.pageX,$$b(window).mousemove(Ft),jt=!1,setTimeout(function(){jt=!0},20)}).mouseup(function(e){Vt||Ut(),Bt=-1,Vt=!1}),$$b(window).mouseup(function(){Bt=-1,Vt=!1,$$b("#svg_editor").unbind("mousemove",Ft)}),k();$$b(window).bind("load resize",function(){p.css("line-height",p.height()+"px")}),$$b("#resolution").change(function(){var e=$$b("#canvas_width,#canvas_height");if(this.selectedIndex)if("content"===this.value)e.val("fit").attr("disabled","disabled");else{var t=this.value.split("x");$$b("#canvas_width").val(t[0]),$$b("#canvas_height").val(t[1]),e.removeAttr("disabled")}else"fit"===$$b("#canvas_width").val()&&e.removeAttr("disabled").val(100)}),$$b("input,select").attr("autocomplete","off");var Ht,zt,qt=["#tool_source_cancel","#tool_docprops_cancel","#tool_prefs_cancel",".overlay"],Wt=(Ht=[{sel:"#tool_select",fn:M,evt:"click",key:["V",!0]},{sel:"#tool_fhpath",fn:be,evt:"click",key:["Q",!0]},{sel:"#tool_line",fn:ye,evt:"click",key:["L",!0],parent:"#tools_line",prepend:!0},{sel:"#tool_rect",fn:Ce,evt:"mouseup",key:["R",!0],parent:"#tools_rect",icon:"rect"},{sel:"#tool_square",fn:xe,evt:"mouseup",parent:"#tools_rect",icon:"square"},{sel:"#tool_fhrect",fn:Se,evt:"mouseup",parent:"#tools_rect",icon:"fh_rect"},{sel:"#tool_ellipse",fn:$e,evt:"mouseup",key:["E",!0],parent:"#tools_ellipse",icon:"ellipse"},{sel:"#tool_circle",fn:we,evt:"mouseup",parent:"#tools_ellipse",icon:"circle"},{sel:"#tool_fhellipse",fn:ke,evt:"mouseup",parent:"#tools_ellipse",icon:"fh_ellipse"},{sel:"#tool_path",fn:Ne,evt:"click",key:["P",!0]},{sel:"#tool_text",fn:Ge,evt:"click",key:["T",!0]},{sel:"#tool_image",fn:Ae,evt:"mouseup"},{sel:"#tool_zoom",fn:Ee,evt:"mouseup",key:["Z",!0]},{sel:"#tool_clear",fn:Ze,evt:"mouseup",key:["N",!0]},{sel:"#tool_save",fn:function(){var e;A?mt():(e={images:$$b.pref("img_save"),round_digits:6},svgCanvas.save(e))},evt:"mouseup",key:["S",!0]},{sel:"#tool_export",fn:tt,evt:"mouseup"},{sel:"#tool_open",fn:nt,evt:"mouseup",key:["O",!0]},{sel:"#tool_import",fn:at,evt:"mouseup"},{sel:"#tool_source",fn:P,evt:"click",key:["U",!0]},{sel:"#tool_wireframe",fn:ct,evt:"click",key:["F",!0]},{key:["esc",!1,!1],fn:function(){qt.every(function(e){return $$b(e+":hidden").length})&&svgCanvas.clearSelection()},hidekey:!0},{sel:qt.join(","),fn:Ct,evt:"click",key:["esc",!1,!1],hidekey:!0},{sel:"#tool_source_save",fn:mt,evt:"click"},{sel:"#tool_docprops_save",fn:bt,evt:"click"},{sel:"#tool_docprops",fn:gt,evt:"mouseup"},{sel:"#tool_prefs_save",fn:yt,evt:"click"},{sel:"#tool_prefs_option",fn:function(){return function(){if(!pt){pt=!0,$$b("#main_menu").hide();var e=$$b("#bg_blocks div"),t="cur_background",n=curPrefs.bkgd_color,a=$$b.pref("bkgd_url");e.each(function(){var e=$$b(this),a=e.css("background-color")===n;e.toggleClass(t,a),a&&$$b("#canvas_bg_url").removeClass(t)}),n||e.eq(0).addClass(t),a&&$$b("#canvas_bg_url").val(a),$$b("#grid_snapping_on").prop("checked",curConfig.gridSnapping),$$b("#grid_snapping_step").attr("value",curConfig.snappingStep),$$b("#grid_color").attr("value",curConfig.gridColor),$$b("#svg_prefs").show()}}(),!1},evt:"mouseup"},{sel:"#tool_delete,#tool_delete_multi",fn:Le,evt:"click",key:["del/backspace",!0]},{sel:"#tool_reorient",fn:De,evt:"click"},{sel:"#tool_node_link",fn:He,evt:"click"},{sel:"#tool_node_clone",fn:ze,evt:"click"},{sel:"#tool_node_delete",fn:qe,evt:"click"},{sel:"#tool_openclose_path",fn:Ye,evt:"click"},{sel:"#tool_add_subpath",fn:We,evt:"click"},{sel:"#tool_move_top",fn:Oe,evt:"click",key:"ctrl+shift+]"},{sel:"#tool_move_bottom",fn:Be,evt:"click",key:"ctrl+shift+["},{sel:"#tool_topath",fn:je,evt:"click"},{sel:"#tool_make_link,#tool_make_link_multi",fn:Fe,evt:"click"},{sel:"#tool_undo",fn:rt,evt:"click"},{sel:"#tool_redo",fn:it,evt:"click"},{sel:"#tool_clone,#tool_clone_multi",fn:st,evt:"click",key:["D",!0]},{sel:"#tool_group_elements",fn:ot,evt:"click",key:["G",!0]},{sel:"#tool_ungroup",fn:ot,evt:"click"},{sel:"#tool_unlink_use",fn:ot,evt:"click"},{sel:"[id^=tool_align]",fn:lt,evt:"click"},{sel:"#tool_bold",fn:Je,evt:"mousedown"},{sel:"#tool_italic",fn:et,evt:"mousedown"},{sel:"#sidepanel_handle",fn:Ut,key:["X"]},{sel:"#copy_save_done",fn:Ct,evt:"click"},{key:"ctrl+left",fn:function(){Ke(0,1)}},{key:"ctrl+right",fn:function(){Ke(1,1)}},{key:"ctrl+shift+left",fn:function(){Ke(0,5)}},{key:"ctrl+shift+right",fn:function(){Ke(1,5)}},{key:"shift+O",fn:Qe},{key:"shift+P",fn:Xe},{key:[u+"up",!0],fn:function(){Pe(2)}},{key:[u+"down",!0],fn:function(){Pe(.5)}},{key:[u+"]",!0],fn:function(){Ve("Up")}},{key:[u+"[",!0],fn:function(){Ve("Down")}},{key:["up",!0],fn:function(){Ue(0,-1)}},{key:["down",!0],fn:function(){Ue(0,1)}},{key:["left",!0],fn:function(){Ue(-1,0)}},{key:["right",!0],fn:function(){Ue(1,0)}},{key:"shift+up",fn:function(){Ue(0,-10)}},{key:"shift+down",fn:function(){Ue(0,10)}},{key:"shift+left",fn:function(){Ue(-10,0)}},{key:"shift+right",fn:function(){Ue(10,0)}},{key:["alt+up",!0],fn:function(){svgCanvas.cloneSelectedElements(0,-1)}},{key:["alt+down",!0],fn:function(){svgCanvas.cloneSelectedElements(0,1)}},{key:["alt+left",!0],fn:function(){svgCanvas.cloneSelectedElements(-1,0)}},{key:["alt+right",!0],fn:function(){svgCanvas.cloneSelectedElements(1,0)}},{key:["alt+shift+up",!0],fn:function(){svgCanvas.cloneSelectedElements(0,-10)}},{key:["alt+shift+down",!0],fn:function(){svgCanvas.cloneSelectedElements(0,10)}},{key:["alt+shift+left",!0],fn:function(){svgCanvas.cloneSelectedElements(-10,0)}},{key:["alt+shift+right",!0],fn:function(){svgCanvas.cloneSelectedElements(10,0)}},{key:"a",fn:function(){svgCanvas.selectAllInCurrentLayer()}},{key:u+"a",fn:function(){svgCanvas.selectAllInCurrentLayer()}},{key:u+"z",fn:rt},{key:u+"shift+z",fn:it},{key:u+"y",fn:it},{key:u+"x",fn:Ie},{key:u+"c",fn:Me},{key:u+"v",fn:Re}],zt={"4/Shift+4":"#tools_rect_show","5/Shift+5":"#tools_ellipse_show"},{setAll:function(){var e={};$$b.each(Ht,function(t,n){var a;if(n.sel){if(!(a=$$b(n.sel)).length)return!0;if(n.evt&&(isTouch()&&"click"===n.evt&&(n.evt="mousedown"),a[n.evt](n.fn)),n.parent&&$$b(n.parent+"_show").length){var r=$$b(n.parent);r.length||(r=te(n.parent.substr(1))),n.prepend&&(a[0].style.margin="initial"),r[n.prepend?"prepend":"append"](a),Array.isArray(e[n.parent])||(e[n.parent]=[]),e[n.parent].push(n)}}if(n.key){var i,o=!1;Array.isArray(n.key)?(i=n.key[0],n.key.length>1&&(o=n.key[1])):i=n.key,i+="";var s=n.fn;if($$b.each(i.split("/"),function(e,t){$$b(document).bind("keydown",t,function(e){return s(),o&&e.preventDefault(),!1})}),n.sel&&!n.hidekey&&a.attr("title")){var l=a.attr("title").split("[")[0]+" ("+i+")";zt[i]=n.sel,a.parents("#main_menu").length||a.attr("title",l)}}}),ee(e),$$b(".attr_changer, #image_url").bind("keydown","return",function(e){$$b(this).change(),e.preventDefault()}),$$b(window).bind("keydown","tab",function(e){"canvas"===y&&(e.preventDefault(),Xe())}).bind("keydown","shift+tab",function(e){"canvas"===y&&(e.preventDefault(),Qe())}),$$b("#tool_zoom").dblclick(Te)},setTitles:function(){$$b.each(zt,function(e,t){var n=$$b(t).parents("#main_menu").length;$$b(t).each(function(){var t;t=n?$$b(this).text().split(" [")[0]:this.title.split(" [")[0];var a="";$$b.each(e.split("/"),function(e,t){var n=t.split("+"),r="";n.length>1&&(r=n[0]+"+",t=n[1]),a+=(e?"/":"")+r+(uiStrings$1["key_"+t]||t)}),n?this.lastChild.textContent=t+" ["+a+"]":this.title=t+" ["+a+"]"})})},getButtonData:function(e){return Object.values(Ht).find(function(t){return t.sel===e})}});editor.ready(function(){var e=curConfig.initTool,t=$$b("#tools_left, #svg_editor .tools_flyout"),n=t.find("#tool_"+e),a=t.find("#"+e);(n.length?n:a.length?a:$$b("#tool_select")).click().mouseup(),curConfig.wireframe&&$$b("#tool_wireframe").click(),curConfig.showlayers&&Ut(),$$b("#rulers").toggle(!!curConfig.showRulers),curConfig.showRulers&&($$b("#show_rulers")[0].checked=!0),curConfig.baseUnit&&$$b("#base_unit").val(curConfig.baseUnit),curConfig.gridSnapping&&($$b("#grid_snapping_on")[0].checked=!0),curConfig.snappingStep&&$$b("#grid_snapping_step").val(curConfig.snappingStep),curConfig.gridColor&&$$b("#grid_color").val(curConfig.gridColor)}),$$b("#rect_rx").SpinButton({min:0,max:1e3,stateObj:r,callback:function(e){svgCanvas.setRectRadius(e.value)}}),$$b("#stroke_width").SpinButton({min:0,max:99,smallStep:.1,stateObj:r,callback:function(e){var t=e.value;0===t&&T&&["line","polyline"].includes(T.nodeName)&&(t=e.value=1),svgCanvas.setStrokeWidth(t)}}),$$b("#angle").SpinButton({min:-180,max:180,step:5,stateObj:r,callback:function(e){svgCanvas.setRotationAngle(e.value),$$b("#tool_reorient").toggleClass("disabled",0===parseInt(e.value,10))}}),$$b("#font_size").SpinButton({min:.001,stepfunc:function(e,t){var n=Number(e.value),a=n+t,r=a>=n;return 0===t?n:n>=24?r?Math.round(1.1*n):Math.round(n/1.1):n<=1?r?2*n:n/2:a},stateObj:r,callback:function(e){svgCanvas.setFontSize(e.value)}}),$$b("#group_opacity").SpinButton({min:0,max:100,step:5,stateObj:r,callback:se}),$$b("#blur").SpinButton({min:0,max:10,step:.1,stateObj:r,callback:le}),$$b("#zoom").SpinButton({min:.001,max:1e4,step:50,stepfunc:function(e,t){var n=Number(e.value);if(0===n)return 100;var a=n+t;return 0===t?n:n>=100?a:a>=n?2*n:n/2},stateObj:r,callback:X}).val(100*svgCanvas.getZoom()),$$b("#workarea").contextMenu({menu:"cmenu_canvas",inSpeed:0},function(e,t,n){switch(e){case"delete":Le();break;case"cut":Ie();break;case"copy":Me();break;case"paste":svgCanvas.pasteElements();break;case"paste_in_place":svgCanvas.pasteElements("in_place");break;case"group":case"group_elements":svgCanvas.groupSelectedElements();break;case"ungroup":svgCanvas.ungroupSelectedElement();break;case"move_front":Oe();break;case"move_up":Ve("Up");break;case"move_down":Ve("Down");break;case"move_back":Be();break;default:hasCustomHandler(e)&&getCustomHandler(e).call()}});var Yt=function(e,t,n){switch(e){case"dupe":a=svgCanvas.getCurrentDrawing().getCurrentLayerName()+" copy",$$b.prompt(uiStrings$1.notification.enterUniqueLayerName,a,function(e){e&&(svgCanvas.getCurrentDrawing().hasLayer(e)?$$b.alert(uiStrings$1.notification.dupeLayerName):(svgCanvas.cloneLayer(e),F(),k()))});break;case"delete":Rt();break;case"merge_down":$$b("#layerlist tr.layersel").index()!==svgCanvas.getCurrentDrawing().getNumLayers()-1&&(svgCanvas.mergeLayer(),F(),k());break;case"merge_all":svgCanvas.mergeAllLayers(),F(),k()}var a};function Xt(){var e;try{e=localStorage.getItem("svgedit_clipboard")}catch(e){}g[(e?"en":"dis")+"ableContextMenuItems"]("#paste,#paste_in_place")}if($$b("#layerlist").contextMenu({menu:"cmenu_layers",inSpeed:0},Yt),$$b("#layer_moreopts").contextMenu({menu:"cmenu_layers",inSpeed:0,allowLeft:!0},Yt),$$b(".contextMenu li").mousedown(function(e){e.preventDefault()}),$$b("#cmenu_canvas li").disableContextMenu(),g.enableContextMenuItems("#delete,#cut,#copy"),Xt(),window.addEventListener("storage",function(e){"svgedit_clipboard"===e.key&&Xt()}),window.addEventListener("beforeunload",function(e){if(0===h.getUndoStackSize()&&(editor.showSaveWarning=!1),!curConfig.no_save_warning&&editor.showSaveWarning)return e.returnValue=uiStrings$1.notification.unsavedChanges,uiStrings$1.notification.unsavedChanges}),editor.canvas.getUIStrings=function(){return uiStrings$1},editor.openPrep=function(e){$$b("#main_menu").hide(),0===h.getUndoStackSize()?e(!0):$$b.confirm(uiStrings$1.notification.QwantToOpen,e)},window.FileReader){var Qt=function(e){$$b.process_cancel(uiStrings$1.notification.loadingImage),e.stopPropagation(),e.preventDefault(),$$b("#workarea").removeAttr("style"),$$b("#main_menu").hide();var t,n="drop"===e.type?e.dataTransfer.files[0]:this.files[0];n?n.type.includes("image")&&(n.type.includes("svg")?((t=new FileReader).onloadend=function(e){var t=svgCanvas.importSvgString(e.target.result,!0);svgCanvas.ungroupSelectedElement(),svgCanvas.ungroupSelectedElement(),svgCanvas.groupSelectedElements(),svgCanvas.alignSelectedElements("m","page"),svgCanvas.alignSelectedElements("c","page"),svgCanvas.selectOnly([t]),$$b("#dialog_box").hide()},t.readAsText(n)):((t=new FileReader).onloadend=function(e){var t=e.target.result,n=100,a=100,r=new Image;r.style.opacity=0,r.onload=function(){var e,i,o;n=r.offsetWidth||r.naturalWidth||r.width,a=r.offsetHeight||r.naturalHeight||r.height,e=n,i=a,o=svgCanvas.addSVGElementFromJson({element:"image",attr:{x:0,y:0,width:e,height:i,id:svgCanvas.getNextId(),style:"pointer-events:inherit"}}),svgCanvas.setHref(o,t),svgCanvas.selectOnly([o]),svgCanvas.alignSelectedElements("m","page"),svgCanvas.alignSelectedElements("c","page"),F(),$$b("#dialog_box").hide()},r.src=t},t.readAsDataURL(n))):$$b("#dialog_box").hide()};p[0].addEventListener("dragenter",function(e){e.stopPropagation(),e.preventDefault()}),p[0].addEventListener("dragover",function(e){e.stopPropagation(),e.preventDefault()}),p[0].addEventListener("dragleave",function(e){e.stopPropagation(),e.preventDefault()}),p[0].addEventListener("drop",Qt);var Kt=$$b('').click(function(){var e=this;editor.openPrep(function(t){if(t&&(svgCanvas.clear(),1===e.files.length)){$$b.process_cancel(uiStrings$1.notification.loadingImage);var n=new FileReader;n.onloadend=function(e){loadSvgString(e.target.result),j()},n.readAsText(e.files[0])}})});$$b("#tool_open").show().prepend(Kt);var Zt=$$b('').change(Qt);$$b("#tool_import").show().prepend(Zt)}j(!0);var Jt=[],en=editor.setLang=function(){var e=_asyncToGenerator(regeneratorRuntime.mark(function e(t,n){var a,r,i,o;return regeneratorRuntime.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(editor.langChanged=!0,$$b.pref("lang",t),$$b("#lang_select").val(t),n){e.next=5;break}return e.abrupt("return");case 5:if($$b.extend(uiStrings$1,n),a=$$b("#layerlist tr.layersel td.layername").text(),r=a===uiStrings$1.common.layer+" 1",svgCanvas.setUiStrings(n),Wt.setTitles(),r&&(svgCanvas.renameCurrentLayer(uiStrings$1.common.layer+" 1"),k()),!ae.length){e.next=21;break}case 12:if(!ae.length){e.next=19;break}return i=ae.shift(),Jt.push(i.name),e.next=17,i.langReady({lang:t,uiStrings:uiStrings$1,importLocale:getImportLocale({defaultLang:t,defaultName:i.name})});case 17:e.next=12;break;case 19:e.next=22;break;case 21:Jt.forEach(function(e){svgCanvas.runExtensions("langReady",{lang:t,uiStrings:uiStrings$1,importLocale:getImportLocale({defaultLang:t,defaultName:e})})});case 22:svgCanvas.runExtensions("langChanged",t),Z(),o={"#stroke_color":"#tool_stroke .icon_label, #tool_stroke .color_block","#fill_color":"#tool_fill label, #tool_fill .color_block","#linejoin_miter":"#cur_linejoin","#linecap_butt":"#cur_linecap"},$$b.each(o,function(e,t){$$b(t).attr("title",$$b(e)[0].title)}),$$b("#multiselected_panel div[id^=tool_align]").each(function(){$$b("#tool_pos"+this.id.substr(10))[0].title=this.title});case 27:case"end":return e.stop()}},e,this)}));return function(t,n){return e.apply(this,arguments)}}();init$7({addLangData:function(e){return svgCanvas.runExtensions("addLangData",function(t){return{lang:e,importLocale:getImportLocale({defaultLang:e,defaultName:t})}},!0)},curConfig:curConfig}),"file:"===document.location.protocol?setTimeout(a,100):a()},editor.ready=function(e){isReady?e():callbacks.push(e)},editor.runCallbacks=function(){callbacks.forEach(function(e){e()}),isReady=!0},editor.loadFromString=function(e){editor.ready(function(){loadSvgString(e)})},editor.disableUI=function(e){},editor.loadFromURL=function(e,t){t||(t={});var n=t,a=n.cache,r=n.callback;editor.ready(function(){$$b.ajax({url:e,dataType:"text",cache:!!a,beforeSend:function(){$$b.process_cancel(uiStrings$1.notification.loadingImage)},success:function(e){loadSvgString(e,r)},error:function(e,t,n){404!==e.status&&e.responseText?loadSvgString(e.responseText,r):$$b.alert(uiStrings$1.notification.URLloadFail+": \n"+n,r)},complete:function(){$$b("#dialog_box").hide()}})})},editor.loadFromDataURI=function(e){editor.ready(function(){var t=!1,n=e.match(/^data:image\/svg\+xml;base64,/);n?t=!0:n=e.match(/^data:image\/svg\+xml(?:;(?:utf8)?)?,/),n&&(n=n[0]);var a=e.slice(n.length);loadSvgString(t?decode64(a):decodeURIComponent(a))})},editor.addExtension=function(e,t,n){if(!svgCanvas)throw new Error("Extension added too early");return svgCanvas.addExtension.call(this,e,t,n)},editor.ready(function(){injectExtendedContextMenuItemsIntoDom()});var extensionsAdded=!1,messageQueue=[],messageListener=function(e){var t={data:e.data,origin:e.origin};extensionsAdded?svgCanvas.call("message",t):messageQueue.push(t)};window.addEventListener("message",messageListener),Promise.resolve().then(function(){editor.init()});export default editor; +function _typeof(e){return(_typeof="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})(e)}function asyncGeneratorStep(e,t,n,r,a,i,s){try{var o=e[i](s),l=o.value}catch(e){return void n(e)}o.done?t(l):Promise.resolve(l).then(r,a)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,a){var i=e.apply(t,n);function s(e){asyncGeneratorStep(i,r,a,s,o,"next",e)}function o(e){asyncGeneratorStep(i,r,a,s,o,"throw",e)}s(void 0)})}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(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=r,window.SVGPathSegLinetoAbs=a,window.SVGPathSegLinetoRel=i,window.SVGPathSegCurvetoCubicAbs=s,window.SVGPathSegCurvetoCubicRel=o,window.SVGPathSegCurvetoQuadraticAbs=l,window.SVGPathSegCurvetoQuadraticRel=c,window.SVGPathSegArcAbs=u,window.SVGPathSegArcRel=d,window.SVGPathSegLinetoHorizontalAbs=h,window.SVGPathSegLinetoHorizontalRel=p,window.SVGPathSegLinetoVerticalAbs=g,window.SVGPathSegLinetoVerticalRel=f,window.SVGPathSegCurvetoCubicSmoothAbs=m,window.SVGPathSegCurvetoCubicSmoothRel=v,window.SVGPathSegCurvetoQuadraticSmoothAbs=_,window.SVGPathSegCurvetoQuadraticSmoothRel=b}if(!("SVGPathSegList"in window&&"appendItem"in window.SVGPathSegList.prototype)){var y=function(){function e(t){_classCallCheck(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 _createClass(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(){_classCallCheck(this,e),this.pathSegList=[]}return _createClass(e,[{key:"appendSegment",value:function(e){this.pathSegList.push(e)}}]),e}(),r=function(){function e(t){_classCallCheck(this,e),this._string=t,this._currentIndex=0,this._endIndex=this._string.length,this._previousCommand=SVGPathSeg.PATHSEG_UNKNOWN,this._skipOptionalSpaces()}return _createClass(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,s=this._currentIndex;if(this._skipOptionalSpaces(),this._currentIndex"9")&&"."!==this._string.charAt(this._currentIndex))){for(var o=this._currentIndex;this._currentIndex="0"&&this._string.charAt(this._currentIndex)<="9";)this._currentIndex++;if(this._currentIndex!==o)for(var l=this._currentIndex-1,c=1;l>=o;)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!==s&&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)),s!==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 s={x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicSmoothAbs(t,s.x,s.y,s.x2,s.y2);case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:var o={x1:this._parseNumber(),y1:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoQuadraticRel(t,o.x,o.y,o.x1,o.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}(),a=new n,i=new r(e);if(!i.initialCommandIsMoveTo())return[];for(;i.hasMoreData();){var s=i.parseSegment();if(!s)return[];a.appendSegment(s)}return a.pathSegList}}]),e}();y.prototype.classname="SVGPathSegList",Object.defineProperty(y.prototype,"numberOfItems",{get:function(){return this._checkPathSynchronizedToList(),this._list.length},enumerable:!0}),y._pathSegArrayAsString=function(e){var t="",n=!0;return e.forEach(function(e){n?(n=!1,t+=e._asPathString()):t+=" "+e._asPathString()}),t},Object.defineProperties(SVGPathElement.prototype,{pathSegList:{get:function(){return this._pathSegList||(this._pathSegList=new y(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=y}}();var $=jQuery,supportsSVG_=Boolean(document.createElementNS&&document.createElementNS(NS.SVG,"svg").createSVGRect),_navigator=navigator,userAgent=_navigator.userAgent,svg=document.createElementNS(NS.SVG,"svg"),isOpera_=Boolean(window.opera),isWebkit_=userAgent.includes("AppleWebKit"),isGecko_=userAgent.includes("Gecko/"),isIE_=userAgent.includes("MSIE"),isChrome_=userAgent.includes("Chrome/"),isWindows_=userAgent.includes("Windows"),isMac_=userAgent.includes("Macintosh"),isTouch_="ontouchstart"in window,supportsSelectors_=Boolean(svg.querySelector),supportsXpath_=Boolean(document.evaluate),supportsPathReplaceItem_=function(){var e=document.createElementNS(NS.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}(),supportsPathInsertItemBefore_=function(){var e=document.createElementNS(NS.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}(),supportsGoodTextCharPos_=function(){var e=document.createElementNS(NS.SVG,"svg"),t=document.createElementNS(NS.SVG,"svg");document.documentElement.append(e),t.setAttribute("x",5),e.append(t);var n=document.createElementNS(NS.SVG,"text");n.textContent="a",t.append(n);try{return 0===n.getStartPositionOfChar(0).x}catch(e){return!1}finally{e.remove()}}(),supportsPathBBox_=function(){var e=document.createElementNS(NS.SVG,"svg");document.documentElement.append(e);var t=document.createElementNS(NS.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}(),supportsHVLineContainerBBox_=function(){var e=document.createElementNS(NS.SVG,"svg");document.documentElement.append(e);var t=document.createElementNS(NS.SVG,"path");t.setAttribute("d","M0,0 10,0");var n=document.createElementNS(NS.SVG,"path");n.setAttribute("d","M5,0 15,0");var r=document.createElementNS(NS.SVG,"g");r.append(t,n),e.append(r);var a=r.getBBox();return e.remove(),15===a.width}(),supportsGoodDecimals_=function(){var e=document.createElementNS(NS.SVG,"rect");e.setAttribute("x",.1);var t=!e.cloneNode(!1).getAttribute("x").includes(",");return t||$.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.'),t}(),supportsNonScalingStroke_=function(){var e=document.createElementNS(NS.SVG,"rect");return e.setAttribute("style","vector-effect:non-scaling-stroke"),"non-scaling-stroke"===e.style.vectorEffect}(),supportsNativeSVGTransformLists_=function(){var e=document.createElementNS(NS.SVG,"rect").transform.baseVal,t=svg.createSVGTransform();e.appendItem(t);var n=e.getItem(0);return n instanceof SVGTransform&&t instanceof SVGTransform&&n.type===t.type&&n.angle===t.angle&&n.matrix.a===t.matrix.a&&n.matrix.b===t.matrix.b&&n.matrix.c===t.matrix.c&&n.matrix.d===t.matrix.d&&n.matrix.e===t.matrix.e&&n.matrix.f===t.matrix.f}(),isOpera=function(){return isOpera_},isWebkit=function(){return isWebkit_},isGecko=function(){return isGecko_},isIE=function(){return isIE_},isChrome=function(){return isChrome_},isMac=function(){return isMac_},isTouch=function(){return isTouch_},supportsSelectors=function(){return supportsSelectors_},supportsXpath=function(){return supportsXpath_},supportsPathReplaceItem=function(){return supportsPathReplaceItem_},supportsPathInsertItemBefore=function(){return supportsPathInsertItemBefore_},supportsPathBBox=function(){return supportsPathBBox_},supportsHVLineContainerBBox=function(){return supportsHVLineContainerBBox_},supportsGoodTextCharPos=function(){return supportsGoodTextCharPos_},supportsNonScalingStroke=function(){return supportsNonScalingStroke_},supportsNativeTransformLists=function(){return supportsNativeSVGTransformLists_};function jQueryPluginSVG(e){var t=e.fn.attr;return e.fn.attr=function(e,n){var r=this.length;if(!r)return t.call(this,e,n);for(var a=0;a=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(HistoryEventTypes.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}();BatchCommand.type=BatchCommand.prototype.type;var UndoManager=function(){function e(t){_classCallCheck(this,e),this.handler_=t||null,this.undoStackPointer=0,this.undoStack=[],this.undoChangeStackPointer=-1,this.undoableChangeStack=[]}return _createClass(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 s=t[r];isNullish(s)||(i[r]=s,a[r]=s.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 BatchCommand("Change "+n),a=t.elements.length;a--;){var i=t.elements[a];if(!isNullish(i)){var s={};s[n]=t.oldValues[a],s[n]!==i.getAttribute(n)&&r.addSubCommand(new ChangeElementCommand(i,s,n))}}return this.undoableChangeStack[e]=null,r}}]),e}(),hstry=Object.freeze({HistoryEventTypes:HistoryEventTypes,MoveElementCommand:MoveElementCommand,InsertElementCommand:InsertElementCommand,RemoveElementCommand:RemoveElementCommand,ChangeElementCommand:ChangeElementCommand,BatchCommand:BatchCommand,UndoManager:UndoManager}),NEAR_ZERO=1e-14,svg$1=document.createElementNS(NS.SVG,"svg"),transformPoint=function(e,t,n){return{x:n.a*e+n.c*t+n.e,y:n.b*e+n.d*t+n.f}},isIdentity=function(e){return 1===e.a&&0===e.b&&0===e.c&&1===e.d&&0===e.e&&0===e.f},matrixMultiply=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=svg$1.createSVGMatrix(),i=t;i<=n;++i){var s=i>=0&&ie.x&&t.ye.y},$$1=jQuery,segData={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"]},uiStrings={},setUiStrings=function(e){Object.assign(uiStrings,e.ui)},pathFuncs=[],linkControlPts=!0,pathData={},setLinkControlPoints=function(e){linkControlPts=e},path=null,editorContext_=null,init$1=function(e){editorContext_=e,pathFuncs=[0,"ClosePath"];$$1.each(["Moveto","Lineto","CurvetoCubic","CurvetoQuadratic","Arc","LinetoHorizontal","LinetoVertical","CurvetoCubicSmooth","CurvetoQuadraticSmooth"],function(e,t){pathFuncs.push(t+"Abs"),pathFuncs.push(t+"Rel")})},insertItemBefore=function(e,t,n){var r=e.pathSegList;if(supportsPathInsertItemBefore())r.insertItemBefore(t,n);else{for(var a=r.numberOfItems,i=[],s=0;s0?(p=f element");this.elem=t,this.segs=[],this.selected_pts=[],path=this,this.init()}return _createClass(e,[{key:"init",value:function(){$$1(getGripContainer()).find("*").each(function(){$$1(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[o+1],u=o-1<0?null:i[o-1];if(2===l.type){if(u&&1!==u.type){var d=i[s];d.next=i[s+1],d.next.prev=d,d.addGrip()}s=o}else if(c&&1===c.type)l.next=i[s+1],l.next.prev=l,l.mate=i[s],l.addGrip(),isNullish(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[s];h.next=i[s+1],h.next.prev=h,h.addGrip(),l.addGrip(),this.first_seg||(this.first_seg=i[s])}}return this}},{key:"eachSeg",value:function(e){for(var t=this.segs.length,n=0;n=0&&this.selected_pts.push(r)}this.selected_pts.sort();var a=this.selected_pts.length,i=[];for(i.length=a;a--;){var s=this.selected_pts[a],o=this.segs[s];o.select(!0),i[a]=o.ptgrip}var l=e.subpathIsClosed(this.selected_pts[0]);editorContext_.addPtsToSelection({grips:i,closedSubpath:l})}}]),e}();Path.subpathIsClosed=function(e){var t=!1;return path.eachSeg(function(n){return n<=e||2!==this.type&&(1!==this.type||(t=!0,!1))}),t};var newcx,newcy,oldcx,oldcy,angle,getPath_=function(e){var t=pathData[e.id];return t||(t=pathData[e.id]=new Path(e)),t},removePath_=function(e){e in pathData&&delete pathData[e]},getRotVals=function(e,t){var n=e-oldcx,r=t-oldcy,a=Math.sqrt(n*n+r*r),i=Math.atan2(r,n)+angle;return n=a*Math.cos(i)+oldcx,r=a*Math.sin(i)+oldcy,n-=newcx,r-=newcy,a=Math.sqrt(n*n+r*r),i=Math.atan2(r,n)-angle,{x:a*Math.cos(i)+newcx,y:a*Math.sin(i)+newcy}},recalcRotatedPath=function(){var e=path.elem;if(angle=getRotationAngle(e,!0)){var t=path.oldbbox;oldcx=t.x+t.width/2,oldcy=t.y+t.height/2;var n=getBBox(e);newcx=n.x+n.width/2,newcy=n.y+n.height/2;var r=newcx-oldcx,a=newcy-oldcy,i=Math.sqrt(r*r+a*a),s=Math.atan2(a,r)+angle;newcx=i*Math.cos(s)+oldcx,newcy=i*Math.sin(s)+oldcy;for(var o=e.pathSegList,l=o.numberOfItems;l;){l-=1;var c=o.getItem(l),u=c.pathSegType;if(1!==u){var d=getRotVals(c.x,c.y),h=[d.x,d.y];if(!isNullish(c.x1)&&!isNullish(c.x2)){var p=getRotVals(c.x1,c.y1),g=getRotVals(c.x2,c.y2);h.splice(h.length,0,p.x,p.y,g.x,g.y)}replacePathSeg(u,l,h)}}getBBox(e);var f=editorContext_.getSVGRoot().createSVGTransform(),m=getTransformList(e);f.setRotate(180*angle/Math.PI,newcx,newcy),m.replaceItem(f,0)}},clearData=function(){pathData={}},reorientGrads=function(e,t){for(var n=getBBox(e),r=0;r<2;r++){var a=0===r?"fill":"stroke",i=e.getAttribute(a);if(i&&i.startsWith("url(")){var s=getRefElem(i);if("linearGradient"===s.tagName){var o=s.getAttribute("x1")||0,l=s.getAttribute("y1")||0,c=s.getAttribute("x2")||1,u=s.getAttribute("y2")||0;o=n.width*o+n.x,l=n.height*l+n.y,c=n.width*c+n.x,u=n.height*u+n.y;var d=transformPoint(o,l,t),h=transformPoint(c,u,t),p={};p.x1=(d.x-n.x)/n.width,p.y1=(d.y-n.y)/n.height,p.x2=(h.x-n.x)/n.width,p.y2=(h.y-n.y)/n.height;var g=s.cloneNode(!0);$$1(g).attr(p),g.id=editorContext_.getNextId(),findDefs().append(g),e.setAttribute(a,"url(#"+g.id+")")}}}},pathMap=[0,"z","M","m","L","l","C","c","Q","q","A","a","H","h","V","v","S","s","T","t"],convertPath=function(e,t){for(var n=e.pathSegList,r=n.numberOfItems,a=0,i=0,s="",o=null,l=0;l=k-S&&m<=k+S&&v>=A-S&&v<=A+S){w=!0;break}}s=editorContext_.getId(),removePath_(s);var E,N,T=getElem(s),P=x.numberOfItems;if(w){if(C<=1&&P>=2){var G=x.getItem(0).x,L=x.getItem(0).y;E=4===(N=_.pathSegList.getItem(1)).pathSegType?y.createSVGPathSegLinetoAbs(G,L):y.createSVGPathSegCurvetoCubicAbs(G,L,N.x1/f,N.y1/f,G,L);var I=y.createSVGPathSegClosePath();x.appendItem(E),x.appendItem(I)}else if(P<3)return!1;if($$1(_).remove(),editorContext_.setDrawnPath(null),editorContext_.setStarted(!1),n){path.matrix&&editorContext_.remapElement(T,{},path.matrix.inverse());var M=T.getAttribute("d"),R=$$1(path.elem).attr("d");return $$1(path.elem).attr("d",R+M),$$1(T).remove(),path.matrix&&recalcRotatedPath(),init$1(),pathActions.toEditMode(path.elem),path.selectPt(),!1}}else{if(!$$1.contains(editorContext_.getContainer(),editorContext_.getMouseTarget(t)))return!1;var O=y.pathSegList.numberOfItems,B=y.pathSegList.getItem(O-1),V=B.x,j=B.y;if(t.shiftKey){var F=snapToAngle(V,j,m,v);m=F.x,v=F.y}E=4===(N=_.pathSegList.getItem(1)).pathSegType?y.createSVGPathSegLinetoAbs(editorContext_.round(m),editorContext_.round(v)):y.createSVGPathSegCurvetoCubicAbs(editorContext_.round(m),editorContext_.round(v),N.x1/f,N.y1/f,N.x2/f,N.y2/f),y.pathSegList.appendItem(E),m*=f,v*=f,_.setAttribute("d",["M",m,v,m,v].join(" ")),b=O,n&&(b+=path.segs.length),addPointGrip(b,m,v)}}else{var D="M"+m+","+v+" ";editorContext_.setDrawnPath(editorContext_.addSVGElementFromJson({element:"path",curStyles:!0,attr:{d:D,id:editorContext_.getNextId(),opacity:editorContext_.getOpacity()/2}})),_.setAttribute("d",["M",p,g,p,g].join(" ")),b=n?path.segs.length:0,addPointGrip(b,p,g)}}},mouseMove:function(n,r){var i=editorContext_.getCurrentZoom();a=!0;var s=editorContext_.getDrawnPath();if("path"!==editorContext_.getCurrentMode())if(path.dragging){var o=getPointFromGrip({x:path.dragging[0],y:path.dragging[1]},path),l=getPointFromGrip({x:n,y:r},path),c=l.x-o.x,u=l.y-o.y;path.dragging=[n,r],path.dragctrl?path.moveCtrl(c,u):path.movePts(c,u)}else path.selected_pts=[],path.eachSeg(function(e){if(this.next||this.prev){var t=editorContext_.getRubberBox().getBBox(),n=getGripPt(this),r={x:n.x,y:n.y,width:0,height:0},a=rectsIntersect(t,r);this.select(a),a&&path.selected_pts.push(this.index)}});else{if(!s)return;var d=s.pathSegList,h=d.numberOfItems-1;if(e){var p=addCtrlGrip("1c1"),g=addCtrlGrip("0c2");p.setAttribute("cx",n),p.setAttribute("cy",r),p.setAttribute("display","inline");var f=e[0],m=e[1],v=f+(f-n/i),_=m+(m-r/i);g.setAttribute("cx",v*i),g.setAttribute("cy",_*i),g.setAttribute("display","inline");var b=getCtrlLine(1);if(assignAttributes(b,{x1:n,y1:r,x2:v*i,y2:_*i,display:"inline"}),0===h)t=[n,r];else{var y=d.getItem(h-1),x=y.x,C=y.y;6===y.pathSegType?(x+=x-y.x2,C+=C-y.y2):t&&(x=t[0]/i,C=t[1]/i),replacePathSeg(6,h,[f,m,x,C,v,_],s)}}else{var S=getElem("path_stretch_line");if(S){var w=d.getItem(h);if(6===w.pathSegType){var $=w.x+(w.x-w.x2),k=w.y+(w.y-w.y2);replacePathSeg(6,1,[n,r,$*i,k*i,n,r],S)}else t?replacePathSeg(6,1,[n,r,t[0],t[1],n,r],S):replacePathSeg(4,1,[n,r],S)}}}},mouseUp:function(n,r,i,s){var o=editorContext_.getDrawnPath();if("path"===editorContext_.getCurrentMode())return e=null,o||(r=getElem(editorContext_.getId()),editorContext_.setStarted(!1),t=null),{keep:!0,element:r};var l=editorContext_.getRubberBox();if(path.dragging){var c=path.cur_pt;path.dragging=!1,path.dragctrl=!1,path.update(),a&&path.endChanges("Move path point(s)"),n.shiftKey||a||path.selectPt(c)}else l&&"none"!==l.getAttribute("display")?(l.setAttribute("display","none"),l.getAttribute("width")<=2&&l.getAttribute("height")<=2&&pathActions.toSelectMode(n.target)):pathActions.toSelectMode(n.target);a=!1},toEditMode:function(e){path=getPath_(e),editorContext_.setCurrentMode("pathedit"),editorContext_.clearSelection(),path.show(!0).update(),path.oldbbox=getBBox(path.elem),n=!1},toSelectMode:function(e){var t=e===path.elem;editorContext_.setCurrentMode("select"),path.show(!1),r=!1,editorContext_.clearSelection(),path.matrix&&recalcRotatedPath(),t&&(editorContext_.call("selected",[e]),editorContext_.addToSelection([e],!0))},addSubPath:function(e){e?(editorContext_.setCurrentMode("path"),n=!0):(pathActions.clear(!0),pathActions.toEditMode(path.elem))},select:function(e){r===e?(pathActions.toEditMode(e),editorContext_.setCurrentMode("pathedit")):r=e},reorient:function(){var e=editorContext_.getSelectedElements()[0];if(e&&0!==getRotationAngle(e)){var t=new BatchCommand("Reorient path"),n={d:e.getAttribute("d"),transform:e.getAttribute("transform")};t.addSubCommand(new ChangeElementCommand(e,n)),editorContext_.clearSelection(),this.resetOrientation(e),editorContext_.addCommandToHistory(t),getPath_(e).show(!1).matrix=null,this.clear(),editorContext_.addToSelection([e],!0),editorContext_.call("changed",editorContext_.getSelectedElements())}},clear:function(e){var n=editorContext_.getDrawnPath();if(r=null,n){var a=getElem(editorContext_.getId());$$1(getElem("path_stretch_line")).remove(),$$1(a).remove(),$$1(getElem("pathpointgrip_container")).find("*").attr("display","none"),t=null,editorContext_.setDrawnPath(null),editorContext_.setStarted(!1)}else"pathedit"===editorContext_.getCurrentMode()&&this.toSelectMode();path&&path.init().show(!1)},resetOrientation:function(e){if(isNullish(e)||"path"!==e.nodeName)return!1;var t=getTransformList(e),n=transformListToTransform(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 s=[];$$1.each(["",1,2],function(e,t){var r=a["x"+t],i=a["y"+t];if(void 0!==r&&void 0!==i){var o=transformPoint(r,i,n);s.splice(s.length,0,o.x,o.y)}}),replacePathSeg(i,t,s,e)},s=0;s0){var o=t.getItem(n-1).pathSegType;if(2===o){r(n-1,1),e();break}if(1===o&&t.numberOfItems-1===n){r(n,1),e();break}}}return!1}(),path.elem.pathSegList.numberOfItems<=1)return pathActions.toSelectMode(path.elem),void editorContext_.canvas.deleteSelectedElements();if(path.init(),path.clearSelection(),window.opera){var r=$$1(path.elem);r.attr("d",r.attr("d"))}path.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,s=[];for(s.push(["M",a.x,",",a.y," C"].join("")),t=1;t<=r-4;t+=3){var o=n.getItem(t),l=n.getItem(t+1),c=n.getItem(t+2);if(i){var u=smoothControlPoints(i,o,a);if(u&&2===u.length){var d=s[s.length-1].split(",");d[2]=u[0].x,d[3]=u[0].y,s[s.length-1]=d.join(","),o=u[1]}}s.push([o.x,o.y,l.x,l.y,c.x,c.y].join(",")),a=c,i=l}for(s.push("L");t)/,"$1$2")},toXml=function(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")};function encode64(e){if(e=encodeUTF8(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++),s=e.charCodeAt(n++),o=a>>2,l=(3&a)<<4|i>>4,c=(15&i)<<2|s>>6,u=63&s;isNaN(i)?(c=64,u=64):isNaN(s)&&(u=64),t[r++]=KEYSTR.charAt(o),t[r++]=KEYSTR.charAt(l),t[r++]=KEYSTR.charAt(c),t[r++]=KEYSTR.charAt(u)}while(n>4,l=(15&a)<<4|i>>2,c=(3&i)<<6|s;t+=String.fromCharCode(o),64!==i&&(t+=String.fromCharCode(l)),64!==s&&(t+=String.fromCharCode(c))}while(nSVG-edit "],{type:"text/html"});return createObjectURL(e)}(),text2xml=function(e){var t,n;e.includes("0?t=t[0]:(t=e.ownerDocument.createElementNS(NS.SVG,"defs"),e.firstChild?e.insertBefore(t,e.firstChild.nextSibling):e.append(t)),t},getPathBBox=function(e){for(var t=e.pathSegList,n=t.numberOfItems,r=[[],[]],a=t.getItem(0),i=[a.x,a.y],s=function(e,t,n,r){return function(a){return Math.pow(1-a,3)*i[e]+3*Math.pow(1-a,2)*a*t[e]+3*(1-a)*Math.pow(a,2)*n[e]+Math.pow(a,3)*r[e]}},o=0;o0&&_<1&&r[h].push(p(_));var b=(-g-Math.sqrt(v))/(2*f);b>0&&b<1&&r[h].push(p(b))}}else{if(0===g)continue;var y=-m/g;y>0&&y<1&&r[h].push(p(y))}}i=d}else r[0].push(l.x),r[1].push(l.y)}var x=Math.min.apply(null,r[0]),C=Math.max.apply(null,r[0])-x,S=Math.min.apply(null,r[1]);return{x:x,y:S,width:C,height:Math.max.apply(null,r[1])-S}};function groupBBFix(e){if(supportsHVLineContainerBBox())try{return e.getBBox()}catch(e){}var t,n,r=$$2.data(e,"ref"),a=null;r?(n=$$2(r).children().clone().attr("visibility","hidden"),$$2(svgroot_).append(n),a=n.filter("line, path")):a=$$2(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 s=r?n:$$2(e).children();t=getStrokedBBox(s)}else t=e.getBBox();else t=e.getBBox();return r&&n.remove(),t}var getBBox=function(e){var t=e||editorContext_$1.geSelectedElements()[0];if(1!==e.nodeType)return null;var n=t.nodeName,r=null;switch(n){case"text":""===t.textContent?(t.textContent="a",r=t.getBBox(),t.textContent=""):t.getBBox&&(r=t.getBBox());break;case"path":supportsPathBBox()?t.getBBox&&(r=t.getBBox()):r=getPathBBox(t);break;case"g":case"a":r=groupBBFix(t);break;default:if("use"===n&&(r=groupBBFix(t)),"use"===n||"foreignObject"===n&&isWebkit()){if(r||(r=t.getBBox()),!isWebkit()){var a={};a.width=r.width,a.height=r.height,a.x=r.x+parseFloat(t.getAttribute("x")||0),a.y=r.y+parseFloat(t.getAttribute("y")||0),r=a}}else if(visElemsArr.includes(n))if(t)try{r=t.getBBox()}catch(e){var i=t.getExtentOfChar(0),s=t.getComputedTextLength();r={x:i.x,y:i.y,width:s,height:i.height}}else{var o=$$2(t).closest("foreignObject");o.length&&o[0].getBBox&&(r=o[0].getBBox())}}return r&&(r=bboxToObj(r)),r},getPathDFromSegments=function(e){var t="";return $$2.each(e,function(e,n){var r=_slicedToArray(n,2),a=r[0],i=r[1];t+=a;for(var s=0;s-.001&&n<.001||(n<-89.99||n>89.99))}var getBBoxWithTransform=function(e,t,n){var r=getBBox(e);if(!r)return null;var a=getTransformList(e),i=getRotationAngleFromTransformList(a),s=hasMatrixTransform(a);if(i||s){var o=!1;if(bBoxCanBeOptimizedOverNativeGetBBox(i,s)){if(["ellipse","path","line","polyline","polygon"].includes(e.tagName))r=o=getBBoxOfElementAsPath(e,t,n);else if("rect"===e.tagName){var l=e.getAttribute("rx"),c=e.getAttribute("ry");(l||c)&&(r=o=getBBoxOfElementAsPath(e,t,n))}}if(!o){var u=transformListToTransform(a).matrix;r=transformBox(r.x,r.y,r.width,r.height,u).aabox}}return r};function getStrokeOffsetForBBox(e){var t=e.getAttribute("stroke-width");return isNaN(t)||"none"===e.getAttribute("stroke")?0:t/2}var getStrokedBBox=function(e,t,n){if(!e||!e.length)return!1;var r;if($$2.each(e,function(){r||this.parentNode&&(r=getBBoxWithTransform(this,t,n))}),void 0===r)return null;var a=r.x+r.width,i=r.y+r.height,s=r.x,o=r.y;if(1===e.length){var l=getStrokeOffsetForBBox(e[0]);s-=l,o-=l,a+=l,i+=l}else $$2.each(e,function(e,r){var l=getBBoxWithTransform(r,t,n);if(l){var c=getStrokeOffsetForBBox(r);s=Math.min(s,l.x-c),o=Math.min(o,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=s,r.y=o,r.width=a-s,r.height=i-o,r},getVisibleElements=function(e){e||(e=$$2(editorContext_$1.getSVGContent()).children());var t=[];return $$2(e).children().each(function(e,n){n.getBBox&&t.push(n)}),t.reverse()},getStrokedBBoxDefaultVisible=function(e){return e||(e=getVisibleElements()),getStrokedBBox(e,editorContext_$1.addSVGElementFromJson,editorContext_$1.pathActions)},getRotationAngleFromTransformList=function(e,t){if(!e)return 0;for(var n=e.numberOfItems,r=0;r|:\\-]","g"),"\\$&")},preventClickDefault=function(e){$$2(e).click(function(e){e.preventDefault()})},copyElem=function e(t,n){var r=document.createElementNS(t.namespaceURI,t.nodeName);if($$2.each(t.attributes,function(e,t){"-moz-math-font-style"!==t.localName&&r.setAttributeNS(t.namespaceURI,t.nodeName,t.value)}),r.removeAttribute("id"),r.id=n(),isWebkit()&&"path"===t.nodeName){var a=convertPath(t);r.setAttribute("d",a)}if($$2.each(t.childNodes,function(t,a){switch(a.nodeType){case 1:r.append(e(a,n));break;case 3:r.textContent=a.nodeValue}}),$$2(t).data("gsvg"))$$2(r).data("gsvg",r.firstChild);else if($$2(t).data("symbol")){var i=$$2(t).data("symbol");$$2(r).data("ref",i).data("symbol",i)}else"image"===r.tagName&&preventClickDefault(r);return r},isNullish=function(e){return null==e},$$3=jQuery,contextMenuExtensions={},hasCustomHandler=function(e){return Boolean(contextMenuExtensions[e])},getCustomHandler=function(e){return contextMenuExtensions[e].action},injectExtendedContextMenuItemIntoDom=function(e){Object.keys(contextMenuExtensions).length||$$3("#cmenu_canvas").append("
  • ");var t=e.shortcut||"";$$3("#cmenu_canvas").append("
  • "+e.label+""+t+"
  • ")},injectExtendedContextMenuItemsIntoDom=function(){Object.values(contextMenuExtensions).forEach(function(e){injectExtendedContextMenuItemIntoDom(e)})};function toAbsoluteURL(e){var t=document.createElement("a");return t.setAttribute("href",e),t.cloneNode(!1).href}function addScriptAtts(e,t){["id","class","type"].forEach(function(n){n in t&&(e[n]=t[n])})}function importSetGlobalDefault(e,t){return importSetGlobal(e,_extends({},t,{returnDefault:!0}))}function importSetGlobal(e,t){return _importSetGlobal.apply(this,arguments)}function _importSetGlobal(){return(_importSetGlobal=_asyncToGenerator(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",importModule(t,void 0,{returnDefault:a}));case 4:return e.next=6,importScript(t);case 6:return e.abrupt("return",window[r]);case 7:case"end":return e.stop()}},e,this)}))).apply(this,arguments)}function importScript(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Array.isArray(e)?Promise.all(e.map(function(e){return importScript(e,t)})):new Promise(function(n,r){var a=document.createElement("script"),i=function(){a.onerror=null,a.onload=null,a.remove(),a.src=""};a.defer="defer",addScriptAtts(a,t),a.onerror=function(){r(new Error("Failed to import: ".concat(e))),i()},a.onload=function(){n(),i()},a.src=e,document.head.append(a)})}function importModule(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 importModule(e,t)})):new Promise(function(n,a){var i="$importModule$"+Math.random().toString(32).slice(2),s=document.createElement("script"),o=function(){delete window[i],s.onerror=null,s.onload=null,s.remove(),URL.revokeObjectURL(s.src),s.src=""};addScriptAtts(s,t),s.defer="defer",s.type="module",s.onerror=function(){a(new Error("Failed to import: ".concat(e))),o()},s.onload=function(){n(window[i]),o()};var l=toAbsoluteURL(e),c="import * as m from '".concat(l.replace(/'/g,"\\'"),"'; window.").concat(i," = ").concat(r?"m.default || ":"","m;"),u=new Blob([c],{type:"text/javascript"});s.src=URL.createObjectURL(u),document.head.append(s)})}function jQueryPluginDBox(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ok:"Ok",cancel:"Cancel"};e("#dialog_container").draggable({cancel:"#dialog_content, #dialog_buttons *",containment:"window"}).css("position","absolute");var n=e("#dialog_box"),r=e("#dialog_buttons"),a=e("#dialog_content");function i(i,s,o,l,c,u){a.html("

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

    ")+"

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