diff --git a/.babelrc.json b/.babelrc.json deleted file mode 100644 index ece1d876..00000000 --- a/.babelrc.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "presets": [ - ["@babel/preset-env"] - ] -} diff --git a/.eslintignore b/.eslintignore index b752006a..8cfe15d9 100644 --- a/.eslintignore +++ b/.eslintignore @@ -7,10 +7,16 @@ dist docs/jsdoc archive -src/svgedit-config-es.js -src/svgedit-config-iife.js +jsconfig.json +mochawesome-report +releases +!.eslintrc.js +!.ncurc.js + +es-dev-server.config.js +nyc.config.js + svgedit-custom.css -src/xdomain-svgedit-config-iife.js # Vendor/minified files src/editor/jquery.min.js @@ -22,17 +28,5 @@ src/editor/js-hotkeys src/editor/jspdf/jspdf.min.js src/editor/jspdf/underscore-min.js -src/editor/extensions/mathjax +src/editor/extensions/ext-mathjax/mathjax -# Todo: We should at least check `compat/compat` in our other files, however -## Two "external" items are modified locally, so we undo their ignoring -src/external/**/* -!src/external/dom-polyfill -src/external/dom-polyfill/* -!src/external/dom-polyfill/dom-polyfill.js -!src/external/dynamic-import-polyfill - -mochawesome-report -releases -!.eslintrc.js -!.ncurc.js diff --git a/.eslintrc.js b/.eslintrc.js index 832a1d27..22f2dbbb 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -122,14 +122,15 @@ module.exports = { 'consistent-this': 'off', 'import/no-anonymous-default-export': 'off', 'node/no-unsupported-features/node-builtins': 'warn', - 'prefer-exponentiation-operator': 'warn' + 'prefer-exponentiation-operator': 'warn', + 'node/no-unsupported-features/es-syntax': 'off' }, overrides: [ // Locales have no need for importing outside of SVG-Edit // and translations may need a longer line length { files: [ - 'src/editor/locale/lang.*.js', 'src/editor/extensions/ext-locale/**', + 'src/editor/locale/lang.*.js', 'src/editor/extensions/*/locale/**', 'docs/tutorials/ExtensionDocs.md' ], rules: { @@ -140,12 +141,10 @@ module.exports = { // These browser files don't do importing or requiring { files: [ - 'src/editor/svgpathseg.js', 'src/editor/touch.js', 'src/editor/typedefs.js', 'src/editor/redirect-on-no-module-support.js', - 'src/editor/extensions/imagelib/index.js', - 'src/external/dom-polyfill/dom-polyfill.js', + 'src/editor/extensions/ext-imagelib/index.js', 'screencasts/svgopen2010/script.js' ], rules: { diff --git a/.gitignore b/.gitignore index 3e512014..a841f5bc 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,4 @@ mochawesome.json .vscode .eslintcache +.DS_Store diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 6adf1dcd..00000000 --- a/.gitmodules +++ /dev/null @@ -1,84 +0,0 @@ -[submodule "releases/svg-edit-2.8"] - path = releases/svg-edit-2.8 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v2.8 -[submodule "releases/svg-edit-2.8.1"] - path = releases/svg-edit-2.8.1 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v2.8.1 -[submodule "releases/svg-edit-3.0.0-alpha.1"] - path = releases/svg-edit-3.0.0-alpha.1 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0-alpha.1 -[submodule "releases/svg-edit-3.0.0-alpha.2"] - path = releases/svg-edit-3.0.0-alpha.2 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0-alpha.2 -[submodule "releases/svg-edit-3.0.0-alpha.3"] - path = releases/svg-edit-3.0.0-alpha.3 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0-alpha.3 -[submodule "releases/svg-edit-3.0.0-alpha.4"] - path = releases/svg-edit-3.0.0-alpha.4 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0-alpha.4 -[submodule "releases/svg-edit-3.0.0-rc.1"] - path = releases/svg-edit-3.0.0-rc.1 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0-rc.1 -[submodule "releases/svg-edit-3.0.0-rc.2"] - path = releases/svg-edit-3.0.0-rc.2 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0-rc.2 -[submodule "releases/svg-edit-3.0.0-rc.3"] - path = releases/svg-edit-3.0.0-rc.3 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0-rc.3 -[submodule "releases/svg-edit-3.0.0"] - path = releases/svg-edit-3.0.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.0 -[submodule "releases/svg-edit-3.0.1"] - path = releases/svg-edit-3.0.1 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.0.1 -[submodule "releases/svg-edit-3.1.0"] - path = releases/svg-edit-3.1.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.1.0 -[submodule "releases/svg-edit-3.1.1"] - path = releases/svg-edit-3.1.1 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.1.1 -[submodule "releases/svg-edit-3.2.0"] - path = releases/svg-edit-3.2.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v3.2.0 -[submodule "releases/svg-edit-4.0.0"] - path = releases/svg-edit-4.0.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v4.0.0 -[submodule "releases/svg-edit-4.0.1"] - path = releases/svg-edit-4.0.1 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v4.0.1 -[submodule "releases/svg-edit-4.1.0"] - path = releases/svg-edit-4.1.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v4.1.0 -[submodule "releases/svg-edit-4.2.0"] - path = releases/svg-edit-4.2.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v4.2.0 -[submodule "releases/svg-edit-4.3.0"] - path = releases/svg-edit-4.3.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v4.3.0 -[submodule "releases/svg-edit-5.0.0"] - path = releases/svg-edit-5.0.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v5.0.0 -[submodule "releases/svg-edit-5.1.0"] - path = releases/svg-edit-5.1.0 - url = https://github.com/SVG-Edit/svgedit.git - branch = release-v5.1.0 diff --git a/.htmlhintrc b/.htmlhintrc deleted file mode 100644 index 8412d07b..00000000 --- a/.htmlhintrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "title-require": false -} diff --git a/.ncurc.js b/.ncurc.js deleted file mode 100644 index 0509ea19..00000000 --- a/.ncurc.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -module.exports = { - reject: [ - // Todo: Old copy with jspdf which needs updating: https://github.com/SVG-Edit/svgedit/issues/51 - 'underscore' - ] -}; diff --git a/.npmignore b/.npmignore index d9ccf215..5b73c8a8 100644 --- a/.npmignore +++ b/.npmignore @@ -5,7 +5,6 @@ screencasts gh-disabled-workflows build lgtm.yml -.travis.yml cypress/** cypress.env.json diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index ceabf38f..00000000 --- a/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -os: linux -dist: xenial -language: node_js - -notifications: - email: false - -git: - submodules: false - -jobs: - include: - - language: ruby - rvm: - - 2.3 - script: - - bundle exec jekyll build - - language: node_js - node_js: - - 14 - # Reenable later if doing more than linting (i.e., testing) - # - 12 - # - 10 - script: - - npm run eslint diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..30029089 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team. All complaints will be reviewed and +investigated and will result in a response that is deemed necessary and +appropriate to the circumstances. The project team is obligated to maintain +confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq \ No newline at end of file diff --git a/FUNDING.yml b/FUNDING.yml index 0370ac13..7957d653 100644 --- a/FUNDING.yml +++ b/FUNDING.yml @@ -1,6 +1,6 @@ # These are supported funding model platforms -github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +github: [brettz9] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username diff --git a/README.md b/README.md index e4b1eca9..a18187bb 100644 --- a/README.md +++ b/README.md @@ -44,24 +44,19 @@ to join the project. ## Demo -### [Try SVG-edit here](https://svg-edit.github.io/svgedit/src/editor/svg-editor.html) +### [Try SVG-edit here](https://svg-edit.github.io/svgedit/dist/editor/index.html) -See a working editor on [`master`](https://svg-edit.github.io/svgedit/src/editor/svg-editor.html) (or its [ES6-Module](https://svg-edit.github.io/svgedit/src/editor/svg-editor-es.html) +See a working editor on [`master`](https://svg-edit.github.io/svgedit/src/editor/index.html) version, which requires a modern browser). -You may also try it at -(which redirects to a versioned URL). +We also build a systemJS version at [`master`](https://svg-edit.github.io/svgedit/dist/editor/system/index.html) You may also obtain URLs for specific [releases](https://github.com/SVG-Edit/svgedit/releases). -You may test the [latest version in `master`](https://svg-edit.github.io/svgedit/src/editor/svg-editor-es.html) -which is the ESM version. (The [non-ESM version](https://svg-edit.github.io/svgedit/src/editor/svg-editor.html) -on `master` may be updated less frequently.) - ## Installation ### Quick install @@ -203,14 +198,15 @@ incorporating SVGEdit. You will need to have Node.js/npm installed. ## Supported browsers -The following browsers had been tested for 2.6 or earlier and will -probably continue to work with 3.0. + - Opera 59+, + - IE 12+, + - Chrome 75+, + - FireFox 68+, + - Safari 10+ -- Firefox 1.5+ -- Opera 9.50+ -- Safari 4+ -- Chrome 1+ -- IE 9+ and Edge + Support for old browsers may require to use an older version of the package. However, + please open an issue if you need support for a specific version of your browser so + the project team can decide if we should support with the latest version. ## Further reading and more information @@ -223,3 +219,7 @@ probably continue to work with 3.0. * Join the [svg-edit mailing list](https://groups.google.com/forum/#!forum/svg-edit). * Join us on `#svg-edit` on `freenode.net` (or use the [web client](https://webchat.freenode.net/?channels=svg-edit)). + +# Hosting +SVGedit versions are deployed to: +[![Deploys by Netlify](https://www.netlify.com)](https://www.netlify.com/img/global/badges/netlify-color-accent.svg) diff --git a/src/editor/svg-editor.manifest b/archive/svg-editor.manifest similarity index 98% rename from src/editor/svg-editor.manifest rename to archive/svg-editor.manifest index 8534d59b..071ef35f 100644 --- a/src/editor/svg-editor.manifest +++ b/archive/svg-editor.manifest @@ -1,3 +1,4 @@ +@@ -1,156 +0,0 @@ # To-do: Change to a sample service-worker CACHE MANIFEST @@ -153,4 +154,4 @@ extensions/ext-shapes.js extensions/ext-star.js extensions/ext-storage.js extensions/ext-webappfind.js -extensions/ext-xdomain-messaging.js +extensions/ext-xdomain-messaging.js \ No newline at end of file diff --git a/babel.config.json b/babel.config.json new file mode 100644 index 00000000..e5c26b5f --- /dev/null +++ b/babel.config.json @@ -0,0 +1,11 @@ +{ + "presets": [ + [ + "@babel/env", + { + "useBuiltIns": "usage", + "corejs": "3.6.5" + } + ] + ] +} diff --git a/badges/coverage-badge.svg b/badges/coverage-badge.svg index 7ec30fa8..cca33b5e 100644 --- a/badges/coverage-badge.svg +++ b/badges/coverage-badge.svg @@ -1 +1 @@ -Statements 45.57%Statements 45.57%Branches 34.06%Branches 34.06%Lines 46.73%Lines 46.73%Functions 51.69%Functions 51.69% +Statements 51.13%Statements 51.13%Branches 40.85%Branches 40.85%Lines 51.84%Lines 51.84%Functions 58.67%Functions 58.67% diff --git a/badges/licenses-badge-dev.svg b/badges/licenses-badge-dev.svg index 831d6168..a7a34ae9 100644 --- a/badges/licenses-badge-dev.svg +++ b/badges/licenses-badge-dev.svg @@ -1 +1 @@ -License typesLicense types(all devDeps)(all devDeps)PermissivePermissive1. ISC1. ISC2. MIT2. MIT \ No newline at end of file +License typesLicense types(all devDeps)(all devDeps)PublicPublicdomaindomain1. (MIT OR CC0-1.0)1. (MIT OR CC0-1.0)2. CC0-1.02. CC0-1.03. Unlicense3. UnlicensePermissivePermissive1. (AFL-2.1 OR BSD-3-Clause)1. (AFL-2.1 OR BSD-3-Clause)2. (WTFPL OR ISC)2. (WTFPL OR ISC)3. 0BSD3. 0BSD4. Apache-2.04. Apache-2.05. BSD5. BSD6. BSD-2-Clause6. BSD-2-Clause7. BSD-3-Clause7. BSD-3-Clause8. CC-BY-3.08. CC-BY-3.09. CC-BY-4.09. CC-BY-4.010. ISC10. ISC11. MIT11. MIT12. WTFPL12. WTFPL13. Zlib13. ZlibMissingMissing1. better-assert (1.0.2)1. better-assert (1.0.2)2. callsite (1.0.0)2. callsite (1.0.0)3. component-bind (1.0.0)3. component-bind (1.0.0)4. component-inherit (0.0.3)4. component-inherit (0.0.3)5. exif-parser (0.1.12)5. exif-parser (0.1.12)6. indexof (0.0.1)6. indexof (0.0.1)7. object-component (0.0.3)7. object-component (0.0.3)8. process (0.5.2)8. process (0.5.2) \ No newline at end of file diff --git a/badges/licenses-badge.svg b/badges/licenses-badge.svg index 574fc099..5ed9448a 100644 --- a/badges/licenses-badge.svg +++ b/badges/licenses-badge.svg @@ -1 +1 @@ -License typesLicense types(project, deps, and bundled devDeps)(project, deps, and bundled devDeps)PermissivePermissive1. Apache-2.01. Apache-2.02. ISC2. ISC3. MIT3. MIT4. X114. X11WeaklyWeaklyprotectiveprotective1. LGPL-3.0-or-later1. LGPL-3.0-or-later \ No newline at end of file +License typesLicense types(project, deps, and bundled devDeps)(project, deps, and bundled devDeps)PermissivePermissive1. (MIT OR Apache-2.0)1. (MIT OR Apache-2.0)2. (MPL-2.0 OR Apache-2.0)2. (MPL-2.0 OR Apache-2.0)3. Apache-2.03. Apache-2.04. ISC4. ISC5. MIT5. MIT6. MIT OR SEE LICENSE IN FEEL-FREE.md6. MIT OR SEE LICENSE IN FEEL-FREE.md7. X117. X11WeaklyWeaklyprotectiveprotective1. LGPL-3.0-or-later1. LGPL-3.0-or-laterUncategorizedUncategorized1. Chromium's License (pathseg (1.2.0))1. Chromium's License (pathseg (1.2.0))MissingMissing1. null (base64-arraybuffer (0.2.0))1. null (base64-arraybuffer (0.2.0)) \ No newline at end of file diff --git a/badges/tests-badge.svg b/badges/tests-badge.svg index 0d1ca370..ecc8fc46 100644 --- a/badges/tests-badge.svg +++ b/badges/tests-badge.svg @@ -1 +1 @@ -TestsTests132/132132/132 \ No newline at end of file +TestsTests139/139139/139 \ No newline at end of file diff --git a/build/build-html.js b/build/build-html.js deleted file mode 100644 index 114e21f7..00000000 --- a/build/build-html.js +++ /dev/null @@ -1,148 +0,0 @@ -/* eslint-env node */ -import fs from 'promise-fs'; - -const filesAndReplacements = [ - { - input: 'src/editor/svg-editor-es.html', - output: 'src/editor/xdomain-svg-editor-es.html', - replacements: [ - [ - '', - '' - ] - ] - }, - { - input: 'src/editor/xdomain-svg-editor-es.html', - output: 'src/editor/xdomain-svg-editor.html', - replacements: [ - [ - '', - ` -` - ], - [ - '', - '' - ], - [ - '', - '' - ], - [ - '', - '' - ], - [ - '', - '' - ] - ] - }, - // Now that file has copied, we can replace the DOCTYPE in xdomain - { - input: 'src/editor/xdomain-svg-editor-es.html', - output: 'src/editor/xdomain-svg-editor-es.html', - replacements: [ - [ - '', - ` -` - ] - ] - }, - { - input: 'src/editor/svg-editor-es.html', - output: 'src/editor/svg-editor.html', - replacements: [ - [ - '', - ` -` - ], - [ - '', - '' - ], - [ - '', - '' - ], - [ - '', - '' - ], - [ - '', - '' - ] - ] - }, - { - input: 'src/editor/extensions/imagelib/openclipart-es.html', - output: 'src/editor/extensions/imagelib/openclipart.html', - replacements: [ - [ - '', - ` -` - ], - [ - '', - '' - ], - [ - '', - '' - ], - [ - '', - '' - ] - ] - }, - { - input: 'src/editor/extensions/imagelib/index-es.html', - output: 'src/editor/extensions/imagelib/index.html', - 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); // eslint-disable-line no-console - } - - 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); // eslint-disable-line no-console - return; - } - console.log(`Completed file ${input} rewriting!`); // eslint-disable-line no-console -}, Promise.resolve()); -console.log('Finished!'); // eslint-disable-line no-console -})(); diff --git a/cypress.json b/cypress.json index e4ee2e68..e76775b3 100644 --- a/cypress.json +++ b/cypress.json @@ -4,5 +4,14 @@ "video": false, "reporterOptions": { "configFile": "mocha-multi-reporters.json" + }, + "ignoreTestFiles": ["**/__snapshots__/*", "**/__image_snapshots__/*"], + "defaultCommandTimeout": 10000, + "pageLoadTimeout": 120000, + "cypress-plugin-snapshots": { + "autoCleanUp": true, + "prettier": true, + "updateSnapshots": false, + "diffLines": 5 } } diff --git a/cypress/integration/ui/__snapshots__/scenario.js.snap b/cypress/integration/ui/__snapshots__/scenario.js.snap new file mode 100644 index 00000000..d4d91bdb --- /dev/null +++ b/cypress/integration/ui/__snapshots__/scenario.js.snap @@ -0,0 +1,364 @@ +exports[`use various parts of svg-edit > check tool_source #0`] = ` + + + Layer 1 + + + +`; + +exports[`use various parts of svg-edit > check tool_fhpath #0`] = ` + + + Layer 1 + + + +`; + +exports[`use various parts of svg-edit > check tool_text #0`] = ` + + + Layer 1 + + + B + + + +`; + +exports[`use various parts of svg-edit > check tool_clone #0`] = ` + + + Layer 1 + + + B + + + B + + + +`; + +exports[`use various parts of svg-edit > check tool_italic #0`] = ` + + + Layer 1 + + + B + + + B + + + +`; + +exports[`use various parts of svg-edit > check tool_bold #0`] = ` + + + Layer 1 + + + B + + + B + + + +`; + +exports[`use various parts of svg-edit > check change color #0`] = ` + + + Layer 1 + + + B + + + B + + + +`; diff --git a/cypress/integration/ui/accessibility.js b/cypress/integration/ui/accessibility.js index b1363b03..c192d9f8 100644 --- a/cypress/integration/ui/accessibility.js +++ b/cypress/integration/ui/accessibility.js @@ -1,6 +1,6 @@ describe('UI - Accessibility', function () { beforeEach(() => { - cy.visit('/instrumented/editor/svg-editor-es.html'); + cy.visit('/instrumented/editor/index.html'); cy.injectAxe(); }); diff --git a/cypress/integration/ui/control-points.js b/cypress/integration/ui/control-points.js index bfaa5585..593f2f26 100644 --- a/cypress/integration/ui/control-points.js +++ b/cypress/integration/ui/control-points.js @@ -22,10 +22,10 @@ describe('UI - Control Points', function () { cy.get('#tool_source_save').click(); cy.get('#svg_1').click().click(); - cy.get('#pathpointgrip_0').trigger('mousedown', {which: 1}) + cy.get('#pathpointgrip_0').trigger('mousedown', {which: 1, force: true}) .trigger('mousemove', randomOffset(), randomOffset(), {force: true}) .trigger('mouseup', {force: true}); - cy.get('#pathpointgrip_1').trigger('mousedown', {which: 1}) + cy.get('#pathpointgrip_1').trigger('mousedown', {which: 1, force: true}) .trigger('mousemove', randomOffset(), randomOffset(), {force: true}) .trigger('mouseup', {force: true}); diff --git a/cypress/integration/ui/export.js b/cypress/integration/ui/export.js index 23fe4fb7..48d68ba2 100644 --- a/cypress/integration/ui/export.js +++ b/cypress/integration/ui/export.js @@ -14,7 +14,7 @@ describe('UI - Export tests', function () { it('Editor - No parameters: Export button clicking; dialog opens', () => { openMainMenu(); - cy.get('#tool_export').click(); + cy.get('#tool_export').click({force: true}); cy.get('#dialog_content select'); }); }); diff --git a/cypress/integration/ui/issues/issue-359.js b/cypress/integration/ui/issues/issue-359.js index a07749ca..fed05e2f 100644 --- a/cypress/integration/ui/issues/issue-359.js +++ b/cypress/integration/ui/issues/issue-359.js @@ -11,13 +11,13 @@ describe('Fix issue 359', function () { it('can undo without throwing', function () { cy.get('#tool_source').click(); cy.get('#svg_source_textarea') - .type('{selectall}') + .type('{selectall}', {force: true}) .type(` Layer 1 - `, {parseSpecialCharSequences: false}); + `, {parseSpecialCharSequences: false, force: true}); cy.get('#tool_source_save').click(); cy.get('#tool_undo').click(); cy.get('#tool_redo').click(); // test also redo to make the test more comprehensive diff --git a/cypress/integration/ui/issues/issue-364.js b/cypress/integration/ui/issues/issue-364.js index b2039918..9d024b3a 100644 --- a/cypress/integration/ui/issues/issue-364.js +++ b/cypress/integration/ui/issues/issue-364.js @@ -9,8 +9,10 @@ describe('Issue 364; IE errorwith rectangle selection by click', function () { }); it('should set rectangle selection after click', function () { + // eslint-disable-next-line cypress/no-unnecessary-waiting cy.get('#tools_rect_show') .trigger('mousedown', {force: true}) + .wait(100) // this delay seems necessary .trigger('mouseup', {force: true}) .should((button) => { expect(button).to.have.class('tool_button_current'); diff --git a/cypress/integration/ui/issues/issue-407.js b/cypress/integration/ui/issues/issue-407.js index 101727d9..a67f2f0b 100644 --- a/cypress/integration/ui/issues/issue-407.js +++ b/cypress/integration/ui/issues/issue-407.js @@ -11,7 +11,7 @@ describe('Fix issue 407', function () { it('can enter edit on text child', function () { cy.get('#tool_source').click(); cy.get('#svg_source_textarea') - .type('{selectall}') + .type('{selectall}', {force: true}) .type(` Layer 1 @@ -24,7 +24,12 @@ describe('Fix issue 407', function () { cy.get('#tool_source_save').click(); cy.get('#svg_1').click().dblclick(); cy.get('#a_text').should('exist'); - cy.get('#a_text').trigger('mousedown', {which: 1}).trigger('mouseup').dblclick().type('1234'); + cy.get('#a_text') + .trigger('mousedown', {which: 1, force: true}) + .trigger('mouseup', {force: true}) + .dblclick({force: true}); + // svgedit use the #text text field to capture the text + cy.get('#text').type('1234', {force: true}); cy.get('#a_text').should('have.text', 'he1234llo'); }); }); diff --git a/cypress/integration/ui/issues/issue-423.js b/cypress/integration/ui/issues/issue-423.js index dfb9d442..005d2311 100644 --- a/cypress/integration/ui/issues/issue-423.js +++ b/cypress/integration/ui/issues/issue-423.js @@ -11,7 +11,7 @@ describe('Fix issue 423', function () { it('should not throw when undoing the move', function () { cy.get('#tool_source').click(); cy.get('#svg_source_textarea') - .type('{selectall}') + .type('{selectall}', {force: true}) .type(` Layer 1 @@ -22,12 +22,12 @@ describe('Fix issue 423', function () { - `, {parseSpecialCharSequences: false}); - cy.get('#tool_source_save').click(); + `, {parseSpecialCharSequences: false, force: true}); + cy.get('#tool_source_save').click({force: true}); cy.get('#TANK1') .trigger('mousedown', {force: true}) .trigger('mousemove', 50, 0, {force: true}) .trigger('mouseup', {force: true}); - cy.get('#tool_undo').click(); + cy.get('#tool_undo').click({force: true}); }); }); diff --git a/cypress/integration/ui/scenario.js b/cypress/integration/ui/scenario.js new file mode 100644 index 00000000..c84dbe11 --- /dev/null +++ b/cypress/integration/ui/scenario.js @@ -0,0 +1,76 @@ +import { + visitAndApproveStorage +} from '../../support/ui-test-helper.js'; + +const testSnapshot = () => { + // cy.get('#tool_source').click({force: true}); + // cy.get('#svg_source_textarea').invoke('val').toMatchSnapshot(); + // cy.get('#tool_source_save').click({force: true}); + cy.get('#svgcontent').toMatchSnapshot(); +}; + +describe('use various parts of svg-edit', function () { + before(() => { + visitAndApproveStorage(); + }); + + it('check tool_source', function () { + cy.get('#tool_source').click({force: true}); + cy.get('#svg_source_textarea') + .type('{selectall}', {force: true}) + .type(` + + Layer 1 + + + `, {parseSpecialCharSequences: false}); + cy.get('#tool_source_save').click({force: true}); + testSnapshot(); + }); + it('check tool_fhpath', function () { + cy.get('#tool_fhpath') + .click({force: true}); + cy.get('#rect') + .trigger('mousemove', 200, 200, {force: true}) + .trigger('mousedown', 200, 200, {force: true}) + .trigger('mousemove', 20, 20, {force: true}) + .trigger('mouseup', {force: true}); + cy.get('#svgcontent').toMatchSnapshot(); + }); + it('check tool_text', function () { + cy.get('#tool_text') + .click({force: true}); + cy.get('#rect') + .trigger('mousedown', 'center', {force: true}) + .trigger('mouseup', {force: true}); + // svgedit use the #text text field to capture the text + // cy.get('#text').type('1234', {force: true}); + cy.get('#text').type('B', {force: true}); + testSnapshot(); + }); + + it('check tool_clone', function () { + cy.get('#svg_1').click({force: true}); + cy.get('#tool_clone') + .click({force: true}); + testSnapshot(); + }); + it('check tool_italic', function () { + cy.get('#svg_1').click({force: true}); + cy.get('#tool_italic') + .click({force: true}); + testSnapshot(); + }); + it('check tool_bold', function () { + cy.get('#svg_1').click({force: true}); + cy.get('#tool_bold') + .click({force: true}); + testSnapshot(); + }); + it('check change color', function () { + cy.get('#svg_1').click({force: true}); + cy.get('[data-rgb="#ffff00"]') + .click({force: true}); + testSnapshot(); + }); +}); diff --git a/cypress/integration/unit/path.js b/cypress/integration/unit/path.js index 443c24bd..e6124129 100644 --- a/cypress/integration/unit/path.js +++ b/cypress/integration/unit/path.js @@ -1,7 +1,8 @@ /* globals SVGPathSeg */ +import 'pathseg'; + import '../../../instrumented/editor/jquery.min.js'; -import '../../../instrumented/common/svgpathseg.js'; import {NS} from '../../../instrumented/common/namespaces.js'; import * as utilities from '../../../instrumented/common/utilities.js'; import * as pathModule from '../../../instrumented/svgcanvas/path.js'; diff --git a/cypress/integration/unit/test1.js b/cypress/integration/unit/test1.js index 5660d1a4..4b23449f 100644 --- a/cypress/integration/unit/test1.js +++ b/cypress/integration/unit/test1.js @@ -2,9 +2,10 @@ import '../../../instrumented/editor/jquery.min.js'; import '../../../instrumented/editor/jquery-ui/jquery-ui-1.8.17.custom.min.js'; -import '../../../instrumented/common/svgpathseg.js'; import SvgCanvas from '../../../instrumented/svgcanvas/svgcanvas.js'; +// import '../../../instrumented/' + describe('Basic Module', function () { // helper functions /* diff --git a/cypress/integration/unit/utilities-bbox.js b/cypress/integration/unit/utilities-bbox.js index fb089803..09ca6642 100644 --- a/cypress/integration/unit/utilities-bbox.js +++ b/cypress/integration/unit/utilities-bbox.js @@ -1,7 +1,8 @@ /* eslint-disable max-len */ +import 'pathseg'; + import '../../../instrumented/editor/jquery.min.js'; -import '../../../instrumented/common/svgpathseg.js'; import {NS} from '../../../instrumented/common/namespaces.js'; import * as utilities from '../../../instrumented/common/utilities.js'; import * as transformlist from '../../../instrumented/common/svgtransformlist.js'; diff --git a/cypress/integration/unit/utilities-performance.js b/cypress/integration/unit/utilities-performance.js index 5a167b5a..6db47d1e 100644 --- a/cypress/integration/unit/utilities-performance.js +++ b/cypress/integration/unit/utilities-performance.js @@ -1,7 +1,7 @@ /* eslint-disable max-len */ +import 'pathseg'; import '../../../instrumented/editor/jquery.min.js'; -import '../../../instrumented/common/svgpathseg.js'; import {NS} from '../../../instrumented/common/namespaces.js'; import * as utilities from '../../../instrumented/common/utilities.js'; import * as transformlist from '../../../instrumented/common/svgtransformlist.js'; diff --git a/cypress/plugins/main.js b/cypress/plugins/main.js index 118423bf..f72c424d 100644 --- a/cypress/plugins/main.js +++ b/cypress/plugins/main.js @@ -2,6 +2,7 @@ // the project's config changing) import codeCoverageTask from '@cypress/code-coverage/task.js'; +import {initPlugin} from 'cypress-plugin-snapshots/plugin.js'; export default (on, config) => { // `on` is used to hook into various events Cypress emits @@ -12,5 +13,6 @@ export default (on, config) => { // https://docs.cypress.io/guides/tooling/code-coverage.html#Install-the-plugin codeCoverageTask(on, config); + initPlugin(on, config); return config; }; diff --git a/cypress/support/index.js b/cypress/support/index.js index 8d1916eb..cf57e23e 100644 --- a/cypress/support/index.js +++ b/cypress/support/index.js @@ -42,3 +42,10 @@ import '@cypress/code-coverage/support.js'; * @see https://www.npmjs.com/package/cypress-axe */ import 'cypress-axe'; + +/***** + * SNAPSHOTS + * @see https://www.npmjs.com/package/cypress-plugin-snapshots + */ + +import 'cypress-plugin-snapshots/commands.js'; diff --git a/cypress/support/ui-test-helper.js b/cypress/support/ui-test-helper.js index 69d28514..0c57c3aa 100644 --- a/cypress/support/ui-test-helper.js +++ b/cypress/support/ui-test-helper.js @@ -4,7 +4,7 @@ export const approveStorage = () => { }; export const visitAndApproveStorage = () => { - cy.visit('/instrumented/editor/svg-editor-es.html'); + cy.visit('/instrumented/editor/index.html'); approveStorage(); }; diff --git a/dist/canvg.js b/dist/canvg.js deleted file mode 100644 index 23c96b60..00000000 --- a/dist/canvg.js +++ /dev/null @@ -1,4915 +0,0 @@ -var canvg = (function (exports) { - 'use strict'; - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; - } - - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - - return object; - } - - function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.get) { - return desc.get.call(receiver); - } - - return desc.value; - }; - } - - return _get(target, property, receiver || target); - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _iterableToArrayLimit(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - /** - * For parsing color values. - * @module RGBColor - * @author Stoyan Stefanov - * @see https://www.phpied.com/rgb-color-parser-in-javascript/ - * @license MIT - */ - var simpleColors = { - aliceblue: 'f0f8ff', - antiquewhite: 'faebd7', - aqua: '00ffff', - aquamarine: '7fffd4', - azure: 'f0ffff', - beige: 'f5f5dc', - bisque: 'ffe4c4', - black: '000000', - blanchedalmond: 'ffebcd', - blue: '0000ff', - blueviolet: '8a2be2', - brown: 'a52a2a', - burlywood: 'deb887', - cadetblue: '5f9ea0', - chartreuse: '7fff00', - chocolate: 'd2691e', - coral: 'ff7f50', - cornflowerblue: '6495ed', - cornsilk: 'fff8dc', - crimson: 'dc143c', - cyan: '00ffff', - darkblue: '00008b', - darkcyan: '008b8b', - darkgoldenrod: 'b8860b', - darkgray: 'a9a9a9', - darkgreen: '006400', - darkkhaki: 'bdb76b', - darkmagenta: '8b008b', - darkolivegreen: '556b2f', - darkorange: 'ff8c00', - darkorchid: '9932cc', - darkred: '8b0000', - darksalmon: 'e9967a', - darkseagreen: '8fbc8f', - darkslateblue: '483d8b', - darkslategray: '2f4f4f', - darkturquoise: '00ced1', - darkviolet: '9400d3', - deeppink: 'ff1493', - deepskyblue: '00bfff', - dimgray: '696969', - dodgerblue: '1e90ff', - feldspar: 'd19275', - firebrick: 'b22222', - floralwhite: 'fffaf0', - forestgreen: '228b22', - fuchsia: 'ff00ff', - gainsboro: 'dcdcdc', - ghostwhite: 'f8f8ff', - gold: 'ffd700', - goldenrod: 'daa520', - gray: '808080', - green: '008000', - greenyellow: 'adff2f', - honeydew: 'f0fff0', - hotpink: 'ff69b4', - indianred: 'cd5c5c', - indigo: '4b0082', - ivory: 'fffff0', - khaki: 'f0e68c', - lavender: 'e6e6fa', - lavenderblush: 'fff0f5', - lawngreen: '7cfc00', - lemonchiffon: 'fffacd', - lightblue: 'add8e6', - lightcoral: 'f08080', - lightcyan: 'e0ffff', - lightgoldenrodyellow: 'fafad2', - lightgrey: 'd3d3d3', - lightgreen: '90ee90', - lightpink: 'ffb6c1', - lightsalmon: 'ffa07a', - lightseagreen: '20b2aa', - lightskyblue: '87cefa', - lightslateblue: '8470ff', - lightslategray: '778899', - lightsteelblue: 'b0c4de', - lightyellow: 'ffffe0', - lime: '00ff00', - limegreen: '32cd32', - linen: 'faf0e6', - magenta: 'ff00ff', - maroon: '800000', - mediumaquamarine: '66cdaa', - mediumblue: '0000cd', - mediumorchid: 'ba55d3', - mediumpurple: '9370d8', - mediumseagreen: '3cb371', - mediumslateblue: '7b68ee', - mediumspringgreen: '00fa9a', - mediumturquoise: '48d1cc', - mediumvioletred: 'c71585', - midnightblue: '191970', - mintcream: 'f5fffa', - mistyrose: 'ffe4e1', - moccasin: 'ffe4b5', - navajowhite: 'ffdead', - navy: '000080', - oldlace: 'fdf5e6', - olive: '808000', - olivedrab: '6b8e23', - orange: 'ffa500', - orangered: 'ff4500', - orchid: 'da70d6', - palegoldenrod: 'eee8aa', - palegreen: '98fb98', - paleturquoise: 'afeeee', - palevioletred: 'd87093', - papayawhip: 'ffefd5', - peachpuff: 'ffdab9', - peru: 'cd853f', - pink: 'ffc0cb', - plum: 'dda0dd', - powderblue: 'b0e0e6', - purple: '800080', - red: 'ff0000', - rosybrown: 'bc8f8f', - royalblue: '4169e1', - saddlebrown: '8b4513', - salmon: 'fa8072', - sandybrown: 'f4a460', - seagreen: '2e8b57', - seashell: 'fff5ee', - sienna: 'a0522d', - silver: 'c0c0c0', - skyblue: '87ceeb', - slateblue: '6a5acd', - slategray: '708090', - snow: 'fffafa', - springgreen: '00ff7f', - steelblue: '4682b4', - tan: 'd2b48c', - teal: '008080', - thistle: 'd8bfd8', - tomato: 'ff6347', - turquoise: '40e0d0', - violet: 'ee82ee', - violetred: 'd02090', - wheat: 'f5deb3', - white: 'ffffff', - whitesmoke: 'f5f5f5', - yellow: 'ffff00', - yellowgreen: '9acd32' - }; // array of color definition objects - - var colorDefs = [{ - re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, - // 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(_) { - 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 Number.parseInt(b); - }); - } - }, { - re: /^(\w{2})(\w{2})(\w{2})$/, - // re: /^(?\w{2})(?\w{2})(?\w{2})$/, - example: ['#00ff00', '336699'], - 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 Number.parseInt(b, 16); - }); - } - }, { - re: /^(\w)(\w)(\w)$/, - // re: /^(?\w{1})(?\w{1})(?\w{1})$/, - example: ['#fb0', 'f0f'], - 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 Number.parseInt(b + b, 16); - }); - } - }]; - /** - * A class to parse color values. - */ - - var RGBColor = /*#__PURE__*/function () { - /** - * @param {string} colorString - */ - function RGBColor(colorString) { - var _this = this; - - _classCallCheck(this, RGBColor); - - this.ok = false; // strip any leading # - - if (colorString.charAt(0) === '#') { - // remove # if any - colorString = colorString.substr(1, 6); - } - - colorString = colorString.replace(/ /g, ''); - colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches - // and overwrite the input - - if (colorString in simpleColors) { - colorString = simpleColors[colorString]; - } // end of simple type-in colors - // search through the definitions to find a match - - - colorDefs.forEach(function (_ref) { - var re = _ref.re, - processor = _ref.process; - var bits = re.exec(colorString); - - if (bits) { - var _processor = processor.apply(void 0, _toConsumableArray(bits)), - _processor2 = _slicedToArray(_processor, 3), - r = _processor2[0], - g = _processor2[1], - b = _processor2[2]; - - Object.assign(_this, { - r: r, - g: g, - b: b - }); - _this.ok = true; - } - }); // validate/cleanup values - - this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r; - this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g; - this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b; - } // some getters - - /** - * @returns {string} - */ - - - _createClass(RGBColor, [{ - key: "toRGB", - value: function toRGB() { - return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; - } - /** - * @returns {string} - */ - - }, { - key: "toHex", - value: function toHex() { - var r = this.r.toString(16); - var g = this.g.toString(16); - var b = this.b.toString(16); - - if (r.length === 1) { - r = '0' + r; - } - - if (g.length === 1) { - g = '0' + g; - } - - if (b.length === 1) { - b = '0' + b; - } - - return '#' + r + g + b; - } - /** - * Offers a bulleted list of help. - * @returns {HTMLUListElement} - */ - - }], [{ - key: "getHelpXML", - value: function getHelpXML() { - var examples = [].concat(_toConsumableArray(colorDefs.flatMap(function (_ref2) { - var example = _ref2.example; - return example; - })), _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 = "\n margin: 3px;\n border: 1px solid black;\n background: ".concat(listColor.toHex(), ";\n color: ").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; - } - }]); - - return RGBColor; - }(); - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function _classCallCheck$1(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - /* eslint-disable no-bitwise, unicorn/prefer-query-selector */ - - /** - * 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: - * {@link https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript}. - * - * @module StackBlur - * @author Mario Klingemann - * 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. - */ - - /* eslint-disable max-len */ - - - 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]; - /** - * @param {string|HTMLCanvasElement} canvas - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @throws {Error|TypeError} - * @returns {ImageData} See {@link https://html.spec.whatwg.org/multipage/canvas.html#imagedata} - */ - - - function getImageDataFromCanvas(canvas, topX, topY, width, height) { - if (typeof canvas === 'string') { - canvas = document.getElementById(canvas); - } - - if (!canvas || _typeof(canvas) !== 'object' || !('getContext' in canvas)) { - throw new TypeError('Expecting canvas with `getContext` method ' + 'in processCanvasRGB(A) calls!'); - } - - var context = canvas.getContext('2d'); - - try { - return context.getImageData(topX, topY, width, height); - } catch (e) { - throw new Error('unable to access image data: ' + e); - } - } - /** - * @param {HTMLCanvasElement} canvas - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @param {Float} radius - * @returns {undefined} - */ - - - function processCanvasRGBA(canvas, topX, topY, width, height, radius) { - if (isNaN(radius) || radius < 1) { - return; - } - - radius |= 0; - var imageData = getImageDataFromCanvas(canvas, topX, topY, width, height); - imageData = processImageDataRGBA(imageData, topX, topY, width, height, radius); - canvas.getContext('2d').putImageData(imageData, topX, topY); - } - /** - * @param {ImageData} imageData - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @param {Float} radius - * @returns {ImageData} - */ - - - function processImageDataRGBA(imageData, topX, topY, width, height, radius) { - var pixels = imageData.data; - var x, y, i, p, yp, yi, yw, rSum, gSum, bSum, aSum, rOutSum, gOutSum, bOutSum, aOutSum, rInSum, gInSum, bInSum, aInSum, pr, pg, pb, pa, rbs; - var div = 2 * radius + 1; // const w4 = width << 2; - - var widthMinus1 = width - 1; - var heightMinus1 = height - 1; - var radiusPlus1 = radius + 1; - var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2; - var stackStart = new BlurStack(); - var stack = stackStart; - var stackEnd; - - for (i = 1; i < div; i++) { - stack = stack.next = new BlurStack(); - - if (i === radiusPlus1) { - stackEnd = stack; - } - } - - stack.next = stackStart; - var stackIn = null; - var stackOut = null; - yw = yi = 0; - var mulSum = mulTable[radius]; - var shgSum = shgTable[radius]; - - for (y = 0; y < height; y++) { - rInSum = gInSum = bInSum = aInSum = rSum = gSum = bSum = aSum = 0; - rOutSum = radiusPlus1 * (pr = pixels[yi]); - gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); - bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); - aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); - rSum += sumFactor * pr; - gSum += sumFactor * pg; - bSum += sumFactor * pb; - aSum += sumFactor * pa; - stack = stackStart; - - for (i = 0; i < radiusPlus1; i++) { - stack.r = pr; - stack.g = pg; - stack.b = pb; - stack.a = pa; - stack = stack.next; - } - - for (i = 1; i < radiusPlus1; i++) { - p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2); - rSum += (stack.r = pr = pixels[p]) * (rbs = radiusPlus1 - i); - gSum += (stack.g = pg = pixels[p + 1]) * rbs; - bSum += (stack.b = pb = pixels[p + 2]) * rbs; - aSum += (stack.a = pa = pixels[p + 3]) * rbs; - rInSum += pr; - gInSum += pg; - bInSum += pb; - aInSum += pa; - stack = stack.next; - } - - stackIn = stackStart; - stackOut = stackEnd; - - for (x = 0; x < width; x++) { - pixels[yi + 3] = pa = aSum * mulSum >> shgSum; - - if (pa !== 0) { - pa = 255 / pa; - pixels[yi] = (rSum * mulSum >> shgSum) * pa; - pixels[yi + 1] = (gSum * mulSum >> shgSum) * pa; - pixels[yi + 2] = (bSum * mulSum >> shgSum) * pa; - } else { - pixels[yi] = pixels[yi + 1] = pixels[yi + 2] = 0; - } - - rSum -= rOutSum; - gSum -= gOutSum; - bSum -= bOutSum; - aSum -= aOutSum; - rOutSum -= stackIn.r; - gOutSum -= stackIn.g; - bOutSum -= stackIn.b; - aOutSum -= stackIn.a; - p = yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1) << 2; - rInSum += stackIn.r = pixels[p]; - gInSum += stackIn.g = pixels[p + 1]; - bInSum += stackIn.b = pixels[p + 2]; - aInSum += stackIn.a = pixels[p + 3]; - rSum += rInSum; - gSum += gInSum; - bSum += bInSum; - aSum += aInSum; - stackIn = stackIn.next; - rOutSum += pr = stackOut.r; - gOutSum += pg = stackOut.g; - bOutSum += pb = stackOut.b; - aOutSum += pa = stackOut.a; - rInSum -= pr; - gInSum -= pg; - bInSum -= pb; - aInSum -= pa; - stackOut = stackOut.next; - yi += 4; - } - - yw += width; - } - - for (x = 0; x < width; x++) { - gInSum = bInSum = aInSum = rInSum = gSum = bSum = aSum = rSum = 0; - yi = x << 2; - rOutSum = radiusPlus1 * (pr = pixels[yi]); - gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); - bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); - aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); - rSum += sumFactor * pr; - gSum += sumFactor * pg; - bSum += sumFactor * pb; - aSum += sumFactor * pa; - stack = stackStart; - - for (i = 0; i < radiusPlus1; i++) { - stack.r = pr; - stack.g = pg; - stack.b = pb; - stack.a = pa; - stack = stack.next; - } - - yp = width; - - for (i = 1; i <= radius; i++) { - yi = yp + x << 2; - rSum += (stack.r = pr = pixels[yi]) * (rbs = radiusPlus1 - i); - gSum += (stack.g = pg = pixels[yi + 1]) * rbs; - bSum += (stack.b = pb = pixels[yi + 2]) * rbs; - aSum += (stack.a = pa = pixels[yi + 3]) * rbs; - rInSum += pr; - gInSum += pg; - bInSum += pb; - aInSum += pa; - stack = stack.next; - - if (i < heightMinus1) { - yp += width; - } - } - - yi = x; - stackIn = stackStart; - stackOut = stackEnd; - - for (y = 0; y < height; y++) { - p = yi << 2; - pixels[p + 3] = pa = aSum * mulSum >> shgSum; - - if (pa > 0) { - pa = 255 / pa; - pixels[p] = (rSum * mulSum >> shgSum) * pa; - pixels[p + 1] = (gSum * mulSum >> shgSum) * pa; - pixels[p + 2] = (bSum * mulSum >> shgSum) * pa; - } else { - pixels[p] = pixels[p + 1] = pixels[p + 2] = 0; - } - - rSum -= rOutSum; - gSum -= gOutSum; - bSum -= bOutSum; - aSum -= aOutSum; - rOutSum -= stackIn.r; - gOutSum -= stackIn.g; - bOutSum -= stackIn.b; - aOutSum -= stackIn.a; - p = x + ((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width << 2; - rSum += rInSum += stackIn.r = pixels[p]; - gSum += gInSum += stackIn.g = pixels[p + 1]; - bSum += bInSum += stackIn.b = pixels[p + 2]; - aSum += aInSum += stackIn.a = pixels[p + 3]; - stackIn = stackIn.next; - rOutSum += pr = stackOut.r; - gOutSum += pg = stackOut.g; - bOutSum += pb = stackOut.b; - aOutSum += pa = stackOut.a; - rInSum -= pr; - gInSum -= pg; - bInSum -= pb; - aInSum -= pa; - stackOut = stackOut.next; - yi += width; - } - } - - return imageData; - } - /** - * - */ - - - var BlurStack = - /** - * Set properties. - */ - function BlurStack() { - _classCallCheck$1(this, BlurStack); - - this.r = 0; - this.g = 0; - this.b = 0; - this.a = 0; - this.next = null; - }; - - /** - * 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} - */ - - /** - * @typedef {PlainObject} module:canvg.CanvgOptions - * @property {boolean} ignoreMouse true => ignore mouse events - * @property {boolean} ignoreAnimation true => ignore animations - * @property {boolean} ignoreDimensions true => does not try to resize canvas - * @property {boolean} ignoreClear true => does not clear canvas - * @property {Integer} offsetX int => draws at a x offset - * @property {Integer} offsetY int => draws at a y offset - * @property {Integer} scaleWidth int => scales horizontally to width - * @property {Integer} scaleHeight int => scales vertically to height - * @property {module:canvg.ForceRedraw} forceRedraw function => will call the function on every frame, if it returns true, will redraw - * @property {boolean} log Adds log function - * @property {boolean} useCORS Whether to set CORS `crossOrigin` for the image to `Anonymous` - */ - - /** - * If called with no arguments, it will replace all `` elements on the page - * 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 {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 (isNullish(target) && isNullish(s) && isNullish(opts)) { - var svgTags = document.querySelectorAll('svg'); - return Promise.all(_toConsumableArray(svgTags).map(function (svgTag) { - var c = document.createElement('canvas'); - c.width = svgTag.clientWidth; - c.height = svgTag.clientHeight; - svgTag.before(c); - svgTag.remove(); - var div = document.createElement('div'); - div.append(svgTag); - return canvg(c, div.innerHTML); - })); - } - - if (typeof target === 'string') { - target = document.getElementById(target); - } // store class on canvas - - - 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')) { - target.svg = svg; - } - - var ctx = target.getContext('2d'); - - if (typeof s.documentElement !== 'undefined') { - // load from xml doc - return svg.loadXmlDoc(ctx, s); - } - - if (s.substr(0, 1) === '<') { - // load from xml string - return svg.loadXml(ctx, s); - } // load from url - - - return svg.load(ctx, s); - }; - /* eslint-disable jsdoc/check-types */ - - /** - * @param {module:canvg.CanvgOptions} opts - * @returns {object} - * @todo Flesh out exactly what object is returned here (after updating to latest and reincluding our changes here and those of StackBlur) - */ - - function build(opts) { - /* eslint-enable jsdoc/check-types */ - var svg = { - opts: opts - }; - svg.FRAMERATE = 30; - svg.MAX_VIRTUAL_PIXELS = 30000; - - 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 - - - svg.init = function (ctx) { - var uniqueId = 0; - - svg.UniqueId = function () { - uniqueId++; - return 'canvg' + uniqueId; - }; - - svg.Definitions = {}; - svg.Styles = {}; - svg.Animations = []; - svg.Images = []; - svg.ctx = ctx; - svg.ViewPort = { - viewPorts: [], - Clear: function Clear() { - this.viewPorts = []; - }, - SetCurrent: function SetCurrent(width, height) { - this.viewPorts.push({ - width: width, - height: height - }); - }, - RemoveCurrent: function RemoveCurrent() { - this.viewPorts.pop(); - }, - Current: function Current() { - return this.viewPorts[this.viewPorts.length - 1]; - }, - width: function width() { - return this.Current().width; - }, - height: function height() { - return this.Current().height; - }, - ComputeSize: function ComputeSize(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); - } - }; - }; - - svg.init(); // images loaded - - svg.ImagesLoaded = function () { - return svg.Images.every(function (img) { - return img.loaded; - }); - }; // trim - - - svg.trim = function (s) { - return s.replace(/^\s+|\s+$/g, ''); - }; // compress spaces - - - svg.compressSpaces = function (s) { - return s.replace(/\s+/gm, ' '); - }; // ajax - // Todo: Replace with `fetch` and polyfill - - - svg.ajax = function (url, asynch) { - var AJAX = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP'); - - 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); - }); - AJAX.send(null); - }); - } - - AJAX.open('GET', url, false); - AJAX.send(null); - return AJAX.responseText; - }; // parse xml - - - svg.parseXml = function (xml) { - if (window.DOMParser) { - var parser = new DOMParser(); - return parser.parseFromString(xml, 'text/xml'); - } - - xml = xml.replace(/]*>/, ''); - var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM'); - xmlDoc.async = 'false'; - xmlDoc.loadXML(xml); - return xmlDoc; - }; // text extensions - // get the text baseline - - - var textBaselineMapping = { - baseline: 'alphabetic', - 'before-edge': 'top', - 'text-before-edge': 'top', - middle: 'middle', - central: 'middle', - 'after-edge': 'bottom', - 'text-after-edge': 'bottom', - ideographic: 'ideographic', - alphabetic: 'alphabetic', - hanging: 'hanging', - mathematical: 'alphabetic' - }; - - svg.Property = /*#__PURE__*/function () { - function Property(name, value) { - _classCallCheck(this, Property); - - this.name = name; - this.value = value; - } - - _createClass(Property, [{ - key: "getValue", - value: function getValue() { - return this.value; - } - }, { - key: "hasValue", - value: function hasValue() { - return !isNullish(this.value) && this.value !== ''; - } // return the numerical value of the property - - }, { - key: "numValue", - value: function numValue() { - if (!this.hasValue()) return 0; - var n = Number.parseFloat(this.value); - - if (String(this.value).endsWith('%')) { - n /= 100.0; - } - - return n; - } - }, { - key: "valueOrDefault", - value: function valueOrDefault(def) { - if (this.hasValue()) return this.value; - return def; - } - }, { - key: "numValueOrDefault", - value: function numValueOrDefault(def) { - if (this.hasValue()) return this.numValue(); - return def; - } // color extensions - // augment the current color value with the opacity - - }, { - key: "addOpacity", - value: function addOpacity(opacityProp) { - var newValue = this.value; - - if (!isNullish(opacityProp.value) && opacityProp.value !== '' && typeof this.value === 'string') { - // can only add opacity to colors, not patterns - var color = new RGBColor(this.value); - - if (color.ok) { - newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacityProp.numValue() + ')'; - } - } - - return new svg.Property(this.name, newValue); - } // definition extensions - // get the definition from the definitions table - - }, { - key: "getDefinition", - value: function getDefinition() { - var name = this.value.match(/#([^)'"]+)/); - - if (name) { - name = name[1]; - } - - if (!name) { - name = this.value; - } - - return svg.Definitions[name]; - } - }, { - key: "isUrlDefinition", - value: function isUrlDefinition() { - return this.value.startsWith('url('); - } - }, { - key: "getFillStyleDefinition", - value: function getFillStyleDefinition(e, opacityProp) { - var def = this.getDefinition(); // gradient - - if (!isNullish(def) && def.createGradient) { - return def.createGradient(svg.ctx, e, opacityProp); - } // pattern - - - if (!isNullish(def) && def.createPattern) { - if (def.getHrefAttribute().hasValue()) { - var pt = def.attribute('patternTransform'); - def = def.getHrefAttribute().getDefinition(); - - if (pt.hasValue()) { - def.attribute('patternTransform', true).value = pt.value; - } - } - - return def.createPattern(svg.ctx, e); - } - - return null; - } // length extensions - - }, { - key: "getDPI", - value: function getDPI(viewPort) { - return 96.0; // TODO: compute? - } - }, { - key: "getEM", - value: function getEM(viewPort) { - var em = 12; - var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); - if (fontSize.hasValue()) em = fontSize.toPixels(viewPort); - return em; - } - }, { - key: "getUnits", - value: function getUnits() { - return String(this.value).replace(/[\d.-]/g, ''); - } // get the length as pixels - - }, { - key: "toPixels", - value: function toPixels(viewPort, processPercent) { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('em')) return this.numValue() * this.getEM(viewPort); - if (s.endsWith('ex')) return this.numValue() * this.getEM(viewPort) / 2.0; - if (s.endsWith('px')) return this.numValue(); - if (s.endsWith('pt')) return this.numValue() * this.getDPI(viewPort) * (1.0 / 72.0); - if (s.endsWith('pc')) return this.numValue() * 15; - if (s.endsWith('cm')) return this.numValue() * this.getDPI(viewPort) / 2.54; - if (s.endsWith('mm')) return this.numValue() * this.getDPI(viewPort) / 25.4; - if (s.endsWith('in')) return this.numValue() * this.getDPI(viewPort); - if (s.endsWith('%')) return this.numValue() * svg.ViewPort.ComputeSize(viewPort); - var n = this.numValue(); - if (processPercent && n < 1.0) return n * svg.ViewPort.ComputeSize(viewPort); - return n; - } // time extensions - // get the time as milliseconds - - }, { - key: "toMilliseconds", - value: function toMilliseconds() { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('ms')) return this.numValue(); - if (s.endsWith('s')) return this.numValue() * 1000; - return this.numValue(); - } // angle extensions - // get the angle as radians - - }, { - key: "toRadians", - value: function toRadians() { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('deg')) return this.numValue() * (Math.PI / 180.0); - if (s.endsWith('grad')) return this.numValue() * (Math.PI / 200.0); - if (s.endsWith('rad')) return this.numValue(); - return this.numValue() * (Math.PI / 180.0); - } - }, { - key: "toTextBaseline", - value: function toTextBaseline() { - if (!this.hasValue()) return null; - return textBaselineMapping[this.value]; - } - }]); - - return Property; - }(); // fonts - - - svg.Font = { - Styles: 'normal|italic|oblique|inherit', - 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 = !isNullish(inherit) ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); - return { - fontFamily: fontFamily || f.fontFamily, - fontSize: fontSize || f.fontSize, - fontStyle: fontStyle || f.fontStyle, - fontWeight: fontWeight || f.fontWeight, - fontVariant: fontVariant || f.fontVariant, - toString: function toString() { - return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' '); - } - }; - }, - Parse: function Parse(s) { - var _this = this; - - var f = {}; - var ds = svg.trim(svg.compressSpaces(s || '')).split(' '); - var set = { - fontSize: false, - fontStyle: false, - fontWeight: false, - fontVariant: false - }; - var ff = ''; - ds.forEach(function (d) { - if (!set.fontStyle && _this.Styles.includes(d)) { - if (d !== 'inherit') { - f.fontStyle = d; - } - - set.fontStyle = true; - } else if (!set.fontVariant && _this.Variants.includes(d)) { - if (d !== 'inherit') { - f.fontVariant = d; - } - - set.fontStyle = set.fontVariant = true; - } else if (!set.fontWeight && _this.Weights.includes(d)) { - if (d !== 'inherit') { - f.fontWeight = d; - } - - set.fontStyle = set.fontVariant = set.fontWeight = true; - } else if (!set.fontSize) { - if (d !== 'inherit') { - f.fontSize = d.split('/')[0]; - } - - set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; - } else if (d !== 'inherit') { - ff += d; - } - }); - - if (ff !== '') { - f.fontFamily = ff; - } - - return f; - } - }; // points and paths - - svg.ToNumberArray = function (s) { - var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); - return a.map(function (_a) { - return Number.parseFloat(_a); - }); - }; - - svg.Point = /*#__PURE__*/function () { - function _class(x, y) { - _classCallCheck(this, _class); - - this.x = x; - this.y = y; - } - - _createClass(_class, [{ - key: "angleTo", - value: function angleTo(p) { - return Math.atan2(p.y - this.y, p.x - this.x); - } - }, { - key: "applyTransform", - value: function applyTransform(v) { - var xp = this.x * v[0] + this.y * v[2] + v[4]; - var yp = this.x * v[1] + this.y * v[3] + v[5]; - this.x = xp; - this.y = yp; - } - }]); - - return _class; - }(); - - svg.CreatePoint = function (s) { - var a = svg.ToNumberArray(s); - return new svg.Point(a[0], a[1]); - }; - - svg.CreatePath = function (s) { - var a = svg.ToNumberArray(s); - var path = []; - - for (var i = 0; i < a.length; i += 2) { - path.push(new svg.Point(a[i], a[i + 1])); - } - - return path; - }; // bounding box - - - svg.BoundingBox = /*#__PURE__*/function () { - function _class2(x1, y1, x2, y2) { - _classCallCheck(this, _class2); - - // pass in initial points if you want - this.x1 = Number.NaN; - this.y1 = Number.NaN; - this.x2 = Number.NaN; - this.y2 = Number.NaN; - this.addPoint(x1, y1); - this.addPoint(x2, y2); - } - - _createClass(_class2, [{ - key: "x", - value: function x() { - return this.x1; - } - }, { - key: "y", - value: function y() { - return this.y1; - } - }, { - key: "width", - value: function width() { - return this.x2 - this.x1; - } - }, { - key: "height", - value: function height() { - return this.y2 - this.y1; - } - }, { - key: "addPoint", - value: function addPoint(x, y) { - if (!isNullish(x)) { - if (isNaN(this.x1) || isNaN(this.x2)) { - this.x1 = x; - this.x2 = x; - } - - if (x < this.x1) this.x1 = x; - if (x > this.x2) this.x2 = x; - } - - if (!isNullish(y)) { - if (isNaN(this.y1) || isNaN(this.y2)) { - this.y1 = y; - this.y2 = y; - } - - if (y < this.y1) this.y1 = y; - if (y > this.y2) this.y2 = y; - } - } - }, { - key: "addX", - value: function addX(x) { - this.addPoint(x, null); - } - }, { - key: "addY", - value: function addY(y) { - this.addPoint(null, y); - } - }, { - key: "addBoundingBox", - value: function addBoundingBox(bb) { - this.addPoint(bb.x1, bb.y1); - this.addPoint(bb.x2, bb.y2); - } - }, { - key: "addQuadraticCurve", - value: function addQuadraticCurve(p0x, p0y, p1x, p1y, p2x, p2y) { - var cp1x = p0x + 2 / 3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) - - var cp1y = p0y + 2 / 3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) - - var cp2x = cp1x + 1 / 3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) - - var cp2y = cp1y + 1 / 3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) - - this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); - } - }, { - key: "addBezierCurve", - value: function addBezierCurve(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { - var _this2 = this; - - // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html - var p0 = [p0x, p0y], - p1 = [p1x, p1y], - p2 = [p2x, p2y], - p3 = [p3x, p3y]; - this.addPoint(p0[0], p0[1]); - this.addPoint(p3[0], p3[1]); - - var _loop = function _loop(i) { - var f = function f(t) { - return Math.pow(1 - t, 3) * p0[i] + 3 * Math.pow(1 - t, 2) * t * p1[i] + 3 * (1 - t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; - }; - - var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; - var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; - var c = 3 * p1[i] - 3 * p0[i]; - - if (a === 0) { - if (b === 0) return "continue"; - var t = -c / b; - - if (t > 0 && t < 1) { - if (i === 0) _this2.addX(f(t)); - if (i === 1) _this2.addY(f(t)); - } - - return "continue"; - } - - var b2ac = Math.pow(b, 2) - 4 * c * a; - if (b2ac < 0) return "continue"; - var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); - - if (t1 > 0 && t1 < 1) { - if (i === 0) _this2.addX(f(t1)); - if (i === 1) _this2.addY(f(t1)); - } - - var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); - - if (t2 > 0 && t2 < 1) { - if (i === 0) _this2.addX(f(t2)); - if (i === 1) _this2.addY(f(t2)); - } - }; - - for (var i = 0; i <= 1; i++) { - var _ret = _loop(i); - - if (_ret === "continue") continue; - } - } - }, { - key: "isPointInBox", - value: function isPointInBox(x, y) { - return this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2; - } - }]); - - return _class2; - }(); // transforms - - - svg.Transform = /*#__PURE__*/function () { - function _class3(v) { - var _this6 = this; - - _classCallCheck(this, _class3); - - this.Type = { - translate: function translate(s) { - _classCallCheck(this, translate); - - this.p = svg.CreatePoint(s); - - this.apply = function (ctx) { - ctx.translate(this.p.x || 0.0, this.p.y || 0.0); - }; - - this.unapply = function (ctx) { - ctx.translate(-1.0 * this.p.x || 0.0, -1.0 * this.p.y || 0.0); - }; - - this.applyToPoint = function (p) { - p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); - }; - }, - rotate: function rotate(s) { - _classCallCheck(this, rotate); - - var a = svg.ToNumberArray(s); - this.angle = new svg.Property('angle', a[0]); - this.cx = a[1] || 0; - this.cy = a[2] || 0; - - this.apply = function (ctx) { - ctx.translate(this.cx, this.cy); - ctx.rotate(this.angle.toRadians()); - ctx.translate(-this.cx, -this.cy); - }; - - this.unapply = function (ctx) { - ctx.translate(this.cx, this.cy); - ctx.rotate(-1.0 * this.angle.toRadians()); - ctx.translate(-this.cx, -this.cy); - }; - - this.applyToPoint = function (p) { - 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([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); - }; - }, - scale: function scale(s) { - _classCallCheck(this, scale); - - this.p = svg.CreatePoint(s); - - this.apply = function (ctx) { - ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); - }; - - this.unapply = function (ctx) { - ctx.scale(1.0 / this.p.x || 1.0, 1.0 / this.p.y || this.p.x || 1.0); - }; - - this.applyToPoint = function (p) { - p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); - }; - }, - matrix: function matrix(s) { - _classCallCheck(this, matrix); - - this.m = svg.ToNumberArray(s); - - this.apply = function (ctx) { - ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); - }; - - this.applyToPoint = function (p) { - p.applyTransform(this.m); - }; - } - }; - Object.assign(this.Type, { - SkewBase: /*#__PURE__*/function (_this$Type$matrix) { - _inherits(SkewBase, _this$Type$matrix); - - var _super = _createSuper(SkewBase); - - function SkewBase(s) { - var _this3; - - _classCallCheck(this, SkewBase); - - _this3 = _super.call(this, s); - _this3.angle = new svg.Property('angle', s); - return _this3; - } - - return SkewBase; - }(this.Type.matrix) - }); - Object.assign(this.Type, { - skewX: /*#__PURE__*/function (_this$Type$SkewBase) { - _inherits(skewX, _this$Type$SkewBase); - - var _super2 = _createSuper(skewX); - - function skewX(s) { - var _this4; - - _classCallCheck(this, skewX); - - _this4 = _super2.call(this, s); - _this4.m = [1, 0, Math.tan(_this4.angle.toRadians()), 1, 0, 0]; - return _this4; - } - - return skewX; - }(this.Type.SkewBase), - skewY: /*#__PURE__*/function (_this$Type$SkewBase2) { - _inherits(skewY, _this$Type$SkewBase2); - - var _super3 = _createSuper(skewY); - - function skewY(s) { - var _this5; - - _classCallCheck(this, skewY); - - _this5 = _super3.call(this, s); - _this5.m = [1, Math.tan(_this5.angle.toRadians()), 0, 1, 0, 0]; - return _this5; - } - - return skewY; - }(this.Type.SkewBase) - }); - var data = svg.trim(svg.compressSpaces(v)).replace(/\)([a-zA-Z])/g, ') $1').replace(/\)(\s?,\s?)/g, ') ').split(/\s(?=[a-z])/); - this.transforms = data.map(function (d) { - var type = svg.trim(d.split('(')[0]); - var s = d.split('(')[1].replace(')', ''); - var transform = new _this6.Type[type](s); - transform.type = type; - return transform; - }); - } - - _createClass(_class3, [{ - key: "apply", - value: function apply(ctx) { - this.transforms.forEach(function (transform) { - transform.apply(ctx); - }); - } - }, { - key: "unapply", - value: function unapply(ctx) { - for (var i = this.transforms.length - 1; i >= 0; i--) { - this.transforms[i].unapply(ctx); - } - } - }, { - key: "applyToPoint", - value: function applyToPoint(p) { - this.transforms.forEach(function (transform) { - transform.applyToPoint(p); - }); - } - }]); - - return _class3; - }(); // aspect ratio - - - svg.AspectRatio = function (ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { - // aspect ratio - https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute - aspectRatio = svg.compressSpaces(aspectRatio); - aspectRatio = aspectRatio.replace(/^defer\s/, ''); // ignore defer - - var align = aspectRatio.split(' ')[0] || 'xMidYMid'; - var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale - - var scaleX = width / desiredWidth; - var scaleY = height / desiredHeight; - var scaleMin = Math.min(scaleX, scaleY); - var scaleMax = Math.max(scaleX, scaleY); - - if (meetOrSlice === 'meet') { - desiredWidth *= scaleMin; - desiredHeight *= scaleMin; - } - - if (meetOrSlice === 'slice') { - desiredWidth *= scaleMax; - desiredHeight *= scaleMax; - } - - refX = new svg.Property('refX', refX); - refY = new svg.Property('refY', refY); - - if (refX.hasValue() && refY.hasValue()) { - ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y')); - } else { - // align - if (align.startsWith('xMid') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { - ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); - } - - if (align.endsWith('YMid') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { - ctx.translate(0, height / 2.0 - desiredHeight / 2.0); - } - - if (align.startsWith('xMax') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { - ctx.translate(width - desiredWidth, 0); - } - - if (align.endsWith('YMax') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { - ctx.translate(0, height - desiredHeight); - } - } // scale - - - 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(isNullish(minX) ? 0 : -minX, isNullish(minY) ? 0 : -minY); - }; // elements - - - svg.Element = {}; - svg.EmptyProperty = new svg.Property('EMPTY', ''); - - svg.Element.ElementBase = /*#__PURE__*/function () { - function _class4(node) { - var _this7 = this; - - _classCallCheck(this, _class4); - - // Argument from inheriting class - this.captureTextNodes = arguments[1]; // eslint-disable-line prefer-rest-params - - this.attributes = {}; - this.styles = {}; - this.children = []; - - if (!isNullish(node) && node.nodeType === 1) { - // ELEMENT_NODE - // add children - _toConsumableArray(node.childNodes).forEach(function (childNode) { - if (childNode.nodeType === 1) { - _this7.addChild(childNode, true); // ELEMENT_NODE - - } - - if (_this7.captureTextNodes && (childNode.nodeType === 3 || childNode.nodeType === 4)) { - var text = childNode.nodeValue || childNode.text || ''; - - if (svg.trim(svg.compressSpaces(text)) !== '') { - _this7.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE - - } - } - }); // add attributes - - - _toConsumableArray(node.attributes).forEach(function (_ref) { - var nodeName = _ref.nodeName, - nodeValue = _ref.nodeValue; - _this7.attributes[nodeName] = new svg.Property(nodeName, nodeValue); - }); // add tag styles - - - var styles = svg.Styles[node.nodeName]; - - 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 - - - if (this.attribute('class').hasValue()) { - var classes = svg.compressSpaces(this.attribute('class').value).split(' '); - classes.forEach(function (clss) { - styles = svg.Styles['.' + clss]; - - 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 (!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 - - - if (this.attribute('id').hasValue()) { - var _styles = svg.Styles['#' + this.attribute('id').value]; - - 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 - - - if (this.attribute('style').hasValue()) { - var _styles2 = this.attribute('style').value.split(';'); - - _styles2.forEach(function (style) { - if (svg.trim(style) !== '') { - var _style$split = style.split(':'), - name = _style$split.name, - value = _style$split.value; - - name = svg.trim(name); - value = svg.trim(value); - _this7.styles[name] = new svg.Property(name, value); - } - }); - } // add id - - - if (this.attribute('id').hasValue()) { - if (isNullish(svg.Definitions[this.attribute('id').value])) { - svg.Definitions[this.attribute('id').value] = this; - } - } - } - } // get or create attribute - - - _createClass(_class4, [{ - key: "attribute", - value: function attribute(name, createIfNotExists) { - var a = this.attributes[name]; - if (!isNullish(a)) return a; - - if (createIfNotExists === true) { - a = new svg.Property(name, ''); - this.attributes[name] = a; - } - - return a || svg.EmptyProperty; - } - }, { - key: "getHrefAttribute", - value: function getHrefAttribute() { - for (var a in this.attributes) { - if (a.endsWith(':href')) { - return this.attributes[a]; - } - } - - return svg.EmptyProperty; - } // get or create style, crawls up node tree - - }, { - key: "style", - value: function style(name, createIfNotExists, skipAncestors) { - var s = this.styles[name]; - if (!isNullish(s)) return s; - var a = this.attribute(name); - - if (!isNullish(a) && a.hasValue()) { - this.styles[name] = a; // move up to me to cache - - return a; - } - - if (skipAncestors !== true) { - var p = this.parent; - - if (!isNullish(p)) { - var ps = p.style(name); - - if (!isNullish(ps) && ps.hasValue()) { - return ps; - } - } - } - - if (createIfNotExists === true) { - s = new svg.Property(name, ''); - this.styles[name] = s; - } - - return s || svg.EmptyProperty; - } // base render - - }, { - key: "render", - value: function render(ctx) { - // don't render display=none - if (this.style('display').value === 'none') return; // don't render visibility=hidden - - if (this.style('visibility').value === 'hidden') return; - ctx.save(); - - if (this.attribute('mask').hasValue()) { - // mask - var mask = this.attribute('mask').getDefinition(); - if (!isNullish(mask)) mask.apply(ctx, this); - } else if (this.style('filter').hasValue()) { - // filter - var filter = this.style('filter').getDefinition(); - if (!isNullish(filter)) filter.apply(ctx, this); - } else { - this.setContext(ctx); - this.renderChildren(ctx); - this.clearContext(ctx); - } - - ctx.restore(); - } // base set context - - }, { - key: "setContext", - value: function setContext(ctx) {// OVERRIDE ME! - } // base clear context - - }, { - key: "clearContext", - value: function clearContext(ctx) {// OVERRIDE ME! - } // base render children - - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - this.children.forEach(function (child) { - child.render(ctx); - }); - } - }, { - key: "addChild", - value: function addChild(childNode, create) { - var child = create ? svg.CreateElement(childNode) : childNode; - child.parent = this; - - if (child.type !== 'title') { - this.children.push(child); - } - } - }]); - - return _class4; - }(); - - svg.Element.RenderedElementBase = /*#__PURE__*/function (_svg$Element$ElementB) { - _inherits(_class5, _svg$Element$ElementB); - - var _super4 = _createSuper(_class5); - - function _class5() { - _classCallCheck(this, _class5); - - return _super4.apply(this, arguments); - } - - _createClass(_class5, [{ - key: "setContext", - value: function setContext(ctx) { - // fill - if (this.style('fill').isUrlDefinition()) { - var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity')); - 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; - ctx.fillStyle = fillStyle.value === 'none' ? 'rgba(0,0,0,0)' : fillStyle.value; - } - - if (this.style('fill-opacity').hasValue()) { - var _fillStyle = new svg.Property('fill', ctx.fillStyle); - - _fillStyle = _fillStyle.addOpacity(this.style('fill-opacity')); - ctx.fillStyle = _fillStyle.value; - } // stroke - - - if (this.style('stroke').isUrlDefinition()) { - var _fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity')); - - 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; - ctx.strokeStyle = strokeStyle.value === 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value; - } - - if (this.style('stroke-opacity').hasValue()) { - var _strokeStyle = new svg.Property('stroke', ctx.strokeStyle); - - _strokeStyle = _strokeStyle.addOpacity(this.style('stroke-opacity')); - ctx.strokeStyle = _strokeStyle.value; - } - - if (this.style('stroke-width').hasValue()) { - var newLineWidth = this.style('stroke-width').toPixels(); - ctx.lineWidth = newLineWidth === 0 ? 0.001 : newLineWidth; // browsers don't respect 0 - } - - if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; - if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; - if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; - - if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value !== 'none') { - var gaps = svg.ToNumberArray(this.style('stroke-dasharray').value); - - if (typeof ctx.setLineDash !== 'undefined') { - ctx.setLineDash(gaps); - } else if (typeof ctx.webkitLineDash !== 'undefined') { - ctx.webkitLineDash = gaps; - } else if (typeof ctx.mozDash !== 'undefined' && !(gaps.length === 1 && gaps[0] === 0)) { - ctx.mozDash = gaps; - } - - var offset = this.style('stroke-dashoffset').numValueOrDefault(1); - - if (typeof ctx.lineDashOffset !== 'undefined') { - ctx.lineDashOffset = offset; - } else if (typeof ctx.webkitLineDashOffset !== 'undefined') { - ctx.webkitLineDashOffset = offset; - } else if (typeof ctx.mozDashOffset !== 'undefined') { - ctx.mozDashOffset = offset; - } - } // font - - - if (typeof ctx.font !== 'undefined') { - ctx.font = svg.Font.CreateFont(this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '', this.style('font-family').value).toString(); - } // transform - - - if (this.attribute('transform').hasValue()) { - var transform = new svg.Transform(this.attribute('transform').value); - transform.apply(ctx); - } // clip - - - if (this.style('clip-path', false, true).hasValue()) { - var clip = this.style('clip-path', false, true).getDefinition(); - if (!isNullish(clip)) clip.apply(ctx); - } // opacity - - - if (this.style('opacity').hasValue()) { - ctx.globalAlpha = this.style('opacity').numValue(); - } - } - }]); - - return _class5; - }(svg.Element.ElementBase); - - svg.Element.PathElementBase = /*#__PURE__*/function (_svg$Element$Rendered) { - _inherits(_class6, _svg$Element$Rendered); - - var _super5 = _createSuper(_class6); - - function _class6() { - _classCallCheck(this, _class6); - - return _super5.apply(this, arguments); - } - - _createClass(_class6, [{ - key: "path", - value: function path(ctx) { - if (!isNullish(ctx)) ctx.beginPath(); - return new svg.BoundingBox(); - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - this.path(ctx); - svg.Mouse.checkPath(this, ctx); - - if (ctx.fillStyle !== '') { - if (this.style('fill-rule').valueOrDefault('inherit') !== 'inherit') { - ctx.fill(this.style('fill-rule').value); - } else { - ctx.fill(); - } - } - - if (ctx.strokeStyle !== '') ctx.stroke(); - var markers = this.getMarkers(); - - 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]); - } - - if (this.style('marker-mid').isUrlDefinition()) { - var _marker = this.style('marker-mid').getDefinition(); - - for (var i = 1; i < markers.length - 1; i++) { - _marker.render(ctx, markers[i][0], markers[i][1]); - } - } - - if (this.style('marker-end').isUrlDefinition()) { - var _marker2 = this.style('marker-end').getDefinition(); - - _marker2.render(ctx, markers[markers.length - 1][0], markers[markers.length - 1][1]); - } - } - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - return this.path(); - } - }, { - key: "getMarkers", - value: function getMarkers() { - return null; - } - }]); - - return _class6; - }(svg.Element.RenderedElementBase); // svg element - - - svg.Element.svg = /*#__PURE__*/function (_svg$Element$Rendered2) { - _inherits(_class7, _svg$Element$Rendered2); - - var _super6 = _createSuper(_class7); - - function _class7() { - _classCallCheck(this, _class7); - - return _super6.apply(this, arguments); - } - - _createClass(_class7, [{ - key: "clearContext", - value: function clearContext(ctx) { - _get(_getPrototypeOf(_class7.prototype), "clearContext", this).call(this, ctx); - - svg.ViewPort.RemoveCurrent(); - } - }, { - key: "setContext", - value: function setContext(ctx) { - // initial values and defaults - ctx.strokeStyle = 'rgba(0,0,0,0)'; - ctx.lineCap = 'butt'; - ctx.lineJoin = 'miter'; - ctx.miterLimit = 4; - - if (typeof ctx.font !== 'undefined' && typeof window.getComputedStyle !== 'undefined') { - ctx.font = window.getComputedStyle(ctx.canvas).getPropertyValue('font'); - } - - _get(_getPrototypeOf(_class7.prototype), "setContext", this).call(this, ctx); // create new view port - - - if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0; - if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0; - ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y')); - var width = svg.ViewPort.width(); - var height = svg.ViewPort.height(); - if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%'; - if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%'; - - if (typeof this.root === 'undefined') { - width = this.attribute('width').toPixels('x'); - height = this.attribute('height').toPixels('y'); - var x = 0; - var y = 0; - - if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { - x = -this.attribute('refX').toPixels('x'); - y = -this.attribute('refY').toPixels('y'); - } - - if (this.attribute('overflow').valueOrDefault('hidden') !== 'visible') { - ctx.beginPath(); - ctx.moveTo(x, y); - ctx.lineTo(width, y); - ctx.lineTo(width, height); - ctx.lineTo(x, height); - ctx.closePath(); - ctx.clip(); - } - } - - svg.ViewPort.SetCurrent(width, height); // viewbox - - if (this.attribute('viewBox').hasValue()) { - var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); - var minX = viewBox[0]; - var minY = viewBox[1]; - width = viewBox[2]; - height = viewBox[3]; - svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); - svg.ViewPort.RemoveCurrent(); - svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); - } - } - }]); - - return _class7; - }(svg.Element.RenderedElementBase); // rect element - - - svg.Element.rect = /*#__PURE__*/function (_svg$Element$PathElem) { - _inherits(_class8, _svg$Element$PathElem); - - var _super7 = _createSuper(_class8); - - function _class8() { - _classCallCheck(this, _class8); - - return _super7.apply(this, arguments); - } - - _createClass(_class8, [{ - key: "path", - value: function path(ctx) { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - var rx = this.attribute('rx').toPixels('x'); - var ry = this.attribute('ry').toPixels('y'); - if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; - if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; - rx = Math.min(rx, width / 2.0); - ry = Math.min(ry, height / 2.0); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(x + rx, y); - ctx.lineTo(x + width - rx, y); - ctx.quadraticCurveTo(x + width, y, x + width, y + ry); - ctx.lineTo(x + width, y + height - ry); - ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height); - ctx.lineTo(x + rx, y + height); - ctx.quadraticCurveTo(x, y + height, x, y + height - ry); - ctx.lineTo(x, y + ry); - ctx.quadraticCurveTo(x, y, x + rx, y); - ctx.closePath(); - } - - return new svg.BoundingBox(x, y, x + width, y + height); - } - }]); - - return _class8; - }(svg.Element.PathElementBase); // circle element - - - svg.Element.circle = /*#__PURE__*/function (_svg$Element$PathElem2) { - _inherits(_class9, _svg$Element$PathElem2); - - var _super8 = _createSuper(_class9); - - function _class9() { - _classCallCheck(this, _class9); - - return _super8.apply(this, arguments); - } - - _createClass(_class9, [{ - key: "path", - value: function path(ctx) { - var cx = this.attribute('cx').toPixels('x'); - var cy = this.attribute('cy').toPixels('y'); - var r = this.attribute('r').toPixels(); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.arc(cx, cy, r, 0, Math.PI * 2, true); - ctx.closePath(); - } - - return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); - } - }]); - - return _class9; - }(svg.Element.PathElementBase); // ellipse element - - - var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); - - svg.Element.ellipse = /*#__PURE__*/function (_svg$Element$PathElem3) { - _inherits(_class10, _svg$Element$PathElem3); - - var _super9 = _createSuper(_class10); - - function _class10() { - _classCallCheck(this, _class10); - - return _super9.apply(this, arguments); - } - - _createClass(_class10, [{ - key: "path", - value: function path(ctx) { - var rx = this.attribute('rx').toPixels('x'); - var ry = this.attribute('ry').toPixels('y'); - var cx = this.attribute('cx').toPixels('x'); - var cy = this.attribute('cy').toPixels('y'); - - 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); - ctx.bezierCurveTo(cx + rx, cy + KAPPA * ry, cx + KAPPA * rx, cy + ry, cx, cy + ry); - ctx.bezierCurveTo(cx - KAPPA * rx, cy + ry, cx - rx, cy + KAPPA * ry, cx - rx, cy); - ctx.bezierCurveTo(cx - rx, cy - KAPPA * ry, cx - KAPPA * rx, cy - ry, cx, cy - ry); - ctx.closePath(); - } - - return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); - } - }]); - - return _class10; - }(svg.Element.PathElementBase); // line element - - - svg.Element.line = /*#__PURE__*/function (_svg$Element$PathElem4) { - _inherits(_class11, _svg$Element$PathElem4); - - var _super10 = _createSuper(_class11); - - function _class11() { - _classCallCheck(this, _class11); - - return _super10.apply(this, arguments); - } - - _createClass(_class11, [{ - key: "getPoints", - value: function getPoints() { - return [new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')), new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))]; - } - }, { - key: "path", - value: function path(ctx) { - var points = this.getPoints(); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(points[0].x, points[0].y); - ctx.lineTo(points[1].x, points[1].y); - } - - return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); - } - }, { - key: "getMarkers", - value: function getMarkers() { - var points = this.getPoints(); - var a = points[0].angleTo(points[1]); - return [[points[0], a], [points[1], a]]; - } - }]); - - return _class11; - }(svg.Element.PathElementBase); // polyline element - - - svg.Element.polyline = /*#__PURE__*/function (_svg$Element$PathElem5) { - _inherits(_class12, _svg$Element$PathElem5); - - var _super11 = _createSuper(_class12); - - function _class12(node) { - var _this8; - - _classCallCheck(this, _class12); - - _this8 = _super11.call(this, node); - _this8.points = svg.CreatePath(_this8.attribute('points').value); - return _this8; - } - - _createClass(_class12, [{ - key: "path", - value: function path(ctx) { - var _this$points$ = this.points[0], - x = _this$points$.x, - y = _this$points$.y; - var bb = new svg.BoundingBox(x, y); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(x, y); - } - - for (var i = 1; i < this.points.length; i++) { - var _this$points$i = this.points[i], - _x = _this$points$i.x, - _y = _this$points$i.y; - bb.addPoint(_x, _y); - if (!isNullish(ctx)) ctx.lineTo(_x, _y); - } - - return bb; - } - }, { - key: "getMarkers", - value: function getMarkers() { - var markers = []; - - for (var i = 0; i < this.points.length - 1; i++) { - markers.push([this.points[i], this.points[i].angleTo(this.points[i + 1])]); - } - - markers.push([this.points[this.points.length - 1], markers[markers.length - 1][1]]); - return markers; - } - }]); - - return _class12; - }(svg.Element.PathElementBase); // polygon element - - - svg.Element.polygon = /*#__PURE__*/function (_svg$Element$polyline) { - _inherits(_class13, _svg$Element$polyline); - - var _super12 = _createSuper(_class13); - - function _class13() { - _classCallCheck(this, _class13); - - return _super12.apply(this, arguments); - } - - _createClass(_class13, [{ - key: "path", - value: function path(ctx) { - var bb = _get(_getPrototypeOf(_class13.prototype), "path", this).call(this, ctx); - - if (!isNullish(ctx)) { - ctx.lineTo(this.points[0].x, this.points[0].y); - ctx.closePath(); - } - - return bb; - } - }]); - - return _class13; - }(svg.Element.polyline); // path element - - - svg.Element.path = /*#__PURE__*/function (_svg$Element$PathElem6) { - _inherits(_class14, _svg$Element$PathElem6); - - var _super13 = _createSuper(_class14); - - function _class14(node) { - var _this9; - - _classCallCheck(this, _class14); - - _this9 = _super13.call(this, node); - - var d = _this9.attribute('d').value // TODO: convert to real lexer based on https://www.w3.org/TR/SVG11/paths.html#PathDataBNF - .replace(/,/gm, ' ') // get rid of all commas - .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands - .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands - .replace(/([MmZzLlHhVvCcSsQqTtAa])(\S)/gm, '$1 $2') // separate commands from points - .replace(/(\S)([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from points - .replace(/(\d)([+-])/gm, '$1 $2') // separate digits when no comma - .replace(/(\.\d*)(\.)/gm, '$1 $2') // separate digits when no comma - .replace(/([Aa](\s+\d+)(\s+\d+)(\s+\d+))\s+([01])\s*([01])/gm, '$1 $5 $6 '); // shorthand elliptical arc path syntax - - - d = svg.compressSpaces(d); // compress multiple spaces - - d = svg.trim(d); - _this9.PathParser = { - tokens: d.split(' '), - reset: function reset() { - this.i = -1; - this.command = ''; - this.previousCommand = ''; - this.start = new svg.Point(0, 0); - this.control = new svg.Point(0, 0); - this.current = new svg.Point(0, 0); - this.points = []; - this.angles = []; - }, - isEnd: function isEnd() { - return this.i >= this.tokens.length - 1; - }, - isCommandOrEnd: function isCommandOrEnd() { - if (this.isEnd()) return true; - return !isNullish(this.tokens[this.i + 1].match(/^[A-Za-z]$/)); - }, - isRelativeCommand: function isRelativeCommand() { - switch (this.command) { - case 'm': - case 'l': - case 'h': - case 'v': - case 'c': - case 's': - case 'q': - case 't': - case 'a': - case 'z': - return true; - } - - return false; - }, - getToken: function getToken() { - this.i++; - return this.tokens[this.i]; - }, - getScalar: function getScalar() { - return Number.parseFloat(this.getToken()); - }, - nextCommand: function nextCommand() { - this.previousCommand = this.command; - this.command = this.getToken(); - }, - getPoint: function getPoint() { - var p = new svg.Point(this.getScalar(), this.getScalar()); - return this.makeAbsolute(p); - }, - getAsControlPoint: function getAsControlPoint() { - var p = this.getPoint(); - this.control = p; - return p; - }, - getAsCurrentPoint: function getAsCurrentPoint() { - var p = this.getPoint(); - this.current = p; - return p; - }, - getReflectedControlPoint: function getReflectedControlPoint() { - if (this.previousCommand.toLowerCase() !== 'c' && this.previousCommand.toLowerCase() !== 's' && this.previousCommand.toLowerCase() !== 'q' && this.previousCommand.toLowerCase() !== 't') { - return this.current; - } // reflect point - - - var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); - return p; - }, - makeAbsolute: function makeAbsolute(p) { - if (this.isRelativeCommand()) { - p.x += this.current.x; - p.y += this.current.y; - } - - return p; - }, - addMarker: function addMarker(p, from, priorTo) { - // if the last angle isn't filled in because we didn't have this point yet ... - 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, isNullish(from) ? null : from.angleTo(p)); - }, - addMarkerAngle: function addMarkerAngle(p, a) { - this.points.push(p); - this.angles.push(a); - }, - getMarkerPoints: function getMarkerPoints() { - return this.points; - }, - getMarkerAngles: function getMarkerAngles() { - for (var i = 0; i < this.angles.length; i++) { - if (isNullish(this.angles[i])) { - for (var j = i + 1; j < this.angles.length; j++) { - if (!isNullish(this.angles[j])) { - this.angles[i] = this.angles[j]; - break; - } - } - } - } - - return this.angles; - } - }; - return _this9; - } - - _createClass(_class14, [{ - key: "path", - value: function path(ctx) { - var pp = this.PathParser; - pp.reset(); - var bb = new svg.BoundingBox(); - if (!isNullish(ctx)) ctx.beginPath(); - - while (!pp.isEnd()) { - pp.nextCommand(); - - switch (pp.command) { - case 'M': - case 'm': - { - 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(); - - pp.addMarker(_p, pp.start); - bb.addPoint(_p.x, _p.y); - if (!isNullish(ctx)) ctx.lineTo(_p.x, _p.y); - } - - break; - } - - case 'L': - case 'l': - while (!pp.isCommandOrEnd()) { - var c = pp.current; - - var _p2 = pp.getAsCurrentPoint(); - - pp.addMarker(_p2, c); - bb.addPoint(_p2.x, _p2.y); - if (!isNullish(ctx)) ctx.lineTo(_p2.x, _p2.y); - } - - break; - - case 'H': - case 'h': - while (!pp.isCommandOrEnd()) { - var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); - pp.addMarker(newP, pp.current); - pp.current = newP; - bb.addPoint(pp.current.x, pp.current.y); - if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); - } - - break; - - case 'V': - case 'v': - while (!pp.isCommandOrEnd()) { - var _newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); - - pp.addMarker(_newP, pp.current); - pp.current = _newP; - bb.addPoint(pp.current.x, pp.current.y); - if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); - } - - break; - - case 'C': - case 'c': - while (!pp.isCommandOrEnd()) { - var curr = pp.current; - var p1 = pp.getPoint(); - var cntrl = pp.getAsControlPoint(); - 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 (!isNullish(ctx)) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); - } - - break; - - case 'S': - case 's': - while (!pp.isCommandOrEnd()) { - var _curr = pp.current; - - var _p3 = pp.getReflectedControlPoint(); - - var _cntrl = pp.getAsControlPoint(); - - var _cp = pp.getAsCurrentPoint(); - - pp.addMarker(_cp, _cntrl, _p3); - bb.addBezierCurve(_curr.x, _curr.y, _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; - - case 'Q': - case 'q': - while (!pp.isCommandOrEnd()) { - var _curr2 = pp.current; - - var _cntrl2 = pp.getAsControlPoint(); - - var _cp2 = pp.getAsCurrentPoint(); - - pp.addMarker(_cp2, _cntrl2, _cntrl2); - bb.addQuadraticCurve(_curr2.x, _curr2.y, _cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); - if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); - } - - break; - - case 'T': - case 't': - while (!pp.isCommandOrEnd()) { - var _curr3 = pp.current; - - var _cntrl3 = pp.getReflectedControlPoint(); - - pp.control = _cntrl3; - - var _cp3 = pp.getAsCurrentPoint(); - - pp.addMarker(_cp3, _cntrl3, _cntrl3); - bb.addQuadraticCurve(_curr3.x, _curr3.y, _cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); - if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); - } - - break; - - case 'A': - case 'a': - var _loop2 = function _loop2() { - var curr = pp.current; - var rx = pp.getScalar(); - var ry = pp.getScalar(); - var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); - var largeArcFlag = pp.getScalar(); - var sweepFlag = pp.getScalar(); - var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization - // https://www.w3.org/TR/SVG11/implnote.html#ArcConversionEndpointToCenter - // x1', y1' - - var currp = new svg.Point(Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0); // adjust radii - - var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2); - - if (l > 1) { - rx *= Math.sqrt(l); - ry *= Math.sqrt(l); - } // cx', cy' - - - var s = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt((Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(currp.y, 2) - Math.pow(ry, 2) * Math.pow(currp.x, 2)) / (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))); - if (isNaN(s)) s = 0; - var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy - - var centp = new svg.Point((curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y); // vector magnitude - - var m = function m(v) { - return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)); - }; // ratio between two vectors - - - var r = function r(u, v) { - return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v)); - }; // angle between two vectors - - - var a = function a(u, v) { - return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v)); - }; // initial angle - - - var a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]); // angle delta - - var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]; - var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry]; - var ad = a(u, v); - if (r(u, v) <= -1) ad = Math.PI; - if (r(u, v) >= 1) ad = 0; // for markers - - var dir = 1 - sweepFlag ? 1.0 : -1.0; - var ah = a1 + dir * (ad / 2.0); - var halfWay = new svg.Point(centp.x + rx * Math.cos(ah), centp.y + ry * Math.sin(ah)); - pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2); - pp.addMarkerAngle(cp, ah - dir * Math.PI); - bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better - - if (!isNullish(ctx)) { - var _r = rx > ry ? rx : ry; - - var sx = rx > ry ? 1 : rx / ry; - var sy = rx > ry ? ry / rx : 1; - ctx.translate(centp.x, centp.y); - ctx.rotate(xAxisRotation); - ctx.scale(sx, sy); - ctx.arc(0, 0, _r, a1, a1 + ad, 1 - sweepFlag); - ctx.scale(1 / sx, 1 / sy); - ctx.rotate(-xAxisRotation); - ctx.translate(-centp.x, -centp.y); - } - }; - - while (!pp.isCommandOrEnd()) { - _loop2(); - } - - break; - - case 'Z': - case 'z': - if (!isNullish(ctx)) ctx.closePath(); - pp.current = pp.start; - } - } - - return bb; - } - }, { - key: "getMarkers", - value: function getMarkers() { - var points = this.PathParser.getMarkerPoints(); - var angles = this.PathParser.getMarkerAngles(); - var markers = points.map(function (point, i) { - return [point, angles[i]]; - }); - return markers; - } - }]); - - return _class14; - }(svg.Element.PathElementBase); // pattern element - - - svg.Element.pattern = /*#__PURE__*/function (_svg$Element$ElementB2) { - _inherits(_class15, _svg$Element$ElementB2); - - var _super14 = _createSuper(_class15); - - function _class15() { - _classCallCheck(this, _class15); - - return _super14.apply(this, arguments); - } - - _createClass(_class15, [{ - key: "createPattern", - value: function createPattern(ctx, element) { - var width = this.attribute('width').toPixels('x', true); - 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.children = this.children; - var c = document.createElement('canvas'); - c.width = width; - c.height = height; - var cctx = c.getContext('2d'); - - if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { - cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true)); - } // render 3x3 grid so when we transform there's no white space on edges - - - for (var x = -1; x <= 1; x++) { - for (var y = -1; y <= 1; y++) { - cctx.save(); - cctx.translate(x * c.width, y * c.height); - tempSvg.render(cctx); - cctx.restore(); - } - } - - var pattern = ctx.createPattern(c, 'repeat'); - return pattern; - } - }]); - - return _class15; - }(svg.Element.ElementBase); // marker element - - - svg.Element.marker = /*#__PURE__*/function (_svg$Element$ElementB3) { - _inherits(_class16, _svg$Element$ElementB3); - - var _super15 = _createSuper(_class16); - - function _class16() { - _classCallCheck(this, _class16); - - return _super15.apply(this, arguments); - } - - _createClass(_class16, [{ - key: "render", - value: function render(ctx, point, angle) { - ctx.translate(point.x, point.y); - if (this.attribute('orient').valueOrDefault('auto') === 'auto') ctx.rotate(angle); - if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); - 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.children = this.children; - tempSvg.render(ctx); - ctx.restore(); - if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(1 / ctx.lineWidth, 1 / ctx.lineWidth); - - if (this.attribute('orient').valueOrDefault('auto') === 'auto') { - ctx.rotate(-angle); - } - - ctx.translate(-point.x, -point.y); - } - }]); - - return _class16; - }(svg.Element.ElementBase); // definitions element - - - svg.Element.defs = /*#__PURE__*/function (_svg$Element$ElementB4) { - _inherits(_class17, _svg$Element$ElementB4); - - var _super16 = _createSuper(_class17); - - function _class17() { - _classCallCheck(this, _class17); - - return _super16.apply(this, arguments); - } - - _createClass(_class17, [{ - key: "render", - value: function render(ctx) {// NOOP - } - }]); - - return _class17; - }(svg.Element.ElementBase); // base for gradients - - - svg.Element.GradientBase = /*#__PURE__*/function (_svg$Element$ElementB5) { - _inherits(_class18, _svg$Element$ElementB5); - - var _super17 = _createSuper(_class18); - - function _class18(node) { - var _this10; - - _classCallCheck(this, _class18); - - _this10 = _super17.call(this, node); - _this10.gradientUnits = _this10.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); - _this10.stops = []; - - _this10.children.forEach(function (child) { - if (child.type === 'stop') { - _this10.stops.push(child); - } - }); - - return _this10; - } - - _createClass(_class18, [{ - key: "getGradient", - value: function getGradient() {// OVERRIDE ME! - } - }, { - key: "createGradient", - value: function createGradient(ctx, element, parentOpacityProp) { - var stopsContainer = this.getHrefAttribute().hasValue() ? this.getHrefAttribute().getDefinition() : this; - - var addParentOpacity = function addParentOpacity(color) { - if (parentOpacityProp.hasValue()) { - var p = new svg.Property('color', color); - return p.addOpacity(parentOpacityProp).value; - } - - return color; - }; - - var g = this.getGradient(ctx, element); - 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)); - }); - - if (this.attribute('gradientTransform').hasValue()) { - // 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); - var group = new svg.Element.g(); - 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.children = [group]; - var c = document.createElement('canvas'); - c.width = rootView.width; - c.height = rootView.height; - var tempCtx = c.getContext('2d'); - tempCtx.fillStyle = g; - tempSvg.render(tempCtx); - return tempCtx.createPattern(c, 'no-repeat'); - } - - return g; - } - }]); - - return _class18; - }(svg.Element.ElementBase); // linear gradient element - - - svg.Element.linearGradient = /*#__PURE__*/function (_svg$Element$Gradient) { - _inherits(_class19, _svg$Element$Gradient); - - var _super18 = _createSuper(_class19); - - function _class19() { - _classCallCheck(this, _class19); - - return _super18.apply(this, arguments); - } - - _createClass(_class19, [{ - key: "getGradient", - value: function getGradient(ctx, element) { - var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; - var bb = useBB ? element.getBoundingBox() : null; - - if (!this.attribute('x1').hasValue() && !this.attribute('y1').hasValue() && !this.attribute('x2').hasValue() && !this.attribute('y2').hasValue()) { - this.attribute('x1', true).value = 0; - this.attribute('y1', true).value = 0; - this.attribute('x2', true).value = 1; - this.attribute('y2', true).value = 0; - } - - var x1 = useBB ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').toPixels('x'); - var y1 = useBB ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').toPixels('y'); - var x2 = useBB ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').toPixels('x'); - var y2 = useBB ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').toPixels('y'); - if (x1 === x2 && y1 === y2) return null; - return ctx.createLinearGradient(x1, y1, x2, y2); - } - }]); - - return _class19; - }(svg.Element.GradientBase); // radial gradient element - - - svg.Element.radialGradient = /*#__PURE__*/function (_svg$Element$Gradient2) { - _inherits(_class20, _svg$Element$Gradient2); - - var _super19 = _createSuper(_class20); - - function _class20() { - _classCallCheck(this, _class20); - - return _super19.apply(this, arguments); - } - - _createClass(_class20, [{ - key: "getGradient", - value: function getGradient(ctx, element) { - var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; - var bb = useBB ? element.getBoundingBox() : null; - if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%'; - if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%'; - if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%'; - var cx = useBB ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').toPixels('x'); - var cy = useBB ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').toPixels('y'); - var fx = cx; - var fy = cy; - - if (this.attribute('fx').hasValue()) { - fx = useBB ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').toPixels('x'); - } - - if (this.attribute('fy').hasValue()) { - fy = useBB ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').toPixels('y'); - } - - var r = useBB ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').toPixels(); - return ctx.createRadialGradient(fx, fy, 0, cx, cy, r); - } - }]); - - return _class20; - }(svg.Element.GradientBase); // gradient stop element - - - svg.Element.stop = /*#__PURE__*/function (_svg$Element$ElementB6) { - _inherits(_class21, _svg$Element$ElementB6); - - var _super20 = _createSuper(_class21); - - function _class21(node) { - var _this11; - - _classCallCheck(this, _class21); - - _this11 = _super20.call(this, node); - _this11.offset = _this11.attribute('offset').numValue(); - if (_this11.offset < 0) _this11.offset = 0; - if (_this11.offset > 1) _this11.offset = 1; - - var stopColor = _this11.style('stop-color'); - - if (_this11.style('stop-opacity').hasValue()) { - stopColor = stopColor.addOpacity(_this11.style('stop-opacity')); - } - - _this11.color = stopColor.value; - return _this11; - } - - return _class21; - }(svg.Element.ElementBase); // animation base element - - - svg.Element.AnimateBase = /*#__PURE__*/function (_svg$Element$ElementB7) { - _inherits(_class22, _svg$Element$ElementB7); - - var _super21 = _createSuper(_class22); - - function _class22(node) { - var _this12; - - _classCallCheck(this, _class22); - - _this12 = _super21.call(this, node); - svg.Animations.push(_assertThisInitialized(_this12)); - _this12.duration = 0.0; - _this12.begin = _this12.attribute('begin').toMilliseconds(); - _this12.maxDuration = _this12.begin + _this12.attribute('dur').toMilliseconds(); - _this12.initialValue = null; - _this12.initialUnits = ''; - _this12.removed = false; - _this12.from = _this12.attribute('from'); - _this12.to = _this12.attribute('to'); - _this12.values = _this12.attribute('values'); - if (_this12.values.hasValue()) _this12.values.value = _this12.values.value.split(';'); - return _this12; - } - - _createClass(_class22, [{ - key: "getProperty", - value: function getProperty() { - var attributeType = this.attribute('attributeType').value; - var attributeName = this.attribute('attributeName').value; - - if (attributeType === 'CSS') { - return this.parent.style(attributeName, true); - } - - return this.parent.attribute(attributeName, true); - } - }, { - key: "calcValue", - value: function calcValue() { - // OVERRIDE ME! - return ''; - } - }, { - key: "update", - value: function update(delta) { - // set initial value - if (isNullish(this.initialValue)) { - this.initialValue = this.getProperty().value; - this.initialUnits = this.getProperty().getUnits(); - } // if we're past the end time - - - if (this.duration > this.maxDuration) { - // loop for indefinitely repeating animations - if (this.attribute('repeatCount').value === 'indefinite' || this.attribute('repeatDur').value === 'indefinite') { - this.duration = 0.0; - } else if (this.attribute('fill').valueOrDefault('remove') === 'freeze' && !this.frozen) { - this.frozen = true; - this.parent.animationFrozen = true; - this.parent.animationFrozenValue = this.getProperty().value; - } else if (this.attribute('fill').valueOrDefault('remove') === 'remove' && !this.removed) { - this.removed = true; - this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue; - return true; - } - - return false; - } - - this.duration += delta; // if we're past the begin time - - var updated = false; - - if (this.begin < this.duration) { - var newValue = this.calcValue(); // tween - - if (this.attribute('type').hasValue()) { - // for transform, etc. - var type = this.attribute('type').value; - newValue = type + '(' + newValue + ')'; - } - - this.getProperty().value = newValue; - updated = true; - } - - return updated; - } // fraction of duration we've covered - - }, { - key: "progress", - value: function progress() { - var ret = { - progress: (this.duration - this.begin) / (this.maxDuration - this.begin) - }; - - if (this.values.hasValue()) { - var p = ret.progress * (this.values.value.length - 1); - var lb = Math.floor(p), - ub = Math.ceil(p); - ret.from = new svg.Property('from', Number.parseFloat(this.values.value[lb])); - ret.to = new svg.Property('to', Number.parseFloat(this.values.value[ub])); - ret.progress = (p - lb) / (ub - lb); - } else { - ret.from = this.from; - ret.to = this.to; - } - - return ret; - } - }]); - - return _class22; - }(svg.Element.ElementBase); // animate element - - - svg.Element.animate = /*#__PURE__*/function (_svg$Element$AnimateB) { - _inherits(_class23, _svg$Element$AnimateB); - - var _super22 = _createSuper(_class23); - - function _class23() { - _classCallCheck(this, _class23); - - return _super22.apply(this, arguments); - } - - _createClass(_class23, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); // tween value linearly - - var newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress; - return newValue + this.initialUnits; - } - }]); - - return _class23; - }(svg.Element.AnimateBase); // animate color element - - - svg.Element.animateColor = /*#__PURE__*/function (_svg$Element$AnimateB2) { - _inherits(_class24, _svg$Element$AnimateB2); - - var _super23 = _createSuper(_class24); - - function _class24() { - _classCallCheck(this, _class24); - - return _super23.apply(this, arguments); - } - - _createClass(_class24, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); - var from = new RGBColor(p.from.value); - var to = new RGBColor(p.to.value); - - if (from.ok && to.ok) { - // tween color linearly - 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(' + Number.parseInt(r) + ',' + Number.parseInt(g) + ',' + Number.parseInt(b) + ')'; - } - - return this.attribute('from').value; - } - }]); - - return _class24; - }(svg.Element.AnimateBase); // animate transform element - - - svg.Element.animateTransform = /*#__PURE__*/function (_svg$Element$animate) { - _inherits(_class25, _svg$Element$animate); - - var _super24 = _createSuper(_class25); - - function _class25() { - _classCallCheck(this, _class25); - - return _super24.apply(this, arguments); - } - - _createClass(_class25, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); // tween value linearly - - var from = svg.ToNumberArray(p.from.value); - var to = svg.ToNumberArray(p.to.value); - var newValue = ''; - from.forEach(function (fr, i) { - newValue += fr + (to[i] - fr) * p.progress + ' '; - }); - return newValue; - } - }]); - - return _class25; - }(svg.Element.animate); // font element - - - svg.Element.font = /*#__PURE__*/function (_svg$Element$ElementB8) { - _inherits(_class26, _svg$Element$ElementB8); - - var _super25 = _createSuper(_class26); - - function _class26(node) { - var _this13; - - _classCallCheck(this, _class26); - - _this13 = _super25.call(this, node); - _this13.horizAdvX = _this13.attribute('horiz-adv-x').numValue(); - _this13.isRTL = false; - _this13.isArabic = false; - _this13.fontFace = null; - _this13.missingGlyph = null; - _this13.glyphs = []; - - _this13.children.forEach(function (child) { - if (child.type === 'font-face') { - _this13.fontFace = child; - - if (child.style('font-family').hasValue()) { - svg.Definitions[child.style('font-family').value] = _assertThisInitialized(_this13); - } - } else if (child.type === 'missing-glyph') { - _this13.missingGlyph = child; - } else if (child.type === 'glyph') { - if (child.arabicForm !== '') { - _this13.isRTL = true; - _this13.isArabic = true; - - if (typeof _this13.glyphs[child.unicode] === 'undefined') { - _this13.glyphs[child.unicode] = []; - } - - _this13.glyphs[child.unicode][child.arabicForm] = child; - } else { - _this13.glyphs[child.unicode] = child; - } - } - }); - - return _this13; - } - - return _class26; - }(svg.Element.ElementBase); // font-face element - - - svg.Element.fontface = /*#__PURE__*/function (_svg$Element$ElementB9) { - _inherits(_class27, _svg$Element$ElementB9); - - var _super26 = _createSuper(_class27); - - function _class27(node) { - var _this14; - - _classCallCheck(this, _class27); - - _this14 = _super26.call(this, node); - _this14.ascent = _this14.attribute('ascent').value; - _this14.descent = _this14.attribute('descent').value; - _this14.unitsPerEm = _this14.attribute('units-per-em').numValue(); - return _this14; - } - - return _class27; - }(svg.Element.ElementBase); // missing-glyph element - - - svg.Element.missingglyph = /*#__PURE__*/function (_svg$Element$path) { - _inherits(_class28, _svg$Element$path); - - var _super27 = _createSuper(_class28); - - function _class28(node) { - var _this15; - - _classCallCheck(this, _class28); - - _this15 = _super27.call(this, node); - _this15.horizAdvX = 0; - return _this15; - } - - return _class28; - }(svg.Element.path); // glyph element - - - svg.Element.glyph = /*#__PURE__*/function (_svg$Element$path2) { - _inherits(_class29, _svg$Element$path2); - - var _super28 = _createSuper(_class29); - - function _class29(node) { - var _this16; - - _classCallCheck(this, _class29); - - _this16 = _super28.call(this, node); - _this16.horizAdvX = _this16.attribute('horiz-adv-x').numValue(); - _this16.unicode = _this16.attribute('unicode').value; - _this16.arabicForm = _this16.attribute('arabic-form').value; - return _this16; - } - - return _class29; - }(svg.Element.path); // text element - - - svg.Element.text = /*#__PURE__*/function (_svg$Element$Rendered3) { - _inherits(_class30, _svg$Element$Rendered3); - - var _super29 = _createSuper(_class30); - - function _class30(node) { - _classCallCheck(this, _class30); - - return _super29.call(this, node, true); - } - - _createClass(_class30, [{ - key: "setContext", - value: function setContext(ctx) { - _get(_getPrototypeOf(_class30.prototype), "setContext", this).call(this, ctx); - - var textBaseline = this.style('dominant-baseline').toTextBaseline(); - if (isNullish(textBaseline)) textBaseline = this.style('alignment-baseline').toTextBaseline(); - if (!isNullish(textBaseline)) ctx.textBaseline = textBaseline; - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); - return new svg.BoundingBox(x, y - fontSize, x + Math.floor(fontSize * 2.0 / 3.0) * this.children[0].getText().length, y); - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var _this17 = this; - - this.x = this.attribute('x').toPixels('x'); - this.y = this.attribute('y').toPixels('y'); - this.x += this.getAnchorDelta(ctx, this, 0); - this.children.forEach(function (child, i) { - _this17.renderChild(ctx, _this17, i); - }); - } - }, { - key: "getAnchorDelta", - value: function getAnchorDelta(ctx, parent, startI) { - var textAnchor = this.style('text-anchor').valueOrDefault('start'); - - if (textAnchor !== 'start') { - var width = 0; - - for (var i = startI; i < parent.children.length; i++) { - var child = parent.children[i]; - if (i > startI && child.attribute('x').hasValue()) break; // new group - - width += child.measureTextRecursive(ctx); - } - - return -1 * (textAnchor === 'end' ? width : width / 2.0); - } - - return 0; - } - }, { - key: "renderChild", - value: function renderChild(ctx, parent, i) { - var child = parent.children[i]; - - if (child.attribute('x').hasValue()) { - child.x = child.attribute('x').toPixels('x') + this.getAnchorDelta(ctx, parent, i); - if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x'); - } else { - if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x'); - if (child.attribute('dx').hasValue()) this.x += child.attribute('dx').toPixels('x'); - child.x = this.x; - } - - this.x = child.x + child.measureText(ctx); - - if (child.attribute('y').hasValue()) { - child.y = child.attribute('y').toPixels('y'); - if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y'); - } else { - if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y'); - if (child.attribute('dy').hasValue()) this.y += child.attribute('dy').toPixels('y'); - child.y = this.y; - } - - this.y = child.y; - child.render(ctx); - - for (var j = 0; j < child.children.length; j++) { - this.renderChild(ctx, child, j); - } - } - }]); - - return _class30; - }(svg.Element.RenderedElementBase); // text base - - - svg.Element.TextElementBase = /*#__PURE__*/function (_svg$Element$Rendered4) { - _inherits(_class31, _svg$Element$Rendered4); - - var _super30 = _createSuper(_class31); - - function _class31() { - _classCallCheck(this, _class31); - - return _super30.apply(this, arguments); - } - - _createClass(_class31, [{ - key: "getGlyph", - value: function getGlyph(font, text, i) { - var c = text[i]; - var glyph = null; - - if (font.isArabic) { - var arabicForm = 'isolated'; - if ((i === 0 || text[i - 1] === ' ') && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'terminal'; - if (i > 0 && text[i - 1] !== ' ' && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'medial'; - if (i > 0 && text[i - 1] !== ' ' && (i === text.length - 1 || text[i + 1] === ' ')) arabicForm = 'initial'; - - if (typeof font.glyphs[c] !== 'undefined') { - glyph = font.glyphs[c][arabicForm]; - if (isNullish(glyph) && font.glyphs[c].type === 'glyph') glyph = font.glyphs[c]; - } - } else { - glyph = font.glyphs[c]; - } - - if (isNullish(glyph)) glyph = font.missingGlyph; - return glyph; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var customFont = this.parent.style('font-family').getDefinition(); - - 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(); - if (customFont.isRTL) text = text.split('').reverse().join(''); - var dx = svg.ToNumberArray(this.parent.attribute('dx').value); - - for (var i = 0; i < text.length; i++) { - var glyph = this.getGlyph(customFont, text, i); - var scale = fontSize / customFont.fontFace.unitsPerEm; - ctx.translate(this.x, this.y); - ctx.scale(scale, -scale); - var lw = ctx.lineWidth; - ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize; - if (fontStyle === 'italic') ctx.transform(1, 0, 0.4, 1, 0, 0); - glyph.render(ctx); - if (fontStyle === 'italic') ctx.transform(1, 0, -0.4, 1, 0, 0); - ctx.lineWidth = lw; - ctx.scale(1 / scale, -1 / scale); - ctx.translate(-this.x, -this.y); - this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm; - - if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { - this.x += dx[i]; - } - } - - return; - } - - if (ctx.fillStyle !== '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); - if (ctx.strokeStyle !== '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y); - } - }, { - key: "getText", - value: function getText() {// OVERRIDE ME - } - }, { - key: "measureTextRecursive", - value: function measureTextRecursive(ctx) { - var width = this.measureText(ctx); - this.children.forEach(function (child) { - width += child.measureTextRecursive(ctx); - }); - return width; - } - }, { - key: "measureText", - value: function measureText(ctx) { - var customFont = this.parent.style('font-family').getDefinition(); - - 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(); - if (customFont.isRTL) text = text.split('').reverse().join(''); - var dx = svg.ToNumberArray(this.parent.attribute('dx').value); - - for (var i = 0; i < text.length; i++) { - var glyph = this.getGlyph(customFont, text, i); - measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm; - - if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { - measure += dx[i]; - } - } - - return measure; - } - - var textToMeasure = svg.compressSpaces(this.getText()); - if (!ctx.measureText) return textToMeasure.length * 10; - ctx.save(); - this.setContext(ctx); - - var _ctx$measureText = ctx.measureText(textToMeasure), - width = _ctx$measureText.width; - - ctx.restore(); - return width; - } - }]); - - return _class31; - }(svg.Element.RenderedElementBase); // tspan - - - svg.Element.tspan = /*#__PURE__*/function (_svg$Element$TextElem) { - _inherits(_class32, _svg$Element$TextElem); - - var _super31 = _createSuper(_class32); - - function _class32(node) { - var _this18; - - _classCallCheck(this, _class32); - - _this18 = _super31.call(this, node, true); - _this18.text = node.nodeValue || node.text || ''; - return _this18; - } - - _createClass(_class32, [{ - key: "getText", - value: function getText() { - return this.text; - } - }]); - - return _class32; - }(svg.Element.TextElementBase); // tref - - - svg.Element.tref = /*#__PURE__*/function (_svg$Element$TextElem2) { - _inherits(_class33, _svg$Element$TextElem2); - - var _super32 = _createSuper(_class33); - - function _class33() { - _classCallCheck(this, _class33); - - return _super32.apply(this, arguments); - } - - _createClass(_class33, [{ - key: "getText", - value: function getText() { - var element = this.getHrefAttribute().getDefinition(); - if (!isNullish(element)) return element.children[0].getText(); - return undefined; - } - }]); - - return _class33; - }(svg.Element.TextElementBase); // a element - - - svg.Element.a = /*#__PURE__*/function (_svg$Element$TextElem3) { - _inherits(_class34, _svg$Element$TextElem3); - - var _super33 = _createSuper(_class34); - - function _class34(node) { - var _this19; - - _classCallCheck(this, _class34); - - _this19 = _super33.call(this, node); - _this19.hasText = true; - - _toConsumableArray(node.childNodes).forEach(function (childNode) { - if (childNode.nodeType !== 3) { - _this19.hasText = false; - } - }); // this might contain text - - - _this19.text = _this19.hasText ? node.childNodes[0].nodeValue : ''; - return _this19; - } - - _createClass(_class34, [{ - key: "getText", - value: function getText() { - return this.text; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - if (this.hasText) { - // render as text element - _get(_getPrototypeOf(_class34.prototype), "renderChildren", this).call(this, ctx); - - var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); - svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y)); - } else { - // render as temporary group - var g = new svg.Element.g(); - g.children = this.children; - g.parent = this; - g.render(ctx); - } - } - }, { - key: "onclick", - value: function onclick() { - window.open(this.getHrefAttribute().value); - } - }, { - key: "onmousemove", - value: function onmousemove() { - svg.ctx.canvas.style.cursor = 'pointer'; - } - }]); - - return _class34; - }(svg.Element.TextElementBase); // image element - - - svg.Element.image = /*#__PURE__*/function (_svg$Element$Rendered5) { - _inherits(_class35, _svg$Element$Rendered5); - - var _super34 = _createSuper(_class35); - - function _class35(node) { - var _this20; - - _classCallCheck(this, _class35); - - _this20 = _super34.call(this, node); - - var href = _this20.getHrefAttribute().value; - - if (href === '') { - return _possibleConstructorReturn(_this20); - } - - _this20._isSvg = href.match(/\.svg$/); - svg.Images.push(_assertThisInitialized(_this20)); - _this20.loaded = false; - - if (!_this20._isSvg) { - _this20.img = document.createElement('img'); - - if (svg.opts.useCORS === true) { - _this20.img.crossOrigin = 'Anonymous'; - } - - _this20.img.addEventListener('load', function () { - _this20.loaded = true; - }); - - _this20.img.addEventListener('error', function () { - svg.log('ERROR: image "' + href + '" not found'); - _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 - }); - } - - return _this20; - } - - _createClass(_class35, [{ - key: "renderChildren", - value: function renderChildren(ctx) { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - if (width === 0 || height === 0) return; - ctx.save(); - - if (this._isSvg) { - ctx.drawSvg(this.img, x, y, width, height); - } else { - ctx.translate(x, y); - svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); - ctx.drawImage(this.img, 0, 0); - } - - ctx.restore(); - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - return new svg.BoundingBox(x, y, x + width, y + height); - } - }]); - - return _class35; - }(svg.Element.RenderedElementBase); // group element - - - svg.Element.g = /*#__PURE__*/function (_svg$Element$Rendered6) { - _inherits(_class36, _svg$Element$Rendered6); - - var _super35 = _createSuper(_class36); - - function _class36() { - _classCallCheck(this, _class36); - - return _super35.apply(this, arguments); - } - - _createClass(_class36, [{ - key: "getBoundingBox", - value: function getBoundingBox() { - var bb = new svg.BoundingBox(); - this.children.forEach(function (child) { - bb.addBoundingBox(child.getBoundingBox()); - }); - return bb; - } - }]); - - return _class36; - }(svg.Element.RenderedElementBase); // symbol element - - - svg.Element.symbol = /*#__PURE__*/function (_svg$Element$Rendered7) { - _inherits(_class37, _svg$Element$Rendered7); - - var _super36 = _createSuper(_class37); - - function _class37() { - _classCallCheck(this, _class37); - - return _super36.apply(this, arguments); - } - - _createClass(_class37, [{ - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class37; - }(svg.Element.RenderedElementBase); // style element - - - svg.Element.style = /*#__PURE__*/function (_svg$Element$ElementB10) { - _inherits(_class38, _svg$Element$ElementB10); - - var _super37 = _createSuper(_class38); - - function _class38(node) { - var _this21; - - _classCallCheck(this, _class38); - - _this21 = _super37.call(this, node); // text, or spaces then CDATA - - var css = ''; - - _toConsumableArray(node.childNodes).forEach(function (_ref11) { - var nodeValue = _ref11.nodeValue; - css += nodeValue; - }); // remove comments - - - css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(^\s*\/\/.*)/gm, ''); // eslint-disable-line unicorn/no-unsafe-regex - // replace whitespace - - css = svg.compressSpaces(css); - var cssDefs = css.split('}'); - cssDefs.forEach(function (cssDef) { - if (svg.trim(cssDef) !== '') { - var _cssDef$split = cssDef.split('{'), - _cssDef$split2 = _slicedToArray(_cssDef$split, 2), - cssClasses = _cssDef$split2[0], - cssProps = _cssDef$split2[1]; - - cssClasses = cssClasses.split(','); - cssProps = cssProps.split(';'); - cssClasses.forEach(function (cssClass) { - cssClass = svg.trim(cssClass); - - if (cssClass !== '') { - var props = {}; - cssProps.forEach(function (cssProp) { - var prop = cssProp.indexOf(':'); - var name = cssProp.substr(0, prop); - var value = cssProp.substr(prop + 1, cssProp.length - prop); - - if (!isNullish(name) && !isNullish(value)) { - props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value)); - } - }); - svg.Styles[cssClass] = props; - - if (cssClass === '@font-face') { - var fontFamily = props['font-family'].value.replace(/"/g, ''); - var srcs = props.src.value.split(','); - srcs.forEach(function (src) { - if (src.includes('format("svg")')) { - var urlStart = src.indexOf('url'); - var urlEnd = src.indexOf(')', urlStart); - var url = src.substr(urlStart + 5, urlEnd - urlStart - 6); // Can this ajax safely be converted to async? - - var doc = svg.parseXml(svg.ajax(url)); - var fonts = doc.getElementsByTagName('font'); - - _toConsumableArray(fonts).forEach(function (font) { - font = svg.CreateElement(font); - svg.Definitions[fontFamily] = font; - }); - } - }); - } - } - }); - } - }); - return _this21; - } - - return _class38; - }(svg.Element.ElementBase); // use element - - - svg.Element.use = /*#__PURE__*/function (_svg$Element$Rendered8) { - _inherits(_class39, _svg$Element$Rendered8); - - var _super38 = _createSuper(_class39); - - function _class39(node) { - var _this22; - - _classCallCheck(this, _class39); - - _this22 = _super38.call(this, node); - _this22._el = _this22.getHrefAttribute().getDefinition(); - return _this22; - } - - _createClass(_class39, [{ - key: "setContext", - value: function setContext(ctx) { - _get(_getPrototypeOf(_class39.prototype), "setContext", this).call(this, ctx); - - if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0); - if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y')); - } - }, { - key: "path", - value: function path(ctx) { - var element = this._el; - if (!isNullish(element)) element.path(ctx); - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var element = this._el; - if (!isNullish(element)) return element.getBoundingBox(); - return undefined; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var element = this._el; - - 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.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); - } - } - - var oldParent = tempSvg.parent; - tempSvg.parent = null; - tempSvg.render(ctx); - tempSvg.parent = oldParent; - } - } - }]); - - return _class39; - }(svg.Element.RenderedElementBase); // mask element - - - svg.Element.mask = /*#__PURE__*/function (_svg$Element$ElementB11) { - _inherits(_class40, _svg$Element$ElementB11); - - var _super39 = _createSuper(_class40); - - function _class40() { - _classCallCheck(this, _class40); - - return _super39.apply(this, arguments); - } - - _createClass(_class40, [{ - key: "apply", - value: function apply(ctx, element) { - // render as temp svg - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - - if (width === 0 && height === 0) { - var bb = new svg.BoundingBox(); - this.children.forEach(function (child) { - bb.addBoundingBox(child.getBoundingBox()); - }); - x = Math.floor(bb.x1); - y = Math.floor(bb.y1); - width = Math.floor(bb.width()); - height = Math.floor(bb.height()); - } // temporarily remove mask to avoid recursion - - - var mask = element.attribute('mask').value; - element.attribute('mask').value = ''; - var cMask = document.createElement('canvas'); - cMask.width = x + width; - cMask.height = y + height; - var maskCtx = cMask.getContext('2d'); - this.renderChildren(maskCtx); - var c = document.createElement('canvas'); - c.width = x + width; - c.height = y + height; - var tempCtx = c.getContext('2d'); - element.render(tempCtx); - tempCtx.globalCompositeOperation = 'destination-in'; - tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat'); - tempCtx.fillRect(0, 0, x + width, y + height); - ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat'); - ctx.fillRect(0, 0, x + width, y + height); // reassign mask - - element.attribute('mask').value = mask; - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class40; - }(svg.Element.ElementBase); // clip element - - - svg.Element.clipPath = /*#__PURE__*/function (_svg$Element$ElementB12) { - _inherits(_class41, _svg$Element$ElementB12); - - var _super40 = _createSuper(_class41); - - function _class41() { - _classCallCheck(this, _class41); - - return _super40.apply(this, arguments); - } - - _createClass(_class41, [{ - key: "apply", - value: function apply(ctx) { - this.children.forEach(function (child) { - if (typeof child.path !== 'undefined') { - var transform = null; - - if (child.attribute('transform').hasValue()) { - transform = new svg.Transform(child.attribute('transform').value); - transform.apply(ctx); - } - - child.path(ctx); - ctx.clip(); - - if (transform) { - transform.unapply(ctx); - } - } - }); - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class41; - }(svg.Element.ElementBase); // filters - - - svg.Element.filter = /*#__PURE__*/function (_svg$Element$ElementB13) { - _inherits(_class42, _svg$Element$ElementB13); - - var _super41 = _createSuper(_class42); - - function _class42() { - _classCallCheck(this, _class42); - - return _super41.apply(this, arguments); - } - - _createClass(_class42, [{ - key: "apply", - value: function apply(ctx, element) { - // render as temp svg - var bb = element.getBoundingBox(); - var x = Math.floor(bb.x1); - var y = Math.floor(bb.y1); - var width = Math.floor(bb.width()); - var height = Math.floor(bb.height()); // temporarily remove filter to avoid recursion - - var filter = element.style('filter').value; - element.style('filter').value = ''; - var px = 0, - py = 0; - this.children.forEach(function (child) { - var efd = child.extraFilterDistance || 0; - px = Math.max(px, efd); - py = Math.max(py, efd); - }); - var c = document.createElement('canvas'); - c.width = width + 2 * px; - c.height = height + 2 * py; - var tempCtx = c.getContext('2d'); - tempCtx.translate(-x + px, -y + py); - element.render(tempCtx); // apply filters - - this.children.forEach(function (child) { - child.apply(tempCtx, 0, 0, width + 2 * px, height + 2 * py); - }); // render on me - - ctx.drawImage(c, 0, 0, width + 2 * px, height + 2 * py, x - px, y - py, width + 2 * px, height + 2 * py); // reassign filter - - element.style('filter', true).value = filter; - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class42; - }(svg.Element.ElementBase); - - svg.Element.feMorphology = /*#__PURE__*/function (_svg$Element$ElementB14) { - _inherits(_class43, _svg$Element$ElementB14); - - var _super42 = _createSuper(_class43); - - function _class43() { - _classCallCheck(this, _class43); - - return _super42.apply(this, arguments); - } - - _createClass(_class43, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) {// TODO: implement - } - }]); - - return _class43; - }(svg.Element.ElementBase); - - svg.Element.feComposite = /*#__PURE__*/function (_svg$Element$ElementB15) { - _inherits(_class44, _svg$Element$ElementB15); - - var _super43 = _createSuper(_class44); - - function _class44() { - _classCallCheck(this, _class44); - - return _super43.apply(this, arguments); - } - - _createClass(_class44, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) {// TODO: implement - } - }]); - - return _class44; - }(svg.Element.ElementBase); - /** - * @param {Uint8ClampedArray} img - * @param {Integer} x - * @param {Integer} y - * @param {Float} width - * @param {Float} height - * @param {Integer} rgba - * @returns {Integer} - */ - - - 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 {void} - */ - - - function imSet(img, x, y, width, height, rgba, val) { - img[y * width * 4 + x * 4 + rgba] = val; - } - - svg.Element.feColorMatrix = /*#__PURE__*/function (_svg$Element$ElementB16) { - _inherits(_class45, _svg$Element$ElementB16); - - var _super44 = _createSuper(_class45); - - function _class45(node) { - var _this23; - - _classCallCheck(this, _class45); - - _this23 = _super44.call(this, node); - var matrix = svg.ToNumberArray(_this23.attribute('values').value); - - 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; - } - - case 'hueRotate': - { - 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; - }; - - 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]; - break; - } - - _this23.matrix = matrix; - - _this23._m = function (i, v) { - var mi = matrix[i]; - return mi * (mi < 0 ? v - 255 : v); - }; - - return _this23; - } - - _createClass(_class45, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) { - var m = this._m; // assuming x==0 && y==0 for now - - var srcData = ctx.getImageData(0, 0, width, height); - - 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)); - } - } - - ctx.clearRect(0, 0, width, height); - ctx.putImageData(srcData, 0, 0); - } - }]); - - return _class45; - }(svg.Element.ElementBase); - - svg.Element.feGaussianBlur = /*#__PURE__*/function (_svg$Element$ElementB17) { - _inherits(_class46, _svg$Element$ElementB17); - - var _super45 = _createSuper(_class46); - - function _class46(node) { - var _this24; - - _classCallCheck(this, _class46); - - _this24 = _super45.call(this, node); - _this24.blurRadius = Math.floor(_this24.attribute('stdDeviation').numValue()); - _this24.extraFilterDistance = _this24.blurRadius; - return _this24; - } - - _createClass(_class46, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) { - // 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); - processCanvasRGBA(ctx.canvas, x, y, width, height, this.blurRadius); - ctx.canvas.remove(); - } - }]); - - return _class46; - }(svg.Element.ElementBase); // title element, do nothing - - - svg.Element.title = /*#__PURE__*/function (_svg$Element$ElementB18) { - _inherits(_class47, _svg$Element$ElementB18); - - var _super46 = _createSuper(_class47); - - function _class47(node) { - _classCallCheck(this, _class47); - - return _super46.call(this); - } - - return _class47; - }(svg.Element.ElementBase); // desc element, do nothing - - - svg.Element.desc = /*#__PURE__*/function (_svg$Element$ElementB19) { - _inherits(_class48, _svg$Element$ElementB19); - - var _super47 = _createSuper(_class48); - - function _class48(node) { - _classCallCheck(this, _class48); - - return _super47.call(this); - } - - return _class48; - }(svg.Element.ElementBase); - - svg.Element.MISSING = /*#__PURE__*/function (_svg$Element$ElementB20) { - _inherits(_class49, _svg$Element$ElementB20); - - var _super48 = _createSuper(_class49); - - function _class49(node) { - var _this25; - - _classCallCheck(this, _class49); - - _this25 = _super48.call(this); - svg.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); - return _this25; - } - - return _class49; - }(svg.Element.ElementBase); // element factory - - - svg.CreateElement = function (node) { - var className = node.nodeName.replace(/^[^:]+:/, '') // remove namespace - .replace(/-/g, ''); // remove dashes - - var e; - - if (typeof svg.Element[className] !== 'undefined') { - e = new svg.Element[className](node); - } else { - e = new svg.Element.MISSING(node); - } - - e.type = node.nodeName; - return e; - }; // load from url - - - svg.load = /*#__PURE__*/function () { - var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(ctx, url) { - var dom; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return svg.ajax(url, true); - - case 2: - dom = _context.sent; - return _context.abrupt("return", svg.loadXml(ctx, dom)); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function (_x2, _x3) { - return _ref12.apply(this, arguments); - }; - }(); // load from xml - - - svg.loadXml = function (ctx, xml) { - return svg.loadXmlDoc(ctx, svg.parseXml(xml)); - }; - - svg.loadXmlDoc = function (ctx, dom) { - var res; - svg.init(ctx); - - var mapXY = function mapXY(p) { - var e = ctx.canvas; - - while (e) { - p.x -= e.offsetLeft; - p.y -= e.offsetTop; - e = e.offsetParent; - } - - if (window.scrollX) p.x += window.scrollX; - if (window.scrollY) p.y += window.scrollY; - return p; - }; // bind mouse - - - if (svg.opts.ignoreMouse !== true) { - ctx.canvas.addEventListener('click', function (e) { - 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, - y = _mapXY.y; - - svg.Mouse.onclick(x, y); - }); - ctx.canvas.addEventListener('mousemove', function (e) { - 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, - y = _mapXY2.y; - - svg.Mouse.onmousemove(x, y); - }); - } - - var e = svg.CreateElement(dom.documentElement); - e.root = true; // render loop - - var isFirstRender = true; - - var draw = function draw(resolve) { - svg.ViewPort.Clear(); - - if (ctx.canvas.parentNode) { - svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight); - } - - if (svg.opts.ignoreDimensions !== true) { - // set canvas size - if (e.style('width').hasValue()) { - ctx.canvas.width = e.style('width').toPixels('x'); - ctx.canvas.style.width = ctx.canvas.width + 'px'; - } - - if (e.style('height').hasValue()) { - ctx.canvas.height = e.style('height').toPixels('y'); - ctx.canvas.style.height = ctx.canvas.height + 'px'; - } - } - - var cWidth = ctx.canvas.clientWidth || ctx.canvas.width; - var cHeight = ctx.canvas.clientHeight || ctx.canvas.height; - - if (svg.opts.ignoreDimensions === true && e.style('width').hasValue() && e.style('height').hasValue()) { - cWidth = e.style('width').toPixels('x'); - cHeight = e.style('height').toPixels('y'); - } - - svg.ViewPort.SetCurrent(cWidth, cHeight); - - if (!isNullish(svg.opts.offsetX)) { - e.attribute('x', true).value = svg.opts.offsetX; - } - - if (!isNullish(svg.opts.offsetY)) { - e.attribute('y', true).value = svg.opts.offsetY; - } - - if (!isNullish(svg.opts.scaleWidth) || !isNullish(svg.opts.scaleHeight)) { - var viewBox = svg.ToNumberArray(e.attribute('viewBox').value); - var xRatio = null, - yRatio = 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])) { - xRatio = viewBox[2] / svg.opts.scaleWidth; - } - } - - if (!isNullish(svg.opts.scaleHeight)) { - if (e.attribute('height').hasValue()) { - yRatio = e.attribute('height').toPixels('y') / svg.opts.scaleHeight; - } else if (!isNaN(viewBox[3])) { - yRatio = viewBox[3] / svg.opts.scaleHeight; - } - } - - if (isNullish(xRatio)) { - xRatio = yRatio; - } - - if (isNullish(yRatio)) { - yRatio = xRatio; - } - - e.attribute('width', true).value = svg.opts.scaleWidth; - e.attribute('height', true).value = svg.opts.scaleHeight; - e.attribute('viewBox', true).value = '0 0 ' + cWidth * xRatio + ' ' + cHeight * yRatio; - e.attribute('preserveAspectRatio', true).value = 'none'; - } // clear and render - - - if (svg.opts.ignoreClear !== true) { - ctx.clearRect(0, 0, cWidth, cHeight); - } - - e.render(ctx); - - if (isFirstRender) { - isFirstRender = false; - resolve(dom); - } - }; - - var waitingForImages = true; - svg.intervalID = setInterval(function () { - var needUpdate = false; - - if (waitingForImages && svg.ImagesLoaded()) { - waitingForImages = false; - needUpdate = true; - } // need update from mouse events? - - - if (svg.opts.ignoreMouse !== true) { - needUpdate = needUpdate || svg.Mouse.hasEvents(); - } // need update from animations? - - - if (svg.opts.ignoreAnimation !== true) { - svg.Animations.forEach(function (animation) { - var needAnimationUpdate = animation.update(1000 / svg.FRAMERATE); - needUpdate = needUpdate || needAnimationUpdate; - }); - } // need update from redraw? - - - if (typeof svg.opts.forceRedraw === 'function') { - if (svg.opts.forceRedraw() === true) { - needUpdate = true; - } - } // render if needed - - - if (needUpdate) { - draw(res); - svg.Mouse.runEvents(); // run and clear our events - } - }, 1000 / svg.FRAMERATE); // Todo: Replace with an image loading Promise utility? - // eslint-disable-next-line promise/avoid-new - - return new Promise(function (resolve, reject) { - if (svg.ImagesLoaded()) { - waitingForImages = false; - draw(resolve); - return; - } - - res = resolve; - }); - }; - - svg.stop = function () { - if (svg.intervalID) { - clearInterval(svg.intervalID); - } - }; - - svg.Mouse = { - events: [], - hasEvents: function hasEvents() { - return this.events.length !== 0; - }, - onclick: function onclick(x, y) { - this.events.push({ - type: 'onclick', - x: x, - y: y, - run: function run(e) { - if (e.onclick) e.onclick(); - } - }); - }, - onmousemove: function onmousemove(x, y) { - this.events.push({ - type: 'onmousemove', - x: x, - y: y, - run: function run(e) { - if (e.onmousemove) e.onmousemove(); - } - }); - }, - eventElements: [], - checkPath: function checkPath(element, ctx) { - var _this26 = this; - - this.events.forEach(function (_ref13, i) { - var x = _ref13.x, - y = _ref13.y; - - if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { - _this26.eventElements[i] = element; - } - }); - }, - checkBoundingBox: function checkBoundingBox(element, bb) { - var _this27 = this; - - this.events.forEach(function (_ref14, i) { - var x = _ref14.x, - y = _ref14.y; - - if (bb.isPointInBox(x, y)) { - _this27.eventElements[i] = element; - } - }); - }, - runEvents: function runEvents() { - var _this28 = this; - - svg.ctx.canvas.style.cursor = ''; - this.events.forEach(function (e, i) { - var element = _this28.eventElements[i]; - - while (element) { - e.run(element); - element = element.parent; - } - }); // done running, clear - - this.events = []; - this.eventElements = []; - } - }; - return svg; - } - - if (typeof CanvasRenderingContext2D !== 'undefined') { - CanvasRenderingContext2D.prototype.drawSvg = function (s, dx, dy, dw, dh) { - canvg(this.canvas, s, { - ignoreMouse: true, - ignoreAnimation: true, - ignoreDimensions: true, - ignoreClear: true, - offsetX: dx, - offsetY: dy, - scaleWidth: dw, - scaleHeight: dh - }); - }; - } - - exports.canvg = canvg; - - return exports; - -}({})); diff --git a/dist/dom-polyfill.js b/dist/dom-polyfill.js deleted file mode 100644 index bd2ec167..00000000 --- a/dist/dom-polyfill.js +++ /dev/null @@ -1,165 +0,0 @@ -(function () { - 'use strict'; - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - // From https://github.com/inexorabletash/polyfill/blob/master/dom.js - - /** - * @module DOMPolyfill - */ - - /** - * - * @param {Node} o - * @param {module:DOMPolyfill~ParentNode|module:DOMPolyfill~ChildNode} ps - * @returns {void} - */ - function mixin(o, ps) { - if (!o) return; - Object.keys(ps).forEach(function (p) { - if (p in o || p in o.prototype) { - return; - } - - try { - Object.defineProperty(o.prototype, p, Object.getOwnPropertyDescriptor(ps, p)); - } catch (ex) { - // Throws in IE8; just copy it - o[p] = ps[p]; - } - }); - } - /** - * - * @param {Node[]} nodes - * @returns {Node} - */ - - - function convertNodesIntoANode(nodes) { - nodes = nodes.map(function (node) { - var isNode = node && _typeof(node) === 'object' && 'nodeType' in node; - return isNode ? node : document.createTextNode(node); - }); - - if (nodes.length === 1) { - return nodes[0]; - } - - var node = document.createDocumentFragment(); - nodes.forEach(function (n) { - // // eslint-disable-next-line unicorn/prefer-node-append - node.appendChild(n); - }); - return node; - } - - var ParentNode = { - prepend: function prepend() { - for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) { - nodes[_key] = arguments[_key]; - } - - nodes = convertNodesIntoANode(nodes); - this.insertBefore(nodes, this.firstChild); - }, - append: function append() { - for (var _len2 = arguments.length, nodes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - nodes[_key2] = arguments[_key2]; - } - - nodes = convertNodesIntoANode(nodes); // // eslint-disable-next-line unicorn/prefer-node-append - - this.appendChild(nodes); - } - }; - mixin(Document || HTMLDocument, ParentNode); // HTMLDocument for IE8 - - mixin(DocumentFragment, ParentNode); - mixin(Element, ParentNode); // Mixin ChildNode - // https://dom.spec.whatwg.org/#interface-childnode - - var ChildNode = { - before: function before() { - var parent = this.parentNode; - if (!parent) return; - var viablePreviousSibling = this.previousSibling; - - for (var _len3 = arguments.length, nodes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - nodes[_key3] = arguments[_key3]; - } - - while (nodes.includes(viablePreviousSibling)) { - viablePreviousSibling = viablePreviousSibling.previousSibling; - } - - var node = convertNodesIntoANode(nodes); - parent.insertBefore(node, viablePreviousSibling ? viablePreviousSibling.nextSibling : parent.firstChild); - }, - after: function after() { - var parent = this.parentNode; - if (!parent) return; - var viableNextSibling = this.nextSibling; - - for (var _len4 = arguments.length, nodes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - nodes[_key4] = arguments[_key4]; - } - - while (nodes.includes(viableNextSibling)) { - viableNextSibling = viableNextSibling.nextSibling; - } - - var node = convertNodesIntoANode(nodes); // eslint-disable-next-line unicorn/prefer-modern-dom-apis - - parent.insertBefore(node, viableNextSibling); - }, - replaceWith: function replaceWith() { - var parent = this.parentNode; - if (!parent) return; - var viableNextSibling = this.nextSibling; - - for (var _len5 = arguments.length, nodes = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { - nodes[_key5] = arguments[_key5]; - } - - while (nodes.includes(viableNextSibling)) { - viableNextSibling = viableNextSibling.nextSibling; - } - - var node = convertNodesIntoANode(nodes); - - if (this.parentNode === parent) { - parent.replaceChild(node, this); - } else { - // eslint-disable-next-line unicorn/prefer-modern-dom-apis - parent.insertBefore(node, viableNextSibling); - } - }, - remove: function remove() { - if (!this.parentNode) { - return; - } - - this.parentNode.removeChild(this); // eslint-disable-line unicorn/prefer-node-remove - } - }; - mixin(DocumentType, ChildNode); - mixin(Element, ChildNode); - mixin(CharacterData, ChildNode); - -}()); diff --git a/dist/editor/browser-not-supported.html b/dist/editor/browser-not-supported.html new file mode 100644 index 00000000..ca55d156 --- /dev/null +++ b/dist/editor/browser-not-supported.html @@ -0,0 +1,54 @@ + + + + + + + + Browser does not support SVG | SVG-edit + + + + +

Sorry, but your browser does not support SVG. Below is a list of + alternate browsers and versions that support SVG and SVG-edit + (from caniuse.com). +

+

Try the latest version of + Firefox, + Chrome, + Safari, + Opera or + Internet Explorer. +

+
+ +
+ + diff --git a/dist/editor/embedapi.html b/dist/editor/embedapi.html new file mode 100644 index 00000000..dda45a19 --- /dev/null +++ b/dist/editor/embedapi.html @@ -0,0 +1,17 @@ + + + + + Embed API + + + + + + + + + +
+ + diff --git a/dist/editor/embedapi.js b/dist/editor/embedapi.js new file mode 100644 index 00000000..dd6459c4 --- /dev/null +++ b/dist/editor/embedapi.js @@ -0,0 +1,395 @@ +/** +* Handles underlying communication between the embedding window and the +* editor frame. +* @module EmbeddedSVGEdit +*/ + +let cbid = 0; + +/** +* @callback module:EmbeddedSVGEdit.CallbackSetter +* @param {GenericCallback} newCallback Callback to be stored (signature dependent on function) +* @returns {void} +*/ +/** +* @callback module:EmbeddedSVGEdit.CallbackSetGetter +* @param {...any} args Signature dependent on the function +* @returns {module:EmbeddedSVGEdit.CallbackSetter} +*/ + +/** +* @param {string} funcName +* @returns {module:EmbeddedSVGEdit.CallbackSetGetter} +*/ +function getCallbackSetter (funcName) { + return function (...args) { + const that = this, // New callback + callbackID = this.send(funcName, args, function () { /* */ }); // The callback (currently it's nothing, but will be set later) + + return function (newCallback) { + that.callbacks[callbackID] = newCallback; // Set callback + }; + }; +} + +/** +* Having this separate from messageListener allows us to +* avoid using JSON parsing (and its limitations) in the case +* of same domain control. +* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value +* @param {PlainObject} data +* @param {JSON} data.result +* @param {string} data.error +* @param {Integer} data.id +* @returns {void} +*/ +function addCallback (t, {result, error, id: callbackID}) { + if (typeof callbackID === 'number' && t.callbacks[callbackID]) { + // These should be safe both because we check `cbid` is numeric and + // because the calls are from trusted origins + if (result) { + t.callbacks[callbackID](result); // lgtm [js/unvalidated-dynamic-method-call] + } else { + t.callbacks[callbackID](error, 'error'); // lgtm [js/unvalidated-dynamic-method-call] + } + } +} + +/** +* @param {Event} e +* @returns {void} +*/ +function messageListener (e) { + // We accept and post strings as opposed to objects for the sake of IE9 support; this + // will most likely be changed in the future + if (!e.data || !['string', 'object'].includes(typeof e.data)) { + return; + } + const {allowedOrigins} = this, + data = typeof e.data === 'object' ? e.data : JSON.parse(e.data); + if (!data || typeof data !== 'object' || data.namespace !== 'svg-edit' || + e.source !== this.frame.contentWindow || + (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) + ) { + // eslint-disable-next-line no-console -- Info for developers + console.error( + `The origin ${e.origin} was not whitelisted as an origin from ` + + `which responses may be received by this ${window.origin} script.` + ); + return; + } + addCallback(this, data); +} + +/** +* @callback module:EmbeddedSVGEdit.MessageListener +* @param {MessageEvent} e +* @returns {void} +*/ +/** +* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value +* @returns {module:EmbeddedSVGEdit.MessageListener} Event listener +*/ +function getMessageListener (t) { + return function (e) { + messageListener.call(t, e); + }; +} + +/** +* Embedded SVG-edit API. +* General usage: +* - Have an iframe somewhere pointing to a version of svg-edit > r1000. +* @example +// Initialize the magic with: +const svgCanvas = new EmbeddedSVGEdit(window.frames.svgedit); + +// Pass functions in this format: +svgCanvas.setSvgString('string'); + +// Or if a callback is needed: +svgCanvas.setSvgString('string')(function (data, error) { + if (error) { + // There was an error + } else { + // Handle data + } +}); + +// Everything is done with the same API as the real svg-edit, +// and all documentation is unchanged. + +// However, this file depends on the postMessage API which +// can only support JSON-serializable arguments and +// return values, so, for example, arguments whose value is +// 'undefined', a function, a non-finite number, or a built-in +// object like Date(), RegExp(), etc. will most likely not behave +// as expected. In such a case one may need to host +// the SVG editor on the same domain and reference the +// JavaScript methods on the frame itself. + +// The only other difference is when handling returns: +// the callback notation is used instead. +const blah = new EmbeddedSVGEdit(window.frames.svgedit); +blah.clearSelection('woot', 'blah', 1337, [1, 2, 3, 4, 5, 'moo'], -42, { + a: 'tree', b: 6, c: 9 +})(function () { console.log('GET DATA', args); }); +* +* @memberof module:EmbeddedSVGEdit +*/ +class EmbeddedSVGEdit { + /** + * @param {HTMLIFrameElement} frame + * @param {string[]} [allowedOrigins=[]] Array of origins from which incoming + * messages will be allowed when same origin is not used; defaults to none. + * If supplied, it should probably be the same as svgEditor's allowedOrigins + */ + constructor (frame, allowedOrigins) { + const that = this; + this.allowedOrigins = allowedOrigins || []; + // Initialize communication + this.frame = frame; + this.callbacks = {}; + // List of functions extracted with this: + // Run in firebug on http://svg-edit.googlecode.com/svn/trunk/docs/files/svgcanvas-js.html + + // for (const i=0,q=[],f = document.querySelectorAll('div.CFunction h3.CTitle a'); i < f.length; i++) { q.push(f[i].name); }; q + // const functions = ['clearSelection', 'addToSelection', 'removeFromSelection', 'open', 'save', 'getSvgString', 'setSvgString', + // 'createLayer', 'deleteCurrentLayer', 'setCurrentLayer', 'renameCurrentLayer', 'setCurrentLayerPosition', 'setLayerVisibility', + // 'moveSelectedToLayer', 'clear']; + + // Newer, well, it extracts things that aren't documented as well. All functions accessible through the normal thingy can now be accessed though the API + // const {svgCanvas} = frame.contentWindow; + // const l = []; + // for (const i in svgCanvas) { if (typeof svgCanvas[i] === 'function') { l.push(i);} }; + // alert("['" + l.join("', '") + "']"); + // Run in svgedit itself + const functions = [ + 'addExtension', + 'addSVGElementFromJson', + 'addToSelection', + 'alignSelectedElements', + 'assignAttributes', + 'bind', + 'call', + 'changeSelectedAttribute', + 'cleanupElement', + 'clear', + 'clearSelection', + 'clearSvgContentElement', + 'cloneLayer', + 'cloneSelectedElements', + 'convertGradients', + 'convertToGroup', + 'convertToNum', + 'convertToPath', + 'copySelectedElements', + 'createLayer', + 'cutSelectedElements', + 'cycleElement', + 'deleteCurrentLayer', + 'deleteSelectedElements', + 'embedImage', + 'exportPDF', + 'findDefs', + 'getBBox', + 'getBlur', + 'getBold', + 'getColor', + 'getContentElem', + 'getCurrentDrawing', + 'getDocumentTitle', + 'getEditorNS', + 'getElem', + 'getFillOpacity', + 'getFontColor', + 'getFontFamily', + 'getFontSize', + 'getHref', + 'getId', + 'getIntersectionList', + 'getItalic', + 'getMode', + 'getMouseTarget', + 'getNextId', + 'getOffset', + 'getOpacity', + 'getPaintOpacity', + 'getPrivateMethods', + 'getRefElem', + 'getResolution', + 'getRootElem', + 'getRotationAngle', + 'getSelectedElems', + 'getStrokeOpacity', + 'getStrokeWidth', + 'getStrokedBBox', + 'getStyle', + 'getSvgString', + 'getText', + 'getTitle', + 'getTransformList', + 'getUIStrings', + 'getUrlFromAttr', + 'getVersion', + 'getVisibleElements', + 'getVisibleElementsAndBBoxes', + 'getZoom', + 'groupSelectedElements', + 'groupSvgElem', + 'hasMatrixTransform', + 'identifyLayers', + 'importSvgString', + 'leaveContext', + 'linkControlPoints', + 'makeHyperlink', + 'matrixMultiply', + 'mergeAllLayers', + 'mergeLayer', + 'moveSelectedElements', + 'moveSelectedToLayer', + 'moveToBottomSelectedElement', + 'moveToTopSelectedElement', + 'moveUpDownSelected', + 'open', + 'pasteElements', + 'prepareSvg', + 'pushGroupProperties', + 'randomizeIds', + 'rasterExport', + 'ready', + 'recalculateAllSelectedDimensions', + 'recalculateDimensions', + 'remapElement', + 'removeFromSelection', + 'removeHyperlink', + 'removeUnusedDefElems', + 'renameCurrentLayer', + 'round', + 'runExtensions', + 'sanitizeSvg', + 'save', + 'selectAllInCurrentLayer', + 'selectOnly', + 'setBBoxZoom', + 'setBackground', + 'setBlur', + 'setBlurNoUndo', + 'setBlurOffsets', + 'setBold', + 'setColor', + 'setConfig', + 'setContext', + 'setCurrentLayer', + 'setCurrentLayerPosition', + 'setDocumentTitle', + 'setFillPaint', + 'setFontColor', + 'setFontFamily', + 'setFontSize', + 'setGoodImage', + 'setGradient', + 'setGroupTitle', + 'setHref', + 'setIdPrefix', + 'setImageURL', + 'setItalic', + 'setLayerVisibility', + 'setLinkURL', + 'setMode', + 'setOpacity', + 'setPaint', + 'setPaintOpacity', + 'setRectRadius', + 'setResolution', + 'setRotationAngle', + 'setSegType', + 'setStrokeAttr', + 'setStrokePaint', + 'setStrokeWidth', + 'setSvgString', + 'setTextContent', + 'setUiStrings', + 'setUseData', + 'setZoom', + 'svgCanvasToString', + 'svgToString', + 'transformListToTransform', + 'ungroupSelectedElement', + 'uniquifyElems', + 'updateCanvas', + 'zoomChanged' + ]; + + // TODO: rewrite the following, it's pretty scary. + for (const func of functions) { + this[func] = getCallbackSetter(func); + } + + // Older IE may need a polyfill for addEventListener, but so it would for SVG + window.addEventListener('message', getMessageListener(this)); + window.addEventListener('keydown', (e) => { + const {type, key} = e; + if (key === 'Backspace') { + e.preventDefault(); + const keyboardEvent = new KeyboardEvent(type, {key}); + that.frame.contentDocument.dispatchEvent(keyboardEvent); + } + }); + } + + /** + * @param {string} name + * @param {ArgumentsArray} args Signature dependent on function + * @param {GenericCallback} callback (This may be better than a promise in case adding an event.) + * @returns {Integer} + */ + send (name, args, callback) { // eslint-disable-line promise/prefer-await-to-callbacks + const that = this; + cbid++; + + this.callbacks[cbid] = callback; + setTimeout((function (callbackID) { + return function () { // Delay for the callback to be set in case its synchronous + /* + * Todo: Handle non-JSON arguments and return values (undefined, + * nonfinite numbers, functions, and built-in objects like Date, + * RegExp), etc.? Allow promises instead of callbacks? Review + * SVG-Edit functions for whether JSON-able parameters can be + * made compatile with all API functionality + */ + // We accept and post strings for the sake of IE9 support + let sameOriginWithGlobal = false; + try { + sameOriginWithGlobal = window.location.origin === that.frame.contentWindow.location.origin && + that.frame.contentWindow.svgEditor.canvas; + } catch (err) {} + + if (sameOriginWithGlobal) { + // Although we do not really need this API if we are working same + // domain, it could allow us to write in a way that would work + // cross-domain as well, assuming we stick to the argument limitations + // of the current JSON-based communication API (e.g., not passing + // callbacks). We might be able to address these shortcomings; see + // the todo elsewhere in this file. + const message = {id: callbackID}, + {svgEditor: {canvas: svgCanvas}} = that.frame.contentWindow; + try { + message.result = svgCanvas[name](...args); + } catch (err) { + message.error = err.message; + } + addCallback(that, message); + } else { // Requires the ext-xdomain-messaging.js extension + that.frame.contentWindow.postMessage(JSON.stringify({ + namespace: 'svgCanvas', id: callbackID, name, args + }), '*'); + } + }; + }(cbid)), 0); + + return cbid; + } +} + +export default EmbeddedSVGEdit; diff --git a/dist/editor/extensions/ext-arrows/ext-arrows.js b/dist/editor/extensions/ext-arrows/ext-arrows.js new file mode 100644 index 00000000..a461338c --- /dev/null +++ b/dist/editor/extensions/ext-arrows/ext-arrows.js @@ -0,0 +1,10 @@ +var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t,e,r){return t(r={path:e,exports:{},require:function(t,e){return function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==e&&r.path)}},r.exports),r.exports}var check=function(t){return t&&t.Math==Math&&t},e=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof t&&t)||Function("return this")(),fails=function(t){try{return!!t()}catch(t){return!0}},r=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),n={}.propertyIsEnumerable,o=Object.getOwnPropertyDescriptor,i={f:o&&!n.call({1:2},1)?function propertyIsEnumerable(t){var e=o(this,t);return!!e&&e.enumerable}:n},createPropertyDescriptor=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},a={}.toString,classofRaw=function(t){return a.call(t).slice(8,-1)},c="".split,u=fails((function(){return!Object("z").propertyIsEnumerable(0)}))?function(t){return"String"==classofRaw(t)?c.call(t,""):Object(t)}:Object,requireObjectCoercible=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t},toIndexedObject=function(t){return u(requireObjectCoercible(t))},isObject=function(t){return"object"==typeof t?null!==t:"function"==typeof t},toPrimitive=function(t,e){if(!isObject(t))return t;var r,n;if(e&&"function"==typeof(r=t.toString)&&!isObject(n=r.call(t)))return n;if("function"==typeof(r=t.valueOf)&&!isObject(n=r.call(t)))return n;if(!e&&"function"==typeof(r=t.toString)&&!isObject(n=r.call(t)))return n;throw TypeError("Can't convert object to primitive value")},f={}.hasOwnProperty,has=function(t,e){return f.call(t,e)},l=e.document,s=isObject(l)&&isObject(l.createElement),documentCreateElement=function(t){return s?l.createElement(t):{}},p=!r&&!fails((function(){return 7!=Object.defineProperty(documentCreateElement("div"),"a",{get:function(){return 7}}).a})),h=Object.getOwnPropertyDescriptor,d={f:r?h:function getOwnPropertyDescriptor(t,e){if(t=toIndexedObject(t),e=toPrimitive(e,!0),p)try{return h(t,e)}catch(t){}if(has(t,e))return createPropertyDescriptor(!i.f.call(t,e),t[e])}},anObject=function(t){if(!isObject(t))throw TypeError(String(t)+" is not an object");return t},v=Object.defineProperty,y={f:r?v:function defineProperty(t,e,r){if(anObject(t),e=toPrimitive(e,!0),anObject(r),p)try{return v(t,e,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported");return"value"in r&&(t[e]=r.value),t}},g=r?function(t,e,r){return y.f(t,e,createPropertyDescriptor(1,r))}:function(t,e,r){return t[e]=r,t},setGlobal=function(t,r){try{g(e,t,r)}catch(n){e[t]=r}return r},m=e["__core-js_shared__"]||setGlobal("__core-js_shared__",{}),b=Function.toString;"function"!=typeof m.inspectSource&&(m.inspectSource=function(t){return b.call(t)});var w,S,x,E=m.inspectSource,_=e.WeakMap,O="function"==typeof _&&/native code/.test(E(_)),j=createCommonjsModule((function(t){(t.exports=function(t,e){return m[t]||(m[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})})),k=0,P=Math.random(),uid=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++k+P).toString(36)},A=j("keys"),sharedKey=function(t){return A[t]||(A[t]=uid(t))},T={},I=e.WeakMap;if(O){var L=new I,R=L.get,C=L.has,M=L.set;w=function(t,e){return M.call(L,t,e),e},S=function(t){return R.call(L,t)||{}},x=function(t){return C.call(L,t)}}else{var G=sharedKey("state");T[G]=!0,w=function(t,e){return g(t,G,e),e},S=function(t){return has(t,G)?t[G]:{}},x=function(t){return has(t,G)}}var N,D={set:w,get:S,has:x,enforce:function(t){return x(t)?S(t):w(t,{})},getterFor:function(t){return function(e){var r;if(!isObject(e)||(r=S(e)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return r}}},U=createCommonjsModule((function(t){var r=D.get,n=D.enforce,o=String(String).split("String");(t.exports=function(t,r,i,a){var c=!!a&&!!a.unsafe,u=!!a&&!!a.enumerable,f=!!a&&!!a.noTargetGet;"function"==typeof i&&("string"!=typeof r||has(i,"name")||g(i,"name",r),n(i).source=o.join("string"==typeof r?r:"")),t!==e?(c?!f&&t[r]&&(u=!0):delete t[r],u?t[r]=i:g(t,r,i)):u?t[r]=i:setGlobal(r,i)})(Function.prototype,"toString",(function toString(){return"function"==typeof this&&r(this).source||E(this)}))})),z=e,aFunction=function(t){return"function"==typeof t?t:void 0},getBuiltIn=function(t,r){return arguments.length<2?aFunction(z[t])||aFunction(e[t]):z[t]&&z[t][r]||e[t]&&e[t][r]},W=Math.ceil,$=Math.floor,toInteger=function(t){return isNaN(t=+t)?0:(t>0?$:W)(t)},B=Math.min,toLength=function(t){return t>0?B(toInteger(t),9007199254740991):0},V=Math.max,Y=Math.min,toAbsoluteIndex=function(t,e){var r=toInteger(t);return r<0?V(r+e,0):Y(r,e)},createMethod=function(t){return function(e,r,n){var o,i=toIndexedObject(e),a=toLength(i.length),c=toAbsoluteIndex(n,a);if(t&&r!=r){for(;a>c;)if((o=i[c++])!=o)return!0}else for(;a>c;c++)if((t||c in i)&&i[c]===r)return t||c||0;return!t&&-1}},q={includes:createMethod(!0),indexOf:createMethod(!1)},H=q.indexOf,objectKeysInternal=function(t,e){var r,n=toIndexedObject(t),o=0,i=[];for(r in n)!has(T,r)&&has(n,r)&&i.push(r);for(;e.length>o;)has(n,r=e[o++])&&(~H(i,r)||i.push(r));return i},K=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],J=K.concat("length","prototype"),X={f:Object.getOwnPropertyNames||function getOwnPropertyNames(t){return objectKeysInternal(t,J)}},Q={f:Object.getOwnPropertySymbols},Z=getBuiltIn("Reflect","ownKeys")||function ownKeys(t){var e=X.f(anObject(t)),r=Q.f;return r?e.concat(r(t)):e},copyConstructorProperties=function(t,e){for(var r=Z(e),n=y.f,o=d.f,i=0;ii;)y.f(t,r=n[i++],e[r]);return t},dt=getBuiltIn("document","documentElement"),vt=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(t){return"`, */\n // mathjaxSrc = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js',\n // Had been on https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG.js\n // Obtained Text-AMS-MML_SVG.js from https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.3/config/TeX-AMS-MML_SVG.js\n {uiStrings} = svgEditor;\n let\n math,\n locationX,\n locationY,\n mathjaxLoaded = false;\n\n // TODO: Implement language support. Move these uiStrings to the locale files and\n // the code to the langReady callback. Also i18nize alert and HTML below\n $.extend(uiStrings, {\n mathjax: {\n embed_svg: 'Save as mathematics',\n embed_mathml: 'Save as figure',\n svg_save_warning: 'The math will be transformed into a figure is ' +\n 'manipulatable like everything else. You will not be able to ' +\n 'manipulate the TeX-code anymore.',\n mathml_save_warning: 'Advised. The math will be saved as a figure.',\n title: 'Mathematics code editor'\n }\n });\n\n /**\n *\n * @returns {void}\n */\n function saveMath () {\n const code = $('#mathjax_code_textarea').val();\n // displaystyle to force MathJax NOT to use the inline style. Because it is\n // less fancy!\n MathJax.Hub.queue.Push(['Text', math, '\\\\displaystyle{' + code + '}']);\n\n /*\n * The MathJax library doesn't want to bloat your webpage so it creates\n * every symbol (glymph) you need only once. These are saved in a `` on\n * the top of your html document, just under the body tag. Each glymph has\n * its unique id and is saved as a `` in the `` tag of the ``\n *\n * Then when the symbols are needed in the rest of your html document they\n * are refferd to by a `` tag.\n * Because of bug 1076 we can't just grab the defs tag on the top and add it\n * to your formula's `` and copy the lot. So we have to replace each\n * `` tag by its ``.\n */\n MathJax.Hub.queue.Push(\n function () {\n const mathjaxMath = $('.MathJax_SVG');\n const svg = $(mathjaxMath.html());\n svg.find('use').each(function () {\n // TODO: find a less pragmatic and more elegant solution to this.\n const id = $(this).attr('href')\n ? $(this).attr('href').slice(1) // Works in Chrome.\n : $(this).attr('xlink:href').slice(1); // Works in Firefox.\n const glymph = $('#' + id).clone().removeAttr('id');\n const x = $(this).attr('x');\n const y = $(this).attr('y');\n const transform = $(this).attr('transform');\n if (transform && (x || y)) {\n glymph.attr('transform', transform + ' translate(' + x + ',' + y + ')');\n } else if (transform) {\n glymph.attr('transform', transform);\n } else if (x || y) {\n glymph.attr('transform', 'translate(' + x + ',' + y + ')');\n }\n $(this).replaceWith(glymph);\n });\n // Remove the style tag because it interferes with SVG-Edit.\n svg.removeAttr('style');\n svg.attr('xmlns', 'http://www.w3.org/2000/svg');\n svgCanvas.importSvgString($('
').append(svg.clone()).html(), true);\n svgCanvas.ungroupSelectedElement();\n // TODO: To undo the adding of the Formula you now have to undo twice.\n // This should only be once!\n svgCanvas.moveSelectedElements(locationX, locationY, true);\n }\n );\n }\n\n const buttons = [{\n id: 'tool_mathjax',\n type: 'mode',\n icon: 'mathjax.png',\n events: {\n async click () {\n // Set the mode.\n svgCanvas.setMode('mathjax');\n\n // Only load Mathjax when needed, we don't want to strain Svg-Edit any more.\n // From this point on it is very probable that it will be needed, so load it.\n if (mathjaxLoaded === false) {\n $(\n '
' +\n '' +\n '
' +\n '$${}$$' +\n '
' +\n '
' +\n '
' +\n '
' +\n '' +\n '' +\n '
' +\n '
' +\n 'Mathematics Editor' +\n '' +\n '' +\n '
' +\n '
' +\n '
'\n ).insertAfter('#svg_prefs').hide();\n\n // Make the MathEditor draggable.\n $('#mathjax_container').draggable({\n cancel: 'button,fieldset',\n containment: 'window'\n });\n\n // Add functionality and picture to cancel button.\n $('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true))\n .on('click touched', function () {\n $('#mathjax').hide();\n });\n\n // Add functionality and picture to the save button.\n $('#tool_mathjax_save').prepend($.getSvgIcon('ok', true))\n .on('click touched', function () {\n saveMath();\n $('#mathjax').hide();\n });\n\n // MathJax preprocessing has to ignore most of the page.\n $('body').addClass('tex2jax_ignore');\n\n try {\n await import('./mathjax/MathJax.min.js'); // ?config=TeX-AMS-MML_SVG.js');\n // When MathJax is loaded get the div where the math will be rendered.\n MathJax.Hub.queue.Push(function () {\n math = MathJax.Hub.getAllJax('#mathjax_creator')[0];\n console.log(math); // eslint-disable-line no-console\n mathjaxLoaded = true;\n console.log('MathJax Loaded'); // eslint-disable-line no-console\n });\n } catch (e) {\n console.log('Failed loading MathJax.'); // eslint-disable-line no-console\n $.alert('Failed loading MathJax. You will not be able to change the mathematics.');\n }\n }\n }\n }\n }];\n\n return {\n name: strings.name,\n svgicons: 'mathjax-icons.xml',\n buttons: strings.buttons.map((button, i) => {\n return Object.assign(buttons[i], button);\n }),\n\n mouseDown () {\n if (svgCanvas.getMode() === 'mathjax') {\n return {started: true};\n }\n return undefined;\n },\n mouseUp (opts) {\n if (svgCanvas.getMode() === 'mathjax') {\n // Get the coordinates from your mouse.\n const zoom = svgCanvas.getZoom();\n // Get the actual coordinate by dividing by the zoom value\n locationX = opts.mouse_x / zoom;\n locationY = opts.mouse_y / zoom;\n\n $('#mathjax').show();\n return {started: false}; // Otherwise the last selected object dissapears.\n }\n return undefined;\n },\n callback () {\n $('').appendTo("head")),e.text(t?" #tool_topath { display: none !important; }":""),o("#polygon_panel").toggle(t)},n=(r=e).canvas,o=t.$,!1,v.next=9,Yn(r.curPrefs.lang);case 9:return i=v.sent,h=[{id:"tool_polygon",icon:"polygon.png",type:"mode",position:11,events:{click:function click(){n.setMode("polygon"),s(!0)}}}],y=[{type:"input",panel:"polygon_panel",id:"polySides",size:3,defval:5,events:{change:function change(){f("sides",this.value)}}}],v.abrupt("return",{name:i.name,svgicons:"polygon-icons.svg",buttons:i.buttons.map((function(t,e){return Object.assign(h[e],t)})),context_tools:i.contextTools.map((function(t,e){return Object.assign(y[e],t)})),callback:function callback(){o("#polygon_panel").hide(),setTimeout((function(){o("#tool_source_save").clone().hide().attr("id","polygon_save").unbind().appendTo("#tool_source_back").click((function(){})),o("#tool_source_cancel").clone().hide().attr("id","polygon_cancel").unbind().appendTo("#tool_source_back").click((function(){}))}),3e3)},mouseDown:function mouseDown(t){if("polygon"===n.getMode()){var e=n.getColor("fill"),r=n.getColor("stroke"),o=n.getStrokeWidth();return c=!0,u=n.addSVGElementFromJson({element:"polygon",attr:{cx:t.start_x,cy:t.start_y,id:n.getNextId(),shape:"regularPoly",sides:document.getElementById("polySides").value,orient:"x",edge:0,fill:e,strokecolor:r,strokeWidth:o}}),{started:!0}}},mouseMove:function mouseMove(t){if(c&&"polygon"===n.getMode()){var e=o(u).attr(["cx","cy","sides","orient","fill","strokecolor","strokeWidth"]),r=t.mouse_x,i=t.mouse_y,a=e.cx,s=e.cy,f=e.fill,h=e.strokecolor,y=e.strokeWidth,v=e.sides,d=Math.sqrt((r-a)*(r-a)+(i-s)*(i-s))/1.5;u.setAttribute("edge",d);for(var g=d/2*l(Math.PI/v)*p(Math.PI/v),m="",b=0;v>=b;b++){var w=2*Math.PI*b/v;m+=(r=g*Math.cos(w)+a)+","+(i=g*Math.sin(w)+s)+" "}return u.setAttribute("points",m),u.setAttribute("fill",f),u.setAttribute("stroke",h),u.setAttribute("stroke-width",y),{started:!0}}},mouseUp:function mouseUp(t){if("polygon"===n.getMode())return{keep:"0"!==o(u).attr("edge").edge,element:u}},selectedChanged:function selectedChanged(t){for(var e=(a=t.elems).length;e--;){var r=a[e];r&&"regularPoly"===r.getAttribute("shape")&&t.selectedElement&&!t.multiselected?(o("#polySides").val(r.getAttribute("sides")),s(!0)):s(!1)}},elementChanged:function elementChanged(t){}});case 13:case"end":return v.stop()}}),_callee2)})))()}},Jn=Object.freeze({__proto__:null,default:{name:"polygon",buttons:[{title:"Polygon Tool"}],contextTools:[{title:"Number of Sides",label:"sides"}]}}),$n=Object.freeze({__proto__:null,default:{name:"多边形",buttons:[{title:"多边形工具"}],contextTools:[{title:"边数",label:"边数"}]}});export default Hn; +//# sourceMappingURL=ext-polygon.js.map diff --git a/dist/editor/extensions/ext-polygon/ext-polygon.js.map b/dist/editor/extensions/ext-polygon/ext-polygon.js.map new file mode 100644 index 00000000..a30ba210 --- /dev/null +++ b/dist/editor/extensions/ext-polygon/ext-polygon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ext-polygon.js","sources":["../../../../node_modules/core-js/internals/global.js","../../../../node_modules/core-js/internals/fails.js","../../../../node_modules/core-js/internals/descriptors.js","../../../../node_modules/core-js/internals/object-property-is-enumerable.js","../../../../node_modules/core-js/internals/create-property-descriptor.js","../../../../node_modules/core-js/internals/classof-raw.js","../../../../node_modules/core-js/internals/indexed-object.js","../../../../node_modules/core-js/internals/require-object-coercible.js","../../../../node_modules/core-js/internals/to-indexed-object.js","../../../../node_modules/core-js/internals/is-object.js","../../../../node_modules/core-js/internals/to-primitive.js","../../../../node_modules/core-js/internals/has.js","../../../../node_modules/core-js/internals/document-create-element.js","../../../../node_modules/core-js/internals/ie8-dom-define.js","../../../../node_modules/core-js/internals/object-get-own-property-descriptor.js","../../../../node_modules/core-js/internals/an-object.js","../../../../node_modules/core-js/internals/object-define-property.js","../../../../node_modules/core-js/internals/create-non-enumerable-property.js","../../../../node_modules/core-js/internals/set-global.js","../../../../node_modules/core-js/internals/shared-store.js","../../../../node_modules/core-js/internals/inspect-source.js","../../../../node_modules/core-js/internals/internal-state.js","../../../../node_modules/core-js/internals/native-weak-map.js","../../../../node_modules/core-js/internals/shared.js","../../../../node_modules/core-js/internals/uid.js","../../../../node_modules/core-js/internals/shared-key.js","../../../../node_modules/core-js/internals/hidden-keys.js","../../../../node_modules/core-js/internals/object-create.js","../../../../node_modules/core-js/internals/redefine.js","../../../../node_modules/core-js/internals/path.js","../../../../node_modules/core-js/internals/get-built-in.js","../../../../node_modules/core-js/internals/to-integer.js","../../../../node_modules/core-js/internals/to-length.js","../../../../node_modules/core-js/internals/to-absolute-index.js","../../../../node_modules/core-js/internals/array-includes.js","../../../../node_modules/core-js/internals/object-keys-internal.js","../../../../node_modules/core-js/internals/enum-bug-keys.js","../../../../node_modules/core-js/internals/object-get-own-property-names.js","../../../../node_modules/core-js/internals/object-get-own-property-symbols.js","../../../../node_modules/core-js/internals/own-keys.js","../../../../node_modules/core-js/internals/copy-constructor-properties.js","../../../../node_modules/core-js/internals/is-forced.js","../../../../node_modules/core-js/internals/export.js","../../../../node_modules/core-js/internals/to-object.js","../../../../node_modules/core-js/internals/native-symbol.js","../../../../node_modules/core-js/internals/use-symbol-as-uid.js","../../../../node_modules/core-js/internals/well-known-symbol.js","../../../../node_modules/core-js/internals/object-keys.js","../../../../node_modules/core-js/internals/object-define-properties.js","../../../../node_modules/core-js/internals/html.js","../../../../node_modules/core-js/internals/add-to-unscopables.js","../../../../node_modules/core-js/modules/es.array.fill.js","../../../../node_modules/core-js/internals/array-fill.js","../../../../node_modules/core-js/internals/a-function.js","../../../../node_modules/core-js/internals/engine-v8-version.js","../../../../node_modules/core-js/internals/function-bind-context.js","../../../../node_modules/core-js/internals/is-array.js","../../../../node_modules/core-js/internals/array-species-create.js","../../../../node_modules/core-js/internals/array-iteration.js","../../../../node_modules/core-js/internals/engine-user-agent.js","../../../../node_modules/core-js/internals/array-method-has-species-support.js","../../../../node_modules/core-js/internals/array-method-uses-to-length.js","../../../../node_modules/core-js/modules/es.array.map.js","../../../../node_modules/core-js/modules/es.function.name.js","../../../../node_modules/core-js/internals/object-assign.js","../../../../node_modules/core-js/modules/es.object.assign.js","../../../../node_modules/core-js/internals/to-string-tag-support.js","../../../../node_modules/core-js/internals/classof.js","../../../../node_modules/core-js/internals/object-to-string.js","../../../../node_modules/core-js/modules/es.object.to-string.js","../../../../node_modules/core-js/internals/native-promise-constructor.js","../../../../node_modules/core-js/internals/set-to-string-tag.js","../../../../node_modules/core-js/internals/set-species.js","../../../../node_modules/core-js/internals/iterators.js","../../../../node_modules/core-js/internals/is-array-iterator-method.js","../../../../node_modules/core-js/internals/get-iterator-method.js","../../../../node_modules/core-js/internals/call-with-safe-iteration-closing.js","../../../../node_modules/core-js/internals/iterate.js","../../../../node_modules/core-js/internals/check-correctness-of-iteration.js","../../../../node_modules/core-js/internals/task.js","../../../../node_modules/core-js/internals/species-constructor.js","../../../../node_modules/core-js/internals/engine-is-ios.js","../../../../node_modules/core-js/internals/microtask.js","../../../../node_modules/core-js/modules/es.promise.js","../../../../node_modules/core-js/internals/new-promise-capability.js","../../../../node_modules/core-js/internals/promise-resolve.js","../../../../node_modules/core-js/internals/perform.js","../../../../node_modules/core-js/internals/host-report-errors.js","../../../../node_modules/core-js/internals/an-instance.js","../../../../node_modules/core-js/internals/redefine-all.js","../../../../node_modules/core-js/internals/object-get-own-property-names-external.js","../../../../node_modules/core-js/internals/well-known-symbol-wrapped.js","../../../../node_modules/core-js/internals/define-well-known-symbol.js","../../../../node_modules/core-js/modules/es.symbol.js","../../../../node_modules/core-js/modules/es.symbol.description.js","../../../../node_modules/core-js/modules/es.symbol.async-iterator.js","../../../../node_modules/core-js/modules/es.symbol.iterator.js","../../../../node_modules/core-js/modules/es.symbol.to-string-tag.js","../../../../node_modules/core-js/internals/array-method-is-strict.js","../../../../node_modules/core-js/internals/array-for-each.js","../../../../node_modules/core-js/modules/es.array.for-each.js","../../../../node_modules/core-js/internals/correct-prototype-getter.js","../../../../node_modules/core-js/internals/iterators-core.js","../../../../node_modules/core-js/internals/object-get-prototype-of.js","../../../../node_modules/core-js/internals/create-iterator-constructor.js","../../../../node_modules/core-js/internals/object-set-prototype-of.js","../../../../node_modules/core-js/internals/a-possible-prototype.js","../../../../node_modules/core-js/internals/define-iterator.js","../../../../node_modules/core-js/modules/es.array.iterator.js","../../../../node_modules/core-js/modules/es.array.reverse.js","../../../../node_modules/core-js/internals/create-property.js","../../../../node_modules/core-js/modules/es.array.slice.js","../../../../node_modules/core-js/modules/es.date.to-string.js","../../../../node_modules/core-js/modules/es.json.to-string-tag.js","../../../../node_modules/core-js/modules/es.math.to-string-tag.js","../../../../node_modules/core-js/modules/es.object.create.js","../../../../node_modules/core-js/modules/es.object.define-property.js","../../../../node_modules/core-js/modules/es.object.get-prototype-of.js","../../../../node_modules/core-js/modules/es.object.set-prototype-of.js","../../../../node_modules/core-js/internals/regexp-flags.js","../../../../node_modules/core-js/modules/es.regexp.to-string.js","../../../../node_modules/core-js/internals/string-multibyte.js","../../../../node_modules/core-js/modules/es.string.iterator.js","../../../../node_modules/core-js/internals/dom-iterables.js","../../../../node_modules/core-js/modules/web.dom-collections.for-each.js","../../../../node_modules/core-js/modules/web.dom-collections.iterator.js","../../../../node_modules/regenerator-runtime/runtime.js","../../../../src/editor/extensions/ext-polygon/ext-polygon.js","../../../../src/editor/extensions/ext-polygon/locale/en.js","../../../../src/editor/extensions/ext-polygon/locale/zh-CN.js"],"sourcesContent":["var check = function (it) {\n return it && it.Math == Math && it;\n};\n\n// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nmodule.exports =\n // eslint-disable-next-line no-undef\n check(typeof globalThis == 'object' && globalThis) ||\n check(typeof window == 'object' && window) ||\n check(typeof self == 'object' && self) ||\n check(typeof global == 'object' && global) ||\n // eslint-disable-next-line no-new-func\n Function('return this')();\n","module.exports = function (exec) {\n try {\n return !!exec();\n } catch (error) {\n return true;\n }\n};\n","var fails = require('../internals/fails');\n\n// Thank's IE8 for his funny defineProperty\nmodule.exports = !fails(function () {\n return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;\n});\n","'use strict';\nvar nativePropertyIsEnumerable = {}.propertyIsEnumerable;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// Nashorn ~ JDK8 bug\nvar NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);\n\n// `Object.prototype.propertyIsEnumerable` method implementation\n// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable\nexports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {\n var descriptor = getOwnPropertyDescriptor(this, V);\n return !!descriptor && descriptor.enumerable;\n} : nativePropertyIsEnumerable;\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","var fails = require('../internals/fails');\nvar classof = require('../internals/classof-raw');\n\nvar split = ''.split;\n\n// fallback for non-array-like ES3 and non-enumerable old V8 strings\nmodule.exports = fails(function () {\n // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346\n // eslint-disable-next-line no-prototype-builtins\n return !Object('z').propertyIsEnumerable(0);\n}) ? function (it) {\n return classof(it) == 'String' ? split.call(it, '') : Object(it);\n} : Object;\n","// `RequireObjectCoercible` abstract operation\n// https://tc39.github.io/ecma262/#sec-requireobjectcoercible\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","// toObject with fallback for non-array-like ES3 strings\nvar IndexedObject = require('../internals/indexed-object');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\nmodule.exports = function (it) {\n return IndexedObject(requireObjectCoercible(it));\n};\n","module.exports = function (it) {\n return typeof it === 'object' ? it !== null : typeof it === 'function';\n};\n","var isObject = require('../internals/is-object');\n\n// `ToPrimitive` abstract operation\n// https://tc39.github.io/ecma262/#sec-toprimitive\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (input, PREFERRED_STRING) {\n if (!isObject(input)) return input;\n var fn, val;\n if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;\n if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","var hasOwnProperty = {}.hasOwnProperty;\n\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n","var global = require('../internals/global');\nvar isObject = require('../internals/is-object');\n\nvar document = global.document;\n// typeof document.createElement is 'object' in old IE\nvar EXISTS = isObject(document) && isObject(document.createElement);\n\nmodule.exports = function (it) {\n return EXISTS ? document.createElement(it) : {};\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar createElement = require('../internals/document-create-element');\n\n// Thank's IE8 for his funny defineProperty\nmodule.exports = !DESCRIPTORS && !fails(function () {\n return Object.defineProperty(createElement('div'), 'a', {\n get: function () { return 7; }\n }).a != 7;\n});\n","var DESCRIPTORS = require('../internals/descriptors');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toPrimitive = require('../internals/to-primitive');\nvar has = require('../internals/has');\nvar IE8_DOM_DEFINE = require('../internals/ie8-dom-define');\n\nvar nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// `Object.getOwnPropertyDescriptor` method\n// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor\nexports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {\n O = toIndexedObject(O);\n P = toPrimitive(P, true);\n if (IE8_DOM_DEFINE) try {\n return nativeGetOwnPropertyDescriptor(O, P);\n } catch (error) { /* empty */ }\n if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);\n};\n","var isObject = require('../internals/is-object');\n\nmodule.exports = function (it) {\n if (!isObject(it)) {\n throw TypeError(String(it) + ' is not an object');\n } return it;\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar IE8_DOM_DEFINE = require('../internals/ie8-dom-define');\nvar anObject = require('../internals/an-object');\nvar toPrimitive = require('../internals/to-primitive');\n\nvar nativeDefineProperty = Object.defineProperty;\n\n// `Object.defineProperty` method\n// https://tc39.github.io/ecma262/#sec-object.defineproperty\nexports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPrimitive(P, true);\n anObject(Attributes);\n if (IE8_DOM_DEFINE) try {\n return nativeDefineProperty(O, P, Attributes);\n } catch (error) { /* empty */ }\n if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');\n if ('value' in Attributes) O[P] = Attributes.value;\n return O;\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar definePropertyModule = require('../internals/object-define-property');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\n\nmodule.exports = DESCRIPTORS ? function (object, key, value) {\n return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n","var global = require('../internals/global');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\n\nmodule.exports = function (key, value) {\n try {\n createNonEnumerableProperty(global, key, value);\n } catch (error) {\n global[key] = value;\n } return value;\n};\n","var global = require('../internals/global');\nvar setGlobal = require('../internals/set-global');\n\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || setGlobal(SHARED, {});\n\nmodule.exports = store;\n","var store = require('../internals/shared-store');\n\nvar functionToString = Function.toString;\n\n// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper\nif (typeof store.inspectSource != 'function') {\n store.inspectSource = function (it) {\n return functionToString.call(it);\n };\n}\n\nmodule.exports = store.inspectSource;\n","var NATIVE_WEAK_MAP = require('../internals/native-weak-map');\nvar global = require('../internals/global');\nvar isObject = require('../internals/is-object');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar objectHas = require('../internals/has');\nvar sharedKey = require('../internals/shared-key');\nvar hiddenKeys = require('../internals/hidden-keys');\n\nvar WeakMap = global.WeakMap;\nvar set, get, has;\n\nvar enforce = function (it) {\n return has(it) ? get(it) : set(it, {});\n};\n\nvar getterFor = function (TYPE) {\n return function (it) {\n var state;\n if (!isObject(it) || (state = get(it)).type !== TYPE) {\n throw TypeError('Incompatible receiver, ' + TYPE + ' required');\n } return state;\n };\n};\n\nif (NATIVE_WEAK_MAP) {\n var store = new WeakMap();\n var wmget = store.get;\n var wmhas = store.has;\n var wmset = store.set;\n set = function (it, metadata) {\n wmset.call(store, it, metadata);\n return metadata;\n };\n get = function (it) {\n return wmget.call(store, it) || {};\n };\n has = function (it) {\n return wmhas.call(store, it);\n };\n} else {\n var STATE = sharedKey('state');\n hiddenKeys[STATE] = true;\n set = function (it, metadata) {\n createNonEnumerableProperty(it, STATE, metadata);\n return metadata;\n };\n get = function (it) {\n return objectHas(it, STATE) ? it[STATE] : {};\n };\n has = function (it) {\n return objectHas(it, STATE);\n };\n}\n\nmodule.exports = {\n set: set,\n get: get,\n has: has,\n enforce: enforce,\n getterFor: getterFor\n};\n","var global = require('../internals/global');\nvar inspectSource = require('../internals/inspect-source');\n\nvar WeakMap = global.WeakMap;\n\nmodule.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));\n","var IS_PURE = require('../internals/is-pure');\nvar store = require('../internals/shared-store');\n\n(module.exports = function (key, value) {\n return store[key] || (store[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: '3.6.5',\n mode: IS_PURE ? 'pure' : 'global',\n copyright: '© 2020 Denis Pushkarev (zloirock.ru)'\n});\n","var id = 0;\nvar postfix = Math.random();\n\nmodule.exports = function (key) {\n return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);\n};\n","var shared = require('../internals/shared');\nvar uid = require('../internals/uid');\n\nvar keys = shared('keys');\n\nmodule.exports = function (key) {\n return keys[key] || (keys[key] = uid(key));\n};\n","module.exports = {};\n","var anObject = require('../internals/an-object');\nvar defineProperties = require('../internals/object-define-properties');\nvar enumBugKeys = require('../internals/enum-bug-keys');\nvar hiddenKeys = require('../internals/hidden-keys');\nvar html = require('../internals/html');\nvar documentCreateElement = require('../internals/document-create-element');\nvar sharedKey = require('../internals/shared-key');\n\nvar GT = '>';\nvar LT = '<';\nvar PROTOTYPE = 'prototype';\nvar SCRIPT = 'script';\nvar IE_PROTO = sharedKey('IE_PROTO');\n\nvar EmptyConstructor = function () { /* empty */ };\n\nvar scriptTag = function (content) {\n return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;\n};\n\n// Create object with fake `null` prototype: use ActiveX Object with cleared prototype\nvar NullProtoObjectViaActiveX = function (activeXDocument) {\n activeXDocument.write(scriptTag(''));\n activeXDocument.close();\n var temp = activeXDocument.parentWindow.Object;\n activeXDocument = null; // avoid memory leak\n return temp;\n};\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar NullProtoObjectViaIFrame = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = documentCreateElement('iframe');\n var JS = 'java' + SCRIPT + ':';\n var iframeDocument;\n iframe.style.display = 'none';\n html.appendChild(iframe);\n // https://github.com/zloirock/core-js/issues/475\n iframe.src = String(JS);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(scriptTag('document.F=Object'));\n iframeDocument.close();\n return iframeDocument.F;\n};\n\n// Check for document.domain and active x support\n// No need to use active x approach when document.domain is not set\n// see https://github.com/es-shims/es5-shim/issues/150\n// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346\n// avoid IE GC bug\nvar activeXDocument;\nvar NullProtoObject = function () {\n try {\n /* global ActiveXObject */\n activeXDocument = document.domain && new ActiveXObject('htmlfile');\n } catch (error) { /* ignore */ }\n NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();\n var length = enumBugKeys.length;\n while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];\n return NullProtoObject();\n};\n\nhiddenKeys[IE_PROTO] = true;\n\n// `Object.create` method\n// https://tc39.github.io/ecma262/#sec-object.create\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n EmptyConstructor[PROTOTYPE] = anObject(O);\n result = new EmptyConstructor();\n EmptyConstructor[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = NullProtoObject();\n return Properties === undefined ? result : defineProperties(result, Properties);\n};\n","var global = require('../internals/global');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar has = require('../internals/has');\nvar setGlobal = require('../internals/set-global');\nvar inspectSource = require('../internals/inspect-source');\nvar InternalStateModule = require('../internals/internal-state');\n\nvar getInternalState = InternalStateModule.get;\nvar enforceInternalState = InternalStateModule.enforce;\nvar TEMPLATE = String(String).split('String');\n\n(module.exports = function (O, key, value, options) {\n var unsafe = options ? !!options.unsafe : false;\n var simple = options ? !!options.enumerable : false;\n var noTargetGet = options ? !!options.noTargetGet : false;\n if (typeof value == 'function') {\n if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);\n enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');\n }\n if (O === global) {\n if (simple) O[key] = value;\n else setGlobal(key, value);\n return;\n } else if (!unsafe) {\n delete O[key];\n } else if (!noTargetGet && O[key]) {\n simple = true;\n }\n if (simple) O[key] = value;\n else createNonEnumerableProperty(O, key, value);\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, 'toString', function toString() {\n return typeof this == 'function' && getInternalState(this).source || inspectSource(this);\n});\n","var global = require('../internals/global');\n\nmodule.exports = global;\n","var path = require('../internals/path');\nvar global = require('../internals/global');\n\nvar aFunction = function (variable) {\n return typeof variable == 'function' ? variable : undefined;\n};\n\nmodule.exports = function (namespace, method) {\n return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])\n : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];\n};\n","var ceil = Math.ceil;\nvar floor = Math.floor;\n\n// `ToInteger` abstract operation\n// https://tc39.github.io/ecma262/#sec-tointeger\nmodule.exports = function (argument) {\n return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);\n};\n","var toInteger = require('../internals/to-integer');\n\nvar min = Math.min;\n\n// `ToLength` abstract operation\n// https://tc39.github.io/ecma262/#sec-tolength\nmodule.exports = function (argument) {\n return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991\n};\n","var toInteger = require('../internals/to-integer');\n\nvar max = Math.max;\nvar min = Math.min;\n\n// Helper for a popular repeating case of the spec:\n// Let integer be ? ToInteger(index).\n// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).\nmodule.exports = function (index, length) {\n var integer = toInteger(index);\n return integer < 0 ? max(integer + length, 0) : min(integer, length);\n};\n","var toIndexedObject = require('../internals/to-indexed-object');\nvar toLength = require('../internals/to-length');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\n\n// `Array.prototype.{ indexOf, includes }` methods implementation\nvar createMethod = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIndexedObject($this);\n var length = toLength(O.length);\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare\n if (IS_INCLUDES && el != el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare\n if (value != value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) {\n if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.includes` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.includes\n includes: createMethod(true),\n // `Array.prototype.indexOf` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.indexof\n indexOf: createMethod(false)\n};\n","var has = require('../internals/has');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar indexOf = require('../internals/array-includes').indexOf;\nvar hiddenKeys = require('../internals/hidden-keys');\n\nmodule.exports = function (object, names) {\n var O = toIndexedObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has(O, key = names[i++])) {\n ~indexOf(result, key) || result.push(key);\n }\n return result;\n};\n","// IE8- don't enum bug keys\nmodule.exports = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf'\n];\n","var internalObjectKeys = require('../internals/object-keys-internal');\nvar enumBugKeys = require('../internals/enum-bug-keys');\n\nvar hiddenKeys = enumBugKeys.concat('length', 'prototype');\n\n// `Object.getOwnPropertyNames` method\n// https://tc39.github.io/ecma262/#sec-object.getownpropertynames\nexports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return internalObjectKeys(O, hiddenKeys);\n};\n","exports.f = Object.getOwnPropertySymbols;\n","var getBuiltIn = require('../internals/get-built-in');\nvar getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar anObject = require('../internals/an-object');\n\n// all object keys, includes non-enumerable and symbols\nmodule.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {\n var keys = getOwnPropertyNamesModule.f(anObject(it));\n var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;\n return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;\n};\n","var has = require('../internals/has');\nvar ownKeys = require('../internals/own-keys');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar definePropertyModule = require('../internals/object-define-property');\n\nmodule.exports = function (target, source) {\n var keys = ownKeys(source);\n var defineProperty = definePropertyModule.f;\n var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));\n }\n};\n","var fails = require('../internals/fails');\n\nvar replacement = /#|\\.prototype\\./;\n\nvar isForced = function (feature, detection) {\n var value = data[normalize(feature)];\n return value == POLYFILL ? true\n : value == NATIVE ? false\n : typeof detection == 'function' ? fails(detection)\n : !!detection;\n};\n\nvar normalize = isForced.normalize = function (string) {\n return String(string).replace(replacement, '.').toLowerCase();\n};\n\nvar data = isForced.data = {};\nvar NATIVE = isForced.NATIVE = 'N';\nvar POLYFILL = isForced.POLYFILL = 'P';\n\nmodule.exports = isForced;\n","var global = require('../internals/global');\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar setGlobal = require('../internals/set-global');\nvar copyConstructorProperties = require('../internals/copy-constructor-properties');\nvar isForced = require('../internals/is-forced');\n\n/*\n options.target - name of the target object\n options.global - target is the global object\n options.stat - export as static methods of target\n options.proto - export as prototype methods of target\n options.real - real prototype method for the `pure` version\n options.forced - export even if the native feature is available\n options.bind - bind methods to the target, required for the `pure` version\n options.wrap - wrap constructors to preventing global pollution, required for the `pure` version\n options.unsafe - use the simple assignment of property instead of delete + defineProperty\n options.sham - add a flag to not completely full polyfills\n options.enumerable - export as enumerable property\n options.noTargetGet - prevent calling a getter on target\n*/\nmodule.exports = function (options, source) {\n var TARGET = options.target;\n var GLOBAL = options.global;\n var STATIC = options.stat;\n var FORCED, target, key, targetProperty, sourceProperty, descriptor;\n if (GLOBAL) {\n target = global;\n } else if (STATIC) {\n target = global[TARGET] || setGlobal(TARGET, {});\n } else {\n target = (global[TARGET] || {}).prototype;\n }\n if (target) for (key in source) {\n sourceProperty = source[key];\n if (options.noTargetGet) {\n descriptor = getOwnPropertyDescriptor(target, key);\n targetProperty = descriptor && descriptor.value;\n } else targetProperty = target[key];\n FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);\n // contained in target\n if (!FORCED && targetProperty !== undefined) {\n if (typeof sourceProperty === typeof targetProperty) continue;\n copyConstructorProperties(sourceProperty, targetProperty);\n }\n // add a flag to not completely full polyfills\n if (options.sham || (targetProperty && targetProperty.sham)) {\n createNonEnumerableProperty(sourceProperty, 'sham', true);\n }\n // extend global\n redefine(target, key, sourceProperty, options);\n }\n};\n","var requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `ToObject` abstract operation\n// https://tc39.github.io/ecma262/#sec-toobject\nmodule.exports = function (argument) {\n return Object(requireObjectCoercible(argument));\n};\n","var fails = require('../internals/fails');\n\nmodule.exports = !!Object.getOwnPropertySymbols && !fails(function () {\n // Chrome 38 Symbol has incorrect toString conversion\n // eslint-disable-next-line no-undef\n return !String(Symbol());\n});\n","var NATIVE_SYMBOL = require('../internals/native-symbol');\n\nmodule.exports = NATIVE_SYMBOL\n // eslint-disable-next-line no-undef\n && !Symbol.sham\n // eslint-disable-next-line no-undef\n && typeof Symbol.iterator == 'symbol';\n","var global = require('../internals/global');\nvar shared = require('../internals/shared');\nvar has = require('../internals/has');\nvar uid = require('../internals/uid');\nvar NATIVE_SYMBOL = require('../internals/native-symbol');\nvar USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid');\n\nvar WellKnownSymbolsStore = shared('wks');\nvar Symbol = global.Symbol;\nvar createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;\n\nmodule.exports = function (name) {\n if (!has(WellKnownSymbolsStore, name)) {\n if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name];\n else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);\n } return WellKnownSymbolsStore[name];\n};\n","var internalObjectKeys = require('../internals/object-keys-internal');\nvar enumBugKeys = require('../internals/enum-bug-keys');\n\n// `Object.keys` method\n// https://tc39.github.io/ecma262/#sec-object.keys\nmodule.exports = Object.keys || function keys(O) {\n return internalObjectKeys(O, enumBugKeys);\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar definePropertyModule = require('../internals/object-define-property');\nvar anObject = require('../internals/an-object');\nvar objectKeys = require('../internals/object-keys');\n\n// `Object.defineProperties` method\n// https://tc39.github.io/ecma262/#sec-object.defineproperties\nmodule.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {\n anObject(O);\n var keys = objectKeys(Properties);\n var length = keys.length;\n var index = 0;\n var key;\n while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);\n return O;\n};\n","var getBuiltIn = require('../internals/get-built-in');\n\nmodule.exports = getBuiltIn('document', 'documentElement');\n","var wellKnownSymbol = require('../internals/well-known-symbol');\nvar create = require('../internals/object-create');\nvar definePropertyModule = require('../internals/object-define-property');\n\nvar UNSCOPABLES = wellKnownSymbol('unscopables');\nvar ArrayPrototype = Array.prototype;\n\n// Array.prototype[@@unscopables]\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables\nif (ArrayPrototype[UNSCOPABLES] == undefined) {\n definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {\n configurable: true,\n value: create(null)\n });\n}\n\n// add a key to Array.prototype[@@unscopables]\nmodule.exports = function (key) {\n ArrayPrototype[UNSCOPABLES][key] = true;\n};\n","var $ = require('../internals/export');\nvar fill = require('../internals/array-fill');\nvar addToUnscopables = require('../internals/add-to-unscopables');\n\n// `Array.prototype.fill` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.fill\n$({ target: 'Array', proto: true }, {\n fill: fill\n});\n\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables('fill');\n","'use strict';\nvar toObject = require('../internals/to-object');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar toLength = require('../internals/to-length');\n\n// `Array.prototype.fill` method implementation\n// https://tc39.github.io/ecma262/#sec-array.prototype.fill\nmodule.exports = function fill(value /* , start = 0, end = @length */) {\n var O = toObject(this);\n var length = toLength(O.length);\n var argumentsLength = arguments.length;\n var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);\n var end = argumentsLength > 2 ? arguments[2] : undefined;\n var endPos = end === undefined ? length : toAbsoluteIndex(end, length);\n while (endPos > index) O[index++] = value;\n return O;\n};\n","module.exports = function (it) {\n if (typeof it != 'function') {\n throw TypeError(String(it) + ' is not a function');\n } return it;\n};\n","var global = require('../internals/global');\nvar userAgent = require('../internals/engine-user-agent');\n\nvar process = global.process;\nvar versions = process && process.versions;\nvar v8 = versions && versions.v8;\nvar match, version;\n\nif (v8) {\n match = v8.split('.');\n version = match[0] + match[1];\n} else if (userAgent) {\n match = userAgent.match(/Edge\\/(\\d+)/);\n if (!match || match[1] >= 74) {\n match = userAgent.match(/Chrome\\/(\\d+)/);\n if (match) version = match[1];\n }\n}\n\nmodule.exports = version && +version;\n","var aFunction = require('../internals/a-function');\n\n// optional / simple context binding\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 0: return function () {\n return fn.call(that);\n };\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","var classof = require('../internals/classof-raw');\n\n// `IsArray` abstract operation\n// https://tc39.github.io/ecma262/#sec-isarray\nmodule.exports = Array.isArray || function isArray(arg) {\n return classof(arg) == 'Array';\n};\n","var isObject = require('../internals/is-object');\nvar isArray = require('../internals/is-array');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar SPECIES = wellKnownSymbol('species');\n\n// `ArraySpeciesCreate` abstract operation\n// https://tc39.github.io/ecma262/#sec-arrayspeciescreate\nmodule.exports = function (originalArray, length) {\n var C;\n if (isArray(originalArray)) {\n C = originalArray.constructor;\n // cross-realm fallback\n if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;\n else if (isObject(C)) {\n C = C[SPECIES];\n if (C === null) C = undefined;\n }\n } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);\n};\n","var bind = require('../internals/function-bind-context');\nvar IndexedObject = require('../internals/indexed-object');\nvar toObject = require('../internals/to-object');\nvar toLength = require('../internals/to-length');\nvar arraySpeciesCreate = require('../internals/array-species-create');\n\nvar push = [].push;\n\n// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation\nvar createMethod = function (TYPE) {\n var IS_MAP = TYPE == 1;\n var IS_FILTER = TYPE == 2;\n var IS_SOME = TYPE == 3;\n var IS_EVERY = TYPE == 4;\n var IS_FIND_INDEX = TYPE == 6;\n var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;\n return function ($this, callbackfn, that, specificCreate) {\n var O = toObject($this);\n var self = IndexedObject(O);\n var boundFunction = bind(callbackfn, that, 3);\n var length = toLength(self.length);\n var index = 0;\n var create = specificCreate || arraySpeciesCreate;\n var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;\n var value, result;\n for (;length > index; index++) if (NO_HOLES || index in self) {\n value = self[index];\n result = boundFunction(value, index, O);\n if (TYPE) {\n if (IS_MAP) target[index] = result; // map\n else if (result) switch (TYPE) {\n case 3: return true; // some\n case 5: return value; // find\n case 6: return index; // findIndex\n case 2: push.call(target, value); // filter\n } else if (IS_EVERY) return false; // every\n }\n }\n return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.forEach` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.foreach\n forEach: createMethod(0),\n // `Array.prototype.map` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.map\n map: createMethod(1),\n // `Array.prototype.filter` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.filter\n filter: createMethod(2),\n // `Array.prototype.some` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.some\n some: createMethod(3),\n // `Array.prototype.every` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.every\n every: createMethod(4),\n // `Array.prototype.find` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.find\n find: createMethod(5),\n // `Array.prototype.findIndex` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex\n findIndex: createMethod(6)\n};\n","var getBuiltIn = require('../internals/get-built-in');\n\nmodule.exports = getBuiltIn('navigator', 'userAgent') || '';\n","var fails = require('../internals/fails');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar SPECIES = wellKnownSymbol('species');\n\nmodule.exports = function (METHOD_NAME) {\n // We can't use this feature detection in V8 since it causes\n // deoptimization and serious performance degradation\n // https://github.com/zloirock/core-js/issues/677\n return V8_VERSION >= 51 || !fails(function () {\n var array = [];\n var constructor = array.constructor = {};\n constructor[SPECIES] = function () {\n return { foo: 1 };\n };\n return array[METHOD_NAME](Boolean).foo !== 1;\n });\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar has = require('../internals/has');\n\nvar defineProperty = Object.defineProperty;\nvar cache = {};\n\nvar thrower = function (it) { throw it; };\n\nmodule.exports = function (METHOD_NAME, options) {\n if (has(cache, METHOD_NAME)) return cache[METHOD_NAME];\n if (!options) options = {};\n var method = [][METHOD_NAME];\n var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false;\n var argument0 = has(options, 0) ? options[0] : thrower;\n var argument1 = has(options, 1) ? options[1] : undefined;\n\n return cache[METHOD_NAME] = !!method && !fails(function () {\n if (ACCESSORS && !DESCRIPTORS) return true;\n var O = { length: -1 };\n\n if (ACCESSORS) defineProperty(O, 1, { enumerable: true, get: thrower });\n else O[1] = 1;\n\n method.call(O, argument0, argument1);\n });\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar $map = require('../internals/array-iteration').map;\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map');\n// FF49- issue\nvar USES_TO_LENGTH = arrayMethodUsesToLength('map');\n\n// `Array.prototype.map` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.map\n// with adding support of @@species\n$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {\n map: function map(callbackfn /* , thisArg */) {\n return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n","var DESCRIPTORS = require('../internals/descriptors');\nvar defineProperty = require('../internals/object-define-property').f;\n\nvar FunctionPrototype = Function.prototype;\nvar FunctionPrototypeToString = FunctionPrototype.toString;\nvar nameRE = /^\\s*function ([^ (]*)/;\nvar NAME = 'name';\n\n// Function instances `.name` property\n// https://tc39.github.io/ecma262/#sec-function-instances-name\nif (DESCRIPTORS && !(NAME in FunctionPrototype)) {\n defineProperty(FunctionPrototype, NAME, {\n configurable: true,\n get: function () {\n try {\n return FunctionPrototypeToString.call(this).match(nameRE)[1];\n } catch (error) {\n return '';\n }\n }\n });\n}\n","'use strict';\nvar DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar objectKeys = require('../internals/object-keys');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar toObject = require('../internals/to-object');\nvar IndexedObject = require('../internals/indexed-object');\n\nvar nativeAssign = Object.assign;\nvar defineProperty = Object.defineProperty;\n\n// `Object.assign` method\n// https://tc39.github.io/ecma262/#sec-object.assign\nmodule.exports = !nativeAssign || fails(function () {\n // should have correct order of operations (Edge bug)\n if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', {\n enumerable: true,\n get: function () {\n defineProperty(this, 'b', {\n value: 3,\n enumerable: false\n });\n }\n }), { b: 2 })).b !== 1) return true;\n // should work with symbols and should have deterministic property order (V8 bug)\n var A = {};\n var B = {};\n // eslint-disable-next-line no-undef\n var symbol = Symbol();\n var alphabet = 'abcdefghijklmnopqrst';\n A[symbol] = 7;\n alphabet.split('').forEach(function (chr) { B[chr] = chr; });\n return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;\n}) ? function assign(target, source) { // eslint-disable-line no-unused-vars\n var T = toObject(target);\n var argumentsLength = arguments.length;\n var index = 1;\n var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;\n var propertyIsEnumerable = propertyIsEnumerableModule.f;\n while (argumentsLength > index) {\n var S = IndexedObject(arguments[index++]);\n var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);\n var length = keys.length;\n var j = 0;\n var key;\n while (length > j) {\n key = keys[j++];\n if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];\n }\n } return T;\n} : nativeAssign;\n","var $ = require('../internals/export');\nvar assign = require('../internals/object-assign');\n\n// `Object.assign` method\n// https://tc39.github.io/ecma262/#sec-object.assign\n$({ target: 'Object', stat: true, forced: Object.assign !== assign }, {\n assign: assign\n});\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar test = {};\n\ntest[TO_STRING_TAG] = 'z';\n\nmodule.exports = String(test) === '[object z]';\n","var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar classofRaw = require('../internals/classof-raw');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\n// ES3 wrong here\nvar CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (error) { /* empty */ }\n};\n\n// getting tag from ES6+ `Object.prototype.toString`\nmodule.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {\n var O, tag, result;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag\n // builtinTag case\n : CORRECT_ARGUMENTS ? classofRaw(O)\n // ES3 arguments fallback\n : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;\n};\n","'use strict';\nvar TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar classof = require('../internals/classof');\n\n// `Object.prototype.toString` method implementation\n// https://tc39.github.io/ecma262/#sec-object.prototype.tostring\nmodule.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() {\n return '[object ' + classof(this) + ']';\n};\n","var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar redefine = require('../internals/redefine');\nvar toString = require('../internals/object-to-string');\n\n// `Object.prototype.toString` method\n// https://tc39.github.io/ecma262/#sec-object.prototype.tostring\nif (!TO_STRING_TAG_SUPPORT) {\n redefine(Object.prototype, 'toString', toString, { unsafe: true });\n}\n","var global = require('../internals/global');\n\nmodule.exports = global.Promise;\n","var defineProperty = require('../internals/object-define-property').f;\nvar has = require('../internals/has');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\n\nmodule.exports = function (it, TAG, STATIC) {\n if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {\n defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG });\n }\n};\n","'use strict';\nvar getBuiltIn = require('../internals/get-built-in');\nvar definePropertyModule = require('../internals/object-define-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar DESCRIPTORS = require('../internals/descriptors');\n\nvar SPECIES = wellKnownSymbol('species');\n\nmodule.exports = function (CONSTRUCTOR_NAME) {\n var Constructor = getBuiltIn(CONSTRUCTOR_NAME);\n var defineProperty = definePropertyModule.f;\n\n if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {\n defineProperty(Constructor, SPECIES, {\n configurable: true,\n get: function () { return this; }\n });\n }\n};\n","module.exports = {};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\nvar Iterators = require('../internals/iterators');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar ArrayPrototype = Array.prototype;\n\n// check on default Array iterator\nmodule.exports = function (it) {\n return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);\n};\n","var classof = require('../internals/classof');\nvar Iterators = require('../internals/iterators');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\n\nmodule.exports = function (it) {\n if (it != undefined) return it[ITERATOR]\n || it['@@iterator']\n || Iterators[classof(it)];\n};\n","var anObject = require('../internals/an-object');\n\n// call something on iterator step with safe closing on error\nmodule.exports = function (iterator, fn, value, ENTRIES) {\n try {\n return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);\n // 7.4.6 IteratorClose(iterator, completion)\n } catch (error) {\n var returnMethod = iterator['return'];\n if (returnMethod !== undefined) anObject(returnMethod.call(iterator));\n throw error;\n }\n};\n","var anObject = require('../internals/an-object');\nvar isArrayIteratorMethod = require('../internals/is-array-iterator-method');\nvar toLength = require('../internals/to-length');\nvar bind = require('../internals/function-bind-context');\nvar getIteratorMethod = require('../internals/get-iterator-method');\nvar callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');\n\nvar Result = function (stopped, result) {\n this.stopped = stopped;\n this.result = result;\n};\n\nvar iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) {\n var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1);\n var iterator, iterFn, index, length, result, next, step;\n\n if (IS_ITERATOR) {\n iterator = iterable;\n } else {\n iterFn = getIteratorMethod(iterable);\n if (typeof iterFn != 'function') throw TypeError('Target is not iterable');\n // optimisation for array iterators\n if (isArrayIteratorMethod(iterFn)) {\n for (index = 0, length = toLength(iterable.length); length > index; index++) {\n result = AS_ENTRIES\n ? boundFunction(anObject(step = iterable[index])[0], step[1])\n : boundFunction(iterable[index]);\n if (result && result instanceof Result) return result;\n } return new Result(false);\n }\n iterator = iterFn.call(iterable);\n }\n\n next = iterator.next;\n while (!(step = next.call(iterator)).done) {\n result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES);\n if (typeof result == 'object' && result && result instanceof Result) return result;\n } return new Result(false);\n};\n\niterate.stop = function (result) {\n return new Result(true, result);\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar SAFE_CLOSING = false;\n\ntry {\n var called = 0;\n var iteratorWithReturn = {\n next: function () {\n return { done: !!called++ };\n },\n 'return': function () {\n SAFE_CLOSING = true;\n }\n };\n iteratorWithReturn[ITERATOR] = function () {\n return this;\n };\n // eslint-disable-next-line no-throw-literal\n Array.from(iteratorWithReturn, function () { throw 2; });\n} catch (error) { /* empty */ }\n\nmodule.exports = function (exec, SKIP_CLOSING) {\n if (!SKIP_CLOSING && !SAFE_CLOSING) return false;\n var ITERATION_SUPPORT = false;\n try {\n var object = {};\n object[ITERATOR] = function () {\n return {\n next: function () {\n return { done: ITERATION_SUPPORT = true };\n }\n };\n };\n exec(object);\n } catch (error) { /* empty */ }\n return ITERATION_SUPPORT;\n};\n","var global = require('../internals/global');\nvar fails = require('../internals/fails');\nvar classof = require('../internals/classof-raw');\nvar bind = require('../internals/function-bind-context');\nvar html = require('../internals/html');\nvar createElement = require('../internals/document-create-element');\nvar IS_IOS = require('../internals/engine-is-ios');\n\nvar location = global.location;\nvar set = global.setImmediate;\nvar clear = global.clearImmediate;\nvar process = global.process;\nvar MessageChannel = global.MessageChannel;\nvar Dispatch = global.Dispatch;\nvar counter = 0;\nvar queue = {};\nvar ONREADYSTATECHANGE = 'onreadystatechange';\nvar defer, channel, port;\n\nvar run = function (id) {\n // eslint-disable-next-line no-prototype-builtins\n if (queue.hasOwnProperty(id)) {\n var fn = queue[id];\n delete queue[id];\n fn();\n }\n};\n\nvar runner = function (id) {\n return function () {\n run(id);\n };\n};\n\nvar listener = function (event) {\n run(event.data);\n};\n\nvar post = function (id) {\n // old engines have not location.origin\n global.postMessage(id + '', location.protocol + '//' + location.host);\n};\n\n// Node.js 0.9+ & IE10+ has setImmediate, otherwise:\nif (!set || !clear) {\n set = function setImmediate(fn) {\n var args = [];\n var i = 1;\n while (arguments.length > i) args.push(arguments[i++]);\n queue[++counter] = function () {\n // eslint-disable-next-line no-new-func\n (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);\n };\n defer(counter);\n return counter;\n };\n clear = function clearImmediate(id) {\n delete queue[id];\n };\n // Node.js 0.8-\n if (classof(process) == 'process') {\n defer = function (id) {\n process.nextTick(runner(id));\n };\n // Sphere (JS game engine) Dispatch API\n } else if (Dispatch && Dispatch.now) {\n defer = function (id) {\n Dispatch.now(runner(id));\n };\n // Browsers with MessageChannel, includes WebWorkers\n // except iOS - https://github.com/zloirock/core-js/issues/624\n } else if (MessageChannel && !IS_IOS) {\n channel = new MessageChannel();\n port = channel.port2;\n channel.port1.onmessage = listener;\n defer = bind(port.postMessage, port, 1);\n // Browsers with postMessage, skip WebWorkers\n // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'\n } else if (\n global.addEventListener &&\n typeof postMessage == 'function' &&\n !global.importScripts &&\n !fails(post) &&\n location.protocol !== 'file:'\n ) {\n defer = post;\n global.addEventListener('message', listener, false);\n // IE8-\n } else if (ONREADYSTATECHANGE in createElement('script')) {\n defer = function (id) {\n html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {\n html.removeChild(this);\n run(id);\n };\n };\n // Rest old browsers\n } else {\n defer = function (id) {\n setTimeout(runner(id), 0);\n };\n }\n}\n\nmodule.exports = {\n set: set,\n clear: clear\n};\n","var anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar SPECIES = wellKnownSymbol('species');\n\n// `SpeciesConstructor` abstract operation\n// https://tc39.github.io/ecma262/#sec-speciesconstructor\nmodule.exports = function (O, defaultConstructor) {\n var C = anObject(O).constructor;\n var S;\n return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? defaultConstructor : aFunction(S);\n};\n","var userAgent = require('../internals/engine-user-agent');\n\nmodule.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent);\n","var global = require('../internals/global');\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar classof = require('../internals/classof-raw');\nvar macrotask = require('../internals/task').set;\nvar IS_IOS = require('../internals/engine-is-ios');\n\nvar MutationObserver = global.MutationObserver || global.WebKitMutationObserver;\nvar process = global.process;\nvar Promise = global.Promise;\nvar IS_NODE = classof(process) == 'process';\n// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`\nvar queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask');\nvar queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;\n\nvar flush, head, last, notify, toggle, node, promise, then;\n\n// modern engines have queueMicrotask method\nif (!queueMicrotask) {\n flush = function () {\n var parent, fn;\n if (IS_NODE && (parent = process.domain)) parent.exit();\n while (head) {\n fn = head.fn;\n head = head.next;\n try {\n fn();\n } catch (error) {\n if (head) notify();\n else last = undefined;\n throw error;\n }\n } last = undefined;\n if (parent) parent.enter();\n };\n\n // Node.js\n if (IS_NODE) {\n notify = function () {\n process.nextTick(flush);\n };\n // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339\n } else if (MutationObserver && !IS_IOS) {\n toggle = true;\n node = document.createTextNode('');\n new MutationObserver(flush).observe(node, { characterData: true });\n notify = function () {\n node.data = toggle = !toggle;\n };\n // environments with maybe non-completely correct, but existent Promise\n } else if (Promise && Promise.resolve) {\n // Promise.resolve without an argument throws an error in LG WebOS 2\n promise = Promise.resolve(undefined);\n then = promise.then;\n notify = function () {\n then.call(promise, flush);\n };\n // for other environments - macrotask based on:\n // - setImmediate\n // - MessageChannel\n // - window.postMessag\n // - onreadystatechange\n // - setTimeout\n } else {\n notify = function () {\n // strange IE + webpack dev server bug - use .call(global)\n macrotask.call(global, flush);\n };\n }\n}\n\nmodule.exports = queueMicrotask || function (fn) {\n var task = { fn: fn, next: undefined };\n if (last) last.next = task;\n if (!head) {\n head = task;\n notify();\n } last = task;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar global = require('../internals/global');\nvar getBuiltIn = require('../internals/get-built-in');\nvar NativePromise = require('../internals/native-promise-constructor');\nvar redefine = require('../internals/redefine');\nvar redefineAll = require('../internals/redefine-all');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar setSpecies = require('../internals/set-species');\nvar isObject = require('../internals/is-object');\nvar aFunction = require('../internals/a-function');\nvar anInstance = require('../internals/an-instance');\nvar classof = require('../internals/classof-raw');\nvar inspectSource = require('../internals/inspect-source');\nvar iterate = require('../internals/iterate');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\nvar speciesConstructor = require('../internals/species-constructor');\nvar task = require('../internals/task').set;\nvar microtask = require('../internals/microtask');\nvar promiseResolve = require('../internals/promise-resolve');\nvar hostReportErrors = require('../internals/host-report-errors');\nvar newPromiseCapabilityModule = require('../internals/new-promise-capability');\nvar perform = require('../internals/perform');\nvar InternalStateModule = require('../internals/internal-state');\nvar isForced = require('../internals/is-forced');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar SPECIES = wellKnownSymbol('species');\nvar PROMISE = 'Promise';\nvar getInternalState = InternalStateModule.get;\nvar setInternalState = InternalStateModule.set;\nvar getInternalPromiseState = InternalStateModule.getterFor(PROMISE);\nvar PromiseConstructor = NativePromise;\nvar TypeError = global.TypeError;\nvar document = global.document;\nvar process = global.process;\nvar $fetch = getBuiltIn('fetch');\nvar newPromiseCapability = newPromiseCapabilityModule.f;\nvar newGenericPromiseCapability = newPromiseCapability;\nvar IS_NODE = classof(process) == 'process';\nvar DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);\nvar UNHANDLED_REJECTION = 'unhandledrejection';\nvar REJECTION_HANDLED = 'rejectionhandled';\nvar PENDING = 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\nvar HANDLED = 1;\nvar UNHANDLED = 2;\nvar Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;\n\nvar FORCED = isForced(PROMISE, function () {\n var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);\n if (!GLOBAL_CORE_JS_PROMISE) {\n // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables\n // https://bugs.chromium.org/p/chromium/issues/detail?id=830565\n // We can't detect it synchronously, so just check versions\n if (V8_VERSION === 66) return true;\n // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test\n if (!IS_NODE && typeof PromiseRejectionEvent != 'function') return true;\n }\n // We need Promise#finally in the pure version for preventing prototype pollution\n if (IS_PURE && !PromiseConstructor.prototype['finally']) return true;\n // We can't use @@species feature detection in V8 since it causes\n // deoptimization and performance degradation\n // https://github.com/zloirock/core-js/issues/679\n if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false;\n // Detect correctness of subclassing with @@species support\n var promise = PromiseConstructor.resolve(1);\n var FakePromise = function (exec) {\n exec(function () { /* empty */ }, function () { /* empty */ });\n };\n var constructor = promise.constructor = {};\n constructor[SPECIES] = FakePromise;\n return !(promise.then(function () { /* empty */ }) instanceof FakePromise);\n});\n\nvar INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) {\n PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });\n});\n\n// helpers\nvar isThenable = function (it) {\n var then;\n return isObject(it) && typeof (then = it.then) == 'function' ? then : false;\n};\n\nvar notify = function (promise, state, isReject) {\n if (state.notified) return;\n state.notified = true;\n var chain = state.reactions;\n microtask(function () {\n var value = state.value;\n var ok = state.state == FULFILLED;\n var index = 0;\n // variable length - can't use forEach\n while (chain.length > index) {\n var reaction = chain[index++];\n var handler = ok ? reaction.ok : reaction.fail;\n var resolve = reaction.resolve;\n var reject = reaction.reject;\n var domain = reaction.domain;\n var result, then, exited;\n try {\n if (handler) {\n if (!ok) {\n if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state);\n state.rejection = HANDLED;\n }\n if (handler === true) result = value;\n else {\n if (domain) domain.enter();\n result = handler(value); // can throw\n if (domain) {\n domain.exit();\n exited = true;\n }\n }\n if (result === reaction.promise) {\n reject(TypeError('Promise-chain cycle'));\n } else if (then = isThenable(result)) {\n then.call(result, resolve, reject);\n } else resolve(result);\n } else reject(value);\n } catch (error) {\n if (domain && !exited) domain.exit();\n reject(error);\n }\n }\n state.reactions = [];\n state.notified = false;\n if (isReject && !state.rejection) onUnhandled(promise, state);\n });\n};\n\nvar dispatchEvent = function (name, promise, reason) {\n var event, handler;\n if (DISPATCH_EVENT) {\n event = document.createEvent('Event');\n event.promise = promise;\n event.reason = reason;\n event.initEvent(name, false, true);\n global.dispatchEvent(event);\n } else event = { promise: promise, reason: reason };\n if (handler = global['on' + name]) handler(event);\n else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);\n};\n\nvar onUnhandled = function (promise, state) {\n task.call(global, function () {\n var value = state.value;\n var IS_UNHANDLED = isUnhandled(state);\n var result;\n if (IS_UNHANDLED) {\n result = perform(function () {\n if (IS_NODE) {\n process.emit('unhandledRejection', value, promise);\n } else dispatchEvent(UNHANDLED_REJECTION, promise, value);\n });\n // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should\n state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;\n if (result.error) throw result.value;\n }\n });\n};\n\nvar isUnhandled = function (state) {\n return state.rejection !== HANDLED && !state.parent;\n};\n\nvar onHandleUnhandled = function (promise, state) {\n task.call(global, function () {\n if (IS_NODE) {\n process.emit('rejectionHandled', promise);\n } else dispatchEvent(REJECTION_HANDLED, promise, state.value);\n });\n};\n\nvar bind = function (fn, promise, state, unwrap) {\n return function (value) {\n fn(promise, state, value, unwrap);\n };\n};\n\nvar internalReject = function (promise, state, value, unwrap) {\n if (state.done) return;\n state.done = true;\n if (unwrap) state = unwrap;\n state.value = value;\n state.state = REJECTED;\n notify(promise, state, true);\n};\n\nvar internalResolve = function (promise, state, value, unwrap) {\n if (state.done) return;\n state.done = true;\n if (unwrap) state = unwrap;\n try {\n if (promise === value) throw TypeError(\"Promise can't be resolved itself\");\n var then = isThenable(value);\n if (then) {\n microtask(function () {\n var wrapper = { done: false };\n try {\n then.call(value,\n bind(internalResolve, promise, wrapper, state),\n bind(internalReject, promise, wrapper, state)\n );\n } catch (error) {\n internalReject(promise, wrapper, error, state);\n }\n });\n } else {\n state.value = value;\n state.state = FULFILLED;\n notify(promise, state, false);\n }\n } catch (error) {\n internalReject(promise, { done: false }, error, state);\n }\n};\n\n// constructor polyfill\nif (FORCED) {\n // 25.4.3.1 Promise(executor)\n PromiseConstructor = function Promise(executor) {\n anInstance(this, PromiseConstructor, PROMISE);\n aFunction(executor);\n Internal.call(this);\n var state = getInternalState(this);\n try {\n executor(bind(internalResolve, this, state), bind(internalReject, this, state));\n } catch (error) {\n internalReject(this, state, error);\n }\n };\n // eslint-disable-next-line no-unused-vars\n Internal = function Promise(executor) {\n setInternalState(this, {\n type: PROMISE,\n done: false,\n notified: false,\n parent: false,\n reactions: [],\n rejection: false,\n state: PENDING,\n value: undefined\n });\n };\n Internal.prototype = redefineAll(PromiseConstructor.prototype, {\n // `Promise.prototype.then` method\n // https://tc39.github.io/ecma262/#sec-promise.prototype.then\n then: function then(onFulfilled, onRejected) {\n var state = getInternalPromiseState(this);\n var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));\n reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;\n reaction.fail = typeof onRejected == 'function' && onRejected;\n reaction.domain = IS_NODE ? process.domain : undefined;\n state.parent = true;\n state.reactions.push(reaction);\n if (state.state != PENDING) notify(this, state, false);\n return reaction.promise;\n },\n // `Promise.prototype.catch` method\n // https://tc39.github.io/ecma262/#sec-promise.prototype.catch\n 'catch': function (onRejected) {\n return this.then(undefined, onRejected);\n }\n });\n OwnPromiseCapability = function () {\n var promise = new Internal();\n var state = getInternalState(promise);\n this.promise = promise;\n this.resolve = bind(internalResolve, promise, state);\n this.reject = bind(internalReject, promise, state);\n };\n newPromiseCapabilityModule.f = newPromiseCapability = function (C) {\n return C === PromiseConstructor || C === PromiseWrapper\n ? new OwnPromiseCapability(C)\n : newGenericPromiseCapability(C);\n };\n\n if (!IS_PURE && typeof NativePromise == 'function') {\n nativeThen = NativePromise.prototype.then;\n\n // wrap native Promise#then for native async functions\n redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) {\n var that = this;\n return new PromiseConstructor(function (resolve, reject) {\n nativeThen.call(that, resolve, reject);\n }).then(onFulfilled, onRejected);\n // https://github.com/zloirock/core-js/issues/640\n }, { unsafe: true });\n\n // wrap fetch result\n if (typeof $fetch == 'function') $({ global: true, enumerable: true, forced: true }, {\n // eslint-disable-next-line no-unused-vars\n fetch: function fetch(input /* , init */) {\n return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments));\n }\n });\n }\n}\n\n$({ global: true, wrap: true, forced: FORCED }, {\n Promise: PromiseConstructor\n});\n\nsetToStringTag(PromiseConstructor, PROMISE, false, true);\nsetSpecies(PROMISE);\n\nPromiseWrapper = getBuiltIn(PROMISE);\n\n// statics\n$({ target: PROMISE, stat: true, forced: FORCED }, {\n // `Promise.reject` method\n // https://tc39.github.io/ecma262/#sec-promise.reject\n reject: function reject(r) {\n var capability = newPromiseCapability(this);\n capability.reject.call(undefined, r);\n return capability.promise;\n }\n});\n\n$({ target: PROMISE, stat: true, forced: IS_PURE || FORCED }, {\n // `Promise.resolve` method\n // https://tc39.github.io/ecma262/#sec-promise.resolve\n resolve: function resolve(x) {\n return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x);\n }\n});\n\n$({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, {\n // `Promise.all` method\n // https://tc39.github.io/ecma262/#sec-promise.all\n all: function all(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var resolve = capability.resolve;\n var reject = capability.reject;\n var result = perform(function () {\n var $promiseResolve = aFunction(C.resolve);\n var values = [];\n var counter = 0;\n var remaining = 1;\n iterate(iterable, function (promise) {\n var index = counter++;\n var alreadyCalled = false;\n values.push(undefined);\n remaining++;\n $promiseResolve.call(C, promise).then(function (value) {\n if (alreadyCalled) return;\n alreadyCalled = true;\n values[index] = value;\n --remaining || resolve(values);\n }, reject);\n });\n --remaining || resolve(values);\n });\n if (result.error) reject(result.value);\n return capability.promise;\n },\n // `Promise.race` method\n // https://tc39.github.io/ecma262/#sec-promise.race\n race: function race(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var reject = capability.reject;\n var result = perform(function () {\n var $promiseResolve = aFunction(C.resolve);\n iterate(iterable, function (promise) {\n $promiseResolve.call(C, promise).then(capability.resolve, reject);\n });\n });\n if (result.error) reject(result.value);\n return capability.promise;\n }\n});\n","'use strict';\nvar aFunction = require('../internals/a-function');\n\nvar PromiseCapability = function (C) {\n var resolve, reject;\n this.promise = new C(function ($$resolve, $$reject) {\n if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');\n resolve = $$resolve;\n reject = $$reject;\n });\n this.resolve = aFunction(resolve);\n this.reject = aFunction(reject);\n};\n\n// 25.4.1.5 NewPromiseCapability(C)\nmodule.exports.f = function (C) {\n return new PromiseCapability(C);\n};\n","var anObject = require('../internals/an-object');\nvar isObject = require('../internals/is-object');\nvar newPromiseCapability = require('../internals/new-promise-capability');\n\nmodule.exports = function (C, x) {\n anObject(C);\n if (isObject(x) && x.constructor === C) return x;\n var promiseCapability = newPromiseCapability.f(C);\n var resolve = promiseCapability.resolve;\n resolve(x);\n return promiseCapability.promise;\n};\n","module.exports = function (exec) {\n try {\n return { error: false, value: exec() };\n } catch (error) {\n return { error: true, value: error };\n }\n};\n","var global = require('../internals/global');\n\nmodule.exports = function (a, b) {\n var console = global.console;\n if (console && console.error) {\n arguments.length === 1 ? console.error(a) : console.error(a, b);\n }\n};\n","module.exports = function (it, Constructor, name) {\n if (!(it instanceof Constructor)) {\n throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');\n } return it;\n};\n","var redefine = require('../internals/redefine');\n\nmodule.exports = function (target, src, options) {\n for (var key in src) redefine(target, key, src[key], options);\n return target;\n};\n","var toIndexedObject = require('../internals/to-indexed-object');\nvar nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names').f;\n\nvar toString = {}.toString;\n\nvar windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames\n ? Object.getOwnPropertyNames(window) : [];\n\nvar getWindowNames = function (it) {\n try {\n return nativeGetOwnPropertyNames(it);\n } catch (error) {\n return windowNames.slice();\n }\n};\n\n// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window\nmodule.exports.f = function getOwnPropertyNames(it) {\n return windowNames && toString.call(it) == '[object Window]'\n ? getWindowNames(it)\n : nativeGetOwnPropertyNames(toIndexedObject(it));\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nexports.f = wellKnownSymbol;\n","var path = require('../internals/path');\nvar has = require('../internals/has');\nvar wrappedWellKnownSymbolModule = require('../internals/well-known-symbol-wrapped');\nvar defineProperty = require('../internals/object-define-property').f;\n\nmodule.exports = function (NAME) {\n var Symbol = path.Symbol || (path.Symbol = {});\n if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {\n value: wrappedWellKnownSymbolModule.f(NAME)\n });\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar getBuiltIn = require('../internals/get-built-in');\nvar IS_PURE = require('../internals/is-pure');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar NATIVE_SYMBOL = require('../internals/native-symbol');\nvar USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid');\nvar fails = require('../internals/fails');\nvar has = require('../internals/has');\nvar isArray = require('../internals/is-array');\nvar isObject = require('../internals/is-object');\nvar anObject = require('../internals/an-object');\nvar toObject = require('../internals/to-object');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toPrimitive = require('../internals/to-primitive');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar nativeObjectCreate = require('../internals/object-create');\nvar objectKeys = require('../internals/object-keys');\nvar getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');\nvar getOwnPropertyNamesExternal = require('../internals/object-get-own-property-names-external');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar definePropertyModule = require('../internals/object-define-property');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar shared = require('../internals/shared');\nvar sharedKey = require('../internals/shared-key');\nvar hiddenKeys = require('../internals/hidden-keys');\nvar uid = require('../internals/uid');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar wrappedWellKnownSymbolModule = require('../internals/well-known-symbol-wrapped');\nvar defineWellKnownSymbol = require('../internals/define-well-known-symbol');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar InternalStateModule = require('../internals/internal-state');\nvar $forEach = require('../internals/array-iteration').forEach;\n\nvar HIDDEN = sharedKey('hidden');\nvar SYMBOL = 'Symbol';\nvar PROTOTYPE = 'prototype';\nvar TO_PRIMITIVE = wellKnownSymbol('toPrimitive');\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(SYMBOL);\nvar ObjectPrototype = Object[PROTOTYPE];\nvar $Symbol = global.Symbol;\nvar $stringify = getBuiltIn('JSON', 'stringify');\nvar nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\nvar nativeDefineProperty = definePropertyModule.f;\nvar nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;\nvar nativePropertyIsEnumerable = propertyIsEnumerableModule.f;\nvar AllSymbols = shared('symbols');\nvar ObjectPrototypeSymbols = shared('op-symbols');\nvar StringToSymbolRegistry = shared('string-to-symbol-registry');\nvar SymbolToStringRegistry = shared('symbol-to-string-registry');\nvar WellKnownSymbolsStore = shared('wks');\nvar QObject = global.QObject;\n// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173\nvar USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;\n\n// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687\nvar setSymbolDescriptor = DESCRIPTORS && fails(function () {\n return nativeObjectCreate(nativeDefineProperty({}, 'a', {\n get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }\n })).a != 7;\n}) ? function (O, P, Attributes) {\n var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);\n if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];\n nativeDefineProperty(O, P, Attributes);\n if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {\n nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);\n }\n} : nativeDefineProperty;\n\nvar wrap = function (tag, description) {\n var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]);\n setInternalState(symbol, {\n type: SYMBOL,\n tag: tag,\n description: description\n });\n if (!DESCRIPTORS) symbol.description = description;\n return symbol;\n};\n\nvar isSymbol = USE_SYMBOL_AS_UID ? function (it) {\n return typeof it == 'symbol';\n} : function (it) {\n return Object(it) instanceof $Symbol;\n};\n\nvar $defineProperty = function defineProperty(O, P, Attributes) {\n if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);\n anObject(O);\n var key = toPrimitive(P, true);\n anObject(Attributes);\n if (has(AllSymbols, key)) {\n if (!Attributes.enumerable) {\n if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));\n O[HIDDEN][key] = true;\n } else {\n if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;\n Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });\n } return setSymbolDescriptor(O, key, Attributes);\n } return nativeDefineProperty(O, key, Attributes);\n};\n\nvar $defineProperties = function defineProperties(O, Properties) {\n anObject(O);\n var properties = toIndexedObject(Properties);\n var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));\n $forEach(keys, function (key) {\n if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);\n });\n return O;\n};\n\nvar $create = function create(O, Properties) {\n return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);\n};\n\nvar $propertyIsEnumerable = function propertyIsEnumerable(V) {\n var P = toPrimitive(V, true);\n var enumerable = nativePropertyIsEnumerable.call(this, P);\n if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;\n return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;\n};\n\nvar $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {\n var it = toIndexedObject(O);\n var key = toPrimitive(P, true);\n if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;\n var descriptor = nativeGetOwnPropertyDescriptor(it, key);\n if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {\n descriptor.enumerable = true;\n }\n return descriptor;\n};\n\nvar $getOwnPropertyNames = function getOwnPropertyNames(O) {\n var names = nativeGetOwnPropertyNames(toIndexedObject(O));\n var result = [];\n $forEach(names, function (key) {\n if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);\n });\n return result;\n};\n\nvar $getOwnPropertySymbols = function getOwnPropertySymbols(O) {\n var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;\n var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));\n var result = [];\n $forEach(names, function (key) {\n if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {\n result.push(AllSymbols[key]);\n }\n });\n return result;\n};\n\n// `Symbol` constructor\n// https://tc39.github.io/ecma262/#sec-symbol-constructor\nif (!NATIVE_SYMBOL) {\n $Symbol = function Symbol() {\n if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');\n var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);\n var tag = uid(description);\n var setter = function (value) {\n if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);\n if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;\n setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));\n };\n if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });\n return wrap(tag, description);\n };\n\n redefine($Symbol[PROTOTYPE], 'toString', function toString() {\n return getInternalState(this).tag;\n });\n\n redefine($Symbol, 'withoutSetter', function (description) {\n return wrap(uid(description), description);\n });\n\n propertyIsEnumerableModule.f = $propertyIsEnumerable;\n definePropertyModule.f = $defineProperty;\n getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor;\n getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;\n getOwnPropertySymbolsModule.f = $getOwnPropertySymbols;\n\n wrappedWellKnownSymbolModule.f = function (name) {\n return wrap(wellKnownSymbol(name), name);\n };\n\n if (DESCRIPTORS) {\n // https://github.com/tc39/proposal-Symbol-description\n nativeDefineProperty($Symbol[PROTOTYPE], 'description', {\n configurable: true,\n get: function description() {\n return getInternalState(this).description;\n }\n });\n if (!IS_PURE) {\n redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });\n }\n }\n}\n\n$({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, {\n Symbol: $Symbol\n});\n\n$forEach(objectKeys(WellKnownSymbolsStore), function (name) {\n defineWellKnownSymbol(name);\n});\n\n$({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, {\n // `Symbol.for` method\n // https://tc39.github.io/ecma262/#sec-symbol.for\n 'for': function (key) {\n var string = String(key);\n if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];\n var symbol = $Symbol(string);\n StringToSymbolRegistry[string] = symbol;\n SymbolToStringRegistry[symbol] = string;\n return symbol;\n },\n // `Symbol.keyFor` method\n // https://tc39.github.io/ecma262/#sec-symbol.keyfor\n keyFor: function keyFor(sym) {\n if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');\n if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];\n },\n useSetter: function () { USE_SETTER = true; },\n useSimple: function () { USE_SETTER = false; }\n});\n\n$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, {\n // `Object.create` method\n // https://tc39.github.io/ecma262/#sec-object.create\n create: $create,\n // `Object.defineProperty` method\n // https://tc39.github.io/ecma262/#sec-object.defineproperty\n defineProperty: $defineProperty,\n // `Object.defineProperties` method\n // https://tc39.github.io/ecma262/#sec-object.defineproperties\n defineProperties: $defineProperties,\n // `Object.getOwnPropertyDescriptor` method\n // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors\n getOwnPropertyDescriptor: $getOwnPropertyDescriptor\n});\n\n$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, {\n // `Object.getOwnPropertyNames` method\n // https://tc39.github.io/ecma262/#sec-object.getownpropertynames\n getOwnPropertyNames: $getOwnPropertyNames,\n // `Object.getOwnPropertySymbols` method\n // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols\n getOwnPropertySymbols: $getOwnPropertySymbols\n});\n\n// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives\n// https://bugs.chromium.org/p/v8/issues/detail?id=3443\n$({ target: 'Object', stat: true, forced: fails(function () { getOwnPropertySymbolsModule.f(1); }) }, {\n getOwnPropertySymbols: function getOwnPropertySymbols(it) {\n return getOwnPropertySymbolsModule.f(toObject(it));\n }\n});\n\n// `JSON.stringify` method behavior with symbols\n// https://tc39.github.io/ecma262/#sec-json.stringify\nif ($stringify) {\n var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () {\n var symbol = $Symbol();\n // MS Edge converts symbol values to JSON as {}\n return $stringify([symbol]) != '[null]'\n // WebKit converts symbol values to JSON as null\n || $stringify({ a: symbol }) != '{}'\n // V8 throws on boxed symbols\n || $stringify(Object(symbol)) != '{}';\n });\n\n $({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {\n // eslint-disable-next-line no-unused-vars\n stringify: function stringify(it, replacer, space) {\n var args = [it];\n var index = 1;\n var $replacer;\n while (arguments.length > index) args.push(arguments[index++]);\n $replacer = replacer;\n if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined\n if (!isArray(replacer)) replacer = function (key, value) {\n if (typeof $replacer == 'function') value = $replacer.call(this, key, value);\n if (!isSymbol(value)) return value;\n };\n args[1] = replacer;\n return $stringify.apply(null, args);\n }\n });\n}\n\n// `Symbol.prototype[@@toPrimitive]` method\n// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive\nif (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) {\n createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);\n}\n// `Symbol.prototype[@@toStringTag]` property\n// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag\nsetToStringTag($Symbol, SYMBOL);\n\nhiddenKeys[HIDDEN] = true;\n","// `Symbol.prototype.description` getter\n// https://tc39.github.io/ecma262/#sec-symbol.prototype.description\n'use strict';\nvar $ = require('../internals/export');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar has = require('../internals/has');\nvar isObject = require('../internals/is-object');\nvar defineProperty = require('../internals/object-define-property').f;\nvar copyConstructorProperties = require('../internals/copy-constructor-properties');\n\nvar NativeSymbol = global.Symbol;\n\nif (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||\n // Safari 12 bug\n NativeSymbol().description !== undefined\n)) {\n var EmptyStringDescriptionStore = {};\n // wrap Symbol constructor for correct work with undefined description\n var SymbolWrapper = function Symbol() {\n var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);\n var result = this instanceof SymbolWrapper\n ? new NativeSymbol(description)\n // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'\n : description === undefined ? NativeSymbol() : NativeSymbol(description);\n if (description === '') EmptyStringDescriptionStore[result] = true;\n return result;\n };\n copyConstructorProperties(SymbolWrapper, NativeSymbol);\n var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;\n symbolPrototype.constructor = SymbolWrapper;\n\n var symbolToString = symbolPrototype.toString;\n var native = String(NativeSymbol('test')) == 'Symbol(test)';\n var regexp = /^Symbol\\((.*)\\)[^)]+$/;\n defineProperty(symbolPrototype, 'description', {\n configurable: true,\n get: function description() {\n var symbol = isObject(this) ? this.valueOf() : this;\n var string = symbolToString.call(symbol);\n if (has(EmptyStringDescriptionStore, symbol)) return '';\n var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');\n return desc === '' ? undefined : desc;\n }\n });\n\n $({ global: true, forced: true }, {\n Symbol: SymbolWrapper\n });\n}\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.asyncIterator` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.asynciterator\ndefineWellKnownSymbol('asyncIterator');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.iterator` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.iterator\ndefineWellKnownSymbol('iterator');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.toStringTag` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.tostringtag\ndefineWellKnownSymbol('toStringTag');\n","'use strict';\nvar fails = require('../internals/fails');\n\nmodule.exports = function (METHOD_NAME, argument) {\n var method = [][METHOD_NAME];\n return !!method && fails(function () {\n // eslint-disable-next-line no-useless-call,no-throw-literal\n method.call(null, argument || function () { throw 1; }, 1);\n });\n};\n","'use strict';\nvar $forEach = require('../internals/array-iteration').forEach;\nvar arrayMethodIsStrict = require('../internals/array-method-is-strict');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar STRICT_METHOD = arrayMethodIsStrict('forEach');\nvar USES_TO_LENGTH = arrayMethodUsesToLength('forEach');\n\n// `Array.prototype.forEach` method implementation\n// https://tc39.github.io/ecma262/#sec-array.prototype.foreach\nmodule.exports = (!STRICT_METHOD || !USES_TO_LENGTH) ? function forEach(callbackfn /* , thisArg */) {\n return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n} : [].forEach;\n","'use strict';\nvar $ = require('../internals/export');\nvar forEach = require('../internals/array-for-each');\n\n// `Array.prototype.forEach` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.foreach\n$({ target: 'Array', proto: true, forced: [].forEach != forEach }, {\n forEach: forEach\n});\n","var fails = require('../internals/fails');\n\nmodule.exports = !fails(function () {\n function F() { /* empty */ }\n F.prototype.constructor = null;\n return Object.getPrototypeOf(new F()) !== F.prototype;\n});\n","'use strict';\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar has = require('../internals/has');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar IS_PURE = require('../internals/is-pure');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar BUGGY_SAFARI_ITERATORS = false;\n\nvar returnThis = function () { return this; };\n\n// `%IteratorPrototype%` object\n// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object\nvar IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;\n\nif ([].keys) {\n arrayIterator = [].keys();\n // Safari 8 has buggy iterators w/o `next`\n if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;\n else {\n PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));\n if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;\n }\n}\n\nif (IteratorPrototype == undefined) IteratorPrototype = {};\n\n// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()\nif (!IS_PURE && !has(IteratorPrototype, ITERATOR)) {\n createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);\n}\n\nmodule.exports = {\n IteratorPrototype: IteratorPrototype,\n BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS\n};\n","var has = require('../internals/has');\nvar toObject = require('../internals/to-object');\nvar sharedKey = require('../internals/shared-key');\nvar CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');\n\nvar IE_PROTO = sharedKey('IE_PROTO');\nvar ObjectPrototype = Object.prototype;\n\n// `Object.getPrototypeOf` method\n// https://tc39.github.io/ecma262/#sec-object.getprototypeof\nmodule.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {\n O = toObject(O);\n if (has(O, IE_PROTO)) return O[IE_PROTO];\n if (typeof O.constructor == 'function' && O instanceof O.constructor) {\n return O.constructor.prototype;\n } return O instanceof Object ? ObjectPrototype : null;\n};\n","'use strict';\nvar IteratorPrototype = require('../internals/iterators-core').IteratorPrototype;\nvar create = require('../internals/object-create');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar Iterators = require('../internals/iterators');\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (IteratorConstructor, NAME, next) {\n var TO_STRING_TAG = NAME + ' Iterator';\n IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) });\n setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);\n Iterators[TO_STRING_TAG] = returnThis;\n return IteratorConstructor;\n};\n","var anObject = require('../internals/an-object');\nvar aPossiblePrototype = require('../internals/a-possible-prototype');\n\n// `Object.setPrototypeOf` method\n// https://tc39.github.io/ecma262/#sec-object.setprototypeof\n// Works with __proto__ only. Old v8 can't work with null proto objects.\n/* eslint-disable no-proto */\nmodule.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {\n var CORRECT_SETTER = false;\n var test = {};\n var setter;\n try {\n setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;\n setter.call(test, []);\n CORRECT_SETTER = test instanceof Array;\n } catch (error) { /* empty */ }\n return function setPrototypeOf(O, proto) {\n anObject(O);\n aPossiblePrototype(proto);\n if (CORRECT_SETTER) setter.call(O, proto);\n else O.__proto__ = proto;\n return O;\n };\n}() : undefined);\n","var isObject = require('../internals/is-object');\n\nmodule.exports = function (it) {\n if (!isObject(it) && it !== null) {\n throw TypeError(\"Can't set \" + String(it) + ' as a prototype');\n } return it;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar createIteratorConstructor = require('../internals/create-iterator-constructor');\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar IS_PURE = require('../internals/is-pure');\nvar Iterators = require('../internals/iterators');\nvar IteratorsCore = require('../internals/iterators-core');\n\nvar IteratorPrototype = IteratorsCore.IteratorPrototype;\nvar BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;\nvar ITERATOR = wellKnownSymbol('iterator');\nvar KEYS = 'keys';\nvar VALUES = 'values';\nvar ENTRIES = 'entries';\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {\n createIteratorConstructor(IteratorConstructor, NAME, next);\n\n var getIterationMethod = function (KIND) {\n if (KIND === DEFAULT && defaultIterator) return defaultIterator;\n if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];\n switch (KIND) {\n case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };\n case VALUES: return function values() { return new IteratorConstructor(this, KIND); };\n case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };\n } return function () { return new IteratorConstructor(this); };\n };\n\n var TO_STRING_TAG = NAME + ' Iterator';\n var INCORRECT_VALUES_NAME = false;\n var IterablePrototype = Iterable.prototype;\n var nativeIterator = IterablePrototype[ITERATOR]\n || IterablePrototype['@@iterator']\n || DEFAULT && IterablePrototype[DEFAULT];\n var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);\n var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;\n var CurrentIteratorPrototype, methods, KEY;\n\n // fix native\n if (anyNativeIterator) {\n CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));\n if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {\n if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {\n if (setPrototypeOf) {\n setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);\n } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {\n createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);\n }\n }\n // Set @@toStringTag to native iterators\n setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);\n if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;\n }\n }\n\n // fix Array#{values, @@iterator}.name in V8 / FF\n if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {\n INCORRECT_VALUES_NAME = true;\n defaultIterator = function values() { return nativeIterator.call(this); };\n }\n\n // define iterator\n if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {\n createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);\n }\n Iterators[NAME] = defaultIterator;\n\n // export additional methods\n if (DEFAULT) {\n methods = {\n values: getIterationMethod(VALUES),\n keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),\n entries: getIterationMethod(ENTRIES)\n };\n if (FORCED) for (KEY in methods) {\n if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {\n redefine(IterablePrototype, KEY, methods[KEY]);\n }\n } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);\n }\n\n return methods;\n};\n","'use strict';\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar addToUnscopables = require('../internals/add-to-unscopables');\nvar Iterators = require('../internals/iterators');\nvar InternalStateModule = require('../internals/internal-state');\nvar defineIterator = require('../internals/define-iterator');\n\nvar ARRAY_ITERATOR = 'Array Iterator';\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);\n\n// `Array.prototype.entries` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.entries\n// `Array.prototype.keys` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.keys\n// `Array.prototype.values` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.values\n// `Array.prototype[@@iterator]` method\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator\n// `CreateArrayIterator` internal method\n// https://tc39.github.io/ecma262/#sec-createarrayiterator\nmodule.exports = defineIterator(Array, 'Array', function (iterated, kind) {\n setInternalState(this, {\n type: ARRAY_ITERATOR,\n target: toIndexedObject(iterated), // target\n index: 0, // next index\n kind: kind // kind\n });\n// `%ArrayIteratorPrototype%.next` method\n// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next\n}, function () {\n var state = getInternalState(this);\n var target = state.target;\n var kind = state.kind;\n var index = state.index++;\n if (!target || index >= target.length) {\n state.target = undefined;\n return { value: undefined, done: true };\n }\n if (kind == 'keys') return { value: index, done: false };\n if (kind == 'values') return { value: target[index], done: false };\n return { value: [index, target[index]], done: false };\n}, 'values');\n\n// argumentsList[@@iterator] is %ArrayProto_values%\n// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject\n// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject\nIterators.Arguments = Iterators.Array;\n\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables('keys');\naddToUnscopables('values');\naddToUnscopables('entries');\n","'use strict';\nvar $ = require('../internals/export');\nvar isArray = require('../internals/is-array');\n\nvar nativeReverse = [].reverse;\nvar test = [1, 2];\n\n// `Array.prototype.reverse` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.reverse\n// fix for Safari 12.0 bug\n// https://bugs.webkit.org/show_bug.cgi?id=188794\n$({ target: 'Array', proto: true, forced: String(test) === String(test.reverse()) }, {\n reverse: function reverse() {\n // eslint-disable-next-line no-self-assign\n if (isArray(this)) this.length = this.length;\n return nativeReverse.call(this);\n }\n});\n","'use strict';\nvar toPrimitive = require('../internals/to-primitive');\nvar definePropertyModule = require('../internals/object-define-property');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\n\nmodule.exports = function (object, key, value) {\n var propertyKey = toPrimitive(key);\n if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));\n else object[propertyKey] = value;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar isObject = require('../internals/is-object');\nvar isArray = require('../internals/is-array');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar toLength = require('../internals/to-length');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar createProperty = require('../internals/create-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');\nvar USES_TO_LENGTH = arrayMethodUsesToLength('slice', { ACCESSORS: true, 0: 0, 1: 2 });\n\nvar SPECIES = wellKnownSymbol('species');\nvar nativeSlice = [].slice;\nvar max = Math.max;\n\n// `Array.prototype.slice` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.slice\n// fallback for not array-like ES3 strings and DOM objects\n$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {\n slice: function slice(start, end) {\n var O = toIndexedObject(this);\n var length = toLength(O.length);\n var k = toAbsoluteIndex(start, length);\n var fin = toAbsoluteIndex(end === undefined ? length : end, length);\n // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible\n var Constructor, result, n;\n if (isArray(O)) {\n Constructor = O.constructor;\n // cross-realm fallback\n if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {\n Constructor = undefined;\n } else if (isObject(Constructor)) {\n Constructor = Constructor[SPECIES];\n if (Constructor === null) Constructor = undefined;\n }\n if (Constructor === Array || Constructor === undefined) {\n return nativeSlice.call(O, k, fin);\n }\n }\n result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));\n for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);\n result.length = n;\n return result;\n }\n});\n","var redefine = require('../internals/redefine');\n\nvar DatePrototype = Date.prototype;\nvar INVALID_DATE = 'Invalid Date';\nvar TO_STRING = 'toString';\nvar nativeDateToString = DatePrototype[TO_STRING];\nvar getTime = DatePrototype.getTime;\n\n// `Date.prototype.toString` method\n// https://tc39.github.io/ecma262/#sec-date.prototype.tostring\nif (new Date(NaN) + '' != INVALID_DATE) {\n redefine(DatePrototype, TO_STRING, function toString() {\n var value = getTime.call(this);\n // eslint-disable-next-line no-self-compare\n return value === value ? nativeDateToString.call(this) : INVALID_DATE;\n });\n}\n","var global = require('../internals/global');\nvar setToStringTag = require('../internals/set-to-string-tag');\n\n// JSON[@@toStringTag] property\n// https://tc39.github.io/ecma262/#sec-json-@@tostringtag\nsetToStringTag(global.JSON, 'JSON', true);\n","var setToStringTag = require('../internals/set-to-string-tag');\n\n// Math[@@toStringTag] property\n// https://tc39.github.io/ecma262/#sec-math-@@tostringtag\nsetToStringTag(Math, 'Math', true);\n","var $ = require('../internals/export');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar create = require('../internals/object-create');\n\n// `Object.create` method\n// https://tc39.github.io/ecma262/#sec-object.create\n$({ target: 'Object', stat: true, sham: !DESCRIPTORS }, {\n create: create\n});\n","var $ = require('../internals/export');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar objectDefinePropertyModile = require('../internals/object-define-property');\n\n// `Object.defineProperty` method\n// https://tc39.github.io/ecma262/#sec-object.defineproperty\n$({ target: 'Object', stat: true, forced: !DESCRIPTORS, sham: !DESCRIPTORS }, {\n defineProperty: objectDefinePropertyModile.f\n});\n","var $ = require('../internals/export');\nvar fails = require('../internals/fails');\nvar toObject = require('../internals/to-object');\nvar nativeGetPrototypeOf = require('../internals/object-get-prototype-of');\nvar CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');\n\nvar FAILS_ON_PRIMITIVES = fails(function () { nativeGetPrototypeOf(1); });\n\n// `Object.getPrototypeOf` method\n// https://tc39.github.io/ecma262/#sec-object.getprototypeof\n$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !CORRECT_PROTOTYPE_GETTER }, {\n getPrototypeOf: function getPrototypeOf(it) {\n return nativeGetPrototypeOf(toObject(it));\n }\n});\n\n","var $ = require('../internals/export');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\n\n// `Object.setPrototypeOf` method\n// https://tc39.github.io/ecma262/#sec-object.setprototypeof\n$({ target: 'Object', stat: true }, {\n setPrototypeOf: setPrototypeOf\n});\n","'use strict';\nvar anObject = require('../internals/an-object');\n\n// `RegExp.prototype.flags` getter implementation\n// https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags\nmodule.exports = function () {\n var that = anObject(this);\n var result = '';\n if (that.global) result += 'g';\n if (that.ignoreCase) result += 'i';\n if (that.multiline) result += 'm';\n if (that.dotAll) result += 's';\n if (that.unicode) result += 'u';\n if (that.sticky) result += 'y';\n return result;\n};\n","'use strict';\nvar redefine = require('../internals/redefine');\nvar anObject = require('../internals/an-object');\nvar fails = require('../internals/fails');\nvar flags = require('../internals/regexp-flags');\n\nvar TO_STRING = 'toString';\nvar RegExpPrototype = RegExp.prototype;\nvar nativeToString = RegExpPrototype[TO_STRING];\n\nvar NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });\n// FF44- RegExp#toString has a wrong name\nvar INCORRECT_NAME = nativeToString.name != TO_STRING;\n\n// `RegExp.prototype.toString` method\n// https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring\nif (NOT_GENERIC || INCORRECT_NAME) {\n redefine(RegExp.prototype, TO_STRING, function toString() {\n var R = anObject(this);\n var p = String(R.source);\n var rf = R.flags;\n var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf);\n return '/' + p + '/' + f;\n }, { unsafe: true });\n}\n","var toInteger = require('../internals/to-integer');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `String.prototype.{ codePointAt, at }` methods implementation\nvar createMethod = function (CONVERT_TO_STRING) {\n return function ($this, pos) {\n var S = String(requireObjectCoercible($this));\n var position = toInteger(pos);\n var size = S.length;\n var first, second;\n if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;\n first = S.charCodeAt(position);\n return first < 0xD800 || first > 0xDBFF || position + 1 === size\n || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF\n ? CONVERT_TO_STRING ? S.charAt(position) : first\n : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;\n };\n};\n\nmodule.exports = {\n // `String.prototype.codePointAt` method\n // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat\n codeAt: createMethod(false),\n // `String.prototype.at` method\n // https://github.com/mathiasbynens/String.prototype.at\n charAt: createMethod(true)\n};\n","'use strict';\nvar charAt = require('../internals/string-multibyte').charAt;\nvar InternalStateModule = require('../internals/internal-state');\nvar defineIterator = require('../internals/define-iterator');\n\nvar STRING_ITERATOR = 'String Iterator';\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);\n\n// `String.prototype[@@iterator]` method\n// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator\ndefineIterator(String, 'String', function (iterated) {\n setInternalState(this, {\n type: STRING_ITERATOR,\n string: String(iterated),\n index: 0\n });\n// `%StringIteratorPrototype%.next` method\n// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next\n}, function next() {\n var state = getInternalState(this);\n var string = state.string;\n var index = state.index;\n var point;\n if (index >= string.length) return { value: undefined, done: true };\n point = charAt(string, index);\n state.index += point.length;\n return { value: point, done: false };\n});\n","// iterable DOM collections\n// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods\nmodule.exports = {\n CSSRuleList: 0,\n CSSStyleDeclaration: 0,\n CSSValueList: 0,\n ClientRectList: 0,\n DOMRectList: 0,\n DOMStringList: 0,\n DOMTokenList: 1,\n DataTransferItemList: 0,\n FileList: 0,\n HTMLAllCollection: 0,\n HTMLCollection: 0,\n HTMLFormElement: 0,\n HTMLSelectElement: 0,\n MediaList: 0,\n MimeTypeArray: 0,\n NamedNodeMap: 0,\n NodeList: 1,\n PaintRequestList: 0,\n Plugin: 0,\n PluginArray: 0,\n SVGLengthList: 0,\n SVGNumberList: 0,\n SVGPathSegList: 0,\n SVGPointList: 0,\n SVGStringList: 0,\n SVGTransformList: 0,\n SourceBufferList: 0,\n StyleSheetList: 0,\n TextTrackCueList: 0,\n TextTrackList: 0,\n TouchList: 0\n};\n","var global = require('../internals/global');\nvar DOMIterables = require('../internals/dom-iterables');\nvar forEach = require('../internals/array-for-each');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\n\nfor (var COLLECTION_NAME in DOMIterables) {\n var Collection = global[COLLECTION_NAME];\n var CollectionPrototype = Collection && Collection.prototype;\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {\n createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach);\n } catch (error) {\n CollectionPrototype.forEach = forEach;\n }\n}\n","var global = require('../internals/global');\nvar DOMIterables = require('../internals/dom-iterables');\nvar ArrayIteratorMethods = require('../modules/es.array.iterator');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar ArrayValues = ArrayIteratorMethods.values;\n\nfor (var COLLECTION_NAME in DOMIterables) {\n var Collection = global[COLLECTION_NAME];\n var CollectionPrototype = Collection && Collection.prototype;\n if (CollectionPrototype) {\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype[ITERATOR] !== ArrayValues) try {\n createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);\n } catch (error) {\n CollectionPrototype[ITERATOR] = ArrayValues;\n }\n if (!CollectionPrototype[TO_STRING_TAG]) {\n createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);\n }\n if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {\n createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);\n } catch (error) {\n CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];\n }\n }\n }\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","/**\n * @file ext-polygon.js\n *\n *\n * @copyright 2010 CloudCanvas, Inc. All rights reserved\n *\n */\n\nconst loadExtensionTranslation = async function (lang) {\n let translationModule;\n try {\n translationModule = await import(`./locale/${lang}.js`);\n } catch (_error) {\n // eslint-disable-next-line no-console\n console.error(`Missing translation (${lang}) - using 'en'`);\n translationModule = await import(`./locale/en.js`);\n }\n return translationModule.default;\n};\n\nexport default {\n name: 'polygon',\n async init (S) {\n const svgEditor = this;\n const svgCanvas = svgEditor.canvas;\n const {$} = S, // {svgcontent}\n // addElem = svgCanvas.addSVGElementFromJson,\n editingitex = false;\n const strings = await loadExtensionTranslation(svgEditor.curPrefs.lang);\n let selElems,\n // svgdoc = S.svgroot.parentNode.ownerDocument,\n // newFOG, newFOGParent, newDef, newImageName, newMaskID, modeChangeG,\n // edg = 0,\n // undoCommand = 'Not image';\n started, newFO;\n\n // const ccZoom;\n // const wEl, hEl;\n // const wOffset, hOffset;\n // const ccRBG;\n // const ccOpacity;\n // const brushW, brushH;\n\n // const ccDebug = document.getElementById('debugpanel');\n\n /* const properlySourceSizeTextArea = function(){\n // TODO: remove magic numbers here and get values from CSS\n const height = $('#svg_source_container').height() - 80;\n $('#svg_source_textarea').css('height', height);\n }; */\n\n /**\n * @param {boolean} on\n * @returns {void}\n */\n function showPanel (on) {\n let fcRules = $('#fc_rules');\n if (!fcRules.length) {\n fcRules = $('').appendTo('head');\n }\n fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');\n $('#polygon_panel').toggle(on);\n }\n\n /*\n function toggleSourceButtons(on){\n $('#tool_source_save, #tool_source_cancel').toggle(!on);\n $('#polygon_save, #polygon_cancel').toggle(on);\n }\n */\n\n /**\n * @param {string} attr\n * @param {string|Float} val\n * @returns {void}\n */\n function setAttr (attr, val) {\n svgCanvas.changeSelectedAttribute(attr, val);\n svgCanvas.call('changed', selElems);\n }\n\n /**\n * @param {Float} n\n * @returns {Float}\n */\n function cot (n) {\n return 1 / Math.tan(n);\n }\n\n /**\n * @param {Float} n\n * @returns {Float}\n */\n function sec (n) {\n return 1 / Math.cos(n);\n }\n\n /**\n * Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3\n * This function sets the content of of the currently-selected foreignObject element,\n * based on the itex contained in string.\n * @param {string} tex The itex text.\n * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.\n */\n /*\n function setItexString(tex) {\n const mathns = 'http://www.w3.org/1998/Math/MathML',\n xmlnsns = 'http://www.w3.org/2000/xmlns/',\n ajaxEndpoint = '../../itex';\n const elt = selElems[0];\n try {\n const math = svgdoc.createElementNS(mathns, 'math');\n math.setAttributeNS(xmlnsns, 'xmlns', mathns);\n math.setAttribute('display', 'inline');\n const semantics = document.createElementNS(mathns, 'semantics');\n const annotation = document.createElementNS(mathns, 'annotation');\n annotation.setAttribute('encoding', 'application/x-tex');\n annotation.textContent = tex;\n const mrow = document.createElementNS(mathns, 'mrow');\n semantics.append(mrow, annotation);\n math.append(semantics);\n // make an AJAX request to the server, to get the MathML\n $.post(ajaxEndpoint, {tex, display: 'inline'}, function(data){\n const children = data.documentElement.childNodes;\n while (children.length > 0) {\n mrow.append(svgdoc.adoptNode(children[0], true));\n }\n svgCanvas.sanitizeSvg(math);\n svgCanvas.call('changed', [elt]);\n });\n elt.firstChild.replaceWith(math);\n svgCanvas.call('changed', [elt]);\n svgCanvas.clearSelection();\n } catch(e) {\n console.log(e);\n return false;\n }\n\n return true;\n }\n */\n const buttons = [{\n id: 'tool_polygon',\n icon: 'polygon.png',\n type: 'mode',\n position: 11,\n events: {\n click () {\n svgCanvas.setMode('polygon');\n showPanel(true);\n }\n }\n }];\n const contextTools = [{\n type: 'input',\n panel: 'polygon_panel',\n id: 'polySides',\n size: 3,\n defval: 5,\n events: {\n change () {\n setAttr('sides', this.value);\n }\n }\n }];\n return {\n name: strings.name,\n svgicons: 'polygon-icons.svg',\n buttons: strings.buttons.map((button, i) => {\n return Object.assign(buttons[i], button);\n }),\n context_tools: strings.contextTools.map((contextTool, i) => {\n return Object.assign(contextTools[i], contextTool);\n }),\n\n callback () {\n $('#polygon_panel').hide();\n\n const endChanges = function () {\n // Todo: Missing?\n };\n\n // TODO: Needs to be done after orig icon loads\n setTimeout(function () {\n // Create source save/cancel buttons\n /* const save = */ $('#tool_source_save').clone().hide().attr(\n 'id', 'polygon_save'\n ).unbind().appendTo(\n '#tool_source_back'\n ).click(function () {\n if (!editingitex) {\n return;\n }\n // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint?\n /*\n if (!setItexString($('#svg_source_textarea').val())) {\n const ok = await $.confirm('Errors found. Revert to original?', function (ok) {\n if (!ok) {\n return false;\n }\n endChanges();\n } else { */\n endChanges();\n // }\n // setSelectMode();\n });\n\n /* const cancel = */ $('#tool_source_cancel').clone().hide().attr(\n 'id', 'polygon_cancel'\n ).unbind().appendTo('#tool_source_back').click(function () {\n endChanges();\n });\n }, 3000);\n },\n mouseDown (opts) {\n if (svgCanvas.getMode() !== 'polygon') {\n return undefined;\n }\n // const e = opts.event;\n const rgb = svgCanvas.getColor('fill');\n // const ccRgbEl = rgb.substring(1, rgb.length);\n const sRgb = svgCanvas.getColor('stroke');\n // ccSRgbEl = sRgb.substring(1, rgb.length);\n const sWidth = svgCanvas.getStrokeWidth();\n\n started = true;\n\n newFO = svgCanvas.addSVGElementFromJson({\n element: 'polygon',\n attr: {\n cx: opts.start_x,\n cy: opts.start_y,\n id: svgCanvas.getNextId(),\n shape: 'regularPoly',\n sides: document.getElementById('polySides').value,\n orient: 'x',\n edge: 0,\n fill: rgb,\n strokecolor: sRgb,\n strokeWidth: sWidth\n }\n });\n\n return {\n started: true\n };\n },\n mouseMove (opts) {\n if (!started || svgCanvas.getMode() !== 'polygon') {\n return undefined;\n }\n // const e = opts.event;\n const c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']);\n let x = opts.mouse_x;\n let y = opts.mouse_y;\n const {cx, cy, fill, strokecolor, strokeWidth, sides} = c, // {orient} = c,\n edg = (Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy))) / 1.5;\n newFO.setAttribute('edge', edg);\n\n const inradius = (edg / 2) * cot(Math.PI / sides);\n const circumradius = inradius * sec(Math.PI / sides);\n let points = '';\n for (let s = 0; sides >= s; s++) {\n const angle = 2.0 * Math.PI * s / sides;\n x = (circumradius * Math.cos(angle)) + cx;\n y = (circumradius * Math.sin(angle)) + cy;\n\n points += x + ',' + y + ' ';\n }\n\n // const poly = newFO.createElementNS(NS.SVG, 'polygon');\n newFO.setAttribute('points', points);\n newFO.setAttribute('fill', fill);\n newFO.setAttribute('stroke', strokecolor);\n newFO.setAttribute('stroke-width', strokeWidth);\n // newFO.setAttribute('transform', 'rotate(-90)');\n // const shape = newFO.getAttribute('shape');\n // newFO.append(poly);\n // DrawPoly(cx, cy, sides, edg, orient);\n return {\n started: true\n };\n },\n\n mouseUp (opts) {\n if (svgCanvas.getMode() !== 'polygon') {\n return undefined;\n }\n const attrs = $(newFO).attr('edge');\n const keep = (attrs.edge !== '0');\n // svgCanvas.addToSelection([newFO], true);\n return {\n keep,\n element: newFO\n };\n },\n selectedChanged (opts) {\n // Use this to update the current selected elements\n selElems = opts.elems;\n\n let i = selElems.length;\n while (i--) {\n const elem = selElems[i];\n if (elem && elem.getAttribute('shape') === 'regularPoly') {\n if (opts.selectedElement && !opts.multiselected) {\n $('#polySides').val(elem.getAttribute('sides'));\n\n showPanel(true);\n } else {\n showPanel(false);\n }\n } else {\n showPanel(false);\n }\n }\n },\n elementChanged (opts) {\n // const elem = opts.elems[0];\n }\n };\n }\n};\n","export default {\n name: 'polygon',\n buttons: [\n {\n title: 'Polygon Tool'\n }\n ],\n contextTools: [\n {\n title: 'Number of Sides',\n label: 'sides'\n }\n ]\n};\n","export default {\n name: '多边形',\n buttons: [\n {\n title: '多边形工具'\n }\n ],\n contextTools: [\n {\n title: '边数',\n label: '边数'\n }\n ]\n};\n"],"names":["check","it","Math","globalThis","window","self","global","Function","exec","error","fails","Object","defineProperty","get","nativePropertyIsEnumerable","propertyIsEnumerable","getOwnPropertyDescriptor","call","1","V","descriptor","this","enumerable","bitmap","value","configurable","writable","toString","slice","split","classof","undefined","TypeError","IndexedObject","requireObjectCoercible","input","PREFERRED_STRING","isObject","fn","val","valueOf","hasOwnProperty","key","document","EXISTS","createElement","DESCRIPTORS","a","nativeGetOwnPropertyDescriptor","O","P","toIndexedObject","toPrimitive","IE8_DOM_DEFINE","has","createPropertyDescriptor","propertyIsEnumerableModule","f","String","nativeDefineProperty","Attributes","anObject","object","definePropertyModule","createNonEnumerableProperty","setGlobal","functionToString","store","inspectSource","set","WeakMap","test","module","push","version","mode","copyright","id","postfix","random","keys","shared","uid","NATIVE_WEAK_MAP","wmget","wmhas","wmset","metadata","STATE","sharedKey","hiddenKeys","objectHas","activeXDocument","enforce","getterFor","TYPE","state","type","getInternalState","InternalStateModule","enforceInternalState","TEMPLATE","options","unsafe","simple","noTargetGet","source","join","prototype","aFunction","variable","namespace","method","arguments","length","path","ceil","floor","argument","isNaN","min","toInteger","max","index","integer","createMethod","IS_INCLUDES","$this","el","fromIndex","toLength","toAbsoluteIndex","indexOf","includes","names","i","result","enumBugKeys","concat","getOwnPropertyNames","internalObjectKeys","getOwnPropertySymbols","getBuiltIn","ownKeys","getOwnPropertyNamesModule","getOwnPropertySymbolsModule","target","getOwnPropertyDescriptorModule","replacement","isForced","feature","detection","data","normalize","POLYFILL","NATIVE","string","replace","toLowerCase","require$$0","targetProperty","sourceProperty","TARGET","GLOBAL","STATIC","stat","forced","copyConstructorProperties","sham","redefine","Symbol","NATIVE_SYMBOL","iterator","WellKnownSymbolsStore","createWellKnownSymbol","USE_SYMBOL_AS_UID","withoutSetter","name","defineProperties","Properties","objectKeys","IE_PROTO","EmptyConstructor","scriptTag","content","LT","NullProtoObject","domain","ActiveXObject","iframeDocument","iframe","write","close","temp","parentWindow","NullProtoObjectViaActiveX","documentCreateElement","style","display","html","appendChild","src","contentWindow","open","F","create","UNSCOPABLES","wellKnownSymbol","ArrayPrototype","Array","$","proto","fill","toObject","argumentsLength","end","endPos","addToUnscopables","match","that","b","c","apply","isArray","arg","SPECIES","originalArray","C","constructor","IS_MAP","IS_FILTER","IS_SOME","IS_EVERY","IS_FIND_INDEX","NO_HOLES","callbackfn","specificCreate","boundFunction","bind","arraySpeciesCreate","forEach","map","filter","some","every","find","findIndex","process","versions","v8","userAgent","METHOD_NAME","V8_VERSION","array","foo","Boolean","cache","thrower","ACCESSORS","argument0","argument1","$map","HAS_SPECIES_SUPPORT","arrayMethodHasSpeciesSupport","USES_TO_LENGTH","arrayMethodUsesToLength","FunctionPrototype","FunctionPrototypeToString","nameRE","nativeAssign","assign","A","B","symbol","alphabet","chr","T","S","j","TO_STRING_TAG","CORRECT_ARGUMENTS","classofRaw","TO_STRING_TAG_SUPPORT","tag","tryGet","callee","Promise","TAG","ITERATOR","ENTRIES","returnMethod","Result","stopped","iterable","AS_ENTRIES","IS_ITERATOR","iterFn","next","step","Iterators","getIteratorMethod","done","callWithSafeIterationClosing","stop","SAFE_CLOSING","called","iteratorWithReturn","return","from","defer","channel","port","location","setImmediate","clear","clearImmediate","MessageChannel","Dispatch","counter","queue","run","runner","listener","event","post","postMessage","protocol","host","args","nextTick","now","IS_IOS","port2","port1","onmessage","addEventListener","importScripts","removeChild","setTimeout","flush","head","last","notify","toggle","node","promise","then","macrotask","require$$1","MutationObserver","WebKitMutationObserver","IS_NODE","queueMicrotaskDescriptor","queueMicrotask","parent","exit","enter","createTextNode","observe","characterData","resolve","Internal","OwnPromiseCapability","PromiseWrapper","nativeThen","task","PromiseCapability","reject","$$resolve","$$reject","x","promiseCapability","newPromiseCapability","PROMISE","setInternalState","getInternalPromiseState","PromiseConstructor","NativePromise","$fetch","newPromiseCapabilityModule","newGenericPromiseCapability","DISPATCH_EVENT","createEvent","dispatchEvent","FORCED","PromiseRejectionEvent","FakePromise","INCORRECT_ITERATION","SKIP_CLOSING","ITERATION_SUPPORT","checkCorrectnessOfIteration","all","isThenable","isReject","notified","chain","reactions","microtask","ok","exited","reaction","handler","fail","rejection","onHandleUnhandled","onUnhandled","reason","initEvent","console","hostReportErrors","isUnhandled","perform","emit","unwrap","internalReject","internalResolve","wrapper","executor","Constructor","anInstance","redefineAll","onFulfilled","onRejected","defaultConstructor","catch","fetch","promiseResolve","wrap","setToStringTag","CONSTRUCTOR_NAME","setSpecies","r","capability","$promiseResolve","values","remaining","iterate","alreadyCalled","race","nativeGetOwnPropertyNames","windowNames","getWindowNames","NAME","wrappedWellKnownSymbolModule","$forEach","HIDDEN","TO_PRIMITIVE","ObjectPrototype","$Symbol","$stringify","getOwnPropertyNamesExternal","AllSymbols","ObjectPrototypeSymbols","StringToSymbolRegistry","SymbolToStringRegistry","QObject","USE_SETTER","findChild","setSymbolDescriptor","nativeObjectCreate","ObjectPrototypeDescriptor","description","isSymbol","$defineProperty","$defineProperties","properties","$getOwnPropertySymbols","$propertyIsEnumerable","$getOwnPropertyDescriptor","$getOwnPropertyNames","IS_OBJECT_PROTOTYPE","setter","defineWellKnownSymbol","for","keyFor","sym","useSetter","useSimple","FORCED_JSON_STRINGIFY","stringify","replacer","space","$replacer","NativeSymbol","EmptyStringDescriptionStore","SymbolWrapper","symbolPrototype","symbolToString","native","regexp","desc","STRICT_METHOD","arrayMethodIsStrict","IteratorPrototype","PrototypeOfArrayIteratorPrototype","arrayIterator","getPrototypeOf","CORRECT_PROTOTYPE_GETTER","BUGGY_SAFARI_ITERATORS","returnThis","setPrototypeOf","CORRECT_SETTER","aPossiblePrototype","__proto__","IteratorsCore","Iterable","IteratorConstructor","DEFAULT","IS_SET","createIteratorConstructor","CurrentIteratorPrototype","methods","KEY","getIterationMethod","KIND","defaultIterator","IterablePrototype","entries","INCORRECT_VALUES_NAME","nativeIterator","anyNativeIterator","defineIterator","iterated","kind","Arguments","nativeReverse","reverse","0","nativeSlice","start","n","propertyKey","k","fin","DatePrototype","Date","nativeDateToString","getTime","NaN","JSON","objectDefinePropertyModile","FAILS_ON_PRIMITIVES","nativeGetPrototypeOf","ignoreCase","multiline","dotAll","unicode","sticky","RegExpPrototype","RegExp","nativeToString","NOT_GENERIC","flags","INCORRECT_NAME","R","p","rf","CONVERT_TO_STRING","pos","first","second","position","size","charCodeAt","charAt","codeAt","point","CSSRuleList","CSSStyleDeclaration","CSSValueList","ClientRectList","DOMRectList","DOMStringList","DOMTokenList","DataTransferItemList","FileList","HTMLAllCollection","HTMLCollection","HTMLFormElement","HTMLSelectElement","MediaList","MimeTypeArray","NamedNodeMap","NodeList","PaintRequestList","Plugin","PluginArray","SVGLengthList","SVGNumberList","SVGPathSegList","SVGPointList","SVGStringList","SVGTransformList","SourceBufferList","StyleSheetList","TextTrackCueList","TextTrackList","TouchList","COLLECTION_NAME","DOMIterables","Collection","CollectionPrototype","ArrayValues","ArrayIteratorMethods","runtime","exports","Op","hasOwn","iteratorSymbol","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","obj","err","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","context","Context","_invoke","makeInvokeMethod","GenStateSuspendedStart","invoke","GenStateExecuting","Error","GenStateCompleted","doneResult","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","GenStateSuspendedYield","GeneratorFunction","GeneratorFunctionPrototype","getProto","NativeIteratorPrototype","Gp","defineIteratorMethods","AsyncIterator","PromiseImpl","previousPromise","enqueue","callInvokeWithMethodAndArg","_typeof","__await","unwrapped","info","resultName","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","iteratorMethod","displayName","isGeneratorFunction","genFun","ctor","mark","awrap","async","iter","pop","skipTempReset","prev","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","regeneratorRuntime","accidentalStrictMode","loadExtensionTranslation","lang","__variableDynamicImportRuntime0__","translationModule","init","showPanel","setAttr","cot","sec","cos","tan","attr","svgCanvas","changeSelectedAttribute","selElems","on","fcRules","appendTo","text","svgEditor","_this","canvas","curPrefs","strings","buttons","icon","events","click","setMode","contextTools","panel","defval","change","svgicons","button","context_tools","contextTool","callback","hide","clone","unbind","mouseDown","opts","getMode","rgb","getColor","sRgb","sWidth","getStrokeWidth","started","newFO","addSVGElementFromJson","element","cx","start_x","cy","start_y","getNextId","shape","sides","getElementById","orient","edge","strokecolor","strokeWidth","mouseMove","mouse_x","y","mouse_y","edg","sqrt","setAttribute","circumradius","PI","points","s","angle","sin","mouseUp","keep","selectedChanged","elems","elem","getAttribute","selectedElement","multiselected","elementChanged","title","label"],"mappings":"oZAAA,IAAIA,MAAQ,SAAUC,GACpB,OAAOA,GAAMA,EAAGC,MAAQA,MAAQD,KAMhCD,MAA2B,iBAAdG,YAA0BA,aACvCH,MAAuB,iBAAVI,QAAsBA,SACnCJ,MAAqB,iBAARK,MAAoBA,OACjCL,MAAuB,iBAAVM,GAAsBA,IAEnCC,SAAS,cAATA,SCZe,SAAUC,GACzB,IACE,QAASA,IACT,MAAOC,GACP,OAAO,OCDOC,OAAM,WACtB,OAA8E,GAAvEC,OAAOC,eAAe,GAAI,EAAG,CAAEC,IAAK,WAAc,OAAO,KAAQ,MCHtEC,EAA6B,GAAGC,qBAChCC,EAA2BL,OAAOK,8BAGpBA,IAA6BF,EAA2BG,KAAK,CAAEC,EAAG,GAAK,GAI/D,SAASH,qBAAqBI,GACtD,IAAIC,EAAaJ,EAAyBK,KAAMF,GAChD,QAASC,GAAcA,EAAWE,YAChCR,4BCZa,SAAUS,EAAQC,GACjC,MAAO,CACLF,aAAuB,EAATC,GACdE,eAAyB,EAATF,GAChBG,WAAqB,EAATH,GACZC,MAAOA,ICLPG,EAAW,GAAGA,oBAED,SAAU1B,GACzB,OAAO0B,EAASV,KAAKhB,GAAI2B,MAAM,GAAI,ICAjCC,EAAQ,GAAGA,QAGEnB,OAAM,WAGrB,OAAQC,OAAO,KAAKI,qBAAqB,MACtC,SAAUd,GACb,MAAsB,UAAf6B,WAAQ7B,GAAkB4B,EAAMZ,KAAKhB,EAAI,IAAMU,OAAOV,IAC3DU,8BCVa,SAAUV,GACzB,GAAU8B,MAAN9B,EAAiB,MAAM+B,UAAU,wBAA0B/B,GAC/D,OAAOA,mBCAQ,SAAUA,GACzB,OAAOgC,EAAcC,uBAAuBjC,cCL7B,SAAUA,GACzB,MAAqB,iBAAPA,EAAyB,OAAPA,EAA4B,mBAAPA,eCKtC,SAAUkC,EAAOC,GAChC,IAAKC,SAASF,GAAQ,OAAOA,EAC7B,IAAIG,EAAIC,EACR,GAAIH,GAAoD,mBAAxBE,EAAKH,EAAMR,YAA4BU,SAASE,EAAMD,EAAGrB,KAAKkB,IAAS,OAAOI,EAC9G,GAAmC,mBAAvBD,EAAKH,EAAMK,WAA2BH,SAASE,EAAMD,EAAGrB,KAAKkB,IAAS,OAAOI,EACzF,IAAKH,GAAoD,mBAAxBE,EAAKH,EAAMR,YAA4BU,SAASE,EAAMD,EAAGrB,KAAKkB,IAAS,OAAOI,EAC/G,MAAMP,UAAU,4CCZdS,EAAiB,GAAGA,mBAEP,SAAUxC,EAAIyC,GAC7B,OAAOD,EAAexB,KAAKhB,EAAIyC,ICA7BC,EAAWrC,EAAOqC,SAElBC,EAASP,SAASM,IAAaN,SAASM,EAASE,qCAEpC,SAAU5C,GACzB,OAAO2C,EAASD,EAASE,cAAc5C,GAAM,OCH7B6C,IAAgBpC,OAAM,WACtC,OAEQ,GAFDC,OAAOC,eAAeiC,sBAAc,OAAQ,IAAK,CACtDhC,IAAK,WAAc,OAAO,KACzBkC,KCADC,EAAiCrC,OAAOK,8BAIhC8B,EAAcE,EAAiC,SAAShC,yBAAyBiC,EAAGC,GAG9F,GAFAD,EAAIE,gBAAgBF,GACpBC,EAAIE,YAAYF,GAAG,GACfG,EAAgB,IAClB,OAAOL,EAA+BC,EAAGC,GACzC,MAAOzC,IACT,GAAI6C,IAAIL,EAAGC,GAAI,OAAOK,0BAA0BC,EAA2BC,EAAExC,KAAKgC,EAAGC,GAAID,EAAEC,eChB5E,SAAUjD,GACzB,IAAKoC,SAASpC,GACZ,MAAM+B,UAAU0B,OAAOzD,GAAM,qBAC7B,OAAOA,GCAP0D,EAAuBhD,OAAOC,oBAItBkC,EAAca,EAAuB,SAAS/C,eAAeqC,EAAGC,EAAGU,GAI7E,GAHAC,SAASZ,GACTC,EAAIE,YAAYF,GAAG,GACnBW,SAASD,GACLP,EAAgB,IAClB,OAAOM,EAAqBV,EAAGC,EAAGU,GAClC,MAAOnD,IACT,GAAI,QAASmD,GAAc,QAASA,EAAY,MAAM5B,UAAU,2BAEhE,MADI,UAAW4B,IAAYX,EAAEC,GAAKU,EAAWpC,OACtCyB,MCdQH,EAAc,SAAUgB,EAAQpB,EAAKlB,GACpD,OAAOuC,EAAqBN,EAAEK,EAAQpB,EAAKa,yBAAyB,EAAG/B,KACrE,SAAUsC,EAAQpB,EAAKlB,GAEzB,OADAsC,EAAOpB,GAAOlB,EACPsC,aCLQ,SAAUpB,EAAKlB,GAC9B,IACEwC,EAA4B1D,EAAQoC,EAAKlB,GACzC,MAAOf,GACPH,EAAOoC,GAAOlB,EACd,OAAOA,KCJClB,EADC,uBACiB2D,UADjB,qBACmC,ICF5CC,EAAmB3D,SAASoB,SAGE,mBAAvBwC,EAAMC,gBACfD,EAAMC,cAAgB,SAAUnE,GAC9B,OAAOiE,EAAiBjD,KAAKhB,KAIjC,ICFIoE,EAAKxD,EAAKyC,IDEGa,EAAMC,cERnBE,EAAUhE,EAAOgE,UAEe,mBAAZA,GAA0B,cAAcC,KAAKH,EAAcE,yCCFlFE,UAAiB,SAAU9B,EAAKlB,GAC/B,OAAO2C,EAAMzB,KAASyB,EAAMzB,QAAiBX,IAAVP,EAAsBA,EAAQ,MAChE,WAAY,IAAIiD,KAAK,CACtBC,QAAS,QACTC,KAAyB,SACzBC,UAAW,4CCRTC,EAAK,EACLC,EAAU5E,KAAK6E,aAEF,SAAUrC,GACzB,MAAO,UAAYgB,YAAe3B,IAARW,EAAoB,GAAKA,GAAO,QAAUmC,EAAKC,GAASnD,SAAS,KCDzFqD,EAAOC,EAAO,kBAED,SAAUvC,GACzB,OAAOsC,EAAKtC,KAASsC,EAAKtC,GAAOwC,IAAIxC,OCNtB,GLQb4B,EAAUhE,EAAOgE,QAgBrB,GAAIa,EAAiB,CACnB,IAAIhB,EAAQ,IAAIG,EACZc,EAAQjB,EAAMtD,IACdwE,EAAQlB,EAAMb,IACdgC,EAAQnB,EAAME,IAClBA,EAAM,SAAUpE,EAAIsF,GAElB,OADAD,EAAMrE,KAAKkD,EAAOlE,EAAIsF,GACfA,GAET1E,EAAM,SAAUZ,GACd,OAAOmF,EAAMnE,KAAKkD,EAAOlE,IAAO,IAElCqD,EAAM,SAAUrD,GACd,OAAOoF,EAAMpE,KAAKkD,EAAOlE,QAEtB,CACL,IAAIuF,EAAQC,UAAU,SACtBC,EAAWF,IAAS,EACpBnB,EAAM,SAAUpE,EAAIsF,GAElB,OADAvB,EAA4B/D,EAAIuF,EAAOD,GAChCA,GAET1E,EAAM,SAAUZ,GACd,OAAO0F,IAAU1F,EAAIuF,GAASvF,EAAGuF,GAAS,IAE5ClC,EAAM,SAAUrD,GACd,OAAO0F,IAAU1F,EAAIuF,IAIzB,IMHII,INGa,CACfvB,IAAKA,EACLxD,IAAKA,EACLyC,IAAKA,EACLuC,QA/CY,SAAU5F,GACtB,OAAOqD,EAAIrD,GAAMY,EAAIZ,GAAMoE,EAAIpE,EAAI,KA+CnC6F,UA5Cc,SAAUC,GACxB,OAAO,SAAU9F,GACf,IAAI+F,EACJ,IAAK3D,SAASpC,KAAQ+F,EAAQnF,EAAIZ,IAAKgG,OAASF,EAC9C,MAAM/D,UAAU,0BAA4B+D,EAAO,aACnD,OAAOC,yCObb,IAAIE,EAAmBC,EAAoBtF,IACvCuF,EAAuBD,EAAoBN,QAC3CQ,EAAW3C,OAAOA,QAAQ7B,MAAM,WAEnC2C,UAAiB,SAAUvB,EAAGP,EAAKlB,EAAO8E,GACzC,IAAIC,IAASD,KAAYA,EAAQC,OAC7BC,IAASF,KAAYA,EAAQhF,WAC7BmF,IAAcH,KAAYA,EAAQG,YAClB,mBAATjF,IACS,iBAAPkB,GAAoBY,IAAI9B,EAAO,SAASwC,EAA4BxC,EAAO,OAAQkB,GAC9F0D,EAAqB5E,GAAOkF,OAASL,EAASM,KAAmB,iBAAPjE,EAAkBA,EAAM,KAEhFO,IAAM3C,GAIEiG,GAEAE,GAAexD,EAAEP,KAC3B8D,GAAS,UAFFvD,EAAEP,GAIP8D,EAAQvD,EAAEP,GAAOlB,EAChBwC,EAA4Bf,EAAGP,EAAKlB,IATnCgF,EAAQvD,EAAEP,GAAOlB,EAChByC,UAAUvB,EAAKlB,KAUrBjB,SAASqG,UAAW,YAAY,SAASjF,WAC1C,MAAsB,mBAARN,MAAsB6E,EAAiB7E,MAAMqF,QAAUtC,EAAc/C,cC9BpEf,ECCbuG,UAAY,SAAUC,GACxB,MAA0B,mBAAZA,EAAyBA,OAAW/E,cAGnC,SAAUgF,EAAWC,GACpC,OAAOC,UAAUC,OAAS,EAAIL,UAAUM,EAAKJ,KAAeF,UAAUvG,EAAOyG,IACzEI,EAAKJ,IAAcI,EAAKJ,GAAWC,IAAW1G,EAAOyG,IAAczG,EAAOyG,GAAWC,ICTvFI,EAAOlH,KAAKkH,KACZC,EAAQnH,KAAKmH,gBAIA,SAAUC,GACzB,OAAOC,MAAMD,GAAYA,GAAY,GAAKA,EAAW,EAAID,EAAQD,GAAME,ICJrEE,EAAMtH,KAAKsH,aAIE,SAAUF,GACzB,OAAOA,EAAW,EAAIE,EAAIC,UAAUH,GAAW,kBAAoB,GCLjEI,EAAMxH,KAAKwH,IACXF,EAAMtH,KAAKsH,oBAKE,SAAUG,EAAOT,GAChC,IAAIU,EAAUH,UAAUE,GACxB,OAAOC,EAAU,EAAIF,EAAIE,EAAUV,EAAQ,GAAKM,EAAII,EAASV,ICL3DW,aAAe,SAAUC,GAC3B,OAAO,SAAUC,EAAOC,EAAIC,GAC1B,IAGIzG,EAHAyB,EAAIE,gBAAgB4E,GACpBb,EAASgB,SAASjF,EAAEiE,QACpBS,EAAQQ,gBAAgBF,EAAWf,GAIvC,GAAIY,GAAeE,GAAMA,GAAI,KAAOd,EAASS,GAG3C,IAFAnG,EAAQyB,EAAE0E,OAEGnG,EAAO,OAAO,OAEtB,KAAM0F,EAASS,EAAOA,IAC3B,IAAKG,GAAeH,KAAS1E,IAAMA,EAAE0E,KAAWK,EAAI,OAAOF,GAAeH,GAAS,EACnF,OAAQG,IAAgB,IClB1BM,EDsBa,CAGfC,SAAUR,cAAa,GAGvBO,QAASP,cAAa,IC5B6BO,2BAGpC,SAAUtE,EAAQwE,GACjC,IAGI5F,EAHAO,EAAIE,gBAAgBW,GACpByE,EAAI,EACJC,EAAS,GAEb,IAAK9F,KAAOO,GAAIK,IAAIoC,EAAYhD,IAAQY,IAAIL,EAAGP,IAAQ8F,EAAO/D,KAAK/B,GAEnE,KAAO4F,EAAMpB,OAASqB,GAAOjF,IAAIL,EAAGP,EAAM4F,EAAMC,SAC7CH,EAAQI,EAAQ9F,IAAQ8F,EAAO/D,KAAK/B,IAEvC,OAAO8F,KCdQ,CACf,cACA,iBACA,gBACA,uBACA,iBACA,WACA,WCLE9C,EAAa+C,EAAYC,OAAO,SAAU,kBAIlC/H,OAAOgI,qBAAuB,SAASA,oBAAoB1F,GACrE,OAAO2F,mBAAmB3F,EAAGyC,UCRnB/E,OAAOkI,yBCMFC,WAAW,UAAW,YAAc,SAASC,QAAQ9I,GACpE,IAAI+E,EAAOgE,EAA0BvF,EAAEI,SAAS5D,IAC5C4I,EAAwBI,EAA4BxF,EACxD,OAAOoF,EAAwB7D,EAAK0D,OAAOG,EAAsB5I,IAAO+E,6BCJzD,SAAUkE,EAAQxC,GAIjC,IAHA,IAAI1B,EAAO+D,EAAQrC,GACf9F,EAAiBmD,EAAqBN,EACtCzC,EAA2BmI,EAA+B1F,EACrD8E,EAAI,EAAGA,EAAIvD,EAAKkC,OAAQqB,IAAK,CACpC,IAAI7F,EAAMsC,EAAKuD,GACVjF,IAAI4F,EAAQxG,IAAM9B,EAAesI,EAAQxG,EAAK1B,EAAyB0F,EAAQhE,MCTpF0G,EAAc,kBAEdC,SAAW,SAAUC,EAASC,GAChC,IAAI/H,EAAQgI,GAAKC,GAAUH,IAC3B,OAAO9H,GAASkI,IACZlI,GAASmI,KACW,mBAAbJ,EAA0B7I,MAAM6I,KACrCA,IAGJE,GAAYJ,SAASI,UAAY,SAAUG,GAC7C,OAAOlG,OAAOkG,GAAQC,QAAQT,EAAa,KAAKU,eAG9CN,GAAOH,SAASG,KAAO,GACvBG,GAASN,SAASM,OAAS,IAC3BD,GAAWL,SAASK,SAAW,OAElBL,SCnBbrI,GAA2B+I,EAA2DtG,UAqBzE,SAAU6C,EAASI,GAClC,IAGYwC,EAAQxG,EAAKsH,EAAgBC,EAAgB7I,EAHrD8I,EAAS5D,EAAQ4C,OACjBiB,EAAS7D,EAAQhG,OACjB8J,EAAS9D,EAAQ+D,KASrB,GANEnB,EADEiB,EACO7J,EACA8J,EACA9J,EAAO4J,IAAWjG,UAAUiG,EAAQ,KAEnC5J,EAAO4J,IAAW,IAAItD,UAEtB,IAAKlE,KAAOgE,EAAQ,CAQ9B,GAPAuD,EAAiBvD,EAAOhE,GAGtBsH,EAFE1D,EAAQG,aACVrF,EAAaJ,GAAyBkI,EAAQxG,KACftB,EAAWI,MACpB0H,EAAOxG,IACtB2G,GAASc,EAASzH,EAAMwH,GAAUE,EAAS,IAAM,KAAO1H,EAAK4D,EAAQgE,cAE5CvI,IAAnBiI,EAA8B,CAC3C,UAAWC,UAA0BD,EAAgB,SACrDO,0BAA0BN,EAAgBD,IAGxC1D,EAAQkE,MAASR,GAAkBA,EAAeQ,OACpDxG,EAA4BiG,EAAgB,QAAQ,GAGtDQ,EAASvB,EAAQxG,EAAKuH,EAAgB3D,cC/CzB,SAAUgB,GACzB,OAAO3G,OAAOuB,uBAAuBoF,UCHpB3G,OAAOkI,wBAA0BnI,OAAM,WAGxD,OAAQgD,OAAOgH,gBCHAC,KAEXD,OAAOF,MAEkB,iBAAnBE,OAAOE,SCCfC,GAAwB5F,EAAO,OAC/ByF,GAASpK,EAAOoK,OAChBI,GAAwBC,GAAoBL,GAASA,IAAUA,GAAOM,eAAiB9F,oBAE1E,SAAU+F,GAIvB,OAHG3H,IAAIuH,GAAuBI,KAC1BN,IAAiBrH,IAAIoH,GAAQO,GAAOJ,GAAsBI,GAAQP,GAAOO,GACxEJ,GAAsBI,GAAQH,GAAsB,UAAYG,IAC9DJ,GAAsBI,OCVhBtK,OAAOqE,MAAQ,SAASA,KAAK/B,GAC5C,OAAO2F,mBAAmB3F,EAAGwF,OCCd3F,EAAcnC,OAAOuK,iBAAmB,SAASA,iBAAiBjI,EAAGkI,GACpFtH,SAASZ,GAKT,IAJA,IAGIP,EAHAsC,EAAOoG,GAAWD,GAClBjE,EAASlC,EAAKkC,OACdS,EAAQ,EAELT,EAASS,GAAO5D,EAAqBN,EAAER,EAAGP,EAAMsC,EAAK2C,KAAUwD,EAAWzI,IACjF,OAAOO,MCZQ6F,WAAW,WAAY,mBtBUpCuC,GAAW5F,UAAU,YAErB6F,iBAAmB,aAEnBC,UAAY,SAAUC,GACxB,MAAOC,WAAmBD,EAAnBC,cAmCLC,gBAAkB,WACpB,IAEE9F,EAAkBjD,SAASgJ,QAAU,IAAIC,cAAc,YACvD,MAAOnL,IA1BoB,IAIzBoL,EAFAC,EAyBJJ,gBAAkB9F,EApCY,SAAUA,GACxCA,EAAgBmG,MAAMR,UAAU,KAChC3F,EAAgBoG,QAChB,IAAIC,EAAOrG,EAAgBsG,aAAavL,OAExC,OADAiF,EAAkB,KACXqG,EA+B6BE,CAA0BvG,KAzB1DkG,EAASM,sBAAsB,WAG5BC,MAAMC,QAAU,OACvBC,GAAKC,YAAYV,GAEjBA,EAAOW,IAAM/I,OALJ,gBAMTmI,EAAiBC,EAAOY,cAAc/J,UACvBgK,OACfd,EAAeE,MAAMR,UAAU,sBAC/BM,EAAeG,QACRH,EAAee,GAgBtB,IADA,IAAI1F,EAASuB,EAAYvB,OAClBA,YAAiBwE,gBAAyB,UAAEjD,EAAYvB,IAC/D,OAAOwE,mBAGThG,EAAW2F,KAAY,EAIvB,OAAiB1K,OAAOkM,QAAU,SAASA,OAAO5J,EAAGkI,GACnD,IAAI3C,EAQJ,OAPU,OAANvF,GACFqI,iBAA0B,UAAIzH,SAASZ,GACvCuF,EAAS,IAAI8C,iBACbA,iBAA0B,UAAI,KAE9B9C,EAAO6C,IAAYpI,GACduF,EAASkD,uBACM3J,IAAfoJ,EAA2B3C,EAAS0C,GAAiB1C,EAAQ2C,IuBxElE2B,GAAcC,gBAAgB,eAC9BC,GAAiBC,MAAMrG,UAIQ7E,MAA/BiL,GAAeF,KACjB/I,EAAqBN,EAAEuJ,GAAgBF,GAAa,CAClDrL,cAAc,EACdD,MAAOqL,GAAO,QAKlB,qBAAiB,SAAUnK,GACzBsK,GAAeF,IAAapK,IAAO,GCZrCwK,QAAE,CAAEhE,OAAQ,QAASiE,OAAO,GAAQ,CAClCC,KCAe,SAASA,KAAK5L,GAO7B,IANA,IAAIyB,EAAIoK,SAAShM,MACb6F,EAASgB,SAASjF,EAAEiE,QACpBoG,EAAkBrG,UAAUC,OAC5BS,EAAQQ,gBAAgBmF,EAAkB,EAAIrG,UAAU,QAAKlF,EAAWmF,GACxEqG,EAAMD,EAAkB,EAAIrG,UAAU,QAAKlF,EAC3CyL,OAAiBzL,IAARwL,EAAoBrG,EAASiB,gBAAgBoF,EAAKrG,GACxDsG,EAAS7F,GAAO1E,EAAE0E,KAAWnG,EACpC,OAAOyB,KDJTwK,iBAAiB,QEXjB,ICMIC,GAAOhJ,eDNM,SAAUzE,GACzB,GAAiB,mBAANA,EACT,MAAM+B,UAAU0B,OAAOzD,GAAM,sBAC7B,OAAOA,uBEAM,SAAUqC,EAAIqL,EAAMzG,GAEnC,GADAL,YAAUvE,QACGP,IAAT4L,EAAoB,OAAOrL,EAC/B,OAAQ4E,GACN,KAAK,EAAG,OAAO,WACb,OAAO5E,EAAGrB,KAAK0M,IAEjB,KAAK,EAAG,OAAO,SAAU5K,GACvB,OAAOT,EAAGrB,KAAK0M,EAAM5K,IAEvB,KAAK,EAAG,OAAO,SAAUA,EAAG6K,GAC1B,OAAOtL,EAAGrB,KAAK0M,EAAM5K,EAAG6K,IAE1B,KAAK,EAAG,OAAO,SAAU7K,EAAG6K,EAAGC,GAC7B,OAAOvL,EAAGrB,KAAK0M,EAAM5K,EAAG6K,EAAGC,IAG/B,OAAO,WACL,OAAOvL,EAAGwL,MAAMH,EAAM1G,gBCjBTgG,MAAMc,SAAW,SAASA,QAAQC,GACjD,MAAuB,SAAhBlM,WAAQkM,ICDbC,GAAUlB,gBAAgB,8BAIb,SAAUmB,EAAehH,GACxC,IAAIiH,EASF,OAREJ,GAAQG,KAGM,mBAFhBC,EAAID,EAAcE,cAEaD,IAAMlB,QAASc,GAAQI,EAAEvH,WAC/CvE,SAAS8L,IAEN,QADVA,EAAIA,EAAEF,OACUE,OAAIpM,GAH+CoM,OAAIpM,GAKlE,SAAWA,IAANoM,EAAkBlB,MAAQkB,GAAc,IAAXjH,EAAe,EAAIA,ICZ5DzC,GAAO,GAAGA,KAGVoD,eAAe,SAAU9B,GAC3B,IAAIsI,EAAiB,GAARtI,EACTuI,EAAoB,GAARvI,EACZwI,EAAkB,GAARxI,EACVyI,EAAmB,GAARzI,EACX0I,EAAwB,GAAR1I,EAChB2I,EAAmB,GAAR3I,GAAa0I,EAC5B,OAAO,SAAU1G,EAAO4G,EAAYhB,EAAMiB,GASxC,IARA,IAOIpN,EAAOgH,EAPPvF,EAAIoK,SAAStF,GACb1H,EAAO4B,EAAcgB,GACrB4L,EAAgBC,oBAAKH,EAAYhB,EAAM,GACvCzG,EAASgB,SAAS7H,EAAK6G,QACvBS,EAAQ,EACRkF,EAAS+B,GAAkBG,mBAC3B7F,EAASmF,EAASxB,EAAO9E,EAAOb,GAAUoH,EAAYzB,EAAO9E,EAAO,QAAKhG,EAEvEmF,EAASS,EAAOA,IAAS,IAAI+G,GAAY/G,KAAStH,KAEtDmI,EAASqG,EADTrN,EAAQnB,EAAKsH,GACiBA,EAAO1E,GACjC8C,GACF,GAAIsI,EAAQnF,EAAOvB,GAASa,OACvB,GAAIA,EAAQ,OAAQzC,GACvB,KAAK,EAAG,OAAO,EACf,KAAK,EAAG,OAAOvE,EACf,KAAK,EAAG,OAAOmG,EACf,KAAK,EAAGlD,GAAKxD,KAAKiI,EAAQ1H,QACrB,GAAIgN,EAAU,OAAO,EAGhC,OAAOC,GAAiB,EAAIF,GAAWC,EAAWA,EAAWtF,OAIhD,CAGf8F,QAASnH,eAAa,GAGtBoH,IAAKpH,eAAa,GAGlBqH,OAAQrH,eAAa,GAGrBsH,KAAMtH,eAAa,GAGnBuH,MAAOvH,eAAa,GAGpBwH,KAAMxH,eAAa,GAGnByH,UAAWzH,eAAa,OC7DTiB,WAAW,YAAa,cAAgB,GLCrDyG,GAAUjP,EAAOiP,QACjBC,GAAWD,IAAWA,GAAQC,SAC9BC,GAAKD,IAAYA,GAASC,GAG1BA,GAEF/K,IADAgJ,GAAQ+B,GAAG5N,MAAM,MACD,GAAK6L,GAAM,GAClBgC,OACThC,GAAQgC,GAAUhC,MAAM,iBACVA,GAAM,IAAM,MACxBA,GAAQgC,GAAUhC,MAAM,oBACbhJ,GAAUgJ,GAAM,IAI/B,OAAiBhJ,KAAYA,GMfzBuJ,GAAUlB,gBAAgB,wCAEb,SAAU4C,GAIzB,OAAOC,IAAc,KAAOlP,OAAM,WAChC,IAAImP,EAAQ,GAKZ,OAJkBA,EAAMzB,YAAc,IAC1BH,IAAW,WACrB,MAAO,CAAE6B,IAAK,IAE2B,IAApCD,EAAMF,GAAaI,SAASD,QCZnClP,GAAiBD,OAAOC,eACxBoP,GAAQ,GAERC,QAAU,SAAUhQ,GAAM,MAAMA,2BAEnB,SAAU0P,EAAarJ,GACtC,GAAIhD,IAAI0M,GAAOL,GAAc,OAAOK,GAAML,GACrCrJ,IAASA,EAAU,IACxB,IAAIU,EAAS,GAAG2I,GACZO,IAAY5M,IAAIgD,EAAS,cAAeA,EAAQ4J,UAChDC,EAAY7M,IAAIgD,EAAS,GAAKA,EAAQ,GAAK2J,QAC3CG,EAAY9M,IAAIgD,EAAS,GAAKA,EAAQ,QAAKvE,EAE/C,OAAOiO,GAAML,KAAiB3I,IAAWtG,OAAM,WAC7C,GAAIwP,IAAcpN,EAAa,OAAO,EACtC,IAAIG,EAAI,CAAEiE,QAAS,GAEfgJ,EAAWtP,GAAeqC,EAAG,EAAG,CAAE3B,YAAY,EAAMT,IAAKoP,UACxDhN,EAAE,GAAK,EAEZ+D,EAAO/F,KAAKgC,EAAGkN,EAAWC,OCtB1BC,GAAOtG,GAAwCkF,IAI/CqB,GAAsBC,6BAA6B,OAEnDC,GAAiBC,wBAAwB,OAK7CvD,QAAE,CAAEhE,OAAQ,QAASiE,OAAO,EAAM7C,QAASgG,KAAwBE,IAAkB,CACnFvB,IAAK,SAASA,IAAIN,GAChB,OAAO0B,GAAKhP,KAAMsN,EAAY1H,UAAUC,OAAS,EAAID,UAAU,QAAKlF,MCdxE,IAAInB,GAAiBmJ,EAA+CtG,EAEhEiN,GAAoBnQ,SAASqG,UAC7B+J,GAA4BD,GAAkB/O,SAC9CiP,GAAS,wBAKT9N,KAJO,SAIkB4N,KAC3B9P,GAAe8P,GALN,OAK+B,CACtCjP,cAAc,EACdZ,IAAK,WACH,IACE,OAAO8P,GAA0B1P,KAAKI,MAAMqM,MAAMkD,IAAQ,GAC1D,MAAOnQ,GACP,MAAO,OCRf,IAAIoQ,GAAelQ,OAAOmQ,OACtBlQ,GAAiBD,OAAOC,mBAIViQ,IAAgBnQ,OAAM,WAEtC,GAAIoC,GAQiB,IARF+N,GAAa,CAAEjD,EAAG,GAAKiD,GAAajQ,GAAe,GAAI,IAAK,CAC7EU,YAAY,EACZT,IAAK,WACHD,GAAeS,KAAM,IAAK,CACxBG,MAAO,EACPF,YAAY,OAGd,CAAEsM,EAAG,KAAMA,EAAS,OAAO,EAE/B,IAAImD,EAAI,GACJC,EAAI,GAEJC,EAASvG,SACTwG,EAAW,uBAGf,OAFAH,EAAEE,GAAU,EACZC,EAASrP,MAAM,IAAImN,SAAQ,SAAUmC,GAAOH,EAAEG,GAAOA,KACf,GAA/BN,GAAa,GAAIE,GAAGE,IAAgB7F,GAAWyF,GAAa,GAAIG,IAAIrK,KAAK,KAAOuK,KACpF,SAASJ,OAAO5H,EAAQxC,GAM3B,IALA,IAAI0K,EAAI/D,SAASnE,GACboE,EAAkBrG,UAAUC,OAC5BS,EAAQ,EACRkB,EAAwBI,EAA4BxF,EACpD1C,EAAuByC,EAA2BC,EAC/C6J,EAAkB3F,GAMvB,IALA,IAIIjF,EAJA2O,EAAIpP,EAAcgF,UAAUU,MAC5B3C,EAAO6D,EAAwBuC,GAAWiG,GAAG3I,OAAOG,EAAsBwI,IAAMjG,GAAWiG,GAC3FnK,EAASlC,EAAKkC,OACdoK,EAAI,EAEDpK,EAASoK,GACd5O,EAAMsC,EAAKsM,KACNxO,IAAe/B,EAAqBE,KAAKoQ,EAAG3O,KAAM0O,EAAE1O,GAAO2O,EAAE3O,IAEpE,OAAO0O,GACPP,GC9CJ3D,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,EAAMC,OAAQ3J,OAAOmQ,SAAWA,IAAU,CACpEA,OAAQA,KCJV,IACIvM,GAAO,GAEXA,GAHoBwI,gBAAgB,gBAGd,IAEtB,OAAkC,eAAjBrJ,OAAOa,ICHpBgN,GAAgBxE,gBAAgB,eAEhCyE,GAAuE,aAAnDC,WAAW,WAAc,OAAOxK,UAArB,OAUlByK,GAAwBD,WAAa,SAAUxR,GAC9D,IAAIgD,EAAG0O,EAAKnJ,EACZ,YAAczG,IAAP9B,EAAmB,YAAqB,OAAPA,EAAc,OAEM,iBAAhD0R,EAXD,SAAU1R,EAAIyC,GACzB,IACE,OAAOzC,EAAGyC,GACV,MAAOjC,KAQSmR,CAAO3O,EAAItC,OAAOV,GAAKsR,KAA8BI,EAEnEH,GAAoBC,WAAWxO,GAEH,WAA3BuF,EAASiJ,WAAWxO,KAAsC,mBAAZA,EAAE4O,OAAuB,YAAcrJ,MClB3EkJ,GAAwB,GAAG/P,SAAW,SAASA,WAC9D,MAAO,WAAaG,GAAQT,MAAQ,KCDjCqQ,IACHjH,EAAS9J,OAAOiG,UAAW,WAAYjF,GAAU,CAAE4E,QAAQ,ICL7D,OAAiBjG,EAAOwR,QCFpBlR,GAAiBmJ,EAA+CtG,EAIhE8N,GAAgBxE,gBAAgB,8BAEnB,SAAU9M,EAAI8R,EAAK3H,GAC9BnK,IAAOqD,IAAIrD,EAAKmK,EAASnK,EAAKA,EAAG2G,UAAW2K,KAC9C3Q,GAAeX,EAAIsR,GAAe,CAAE9P,cAAc,EAAMD,MAAOuQ,KCF/D9D,GAAUlB,gBAAgB,cCNb,GCGbiF,GAAWjF,gBAAgB,YAC3BC,GAAiBC,MAAMrG,UCAvBoL,GAAWjF,gBAAgB,yCCDd,SAAUnC,EAAUtI,EAAId,EAAOyQ,GAC9C,IACE,OAAOA,EAAU3P,EAAGuB,SAASrC,GAAO,GAAIA,EAAM,IAAMc,EAAGd,GAEvD,MAAOf,GACP,IAAIyR,EAAetH,EAAiB,OAEpC,WADqB7I,IAAjBmQ,GAA4BrO,SAASqO,EAAajR,KAAK2J,IACrDnK,yCCHV,IAAI0R,OAAS,SAAUC,EAAS5J,GAC9BnH,KAAK+Q,QAAUA,EACf/Q,KAAKmH,OAASA,IAGFhE,UAAiB,SAAU6N,EAAU/P,EAAIqL,EAAM2E,EAAYC,GACvE,IACI3H,EAAU4H,EAAQ7K,EAAOT,EAAQsB,EAAQiK,EAAMC,EHP1BzS,EGMrB4O,EAAgBC,oBAAKxM,EAAIqL,EAAM2E,EAAa,EAAI,GAGpD,GAAIC,EACF3H,EAAWyH,MACN,CAEL,GAAqB,mBADrBG,EFba,SAAUvS,GACzB,GAAU8B,MAAN9B,EAAiB,OAAOA,EAAG+R,KAC1B/R,EAAG,eACH0S,GAAU7Q,GAAQ7B,IEUZ2S,CAAkBP,IACM,MAAMrQ,UAAU,0BAEjD,QHdYD,KADW9B,EGeGuS,KHdAG,GAAU1F,QAAUhN,GAAM+M,GAAegF,MAAc/R,GGc9C,CACjC,IAAK0H,EAAQ,EAAGT,EAASgB,SAASmK,EAASnL,QAASA,EAASS,EAAOA,IAIlE,IAHAa,EAAS8J,EACLzD,EAAchL,SAAS6O,EAAOL,EAAS1K,IAAQ,GAAI+K,EAAK,IACxD7D,EAAcwD,EAAS1K,MACba,aAAkB2J,OAAQ,OAAO3J,EAC/C,OAAO,IAAI2J,QAAO,GAEtBvH,EAAW4H,EAAOvR,KAAKoR,GAIzB,IADAI,EAAO7H,EAAS6H,OACPC,EAAOD,EAAKxR,KAAK2J,IAAWiI,MAEnC,GAAqB,iBADrBrK,EAASsK,6BAA6BlI,EAAUiE,EAAe6D,EAAKlR,MAAO8Q,KAC1C9J,GAAUA,aAAkB2J,OAAQ,OAAO3J,EAC5E,OAAO,IAAI2J,QAAO,KAGdY,KAAO,SAAUvK,GACvB,OAAO,IAAI2J,QAAO,EAAM3J,OCvCtBwJ,GAAWjF,gBAAgB,YAC3BiG,IAAe,EAEnB,IACE,IAAIC,GAAS,EACTC,GAAqB,CACvBT,KAAM,WACJ,MAAO,CAAEI,OAAQI,OAEnBE,OAAU,WACRH,IAAe,IAGnBE,GAAmBlB,IAAY,WAC7B,OAAO3Q,MAGT4L,MAAMmG,KAAKF,IAAoB,WAAc,MAAM,KACnD,MAAOzS,IAET,ICLI4S,GAAOC,GAASC,GCbhBtF,GAAUlB,gBAAgB,cCFb,mCAAmCxI,KAAKmL,IFMrD8D,GAAWlT,EAAOkT,SAClBnP,GAAM/D,EAAOmT,aACbC,GAAQpT,EAAOqT,eACfpE,GAAUjP,EAAOiP,QACjBqE,GAAiBtT,EAAOsT,eACxBC,GAAWvT,EAAOuT,SAClBC,GAAU,EACVC,GAAQ,GAIRC,IAAM,SAAUnP,GAElB,GAAIkP,GAAMtR,eAAeoC,GAAK,CAC5B,IAAIvC,EAAKyR,GAAMlP,UACRkP,GAAMlP,GACbvC,MAIA2R,OAAS,SAAUpP,GACrB,OAAO,WACLmP,IAAInP,KAIJqP,SAAW,SAAUC,GACvBH,IAAIG,EAAM3K,OAGR4K,KAAO,SAAUvP,GAEnBvE,EAAO+T,YAAYxP,EAAK,GAAI2O,GAASc,SAAW,KAAOd,GAASe,OAI7DlQ,IAAQqP,KACXrP,GAAM,SAASoP,aAAanR,GAG1B,IAFA,IAAIkS,EAAO,GACPjM,EAAI,EACDtB,UAAUC,OAASqB,GAAGiM,EAAK/P,KAAKwC,UAAUsB,MAMjD,OALAwL,KAAQD,IAAW,YAEH,mBAANxR,EAAmBA,EAAK/B,SAAS+B,IAAKwL,WAAM/L,EAAWyS,IAEjEnB,GAAMS,IACCA,IAETJ,GAAQ,SAASC,eAAe9O,UACvBkP,GAAMlP,IAGS,WAApB/C,WAAQyN,IACV8D,GAAQ,SAAUxO,GAChB0K,GAAQkF,SAASR,OAAOpP,KAGjBgP,IAAYA,GAASa,IAC9BrB,GAAQ,SAAUxO,GAChBgP,GAASa,IAAIT,OAAOpP,KAIb+O,KAAmBe,IAE5BpB,IADAD,GAAU,IAAIM,IACCgB,MACftB,GAAQuB,MAAMC,UAAYZ,SAC1Bb,GAAQvE,oBAAKyE,GAAKc,YAAad,GAAM,KAIrCjT,EAAOyU,kBACe,mBAAfV,aACN/T,EAAO0U,eACPtU,MAAM0T,OACe,UAAtBZ,GAASc,SAMTjB,GAzEqB,uBAwEUxQ,sBAAc,UACrC,SAAUgC,GAChB0H,GAAKC,YAAY3J,sBAAc,WAA6B,mBAAI,WAC9D0J,GAAK0I,YAAY5T,MACjB2S,IAAInP,KAKA,SAAUA,GAChBqQ,WAAWjB,OAAOpP,GAAK,KAbzBwO,GAAQe,KACR9T,EAAOyU,iBAAiB,UAAWb,UAAU,KAiBjD,IGzFIiB,GAAOC,GAAMC,GAAMC,GAAQC,GAAQC,GAAMC,GAASC,MHyFrC,CACfrR,IAAKA,GACLqP,MAAOA,IGxGL1S,GAA2B+I,EAA2DtG,EAEtFkS,GAAYC,GAA6BvR,IAGzCwR,GAAmBvV,EAAOuV,kBAAoBvV,EAAOwV,uBACrDvG,GAAUjP,EAAOiP,QACjBuC,GAAUxR,EAAOwR,QACjBiE,GAA8B,WAApBjU,WAAQyN,IAElByG,GAA2BhV,GAAyBV,EAAQ,kBAC5D2V,GAAiBD,IAA4BA,GAAyBxU,MAKrEyU,KACHd,GAAQ,WACN,IAAIe,EAAQ5T,EAEZ,IADIyT,KAAYG,EAAS3G,GAAQ5D,SAASuK,EAAOC,OAC1Cf,IAAM,CACX9S,EAAK8S,GAAK9S,GACV8S,GAAOA,GAAK3C,KACZ,IACEnQ,IACA,MAAO7B,GAGP,MAFI2U,GAAME,KACLD,QAAOtT,EACNtB,GAER4U,QAAOtT,EACLmU,GAAQA,EAAOE,SAIjBL,GACFT,GAAS,WACP/F,GAAQkF,SAASU,KAGVU,KAAqBlB,IAC9BY,IAAS,EACTC,GAAO7S,SAAS0T,eAAe,IAC/B,IAAIR,GAAiBV,IAAOmB,QAAQd,GAAM,CAAEe,eAAe,IAC3DjB,GAAS,WACPE,GAAKhM,KAAO+L,IAAUA,KAGfzD,IAAWA,GAAQ0E,SAE5Bf,GAAU3D,GAAQ0E,aAAQzU,GAC1B2T,GAAOD,GAAQC,KACfJ,GAAS,WACPI,GAAKzU,KAAKwU,GAASN,MASrBG,GAAS,WAEPK,GAAU1U,KAAKX,EAAQ6U,MAK7B,ICpBIsB,GAAUC,GAAsBC,GAAgBC,MDoBnCX,IAAkB,SAAU3T,GAC3C,IAAIuU,EAAO,CAAEvU,GAAIA,EAAImQ,UAAM1Q,GACvBsT,KAAMA,GAAK5C,KAAOoE,GACjBzB,KACHA,GAAOyB,EACPvB,MACAD,GAAOwB,GEzEPC,kBAAoB,SAAU3I,GAChC,IAAIqI,EAASO,EACb1V,KAAKoU,QAAU,IAAItH,GAAE,SAAU6I,EAAWC,GACxC,QAAgBlV,IAAZyU,QAAoCzU,IAAXgV,EAAsB,MAAM/U,UAAU,2BACnEwU,EAAUQ,EACVD,EAASE,KAEX5V,KAAKmV,QAAU3P,YAAU2P,GACzBnV,KAAK0V,OAASlQ,YAAUkQ,UAIP,SAAU5I,GAC3B,OAAO,IAAI2I,kBAAkB3I,oBCZd,SAAUA,EAAG+I,GAE5B,GADArT,SAASsK,GACL9L,SAAS6U,IAAMA,EAAE9I,cAAgBD,EAAG,OAAO+I,EAC/C,IAAIC,EAAoBC,GAAqB3T,EAAE0K,GAG/C,OADAqI,EADcW,EAAkBX,SACxBU,GACDC,EAAkB1B,iBCVV,SAAUjV,GACzB,IACE,MAAO,CAAEC,OAAO,EAAOe,MAAOhB,KAC9B,MAAOC,GACP,MAAO,CAAEA,OAAO,EAAMe,MAAOf,KHc7BoW,GAAO9M,GAA6B1F,IAWpC4J,GAAUlB,gBAAgB,WAC1BsK,GAAU,UACVnR,GAAmBC,EAAoBtF,IACvCyW,GAAmBnR,EAAoB9B,IACvCkT,GAA0BpR,EAAoBL,UAAUuR,IACxDG,GAAqBC,GACrBzV,GAAY1B,EAAO0B,UACnBW,GAAWrC,EAAOqC,SAClB4M,GAAUjP,EAAOiP,QACjBmI,GAAS5O,WAAW,SACpBsO,GAAuBO,GAA2BlU,EAClDmU,GAA8BR,GAC9BrB,GAA8B,WAApBjU,WAAQyN,IAClBsI,MAAoBlV,IAAYA,GAASmV,aAAexX,EAAOyX,eAU/DC,GAAS3O,GAASgO,IAAS,WAE7B,KAD6BjT,EAAcoT,MAAwB9T,OAAO8T,KAC7C,CAI3B,GAAmB,KAAf5H,GAAmB,OAAO,EAE9B,IAAKmG,IAA2C,mBAAzBkC,sBAAqC,OAAO,EAOrE,GAAIrI,IAAc,IAAM,cAAcrL,KAAKiT,IAAqB,OAAO,EAEvE,IAAI/B,EAAU+B,GAAmBhB,QAAQ,GACrC0B,YAAc,SAAU1X,GAC1BA,GAAK,eAA6B,gBAIpC,OAFkBiV,EAAQrH,YAAc,IAC5BH,IAAWiK,cACdzC,EAAQC,MAAK,yBAAwCwC,gBAG5DC,GAAsBH,KLxDT,SAAUxX,EAAM4X,GAC/B,IAAKA,IAAiBpF,GAAc,OAAO,EAC3C,IAAIqF,GAAoB,EACxB,IACE,IAAIvU,EAAS,GACbA,EAAOkO,IAAY,WACjB,MAAO,CACLS,KAAM,WACJ,MAAO,CAAEI,KAAMwF,GAAoB,MAIzC7X,EAAKsD,GACL,MAAOrD,IACT,OAAO4X,EK0C4BC,EAA4B,SAAUjG,GACzEmF,GAAmBe,IAAIlG,GAAiB,OAAE,kBAIxCmG,WAAa,SAAUvY,GACzB,IAAIyV,EACJ,SAAOrT,SAASpC,IAAkC,mBAAnByV,EAAOzV,EAAGyV,QAAsBA,GAG7DJ,SAAS,SAAUG,EAASzP,EAAOyS,GACrC,IAAIzS,EAAM0S,SAAV,CACA1S,EAAM0S,UAAW,EACjB,IAAIC,EAAQ3S,EAAM4S,UAClBC,IAAU,WAKR,IAJA,IAAIrX,EAAQwE,EAAMxE,MACdsX,EAhDQ,GAgDH9S,EAAMA,MACX2B,EAAQ,EAELgR,EAAMzR,OAASS,GAAO,CAC3B,IAKIa,EAAQkN,EAAMqD,EALdC,EAAWL,EAAMhR,KACjBsR,EAAUH,EAAKE,EAASF,GAAKE,EAASE,KACtC1C,EAAUwC,EAASxC,QACnBO,EAASiC,EAASjC,OAClBpL,EAASqN,EAASrN,OAEtB,IACMsN,GACGH,IAzDC,IA0DA9S,EAAMmT,WAAyBC,kBAAkB3D,EAASzP,GAC9DA,EAAMmT,UA5DJ,IA8DY,IAAZF,EAAkBzQ,EAAShH,GAEzBmK,GAAQA,EAAOyK,QACnB5N,EAASyQ,EAAQzX,GACbmK,IACFA,EAAOwK,OACP4C,GAAS,IAGTvQ,IAAWwQ,EAASvD,QACtBsB,EAAO/U,GAAU,yBACR0T,EAAO8C,WAAWhQ,IAC3BkN,EAAKzU,KAAKuH,EAAQgO,EAASO,GACtBP,EAAQhO,IACVuO,EAAOvV,GACd,MAAOf,GACHkL,IAAWoN,GAAQpN,EAAOwK,OAC9BY,EAAOtW,IAGXuF,EAAM4S,UAAY,GAClB5S,EAAM0S,UAAW,EACbD,IAAazS,EAAMmT,WAAWE,YAAY5D,EAASzP,QAIvD+R,cAAgB,SAAU9M,EAAMwK,EAAS6D,GAC3C,IAAInF,EAAO8E,EACPpB,KACF1D,EAAQxR,GAASmV,YAAY,UACvBrC,QAAUA,EAChBtB,EAAMmF,OAASA,EACfnF,EAAMoF,UAAUtO,GAAM,GAAO,GAC7B3K,EAAOyX,cAAc5D,IAChBA,EAAQ,CAAEsB,QAASA,EAAS6D,OAAQA,IACvCL,EAAU3Y,EAAO,KAAO2K,IAAOgO,EAAQ9E,GAtGnB,uBAuGflJ,GIhJM,SAAUlI,EAAG6K,GAC5B,IAAI4L,EAAUlZ,EAAOkZ,QACjBA,GAAWA,EAAQ/Y,QACA,IAArBwG,UAAUC,OAAesS,EAAQ/Y,MAAMsC,GAAKyW,EAAQ/Y,MAAMsC,EAAG6K,IJ6IxB6L,CAAiB,8BAA+BH,IAGrFD,YAAc,SAAU5D,EAASzP,GACnC6Q,GAAK5V,KAAKX,GAAQ,WAChB,IAEIkI,EAFAhH,EAAQwE,EAAMxE,MAGlB,GAFmBkY,YAAY1T,KAG7BwC,EAASmR,SAAQ,WACX5D,GACFxG,GAAQqK,KAAK,qBAAsBpY,EAAOiU,GACrCsC,cAnHW,qBAmHwBtC,EAASjU,MAGrDwE,EAAMmT,UAAYpD,IAAW2D,YAAY1T,GAhH/B,EADF,EAkHJwC,EAAO/H,OAAO,MAAM+H,EAAOhH,UAKjCkY,YAAc,SAAU1T,GAC1B,OAxHY,IAwHLA,EAAMmT,YAA0BnT,EAAMkQ,QAG3CkD,kBAAoB,SAAU3D,EAASzP,GACzC6Q,GAAK5V,KAAKX,GAAQ,WACZyV,GACFxG,GAAQqK,KAAK,mBAAoBnE,GAC5BsC,cAnIa,mBAmIoBtC,EAASzP,EAAMxE,WAIvDsN,KAAO,SAAUxM,EAAImT,EAASzP,EAAO6T,GACvC,OAAO,SAAUrY,GACfc,EAAGmT,EAASzP,EAAOxE,EAAOqY,KAI1BC,eAAiB,SAAUrE,EAASzP,EAAOxE,EAAOqY,GAChD7T,EAAM6M,OACV7M,EAAM6M,MAAO,EACTgH,IAAQ7T,EAAQ6T,GACpB7T,EAAMxE,MAAQA,EACdwE,EAAMA,MA/IO,EAgJbsP,SAAOG,EAASzP,GAAO,KAGrB+T,gBAAkB,SAAUtE,EAASzP,EAAOxE,EAAOqY,GACrD,IAAI7T,EAAM6M,KAAV,CACA7M,EAAM6M,MAAO,EACTgH,IAAQ7T,EAAQ6T,GACpB,IACE,GAAIpE,IAAYjU,EAAO,MAAMQ,GAAU,oCACvC,IAAI0T,EAAO8C,WAAWhX,GAClBkU,EACFmD,IAAU,WACR,IAAImB,EAAU,CAAEnH,MAAM,GACtB,IACE6C,EAAKzU,KAAKO,EACRsN,KAAKiL,gBAAiBtE,EAASuE,EAAShU,GACxC8I,KAAKgL,eAAgBrE,EAASuE,EAAShU,IAEzC,MAAOvF,GACPqZ,eAAerE,EAASuE,EAASvZ,EAAOuF,QAI5CA,EAAMxE,MAAQA,EACdwE,EAAMA,MAzKI,EA0KVsP,SAAOG,EAASzP,GAAO,IAEzB,MAAOvF,GACPqZ,eAAerE,EAAS,CAAE5C,MAAM,GAASpS,EAAOuF,MAKhDgS,KAEFR,GAAqB,SAAS1F,QAAQmI,IKlOvB,SAAUha,EAAIia,EAAajP,GAC1C,KAAMhL,aAAcia,GAClB,MAAMlY,UAAU,cAAgBiJ,EAAOA,EAAO,IAAM,IAAM,cLiO1DkP,CAAW9Y,KAAMmW,GAAoBH,IACrCxQ,YAAUoT,GACVxD,GAASxV,KAAKI,MACd,IAAI2E,EAAQE,GAAiB7E,MAC7B,IACE4Y,EAASnL,KAAKiL,gBAAiB1Y,KAAM2E,GAAQ8I,KAAKgL,eAAgBzY,KAAM2E,IACxE,MAAOvF,GACPqZ,eAAezY,KAAM2E,EAAOvF,MAIhCgW,GAAW,SAAS3E,QAAQmI,GAC1B3C,GAAiBjW,KAAM,CACrB4E,KAAMoR,GACNxE,MAAM,EACN6F,UAAU,EACVxC,QAAQ,EACR0C,UAAW,GACXO,WAAW,EACXnT,MAzMQ,EA0MRxE,WAAOO,MAGF6E,UMxPM,SAAUsC,EAAQuD,EAAKnG,GACtC,IAAK,IAAI5D,KAAO+J,EAAKhC,EAASvB,EAAQxG,EAAK+J,EAAI/J,GAAM4D,GACrD,OAAO4C,ENsPckR,CAAY5C,GAAmB5Q,UAAW,CAG7D8O,KAAM,SAASA,KAAK2E,EAAaC,GAC/B,IHtPwBC,EAExBlJ,EADAlD,EGqPInI,EAAQuR,GAAwBlW,MAChC2X,EAAW5B,IHvPSmD,EGuPqC/C,QHpPpDzV,KAFToM,EAAItK,SGsPmDxC,MHtPvC+M,cAEoCrM,OAA7BsP,EAAIxN,SAASsK,GAAGF,KAAyBsM,EAAqB1T,YAAUwK,KG2P/F,OANA2H,EAASF,GAA2B,mBAAfuB,GAA4BA,EACjDrB,EAASE,KAA4B,mBAAdoB,GAA4BA,EACnDtB,EAASrN,OAASoK,GAAUxG,GAAQ5D,YAAS5J,EAC7CiE,EAAMkQ,QAAS,EACflQ,EAAM4S,UAAUnU,KAAKuU,GAvNb,GAwNJhT,EAAMA,OAAkBsP,SAAOjU,KAAM2E,GAAO,GACzCgT,EAASvD,SAIlB+E,MAAS,SAAUF,GACjB,OAAOjZ,KAAKqU,UAAK3T,EAAWuY,MAGhC5D,GAAuB,WACrB,IAAIjB,EAAU,IAAIgB,GACdzQ,EAAQE,GAAiBuP,GAC7BpU,KAAKoU,QAAUA,EACfpU,KAAKmV,QAAU1H,KAAKiL,gBAAiBtE,EAASzP,GAC9C3E,KAAK0V,OAASjI,KAAKgL,eAAgBrE,EAASzP,IAE9C2R,GAA2BlU,EAAI2T,GAAuB,SAAUjJ,GAC9D,OAAOA,IAAMqJ,IAAsBrJ,IAAMwI,GACrC,IAAID,GAAqBvI,GACzByJ,GAA4BzJ,IAGM,mBAAjBsJ,KACrBb,GAAaa,GAAc7Q,UAAU8O,KAGrCjL,EAASgN,GAAc7Q,UAAW,QAAQ,SAAS8O,KAAK2E,EAAaC,GACnE,IAAI3M,EAAOtM,KACX,OAAO,IAAImW,IAAmB,SAAUhB,EAASO,GAC/CH,GAAW3V,KAAK0M,EAAM6I,EAASO,MAC9BrB,KAAK2E,EAAaC,KAEpB,CAAE/T,QAAQ,IAGQ,mBAAVmR,IAAsBxK,QAAE,CAAE5M,QAAQ,EAAMgB,YAAY,EAAMgJ,QAAQ,GAAQ,CAEnFmQ,MAAO,SAASA,MAAMtY,GACpB,OAAOuY,eAAelD,GAAoBE,GAAO5J,MAAMxN,EAAQ2G,iBAMvEiG,QAAE,CAAE5M,QAAQ,EAAMqa,MAAM,EAAMrQ,OAAQ0N,IAAU,CAC9ClG,QAAS0F,KAGXoD,eAAepD,GAAoBH,IAAS,GX7S3B,SAAUwD,GACzB,IAAIX,EAAcpR,WAAW+R,GACzBja,EAAiBmD,EAAqBN,EAEtCX,GAAeoX,IAAgBA,EAAYjM,KAC7CrN,EAAesZ,EAAajM,GAAS,CACnCxM,cAAc,EACdZ,IAAK,WAAc,OAAOQ,QWuShCyZ,CAAWzD,IAEXV,GAAiB7N,WAAWuO,IAG5BnK,QAAE,CAAEhE,OAAQmO,GAAShN,MAAM,EAAMC,OAAQ0N,IAAU,CAGjDjB,OAAQ,SAASA,OAAOgE,GACtB,IAAIC,EAAa5D,GAAqB/V,MAEtC,OADA2Z,EAAWjE,OAAO9V,UAAKc,EAAWgZ,GAC3BC,EAAWvF,WAItBvI,QAAE,CAAEhE,OAAQmO,GAAShN,MAAM,EAAMC,OAAmB0N,IAAU,CAG5DxB,QAAS,SAASA,QAAQU,GACxB,OAAOwD,eAAyErZ,KAAM6V,MAI1FhK,QAAE,CAAEhE,OAAQmO,GAAShN,MAAM,EAAMC,OAAQ6N,IAAuB,CAG9DI,IAAK,SAASA,IAAIlG,GAChB,IAAIlE,EAAI9M,KACJ2Z,EAAa5D,GAAqBjJ,GAClCqI,EAAUwE,EAAWxE,QACrBO,EAASiE,EAAWjE,OACpBvO,EAASmR,SAAQ,WACnB,IAAIsB,EAAkBpU,YAAUsH,EAAEqI,SAC9B0E,EAAS,GACTpH,EAAU,EACVqH,EAAY,EAChBC,GAAQ/I,GAAU,SAAUoD,GAC1B,IAAI9N,EAAQmM,IACRuH,GAAgB,EACpBH,EAAOzW,UAAK1C,GACZoZ,IACAF,EAAgBha,KAAKkN,EAAGsH,GAASC,MAAK,SAAUlU,GAC1C6Z,IACJA,GAAgB,EAChBH,EAAOvT,GAASnG,IACd2Z,GAAa3E,EAAQ0E,MACtBnE,QAEHoE,GAAa3E,EAAQ0E,MAGzB,OADI1S,EAAO/H,OAAOsW,EAAOvO,EAAOhH,OACzBwZ,EAAWvF,SAIpB6F,KAAM,SAASA,KAAKjJ,GAClB,IAAIlE,EAAI9M,KACJ2Z,EAAa5D,GAAqBjJ,GAClC4I,EAASiE,EAAWjE,OACpBvO,EAASmR,SAAQ,WACnB,IAAIsB,EAAkBpU,YAAUsH,EAAEqI,SAClC4E,GAAQ/I,GAAU,SAAUoD,GAC1BwF,EAAgBha,KAAKkN,EAAGsH,GAASC,KAAKsF,EAAWxE,QAASO,SAI9D,OADIvO,EAAO/H,OAAOsW,EAAOvO,EAAOhH,OACzBwZ,EAAWvF,WOvXtB,IAAI8F,GAA4BxR,EAAsDtG,EAElF9B,GAAW,GAAGA,SAEd6Z,GAA+B,iBAAVpb,QAAsBA,QAAUO,OAAOgI,oBAC5DhI,OAAOgI,oBAAoBvI,QAAU,SAWtB,SAASuI,oBAAoB1I,GAC9C,OAAOub,IAAoC,mBAArB7Z,GAASV,KAAKhB,GAVjB,SAAUA,GAC7B,IACE,OAAOsb,GAA0Btb,GACjC,MAAOQ,GACP,OAAO+a,GAAY5Z,SAOjB6Z,CAAexb,GACfsb,GAA0BpY,gBAAgBlD,YClBpC8M,iBCCRnM,GAAiBmJ,EAA+CtG,wBAEnD,SAAUiY,GACzB,IAAIhR,EAASvD,EAAKuD,SAAWvD,EAAKuD,OAAS,IACtCpH,IAAIoH,EAAQgR,IAAO9a,GAAe8J,EAAQgR,EAAM,CACnDla,MAAOma,GAA6BlY,EAAEiY,MC4BtCE,GAAW7R,GAAwCiF,QAEnD6M,GAASpW,UAAU,UAGnBqW,GAAe/O,gBAAgB,eAC/BuK,GAAmBnR,EAAoB9B,IACvC6B,GAAmBC,EAAoBL,UAJ9B,UAKTiW,GAAkBpb,OAAgB,UAClCqb,GAAU1b,EAAOoK,OACjBuR,GAAanT,WAAW,OAAQ,aAChC9F,GAAiCmG,EAA+B1F,EAChEE,GAAuBI,EAAqBN,EAC5C8X,GAA4BW,GAA4BzY,EACxD3C,GAA6B0C,EAA2BC,EACxD0Y,GAAalX,EAAO,WACpBmX,GAAyBnX,EAAO,cAChCoX,GAAyBpX,EAAO,6BAChCqX,GAAyBrX,EAAO,6BAChC4F,GAAwB5F,EAAO,OAC/BsX,GAAUjc,EAAOic,QAEjBC,IAAcD,KAAYA,GAAiB,YAAMA,GAAiB,UAAEE,UAGpEC,GAAsB5Z,GAAepC,OAAM,WAC7C,OAES,GAFFic,GAAmBhZ,GAAqB,GAAI,IAAK,CACtD9C,IAAK,WAAc,OAAO8C,GAAqBtC,KAAM,IAAK,CAAEG,MAAO,IAAKuB,MACtEA,KACD,SAAUE,EAAGC,EAAGU,GACnB,IAAIgZ,EAA4B5Z,GAA+B+Y,GAAiB7Y,GAC5E0Z,UAAkCb,GAAgB7Y,GACtDS,GAAqBV,EAAGC,EAAGU,GACvBgZ,GAA6B3Z,IAAM8Y,IACrCpY,GAAqBoY,GAAiB7Y,EAAG0Z,IAEzCjZ,GAEAgX,KAAO,SAAUhJ,EAAKkL,GACxB,IAAI5L,EAASkL,GAAWxK,GAAOgL,GAAmBX,GAAiB,WAOnE,OANA1E,GAAiBrG,EAAQ,CACvBhL,KAtCS,SAuCT0L,IAAKA,EACLkL,YAAaA,IAEV/Z,IAAamO,EAAO4L,YAAcA,GAChC5L,GAGL6L,GAAW/R,GAAoB,SAAU9K,GAC3C,MAAoB,iBAANA,GACZ,SAAUA,GACZ,OAAOU,OAAOV,aAAe+b,IAG3Be,GAAkB,SAASnc,eAAeqC,EAAGC,EAAGU,GAC9CX,IAAM8Y,IAAiBgB,GAAgBX,GAAwBlZ,EAAGU,GACtEC,SAASZ,GACT,IAAIP,EAAMU,YAAYF,GAAG,GAEzB,OADAW,SAASD,GACLN,IAAI6Y,GAAYzZ,IACbkB,EAAWtC,YAIVgC,IAAIL,EAAG4Y,KAAW5Y,EAAE4Y,IAAQnZ,KAAMO,EAAE4Y,IAAQnZ,IAAO,GACvDkB,EAAa+Y,GAAmB/Y,EAAY,CAAEtC,WAAYiC,yBAAyB,GAAG,OAJjFD,IAAIL,EAAG4Y,KAASlY,GAAqBV,EAAG4Y,GAAQtY,yBAAyB,EAAG,KACjFN,EAAE4Y,IAAQnZ,IAAO,GAIVga,GAAoBzZ,EAAGP,EAAKkB,IAC9BD,GAAqBV,EAAGP,EAAKkB,IAGpCoZ,GAAoB,SAAS9R,iBAAiBjI,EAAGkI,GACnDtH,SAASZ,GACT,IAAIga,EAAa9Z,gBAAgBgI,GAC7BnG,EAAOoG,GAAW6R,GAAYvU,OAAOwU,GAAuBD,IAIhE,OAHArB,GAAS5W,GAAM,SAAUtC,GAClBI,IAAeqa,GAAsBlc,KAAKgc,EAAYva,IAAMqa,GAAgB9Z,EAAGP,EAAKua,EAAWva,OAE/FO,GAOLka,GAAwB,SAASpc,qBAAqBI,GACxD,IAAI+B,EAAIE,YAAYjC,GAAG,GACnBG,EAAaR,GAA2BG,KAAKI,KAAM6B,GACvD,QAAI7B,OAAS0a,IAAmBzY,IAAI6Y,GAAYjZ,KAAOI,IAAI8Y,GAAwBlZ,QAC5E5B,IAAegC,IAAIjC,KAAM6B,KAAOI,IAAI6Y,GAAYjZ,IAAMI,IAAIjC,KAAMwa,KAAWxa,KAAKwa,IAAQ3Y,KAAK5B,IAGlG8b,GAA4B,SAASpc,yBAAyBiC,EAAGC,GACnE,IAAIjD,EAAKkD,gBAAgBF,GACrBP,EAAMU,YAAYF,GAAG,GACzB,GAAIjD,IAAO8b,KAAmBzY,IAAI6Y,GAAYzZ,IAASY,IAAI8Y,GAAwB1Z,GAAnF,CACA,IAAItB,EAAa4B,GAA+B/C,EAAIyC,GAIpD,OAHItB,IAAckC,IAAI6Y,GAAYzZ,IAAUY,IAAIrD,EAAI4b,KAAW5b,EAAG4b,IAAQnZ,KACxEtB,EAAWE,YAAa,GAEnBF,IAGLic,GAAuB,SAAS1U,oBAAoB1F,GACtD,IAAIqF,EAAQiT,GAA0BpY,gBAAgBF,IAClDuF,EAAS,GAIb,OAHAoT,GAAStT,GAAO,SAAU5F,GACnBY,IAAI6Y,GAAYzZ,IAASY,IAAIoC,EAAYhD,IAAM8F,EAAO/D,KAAK/B,MAE3D8F,GAGL0U,GAAyB,SAASrU,sBAAsB5F,GAC1D,IAAIqa,EAAsBra,IAAM8Y,GAC5BzT,EAAQiT,GAA0B+B,EAAsBlB,GAAyBjZ,gBAAgBF,IACjGuF,EAAS,GAMb,OALAoT,GAAStT,GAAO,SAAU5F,IACpBY,IAAI6Y,GAAYzZ,IAAU4a,IAAuBha,IAAIyY,GAAiBrZ,IACxE8F,EAAO/D,KAAK0X,GAAWzZ,OAGpB8F,GAkHT,GA7GKmC,KAcHF,GAbAuR,GAAU,SAAStR,SACjB,GAAIrJ,gBAAgB2a,GAAS,MAAMha,UAAU,+BAC7C,IAAI6a,EAAe5V,UAAUC,aAA2BnF,IAAjBkF,UAAU,GAA+BvD,OAAOuD,UAAU,SAA7BlF,EAChE4P,EAAMzM,IAAI2X,GACVU,OAAS,SAAU/b,GACjBH,OAAS0a,IAAiBwB,OAAOtc,KAAKmb,GAAwB5a,GAC9D8B,IAAIjC,KAAMwa,KAAWvY,IAAIjC,KAAKwa,IAASlK,KAAMtQ,KAAKwa,IAAQlK,IAAO,GACrE+K,GAAoBrb,KAAMsQ,EAAKpO,yBAAyB,EAAG/B,KAG7D,OADIsB,GAAe0Z,IAAYE,GAAoBX,GAAiBpK,EAAK,CAAElQ,cAAc,EAAM4C,IAAKkZ,SAC7F5C,KAAKhJ,EAAKkL,KAGO,UAAG,YAAY,SAASlb,WAChD,OAAOuE,GAAiB7E,MAAMsQ,OAGhClH,EAASuR,GAAS,iBAAiB,SAAUa,GAC3C,OAAOlC,KAAKzV,IAAI2X,GAAcA,MAGhCrZ,EAA2BC,EAAI0Z,GAC/BpZ,EAAqBN,EAAIsZ,GACzB5T,EAA+B1F,EAAI2Z,GACnCpU,EAA0BvF,EAAIyY,GAA4BzY,EAAI4Z,GAC9DpU,EAA4BxF,EAAIyZ,GAEhCvB,GAA6BlY,EAAI,SAAUwH,GACzC,OAAO0P,KAAK5N,gBAAgB9B,GAAOA,IAGjCnI,IAEFa,GAAqBqY,GAAiB,UAAG,cAAe,CACtDva,cAAc,EACdZ,IAAK,SAASgc,cACZ,OAAO3W,GAAiB7E,MAAMwb,eAIhCpS,EAASsR,GAAiB,uBAAwBoB,GAAuB,CAAE5W,QAAQ,MAKzF2G,QAAE,CAAE5M,QAAQ,EAAMqa,MAAM,EAAMrQ,QAASK,GAAeH,MAAOG,IAAiB,CAC5ED,OAAQsR,KAGVJ,GAASxQ,GAAWP,KAAwB,SAAUI,GACpDuS,sBAAsBvS,MAGxBiC,QAAE,CAAEhE,OAjLS,SAiLOmB,MAAM,EAAMC,QAASK,IAAiB,CAGxD8S,IAAO,SAAU/a,GACf,IAAIkH,EAASlG,OAAOhB,GACpB,GAAIY,IAAI+Y,GAAwBzS,GAAS,OAAOyS,GAAuBzS,GACvE,IAAIqH,EAAS+K,GAAQpS,GAGrB,OAFAyS,GAAuBzS,GAAUqH,EACjCqL,GAAuBrL,GAAUrH,EAC1BqH,GAITyM,OAAQ,SAASA,OAAOC,GACtB,IAAKb,GAASa,GAAM,MAAM3b,UAAU2b,EAAM,oBAC1C,GAAIra,IAAIgZ,GAAwBqB,GAAM,OAAOrB,GAAuBqB,IAEtEC,UAAW,WAAcpB,IAAa,GACtCqB,UAAW,WAAcrB,IAAa,KAGxCtP,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,EAAMC,QAASK,GAAeH,MAAO1H,GAAe,CAG9E+J,OA3HY,SAASA,OAAO5J,EAAGkI,GAC/B,YAAsBpJ,IAAfoJ,EAA2BwR,GAAmB1Z,GAAK+Z,GAAkBL,GAAmB1Z,GAAIkI,IA6HnGvK,eAAgBmc,GAGhB7R,iBAAkB8R,GAGlBhc,yBAA0Boc,KAG5BlQ,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,EAAMC,QAASK,IAAiB,CAG1DhC,oBAAqB0U,GAGrBxU,sBAAuBqU,KAKzBhQ,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,EAAMC,OAAQ5J,OAAM,WAAcuI,EAA4BxF,EAAE,OAAU,CACpGoF,sBAAuB,SAASA,sBAAsB5I,GACpD,OAAOgJ,EAA4BxF,EAAE4J,SAASpN,OAM9Cgc,GAAY,CACd,IAAI6B,IAAyBnT,IAAiBjK,OAAM,WAClD,IAAIuQ,EAAS+K,KAEb,MAA+B,UAAxBC,GAAW,CAAChL,KAEe,MAA7BgL,GAAW,CAAElZ,EAAGkO,KAEc,MAA9BgL,GAAWtb,OAAOsQ,OAGzB/D,QAAE,CAAEhE,OAAQ,OAAQmB,MAAM,EAAMC,OAAQwT,IAAyB,CAE/DC,UAAW,SAASA,UAAU9d,EAAI+d,EAAUC,GAI1C,IAHA,IAEIC,EAFA1J,EAAO,CAACvU,GACR0H,EAAQ,EAELV,UAAUC,OAASS,GAAO6M,EAAK/P,KAAKwC,UAAUU,MAErD,GADAuW,EAAYF,GACP3b,SAAS2b,SAAoBjc,IAAP9B,KAAoB6c,GAAS7c,GAMxD,OALK8N,GAAQiQ,KAAWA,EAAW,SAAUtb,EAAKlB,GAEhD,GADwB,mBAAb0c,IAAyB1c,EAAQ0c,EAAUjd,KAAKI,KAAMqB,EAAKlB,KACjEsb,GAAStb,GAAQ,OAAOA,IAE/BgT,EAAK,GAAKwJ,EACH/B,GAAWnO,MAAM,KAAM0G,MAO/BwH,GAAiB,UAAEF,KACtB9X,EAA4BgY,GAAiB,UAAGF,GAAcE,GAAiB,UAAExZ,SAInFoY,eAAeoB,GA7QF,UA+QbtW,EAAWmW,KAAU,EC9SrB,IAAIjb,GAAiBmJ,EAA+CtG,EAGhE0a,GAAe7d,EAAOoK,OAE1B,GAAI5H,GAAsC,mBAAhBqb,OAAiC,gBAAiBA,GAAavX,iBAExD7E,IAA/Boc,KAAetB,aACd,CACD,IAAIuB,GAA8B,GAE9BC,GAAgB,SAAS3T,SAC3B,IAAImS,EAAc5V,UAAUC,OAAS,QAAsBnF,IAAjBkF,UAAU,QAAmBlF,EAAY2B,OAAOuD,UAAU,IAChGuB,EAASnH,gBAAgBgd,GACzB,IAAIF,GAAatB,QAED9a,IAAhB8a,EAA4BsB,KAAiBA,GAAatB,GAE9D,MADoB,KAAhBA,IAAoBuB,GAA4B5V,IAAU,GACvDA,GAET+B,0BAA0B8T,GAAeF,IACzC,IAAIG,GAAkBD,GAAczX,UAAYuX,GAAavX,UAC7D0X,GAAgBlQ,YAAciQ,GAE9B,IAAIE,GAAiBD,GAAgB3c,SACjC6c,GAAyC,gBAAhC9a,OAAOya,GAAa,SAC7BM,GAAS,wBACb7d,GAAe0d,GAAiB,cAAe,CAC7C7c,cAAc,EACdZ,IAAK,SAASgc,cACZ,IAAI5L,EAAS5O,SAAShB,MAAQA,KAAKmB,UAAYnB,KAC3CuI,EAAS2U,GAAetd,KAAKgQ,GACjC,GAAI3N,IAAI8a,GAA6BnN,GAAS,MAAO,GACrD,IAAIyN,EAAOF,GAAS5U,EAAOhI,MAAM,GAAI,GAAKgI,EAAOC,QAAQ4U,GAAQ,MACjE,MAAgB,KAATC,OAAc3c,EAAY2c,KAIrCxR,QAAE,CAAE5M,QAAQ,EAAMgK,QAAQ,GAAQ,CAChCI,OAAQ2T,KC3CZb,sBAAsB,iBCAtBA,sBAAsB,YCAtBA,sBAAsB,eCDtB,ICFI5B,GAAW7R,GAAwCiF,QAInD2P,GDFa,SAAUhP,EAAarI,GACtC,IAAIN,EAAS,GAAG2I,GAChB,QAAS3I,GAAUtG,OAAM,WAEvBsG,EAAO/F,KAAK,KAAMqG,GAAY,WAAc,MAAM,GAAM,MCFxCsX,CAAoB,WACpCpO,GAAiBC,wBAAwB,cAI1BkO,IAAkBnO,GAEjC,GAAGxB,QAFgD,SAASA,QAAQL,GACtE,OAAOiN,GAASva,KAAMsN,EAAY1H,UAAUC,OAAS,EAAID,UAAU,QAAKlF,ICL1EmL,QAAE,CAAEhE,OAAQ,QAASiE,OAAO,EAAM7C,OAAQ,GAAG0E,SAAWA,IAAW,CACjEA,QAASA,KCLX,ICYI6P,GAAmBC,GAAmCC,ODZxCre,OAAM,WACtB,SAASkM,KAET,OADAA,EAAEhG,UAAUwH,YAAc,KACnBzN,OAAOqe,eAAe,IAAIpS,KAASA,EAAEhG,aEA1CyE,GAAW5F,UAAU,YACrBsW,GAAkBpb,OAAOiG,aAIZqY,GAA2Bte,OAAOqe,eAAiB,SAAU/b,GAE5E,OADAA,EAAIoK,SAASpK,GACTK,IAAIL,EAAGoI,IAAkBpI,EAAEoI,IACH,mBAAjBpI,EAAEmL,aAA6BnL,aAAaA,EAAEmL,YAChDnL,EAAEmL,YAAYxH,UACd3D,aAAatC,OAASob,GAAkB,MDR/C/J,GAAWjF,gBAAgB,YAC3BmS,IAAyB,EAQzB,GAAGla,OAGC,SAFN+Z,GAAgB,GAAG/Z,SAIjB8Z,GAAoCE,GAAeA,GAAeD,QACxBpe,OAAOiG,YAAWiY,GAAoBC,IAHlDI,IAAyB,GAOlCnd,MAArB8c,KAAgCA,GAAoB,IAGvCvb,IAAIub,GAAmB7M,KACtChO,EAA4B6a,GAAmB7M,IApBhC,WAAc,OAAO3Q,QAuBtC,OAAiB,CACfwd,kBAAmBA,GACnBK,uBAAwBA,IElCtBL,GAAoB9U,GAAuC8U,kBAM3DM,aAAa,WAAc,OAAO9d,SCArBV,OAAOye,iBAAmB,aAAe,GAAK,WAC7D,IAEI7B,EAFA8B,GAAiB,EACjB9a,EAAO,GAEX,KACEgZ,EAAS5c,OAAOK,yBAAyBL,OAAOiG,UAAW,aAAavC,KACjEpD,KAAKsD,EAAM,IAClB8a,EAAiB9a,aAAgB0I,MACjC,MAAOxM,IACT,OAAO,SAAS2e,eAAenc,EAAGkK,GAKhC,OAJAtJ,SAASZ,GCfI,SAAUhD,GACzB,IAAKoC,SAASpC,IAAc,OAAPA,EACnB,MAAM+B,UAAU,aAAe0B,OAAOzD,GAAM,mBDc5Cqf,CAAmBnS,GACfkS,EAAgB9B,EAAOtc,KAAKgC,EAAGkK,GAC9BlK,EAAEsc,UAAYpS,EACZlK,GAdoD,QAgBzDlB,GEVF8c,GAAoBW,GAAcX,kBAClCK,GAAyBM,GAAcN,uBACvClN,GAAWjF,gBAAgB,YAK3BoS,aAAa,WAAc,OAAO9d,qBAErB,SAAUoe,EAAU/D,EAAMgE,EAAqBjN,EAAMkN,EAASC,EAAQ5H,IHbtE,SAAU0H,EAAqBhE,EAAMjJ,GACpD,IAAIlB,EAAgBmK,EAAO,YAC3BgE,EAAoB9Y,UAAYiG,GAAOgS,GAAmB,CAAEpM,KAAMlP,yBAAyB,EAAGkP,KAC9FmI,eAAe8E,EAAqBnO,GAAe,GACnDoB,GAAUpB,GAAiB4N,aGU3BU,CAA0BH,EAAqBhE,EAAMjJ,GAErD,IAkBIqN,EAA0BC,EAASC,EAlBnCC,mBAAqB,SAAUC,GACjC,GAAIA,IAASP,GAAWQ,EAAiB,OAAOA,EAChD,IAAKjB,IAA0BgB,KAAQE,EAAmB,OAAOA,EAAkBF,GACnF,OAAQA,GACN,IAbK,OAaM,OAAO,SAASlb,OAAS,OAAO,IAAI0a,EAAoBre,KAAM6e,IACzE,IAbO,SAaM,OAAO,SAAShF,SAAW,OAAO,IAAIwE,EAAoBre,KAAM6e,IAC7E,IAbQ,UAaM,OAAO,SAASG,UAAY,OAAO,IAAIX,EAAoBre,KAAM6e,IAC/E,OAAO,WAAc,OAAO,IAAIR,EAAoBre,QAGpDkQ,EAAgBmK,EAAO,YACvB4E,GAAwB,EACxBF,EAAoBX,EAAS7Y,UAC7B2Z,EAAiBH,EAAkBpO,KAClCoO,EAAkB,eAClBT,GAAWS,EAAkBT,GAC9BQ,GAAmBjB,IAA0BqB,GAAkBN,mBAAmBN,GAClFa,EAA4B,SAAR9E,GAAkB0E,EAAkBC,SAA4BE,EAiCxF,GA7BIC,IACFV,EAA2Bd,GAAewB,EAAkBvf,KAAK,IAAIwe,IACjEZ,KAAsBle,OAAOiG,WAAakZ,EAAyBrN,OACrDuM,GAAec,KAA8BjB,KACvDO,GACFA,GAAeU,EAA0BjB,IACa,mBAAtCiB,EAAyB9N,KACzChO,EAA4B8b,EAA0B9N,GAAUmN,eAIpEvE,eAAekF,EAA0BvO,GAAe,KAxCjD,UA8CPoO,GAAqBY,GA9Cd,WA8CgCA,EAAetV,OACxDqV,GAAwB,EACxBH,EAAkB,SAASjF,SAAW,OAAOqF,EAAetf,KAAKI,QAIvC+e,EAAkBpO,MAAcmO,GAC1Dnc,EAA4Boc,EAAmBpO,GAAUmO,GAE3DxN,GAAU+I,GAAQyE,EAGdR,EAMF,GALAI,EAAU,CACR7E,OAAQ+E,mBA5DD,UA6DPjb,KAAM4a,EAASO,EAAkBF,mBA9D5B,QA+DLI,QAASJ,mBA7DD,YA+DNjI,EAAQ,IAAKgI,KAAOD,GAClBb,IAA0BoB,KAA2BN,KAAOI,KAC9D3V,EAAS2V,EAAmBJ,EAAKD,EAAQC,SAEtC9S,QAAE,CAAEhE,OAAQwS,EAAMvO,OAAO,EAAM7C,OAAQ4U,IAA0BoB,GAAyBP,GAGnG,OAAOA,GChFLzI,GAAmBnR,EAAoB9B,IACvC6B,GAAmBC,EAAoBL,UAFtB,qBAcJ2a,eAAexT,MAAO,SAAS,SAAUyT,EAAUC,GAClErJ,GAAiBjW,KAAM,CACrB4E,KAhBiB,iBAiBjBiD,OAAQ/F,gBAAgBud,GACxB/Y,MAAO,EACPgZ,KAAMA,OAIP,WACD,IAAI3a,EAAQE,GAAiB7E,MACzB6H,EAASlD,EAAMkD,OACfyX,EAAO3a,EAAM2a,KACbhZ,EAAQ3B,EAAM2B,QAClB,OAAKuB,GAAUvB,GAASuB,EAAOhC,QAC7BlB,EAAMkD,YAASnH,EACR,CAAEP,WAAOO,EAAW8Q,MAAM,IAEvB,QAAR8N,EAAuB,CAAEnf,MAAOmG,EAAOkL,MAAM,GACrC,UAAR8N,EAAyB,CAAEnf,MAAO0H,EAAOvB,GAAQkL,MAAM,GACpD,CAAErR,MAAO,CAACmG,EAAOuB,EAAOvB,IAASkL,MAAM,KAC7C,UAKHF,GAAUiO,UAAYjO,GAAU1F,MAGhCQ,iBAAiB,QACjBA,iBAAiB,UACjBA,iBAAiB,WChDjB,IAAIoT,GAAgB,GAAGC,QACnBvc,GAAO,CAAC,EAAG,GAMf2I,QAAE,CAAEhE,OAAQ,QAASiE,OAAO,EAAM7C,OAAQ5G,OAAOa,MAAUb,OAAOa,GAAKuc,YAAc,CACnFA,QAAS,SAASA,UAGhB,OADI/S,GAAQ1M,QAAOA,KAAK6F,OAAS7F,KAAK6F,QAC/B2Z,GAAc5f,KAAKI,SCV9B,ICOIiP,GAAsBC,6BAA6B,SACnDC,GAAiBC,wBAAwB,QAAS,CAAEP,WAAW,EAAM6Q,EAAG,EAAG7f,EAAG,IAE9E+M,GAAUlB,gBAAgB,WAC1BiU,GAAc,GAAGpf,MACjB8F,GAAMxH,KAAKwH,IAKfwF,QAAE,CAAEhE,OAAQ,QAASiE,OAAO,EAAM7C,QAASgG,KAAwBE,IAAkB,CACnF5O,MAAO,SAASA,MAAMqf,EAAO1T,GAC3B,IAKI2M,EAAa1R,EAAQ0Y,EDxBFpd,EAAQpB,EAAKlB,EAClC2f,ECkBEle,EAAIE,gBAAgB9B,MACpB6F,EAASgB,SAASjF,EAAEiE,QACpBka,EAAIjZ,gBAAgB8Y,EAAO/Z,GAC3Bma,EAAMlZ,qBAAwBpG,IAARwL,EAAoBrG,EAASqG,EAAKrG,GAG5D,GAAI6G,GAAQ9K,KAGgB,mBAF1BiX,EAAcjX,EAAEmL,cAEyB8L,IAAgBjN,QAASc,GAAQmM,EAAYtT,WAE3EvE,SAAS6X,IAEE,QADpBA,EAAcA,EAAYjM,OACAiM,OAAcnY,GAHxCmY,OAAcnY,EAKZmY,IAAgBjN,YAAyBlL,IAAhBmY,GAC3B,OAAO8G,GAAY/f,KAAKgC,EAAGme,EAAGC,GAIlC,IADA7Y,EAAS,SAAqBzG,IAAhBmY,EAA4BjN,MAAQiN,GAAaxS,GAAI2Z,EAAMD,EAAG,IACvEF,EAAI,EAAGE,EAAIC,EAAKD,IAAKF,IAASE,KAAKne,IDvCjBa,ECuCmC0E,EDvC3B9F,ECuCmCwe,EDvC9B1f,ECuCiCyB,EAAEme,GDtCrED,OAAAA,GAAAA,EAAc/d,YAAYV,MACXoB,EAAQC,EAAqBN,EAAEK,EAAQqd,EAAa5d,yBAAyB,EAAG/B,IAC9FsC,EAAOqd,GAAe3f,GCsCzB,OADAgH,EAAOtB,OAASga,EACT1Y,KC5CX,IAAI8Y,GAAgBC,KAAK3a,UAGrB4a,GAAqBF,GAAuB,SAC5CG,GAAUH,GAAcG,QAIxB,IAAIF,KAAKG,KAAO,IAPD,gBAQjBjX,EAAS6W,GAPK,YAOqB,SAAS3f,WAC1C,IAAIH,EAAQigB,GAAQxgB,KAAKI,MAEzB,OAAOG,GAAUA,EAAQggB,GAAmBvgB,KAAKI,MAXlC,kBCEnBuZ,eAAeta,EAAOqhB,KAAM,QAAQ,GCDpC/G,eAAe1a,KAAM,QAAQ,GCE7BgN,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,EAAMG,MAAO1H,GAAe,CACtD+J,OAAQA,KCDVK,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,EAAMC,QAASxH,EAAa0H,MAAO1H,GAAe,CAC5ElC,eAAgBghB,EAA2Bne,ICD7C,IAAIoe,GAAsBnhB,OAAM,WAAcohB,GAAqB,MAInE5U,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,EAAMC,OAAQuX,GAAqBrX,MAAOyU,IAA4B,CAChGD,eAAgB,SAASA,eAAe/e,GACtC,OAAO6hB,GAAqBzU,SAASpN,OCPzCiN,QAAE,CAAEhE,OAAQ,SAAUmB,MAAM,GAAQ,CAClC+U,eAAgBA,KCDlB,gBAAiB,WACf,IAAIzR,EAAO9J,SAASxC,MAChBmH,EAAS,GAOb,OANImF,EAAKrN,SAAQkI,GAAU,KACvBmF,EAAKoU,aAAYvZ,GAAU,KAC3BmF,EAAKqU,YAAWxZ,GAAU,KAC1BmF,EAAKsU,SAAQzZ,GAAU,KACvBmF,EAAKuU,UAAS1Z,GAAU,KACxBmF,EAAKwU,SAAQ3Z,GAAU,KACpBA,GCPL4Z,GAAkBC,OAAOzb,UACzB0b,GAAiBF,GAAyB,SAE1CG,GAAc7hB,OAAM,WAAc,MAA2D,QAApD4hB,GAAerhB,KAAK,CAAEyF,OAAQ,IAAK8b,MAAO,SAEnFC,GANY,YAMKH,GAAerX,MAIhCsX,IAAeE,KACjBhY,EAAS4X,OAAOzb,UAXF,YAWwB,SAASjF,WAC7C,IAAI+gB,EAAI7e,SAASxC,MACbshB,EAAIjf,OAAOgf,EAAEhc,QACbkc,EAAKF,EAAEF,MAEX,MAAO,IAAMG,EAAI,IADTjf,YAAc3B,IAAP6gB,GAAoBF,aAAaL,UAAY,UAAWD,IAAmBI,YAAMvhB,KAAKyhB,GAAKE,KAEzG,CAAErc,QAAQ,ICnBf,IAAIsB,eAAe,SAAUgb,GAC3B,OAAO,SAAU9a,EAAO+a,GACtB,IAGIC,EAAOC,EAHP3R,EAAI3N,OAAOxB,uBAAuB6F,IAClCkb,EAAWxb,UAAUqb,GACrBI,EAAO7R,EAAEnK,OAEb,OAAI+b,EAAW,GAAKA,GAAYC,EAAaL,EAAoB,QAAK9gB,GACtEghB,EAAQ1R,EAAE8R,WAAWF,IACN,OAAUF,EAAQ,OAAUE,EAAW,IAAMC,IACtDF,EAAS3R,EAAE8R,WAAWF,EAAW,IAAM,OAAUD,EAAS,MAC1DH,EAAoBxR,EAAE+R,OAAOH,GAAYF,EACzCF,EAAoBxR,EAAEzP,MAAMqhB,EAAUA,EAAW,GAA+BD,EAAS,OAAlCD,EAAQ,OAAU,IAA0B,QCdzGK,GDkBa,CAGfC,OAAQxb,gBAAa,GAGrBub,OAAQvb,gBAAa,ICxB+Bub,OAKlD9L,GAAmBnR,EAAoB9B,IACvC6B,GAAmBC,EAAoBL,UAFrB,mBAMtB2a,eAAe/c,OAAQ,UAAU,SAAUgd,GACzCpJ,GAAiBjW,KAAM,CACrB4E,KARkB,kBASlB2D,OAAQlG,OAAOgd,GACf/Y,MAAO,OAIR,SAAS8K,OACV,IAGI6Q,EAHAtd,EAAQE,GAAiB7E,MACzBuI,EAAS5D,EAAM4D,OACfjC,EAAQ3B,EAAM2B,MAElB,OAAIA,GAASiC,EAAO1C,OAAe,CAAE1F,WAAOO,EAAW8Q,MAAM,IAC7DyQ,EAAQF,GAAOxZ,EAAQjC,GACvB3B,EAAM2B,OAAS2b,EAAMpc,OACd,CAAE1F,MAAO8hB,EAAOzQ,MAAM,OCzB/B,OAAiB,CACf0Q,YAAa,EACbC,oBAAqB,EACrBC,aAAc,EACdC,eAAgB,EAChBC,YAAa,EACbC,cAAe,EACfC,aAAc,EACdC,qBAAsB,EACtBC,SAAU,EACVC,kBAAmB,EACnBC,eAAgB,EAChBC,gBAAiB,EACjBC,kBAAmB,EACnBC,UAAW,EACXC,cAAe,EACfC,aAAc,EACdC,SAAU,EACVC,iBAAkB,EAClBC,OAAQ,EACRC,YAAa,EACbC,cAAe,EACfC,cAAe,EACfC,eAAgB,EAChBC,aAAc,EACdC,cAAe,EACfC,iBAAkB,EAClBC,iBAAkB,EAClBC,eAAgB,EAChBC,iBAAkB,EAClBC,cAAe,EACfC,UAAW,GC5Bb,IAAK,IAAIC,MAAmBC,GAAc,CACxC,IAAIC,GAAallB,EAAOglB,IACpBG,GAAsBD,IAAcA,GAAW5e,UAEnD,GAAI6e,IAAuBA,GAAoBzW,UAAYA,GAAS,IAClEhL,EAA4ByhB,GAAqB,UAAWzW,IAC5D,MAAOvO,GACPglB,GAAoBzW,QAAUA,ICNlC,IAAIgD,GAAWjF,gBAAgB,YAC3BwE,GAAgBxE,gBAAgB,eAChC2Y,GAAcC,GAAqBzK,OAEvC,IAAK,IAAIoK,MAAmBC,GAAc,CACxC,IAAIC,GAAallB,EAAOglB,IACpBG,GAAsBD,IAAcA,GAAW5e,UACnD,GAAI6e,GAAqB,CAEvB,GAAIA,GAAoBzT,MAAc0T,GAAa,IACjD1hB,EAA4ByhB,GAAqBzT,GAAU0T,IAC3D,MAAOjlB,GACPglB,GAAoBzT,IAAY0T,GAKlC,GAHKD,GAAoBlU,KACvBvN,EAA4ByhB,GAAqBlU,GAAe+T,IAE9DC,GAAaD,IAAkB,IAAK,IAAI3V,MAAegW,GAEzD,GAAIF,GAAoB9V,MAAiBgW,GAAqBhW,IAAc,IAC1E3L,EAA4ByhB,GAAqB9V,GAAagW,GAAqBhW,KACnF,MAAOlP,GACPglB,GAAoB9V,IAAegW,GAAqBhW,2rBCrB5DiW,EAAW,SAAUC,OAKnB9jB,EAFA+jB,EAAKnlB,OAAOiG,UACZmf,EAASD,EAAGrjB,eAEZuZ,EAA4B,mBAAXtR,OAAwBA,OAAS,GAClDsb,EAAiBhK,EAAQpR,UAAY,aACrCqb,EAAsBjK,EAAQkK,eAAiB,kBAC/CC,EAAoBnK,EAAQoK,aAAe,yBAEtCC,OAAOC,EAAK5jB,EAAKlB,UACxBb,OAAOC,eAAe0lB,EAAK5jB,EAAK,CAC9BlB,MAAOA,EACPF,YAAY,EACZG,cAAc,EACdC,UAAU,IAEL4kB,EAAI5jB,OAIX2jB,OAAO,GAAI,IACX,MAAOE,GACPF,OAAS,gBAASC,EAAK5jB,EAAKlB,UACnB8kB,EAAI5jB,GAAOlB,YAIbmZ,KAAK6L,EAASC,EAASpmB,EAAMqmB,OAEhCC,EAAiBF,GAAWA,EAAQ7f,qBAAqBggB,UAAYH,EAAUG,UAC/EC,EAAYlmB,OAAOkM,OAAO8Z,EAAe/f,WACzCkgB,EAAU,IAAIC,QAAQL,GAAe,WAIzCG,EAAUG,iBAsMHC,iBAAiBT,EAASnmB,EAAMymB,OACnC9gB,EAAQkhB,SAEL,SAASC,OAAOngB,EAAQgH,MACzBhI,IAAUohB,QACN,IAAIC,MAAM,mCAGdrhB,IAAUshB,EAAmB,IAChB,UAAXtgB,QACIgH,SAKDuZ,iBAGTT,EAAQ9f,OAASA,EACjB8f,EAAQ9Y,IAAMA,IAED,KACPwZ,EAAWV,EAAQU,YACnBA,EAAU,KACRC,EAAiBC,oBAAoBF,EAAUV,MAC/CW,EAAgB,IACdA,IAAmBE,EAAkB,gBAClCF,MAIY,SAAnBX,EAAQ9f,OAGV8f,EAAQc,KAAOd,EAAQe,MAAQf,EAAQ9Y,SAElC,GAAuB,UAAnB8Y,EAAQ9f,OAAoB,IACjChB,IAAUkhB,QACZlhB,EAAQshB,EACFR,EAAQ9Y,IAGhB8Y,EAAQgB,kBAAkBhB,EAAQ9Y,SAEN,WAAnB8Y,EAAQ9f,QACjB8f,EAAQiB,OAAO,SAAUjB,EAAQ9Y,KAGnChI,EAAQohB,MAEJY,EAASC,SAASzB,EAASnmB,EAAMymB,MACjB,WAAhBkB,EAAO/hB,KAAmB,IAG5BD,EAAQ8gB,EAAQjU,KACZyU,EACAY,EAEAF,EAAOha,MAAQ2Z,iBAIZ,CACLnmB,MAAOwmB,EAAOha,IACd6E,KAAMiU,EAAQjU,MAGS,UAAhBmV,EAAO/hB,OAChBD,EAAQshB,EAGRR,EAAQ9f,OAAS,QACjB8f,EAAQ9Y,IAAMga,EAAOha,OA9QPiZ,CAAiBT,EAASnmB,EAAMymB,GAE7CD,WAcAoB,SAAS3lB,EAAIgkB,EAAKtY,aAEhB,CAAE/H,KAAM,SAAU+H,IAAK1L,EAAGrB,KAAKqlB,EAAKtY,IAC3C,MAAOuY,SACA,CAAEtgB,KAAM,QAAS+H,IAAKuY,IAhBjCV,EAAQlL,KAAOA,SAoBXuM,EAAyB,iBACzBgB,EAAyB,iBACzBd,EAAoB,YACpBE,EAAoB,YAIpBK,EAAmB,YAMdf,sBACAuB,8BACAC,kCAILvJ,EAAoB,GACxBA,EAAkBmH,GAAkB,kBAC3B3kB,UAGLgnB,EAAW1nB,OAAOqe,eAClBsJ,EAA0BD,GAAYA,EAASA,EAASnN,OAAO,MAC/DoN,GACAA,IAA4BxC,GAC5BC,EAAO9kB,KAAKqnB,EAAyBtC,KAGvCnH,EAAoByJ,OAGlBC,EAAKH,2BAA2BxhB,UAClCggB,UAAUhgB,UAAYjG,OAAOkM,OAAOgS,YAW7B2J,sBAAsB5hB,IAC5B,OAAQ,QAAS,UAAUoI,SAAQ,SAAShI,GAC3Cqf,OAAOzf,EAAWI,GAAQ,SAASgH,UAC1B3M,KAAK2lB,QAAQhgB,EAAQgH,kBAkCzBya,cAAc5B,EAAW6B,OAgC5BC,OAgCC3B,iBA9BI4B,QAAQ5hB,EAAQgH,YACd6a,oCACA,IAAIH,GAAY,SAASlS,EAASO,aAnCpCoQ,OAAOngB,EAAQgH,EAAKwI,EAASO,OAChCiR,EAASC,SAASpB,EAAU7f,GAAS6f,EAAW7Y,MAChC,UAAhBga,EAAO/hB,KAEJ,KACDuC,EAASwf,EAAOha,IAChBxM,EAAQgH,EAAOhH,aACfA,GACiB,WAAjBsnB,QAAOtnB,IACPukB,EAAO9kB,KAAKO,EAAO,WACdknB,EAAYlS,QAAQhV,EAAMunB,SAASrT,MAAK,SAASlU,GACtD2lB,OAAO,OAAQ3lB,EAAOgV,EAASO,MAC9B,SAASwP,GACVY,OAAO,QAASZ,EAAK/P,EAASO,MAI3B2R,EAAYlS,QAAQhV,GAAOkU,MAAK,SAASsT,GAI9CxgB,EAAOhH,MAAQwnB,EACfxS,EAAQhO,MACP,SAAS/H,UAGH0mB,OAAO,QAAS1mB,EAAO+V,EAASO,MAvBzCA,EAAOiR,EAAOha,KAiCZmZ,CAAOngB,EAAQgH,EAAKwI,EAASO,aAI1B4R,EAaLA,EAAkBA,EAAgBjT,KAChCmT,2BAGAA,4BACEA,uCAkHDnB,oBAAoBF,EAAUV,OACjC9f,EAASwgB,EAAS5c,SAASkc,EAAQ9f,WACnCA,IAAWjF,EAAW,IAGxB+kB,EAAQU,SAAW,KAEI,UAAnBV,EAAQ9f,OAAoB,IAE1BwgB,EAAS5c,SAAT,SAGFkc,EAAQ9f,OAAS,SACjB8f,EAAQ9Y,IAAMjM,EACd2lB,oBAAoBF,EAAUV,GAEP,UAAnBA,EAAQ9f,eAGH2gB,EAIXb,EAAQ9f,OAAS,QACjB8f,EAAQ9Y,IAAM,IAAIhM,UAChB,yDAGG2lB,MAGLK,EAASC,SAASjhB,EAAQwgB,EAAS5c,SAAUkc,EAAQ9Y,QAErC,UAAhBga,EAAO/hB,YACT6gB,EAAQ9f,OAAS,QACjB8f,EAAQ9Y,IAAMga,EAAOha,IACrB8Y,EAAQU,SAAW,KACZG,MAGLsB,EAAOjB,EAAOha,WAEZib,EAOFA,EAAKpW,MAGPiU,EAAQU,EAAS0B,YAAcD,EAAKznB,MAGpCslB,EAAQrU,KAAO+U,EAAS2B,QAQD,WAAnBrC,EAAQ9f,SACV8f,EAAQ9f,OAAS,OACjB8f,EAAQ9Y,IAAMjM,GAUlB+kB,EAAQU,SAAW,KACZG,GANEsB,GA3BPnC,EAAQ9f,OAAS,QACjB8f,EAAQ9Y,IAAM,IAAIhM,UAAU,oCAC5B8kB,EAAQU,SAAW,KACZG,YAoDFyB,aAAaC,OAChBC,EAAQ,CAAEC,OAAQF,EAAK,IAEvB,KAAKA,IACPC,EAAME,SAAWH,EAAK,IAGpB,KAAKA,IACPC,EAAMG,WAAaJ,EAAK,GACxBC,EAAMI,SAAWL,EAAK,SAGnBM,WAAWllB,KAAK6kB,YAGdM,cAAcN,OACjBtB,EAASsB,EAAMO,YAAc,GACjC7B,EAAO/hB,KAAO,gBACP+hB,EAAOha,IACdsb,EAAMO,WAAa7B,WAGZjB,QAAQL,QAIViD,WAAa,CAAC,CAAEJ,OAAQ,SAC7B7C,EAAY1X,QAAQoa,aAAc/nB,WAC7ByoB,OAAM,YA8BJ5O,OAAO7I,MACVA,EAAU,KACR0X,EAAiB1X,EAAS2T,MAC1B+D,SACKA,EAAe9oB,KAAKoR,MAGA,mBAAlBA,EAASI,YACXJ,MAGJ9K,MAAM8K,EAASnL,QAAS,KACvBqB,GAAK,EAAGkK,EAAO,SAASA,cACjBlK,EAAI8J,EAASnL,WAChB6e,EAAO9kB,KAAKoR,EAAU9J,UACxBkK,KAAKjR,MAAQ6Q,EAAS9J,GACtBkK,KAAKI,MAAO,EACLJ,YAIXA,KAAKjR,MAAQO,EACb0Q,KAAKI,MAAO,EAELJ,aAGFA,EAAKA,KAAOA,SAKhB,CAAEA,KAAM8U,qBAIRA,mBACA,CAAE/lB,MAAOO,EAAW8Q,MAAM,UA7ZnCsV,kBAAkBvhB,UAAY2hB,EAAGna,YAAcga,2BAC/CA,2BAA2Bha,YAAc+Z,kBACzCA,kBAAkB6B,YAAc3D,OAC9B+B,2BACAjC,EACA,qBAaFN,EAAQoE,oBAAsB,SAASC,OACjCC,EAAyB,mBAAXD,GAAyBA,EAAO9b,oBAC3C+b,IACHA,IAAShC,mBAG2B,uBAAnCgC,EAAKH,aAAeG,EAAKlf,QAIhC4a,EAAQuE,KAAO,SAASF,UAClBvpB,OAAOye,eACTze,OAAOye,eAAe8K,EAAQ9B,6BAE9B8B,EAAO3K,UAAY6I,2BACnB/B,OAAO6D,EAAQ/D,EAAmB,sBAEpC+D,EAAOtjB,UAAYjG,OAAOkM,OAAO0b,GAC1B2B,GAOTrE,EAAQwE,MAAQ,SAASrc,SAChB,CAAE+a,QAAS/a,IAsEpBwa,sBAAsBC,cAAc7hB,WACpC6hB,cAAc7hB,UAAUqf,GAAuB,kBACtC5kB,MAETwkB,EAAQ4C,cAAgBA,cAKxB5C,EAAQyE,MAAQ,SAAS9D,EAASC,EAASpmB,EAAMqmB,EAAagC,QACxC,IAAhBA,IAAwBA,EAAc5W,aAEtCyY,EAAO,IAAI9B,cACb9N,KAAK6L,EAASC,EAASpmB,EAAMqmB,GAC7BgC,UAGK7C,EAAQoE,oBAAoBxD,GAC/B8D,EACAA,EAAK9X,OAAOiD,MAAK,SAASlN,UACjBA,EAAOqK,KAAOrK,EAAOhH,MAAQ+oB,EAAK9X,WAuKjD+V,sBAAsBD,GAEtBlC,OAAOkC,EAAIpC,EAAmB,aAO9BoC,EAAGvC,GAAkB,kBACZ3kB,MAGTknB,EAAG5mB,SAAW,iBACL,sBAkCTkkB,EAAQ7gB,KAAO,SAASlB,OAClBkB,EAAO,OACN,IAAItC,KAAOoB,EACdkB,EAAKP,KAAK/B,UAEZsC,EAAK8b,UAIE,SAASrO,YACPzN,EAAKkC,QAAQ,KACdxE,EAAMsC,EAAKwlB,SACX9nB,KAAOoB,SACT2O,KAAKjR,MAAQkB,EACb+P,KAAKI,MAAO,EACLJ,YAOXA,KAAKI,MAAO,EACLJ,OAsCXoT,EAAQ3K,OAASA,OAMjB6L,QAAQngB,UAAY,CAClBwH,YAAa2Y,QAEb+C,MAAO,eAASW,WACTC,KAAO,OACPjY,KAAO,OAGPmV,KAAOvmB,KAAKwmB,MAAQ9lB,OACpB8Q,MAAO,OACP2U,SAAW,UAEXxgB,OAAS,YACTgH,IAAMjM,OAEN4nB,WAAW3a,QAAQ4a,gBAEnBa,MACE,IAAIxf,KAAQ5J,KAEQ,MAAnB4J,EAAKmY,OAAO,IACZ2C,EAAO9kB,KAAKI,KAAM4J,KACjB1D,OAAO0D,EAAKrJ,MAAM,WAChBqJ,GAAQlJ,IAMrBgR,KAAM,qBACCF,MAAO,MAGR8X,EADYtpB,KAAKsoB,WAAW,GACLE,cACH,UAApBc,EAAW1kB,WACP0kB,EAAW3c,WAGZ3M,KAAKupB,MAGd9C,kBAAmB,2BAAS+C,MACtBxpB,KAAKwR,WACDgY,MAGJ/D,EAAUzlB,cACLypB,OAAOC,EAAKC,UACnBhD,EAAO/hB,KAAO,QACd+hB,EAAOha,IAAM6c,EACb/D,EAAQrU,KAAOsY,EAEXC,IAGFlE,EAAQ9f,OAAS,OACjB8f,EAAQ9Y,IAAMjM,KAGNipB,MAGP,IAAIziB,EAAIlH,KAAKsoB,WAAWziB,OAAS,EAAGqB,GAAK,IAAKA,EAAG,KAChD+gB,EAAQjoB,KAAKsoB,WAAWphB,GACxByf,EAASsB,EAAMO,cAEE,SAAjBP,EAAMC,cAIDuB,OAAO,UAGZxB,EAAMC,QAAUloB,KAAKqpB,KAAM,KACzBO,EAAWlF,EAAO9kB,KAAKqoB,EAAO,YAC9B4B,EAAanF,EAAO9kB,KAAKqoB,EAAO,iBAEhC2B,GAAYC,EAAY,IACtB7pB,KAAKqpB,KAAOpB,EAAME,gBACbsB,OAAOxB,EAAME,UAAU,GACzB,GAAInoB,KAAKqpB,KAAOpB,EAAMG,kBACpBqB,OAAOxB,EAAMG,iBAGjB,GAAIwB,MACL5pB,KAAKqpB,KAAOpB,EAAME,gBACbsB,OAAOxB,EAAME,UAAU,OAG3B,CAAA,IAAI0B,QAMH,IAAI7D,MAAM,6CALZhmB,KAAKqpB,KAAOpB,EAAMG,kBACbqB,OAAOxB,EAAMG,gBAU9B1B,OAAQ,gBAAS9hB,EAAM+H,OAChB,IAAIzF,EAAIlH,KAAKsoB,WAAWziB,OAAS,EAAGqB,GAAK,IAAKA,EAAG,KAChD+gB,EAAQjoB,KAAKsoB,WAAWphB,MACxB+gB,EAAMC,QAAUloB,KAAKqpB,MACrB3E,EAAO9kB,KAAKqoB,EAAO,eACnBjoB,KAAKqpB,KAAOpB,EAAMG,WAAY,KAC5B0B,EAAe7B,SAKnB6B,IACU,UAATllB,GACS,aAATA,IACDklB,EAAa5B,QAAUvb,GACvBA,GAAOmd,EAAa1B,aAGtB0B,EAAe,UAGbnD,EAASmD,EAAeA,EAAatB,WAAa,UACtD7B,EAAO/hB,KAAOA,EACd+hB,EAAOha,IAAMA,EAETmd,QACGnkB,OAAS,YACTyL,KAAO0Y,EAAa1B,WAClB9B,GAGFtmB,KAAK+pB,SAASpD,IAGvBoD,SAAU,kBAASpD,EAAQ0B,MACL,UAAhB1B,EAAO/hB,WACH+hB,EAAOha,UAGK,UAAhBga,EAAO/hB,MACS,aAAhB+hB,EAAO/hB,UACJwM,KAAOuV,EAAOha,IACM,WAAhBga,EAAO/hB,WACX2kB,KAAOvpB,KAAK2M,IAAMga,EAAOha,SACzBhH,OAAS,cACTyL,KAAO,OACa,WAAhBuV,EAAO/hB,MAAqByjB,SAChCjX,KAAOiX,GAGP/B,GAGT0D,OAAQ,gBAAS5B,OACV,IAAIlhB,EAAIlH,KAAKsoB,WAAWziB,OAAS,EAAGqB,GAAK,IAAKA,EAAG,KAChD+gB,EAAQjoB,KAAKsoB,WAAWphB,MACxB+gB,EAAMG,aAAeA,cAClB2B,SAAS9B,EAAMO,WAAYP,EAAMI,UACtCE,cAAcN,GACP3B,UAKJ,gBAAS4B,OACX,IAAIhhB,EAAIlH,KAAKsoB,WAAWziB,OAAS,EAAGqB,GAAK,IAAKA,EAAG,KAChD+gB,EAAQjoB,KAAKsoB,WAAWphB,MACxB+gB,EAAMC,SAAWA,EAAQ,KACvBvB,EAASsB,EAAMO,cACC,UAAhB7B,EAAO/hB,KAAkB,KACvBqlB,EAAStD,EAAOha,IACpB4b,cAAcN,UAETgC,SAML,IAAIjE,MAAM,0BAGlBkE,cAAe,uBAASlZ,EAAU6W,EAAYC,eACvC3B,SAAW,CACd5c,SAAUsQ,OAAO7I,GACjB6W,WAAYA,EACZC,QAASA,GAGS,SAAhB9nB,KAAK2F,cAGFgH,IAAMjM,GAGN4lB,IAQJ9B,EA7sBM,CAotBgBrhB,EAAOqhB,aAIpC2F,mBAAqB5F,EACrB,MAAO6F,GAUPlrB,SAAS,IAAK,yBAAdA,CAAwCqlB,2SCluB1C,IAAM8F,+DAA2B,iBAAgBC,2HAGnBC,qDAAmBD,iBAA7CE,gEAGArS,QAAQ/Y,qCAA8BkrB,+BACZ7Z,wDAA1B+Z,0CAEKA,0FATHH,kEAYS,CACbzgB,KAAM,UACA6gB,mBAAMza,sGAiCD0a,EAqBAC,EASAC,EAQAC,uGAAAA,gBAAKhL,UACL,EAAIhhB,KAAKisB,IAAIjL,IATb+K,gBAAK/K,UACL,EAAIhhB,KAAKksB,IAAIlL,IAVb8K,oBAASK,EAAM9pB,GACtB+pB,EAAUC,wBAAwBF,EAAM9pB,GACxC+pB,EAAUrrB,KAAK,UAAWurB,IAvBnBT,sBAAWU,OACdC,EAAUxf,EAAE,aACXwf,EAAQxlB,SACXwlB,EAAUxf,EAAE,iCAAiCyf,SAAS,SAExDD,EAAQE,KAAMH,EAAU,8CAAL,IACnBvf,EAAE,kBAAkBqI,OAAOkX,IArCvBH,GADAO,EAAYC,GACUC,OACrB7f,EAAKmE,EAALnE,GAES,WACMwe,GAAyBmB,EAAUG,SAASrB,oBAA5DsB,SAiHAC,EAAU,CAAC,CACfroB,GAAI,eACJsoB,KAAM,cACNlnB,KAAM,OACNgd,SAAU,GACVmK,OAAQ,CACNC,uBACEf,EAAUgB,QAAQ,WAClBvB,GAAU,OAIVwB,EAAe,CAAC,CACpBtnB,KAAM,QACNunB,MAAO,gBACP3oB,GAAI,YACJqe,KAAM,EACNuK,OAAQ,EACRL,OAAQ,CACNM,yBACE1B,EAAQ,QAAS3qB,KAAKG,6BAIrB,CACLyJ,KAAMgiB,EAAQhiB,KACd0iB,SAAU,oBACVT,QAASD,EAAQC,QAAQje,KAAI,SAAC2e,EAAQrlB,UAC7B5H,OAAOmQ,OAAOoc,EAAQ3kB,GAAIqlB,MAEnCC,cAAeZ,EAAQM,aAAate,KAAI,SAAC6e,EAAavlB,UAC7C5H,OAAOmQ,OAAOyc,EAAahlB,GAAIulB,MAGxCC,6BACE7gB,EAAE,kBAAkB8gB,OAOpB9Y,YAAW,WAEUhI,EAAE,qBAAqB+gB,QAAQD,OAAO3B,KACvD,KAAM,gBACN6B,SAASvB,SACT,qBACAU,OAAM,eAkBangB,EAAE,uBAAuB+gB,QAAQD,OAAO3B,KAC3D,KAAM,kBACN6B,SAASvB,SAAS,qBAAqBU,OAAM,iBAG9C,MAELc,6BAAWC,MACmB,YAAxB9B,EAAU+B,eAIRC,EAAMhC,EAAUiC,SAAS,QAEzBC,EAAOlC,EAAUiC,SAAS,UAE1BE,EAASnC,EAAUoC,wBAEzBC,GAAU,EAEVC,EAAQtC,EAAUuC,sBAAsB,CACtCC,QAAS,UACTzC,KAAM,CACJ0C,GAAIX,EAAKY,QACTC,GAAIb,EAAKc,QACTrqB,GAAIynB,EAAU6C,YACdC,MAAO,cACPC,MAAO1sB,SAAS2sB,eAAe,aAAa9tB,MAC5C+tB,OAAQ,IACRC,KAAM,EACNpiB,KAAMkhB,EACNmB,YAAajB,EACbkB,YAAajB,KAIV,CACLE,SAAS,KAGbgB,6BAAWvB,MACJO,GAAmC,YAAxBrC,EAAU+B,eAIpBxgB,EAAIX,EAAE0hB,GAAOvC,KAAK,CAAC,KAAM,KAAM,QAAS,SAAU,OAAQ,cAAe,gBAC3EnV,EAAIkX,EAAKwB,QACTC,EAAIzB,EAAK0B,QACNf,EAAiDlhB,EAAjDkhB,GAAIE,EAA6CphB,EAA7CohB,GAAI7hB,EAAyCS,EAAzCT,KAAMqiB,EAAmC5hB,EAAnC4hB,YAAaC,EAAsB7hB,EAAtB6hB,YAAaL,EAASxhB,EAATwhB,MAC7CU,EAAO7vB,KAAK8vB,MAAM9Y,EAAI6X,IAAO7X,EAAI6X,IAAOc,EAAIZ,IAAOY,EAAIZ,IAAQ,IACjEL,EAAMqB,aAAa,OAAQF,WAGrBG,EADYH,EAAM,EAAK9D,EAAI/rB,KAAKiwB,GAAKd,GACXnD,EAAIhsB,KAAKiwB,GAAKd,GAC1Ce,EAAS,GACJC,EAAI,EAAGhB,GAASgB,EAAGA,IAAK,KACzBC,EAAQ,EAAMpwB,KAAKiwB,GAAKE,EAAIhB,EAIlCe,IAHAlZ,EAAKgZ,EAAehwB,KAAKisB,IAAImE,GAAUvB,GAGzB,KAFdc,EAAKK,EAAehwB,KAAKqwB,IAAID,GAAUrB,GAEf,WAI1BL,EAAMqB,aAAa,SAAUG,GAC7BxB,EAAMqB,aAAa,OAAQ7iB,GAC3BwhB,EAAMqB,aAAa,SAAUR,GAC7Bb,EAAMqB,aAAa,eAAgBP,GAK5B,CACLf,SAAS,KAIb6B,yBAASpC,MACqB,YAAxB9B,EAAU+B,gBAMP,CACLoC,KAH2B,MADfvjB,EAAE0hB,GAAOvC,KAAK,QACRmD,KAIlBV,QAASF,IAGb8B,yCAAiBtC,WAIX7lB,GAFJikB,EAAW4B,EAAKuC,OAECzpB,OACVqB,KAAK,KACJqoB,EAAOpE,EAASjkB,GAClBqoB,GAAuC,gBAA/BA,EAAKC,aAAa,UACxBzC,EAAK0C,kBAAoB1C,EAAK2C,eAChC7jB,EAAE,cAAc3K,IAAIquB,EAAKC,aAAa,UAEtC9E,GAAU,IAKZA,GAAU,KAIhBiF,uCAAgB5C,uGC5TP,CACbnjB,KAAM,UACNiiB,QAAS,CACP,CACE+D,MAAO,iBAGX1D,aAAc,CACZ,CACE0D,MAAO,kBACPC,MAAO,sDCVE,CACbjmB,KAAM,MACNiiB,QAAS,CACP,CACE+D,MAAO,UAGX1D,aAAc,CACZ,CACE0D,MAAO,KACPC,MAAO"} \ No newline at end of file diff --git a/dist/editor/extensions/ext-server_moinsave/ext-server_moinsave.js b/dist/editor/extensions/ext-server_moinsave/ext-server_moinsave.js new file mode 100644 index 00000000..898b117c --- /dev/null +++ b/dist/editor/extensions/ext-server_moinsave/ext-server_moinsave.js @@ -0,0 +1,2 @@ +var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t,r,i){return t(i={path:r,exports:{},require:function(t,r){return function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==r&&i.path)}},i.exports),i.exports}var check=function(t){return t&&t.Math==Math&&t},r=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof t&&t)||Function("return this")(),fails=function(t){try{return!!t()}catch(t){return!0}},i=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),o={}.propertyIsEnumerable,a=Object.getOwnPropertyDescriptor,u={f:a&&!o.call({1:2},1)?function propertyIsEnumerable(t){var r=a(this,t);return!!r&&r.enumerable}:o},createPropertyDescriptor=function(t,r){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:r}},l={}.toString,classofRaw=function(t){return l.call(t).slice(8,-1)},h="".split,p=fails((function(){return!Object("z").propertyIsEnumerable(0)}))?function(t){return"String"==classofRaw(t)?h.call(t,""):Object(t)}:Object,requireObjectCoercible=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t},toIndexedObject=function(t){return p(requireObjectCoercible(t))},isObject=function(t){return"object"==typeof t?null!==t:"function"==typeof t},toPrimitive=function(t,r){if(!isObject(t))return t;var i,o;if(r&&"function"==typeof(i=t.toString)&&!isObject(o=i.call(t)))return o;if("function"==typeof(i=t.valueOf)&&!isObject(o=i.call(t)))return o;if(!r&&"function"==typeof(i=t.toString)&&!isObject(o=i.call(t)))return o;throw TypeError("Can't convert object to primitive value")},y={}.hasOwnProperty,has=function(t,r){return y.call(t,r)},g=r.document,v=isObject(g)&&isObject(g.createElement),documentCreateElement=function(t){return v?g.createElement(t):{}},d=!i&&!fails((function(){return 7!=Object.defineProperty(documentCreateElement("div"),"a",{get:function(){return 7}}).a})),x=Object.getOwnPropertyDescriptor,b={f:i?x:function getOwnPropertyDescriptor(t,r){if(t=toIndexedObject(t),r=toPrimitive(r,!0),d)try{return x(t,r)}catch(t){}if(has(t,r))return createPropertyDescriptor(!u.f.call(t,r),t[r])}},anObject=function(t){if(!isObject(t))throw TypeError(String(t)+" is not an object");return t},S=Object.defineProperty,w={f:i?S:function defineProperty(t,r,i){if(anObject(t),r=toPrimitive(r,!0),anObject(i),d)try{return S(t,r,i)}catch(t){}if("get"in i||"set"in i)throw TypeError("Accessors not supported");return"value"in i&&(t[r]=i.value),t}},k=i?function(t,r,i){return w.f(t,r,createPropertyDescriptor(1,i))}:function(t,r,i){return t[r]=i,t},setGlobal=function(t,i){try{k(r,t,i)}catch(o){r[t]=i}return i},E=r["__core-js_shared__"]||setGlobal("__core-js_shared__",{}),P=Function.toString;"function"!=typeof E.inspectSource&&(E.inspectSource=function(t){return P.call(t)});var R,C,A,T=E.inspectSource,_=r.WeakMap,M="function"==typeof _&&/native code/.test(T(_)),O=createCommonjsModule((function(t){(t.exports=function(t,r){return E[t]||(E[t]=void 0!==r?r:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})})),N=0,L=Math.random(),uid=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++N+L).toString(36)},D=O("keys"),sharedKey=function(t){return D[t]||(D[t]=uid(t))},I={},$=r.WeakMap;if(M){var V=new $,j=V.get,B=V.has,G=V.set;R=function(t,r){return G.call(V,t,r),r},C=function(t){return j.call(V,t)||{}},A=function(t){return B.call(V,t)}}else{var z=sharedKey("state");I[z]=!0,R=function(t,r){return k(t,z,r),r},C=function(t){return has(t,z)?t[z]:{}},A=function(t){return has(t,z)}}var U,q,W={set:R,get:C,has:A,enforce:function(t){return A(t)?C(t):R(t,{})},getterFor:function(t){return function(r){var i;if(!isObject(r)||(i=C(r)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return i}}},H=createCommonjsModule((function(t){var i=W.get,o=W.enforce,a=String(String).split("String");(t.exports=function(t,i,u,l){var h=!!l&&!!l.unsafe,p=!!l&&!!l.enumerable,y=!!l&&!!l.noTargetGet;"function"==typeof u&&("string"!=typeof i||has(u,"name")||k(u,"name",i),o(u).source=a.join("string"==typeof i?i:"")),t!==r?(h?!y&&t[i]&&(p=!0):delete t[i],p?t[i]=u:k(t,i,u)):p?t[i]=u:setGlobal(i,u)})(Function.prototype,"toString",(function toString(){return"function"==typeof this&&i(this).source||T(this)}))})),X=r,aFunction=function(t){return"function"==typeof t?t:void 0},getBuiltIn=function(t,i){return arguments.length<2?aFunction(X[t])||aFunction(r[t]):X[t]&&X[t][i]||r[t]&&r[t][i]},Y=Math.ceil,Q=Math.floor,toInteger=function(t){return isNaN(t=+t)?0:(t>0?Q:Y)(t)},K=Math.min,toLength=function(t){return t>0?K(toInteger(t),9007199254740991):0},Z=Math.max,J=Math.min,toAbsoluteIndex=function(t,r){var i=toInteger(t);return i<0?Z(i+r,0):J(i,r)},createMethod=function(t){return function(r,i,o){var a,u=toIndexedObject(r),l=toLength(u.length),h=toAbsoluteIndex(o,l);if(t&&i!=i){for(;l>h;)if((a=u[h++])!=a)return!0}else for(;l>h;h++)if((t||h in u)&&u[h]===i)return t||h||0;return!t&&-1}},tt={includes:createMethod(!0),indexOf:createMethod(!1)},et=tt.indexOf,objectKeysInternal=function(t,r){var i,o=toIndexedObject(t),a=0,u=[];for(i in o)!has(I,i)&&has(o,i)&&u.push(i);for(;r.length>a;)has(o,i=r[a++])&&(~et(u,i)||u.push(i));return u},rt=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],nt=rt.concat("length","prototype"),it={f:Object.getOwnPropertyNames||function getOwnPropertyNames(t){return objectKeysInternal(t,nt)}},ot={f:Object.getOwnPropertySymbols},at=getBuiltIn("Reflect","ownKeys")||function ownKeys(t){var r=it.f(anObject(t)),i=ot.f;return i?r.concat(i(t)):r},copyConstructorProperties=function(t,r){for(var i=at(r),o=w.f,a=b.f,u=0;u=74)&&(U=St.match(/Chrome\/(\d+)/))&&(q=U[1]);var Pt=q&&+q,Rt=wellKnownSymbol("species"),arrayMethodHasSpeciesSupport=function(t){return Pt>=51||!fails((function(){var r=[];return(r.constructor={})[Rt]=function(){return{foo:1}},1!==r[t](Boolean).foo}))},Ct=wellKnownSymbol("isConcatSpreadable"),At=Pt>=51||!fails((function(){var t=[];return t[Ct]=!1,t.concat()[0]!==t})),Tt=arrayMethodHasSpeciesSupport("concat"),isConcatSpreadable=function(t){if(!isObject(t))return!1;var r=t[Ct];return void 0!==r?!!r:yt(t)};_export({target:"Array",proto:!0,forced:!At||!Tt},{concat:function concat(t){var r,i,o,a,u,l=toObject(this),h=arraySpeciesCreate(l,0),p=0;for(r=-1,o=arguments.length;r9007199254740991)throw TypeError("Maximum allowed index exceeded");for(i=0;i=9007199254740991)throw TypeError("Maximum allowed index exceeded");createProperty(h,p++,u)}return h.length=p,h}});var _t,Mt=Object.keys||function keys(t){return objectKeysInternal(t,rt)},Ot=i?Object.defineProperties:function defineProperties(t,r){anObject(t);for(var i,o=Mt(r),a=o.length,u=0;a>u;)w.f(t,i=o[u++],r[i]);return t},Nt=getBuiltIn("document","documentElement"),Lt=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(t){return" + + + + + SVG-edit + + + + + + + + \ No newline at end of file diff --git a/dist/editor/index.js b/dist/editor/index.js new file mode 100644 index 00000000..f5091467 --- /dev/null +++ b/dist/editor/index.js @@ -0,0 +1,581 @@ +var Tn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(Tn,Un,Qn){return Tn(Qn={path:Un,exports:{},require:function(Tn,Un){return function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==Un&&Qn.path)}},Qn.exports),Qn.exports}var check=function(Tn){return Tn&&Tn.Math==Math&&Tn},Un=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof Tn&&Tn)||Function("return this")(),fails=function(Tn){try{return!!Tn()}catch(Tn){return!0}},Qn=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Dn={}.propertyIsEnumerable,Hn=Object.getOwnPropertyDescriptor,Gn={f:Hn&&!Dn.call({1:2},1)?function propertyIsEnumerable(Tn){var Un=Hn(this,Tn);return!!Un&&Un.enumerable}:Dn},createPropertyDescriptor=function(Tn,Un){return{enumerable:!(1&Tn),configurable:!(2&Tn),writable:!(4&Tn),value:Un}},Vn={}.toString,classofRaw=function(Tn){return Vn.call(Tn).slice(8,-1)},zn="".split,Kn=fails((function(){return!Object("z").propertyIsEnumerable(0)}))?function(Tn){return"String"==classofRaw(Tn)?zn.call(Tn,""):Object(Tn)}:Object,requireObjectCoercible=function(Tn){if(null==Tn)throw TypeError("Can't call method on "+Tn);return Tn},toIndexedObject=function(Tn){return Kn(requireObjectCoercible(Tn))},isObject=function(Tn){return"object"==typeof Tn?null!==Tn:"function"==typeof Tn},toPrimitive=function(Tn,Un){if(!isObject(Tn))return Tn;var Qn,Dn;if(Un&&"function"==typeof(Qn=Tn.toString)&&!isObject(Dn=Qn.call(Tn)))return Dn;if("function"==typeof(Qn=Tn.valueOf)&&!isObject(Dn=Qn.call(Tn)))return Dn;if(!Un&&"function"==typeof(Qn=Tn.toString)&&!isObject(Dn=Qn.call(Tn)))return Dn;throw TypeError("Can't convert object to primitive value")},Wn={}.hasOwnProperty,has=function(Tn,Un){return Wn.call(Tn,Un)},Xn=Un.document,Yn=isObject(Xn)&&isObject(Xn.createElement),documentCreateElement=function(Tn){return Yn?Xn.createElement(Tn):{}},Jn=!Qn&&!fails((function(){return 7!=Object.defineProperty(documentCreateElement("div"),"a",{get:function(){return 7}}).a})),$n=Object.getOwnPropertyDescriptor,Zn={f:Qn?$n:function getOwnPropertyDescriptor(Tn,Un){if(Tn=toIndexedObject(Tn),Un=toPrimitive(Un,!0),Jn)try{return $n(Tn,Un)}catch(Tn){}if(has(Tn,Un))return createPropertyDescriptor(!Gn.f.call(Tn,Un),Tn[Un])}},anObject=function(Tn){if(!isObject(Tn))throw TypeError(String(Tn)+" is not an object");return Tn},er=Object.defineProperty,tr={f:Qn?er:function defineProperty(Tn,Un,Qn){if(anObject(Tn),Un=toPrimitive(Un,!0),anObject(Qn),Jn)try{return er(Tn,Un,Qn)}catch(Tn){}if("get"in Qn||"set"in Qn)throw TypeError("Accessors not supported");return"value"in Qn&&(Tn[Un]=Qn.value),Tn}},nr=Qn?function(Tn,Un,Qn){return tr.f(Tn,Un,createPropertyDescriptor(1,Qn))}:function(Tn,Un,Qn){return Tn[Un]=Qn,Tn},setGlobal=function(Tn,Qn){try{nr(Un,Tn,Qn)}catch(Dn){Un[Tn]=Qn}return Qn},rr=Un["__core-js_shared__"]||setGlobal("__core-js_shared__",{}),ir=Function.toString;"function"!=typeof rr.inspectSource&&(rr.inspectSource=function(Tn){return ir.call(Tn)});var or,ar,sr,lr=rr.inspectSource,cr=Un.WeakMap,ur="function"==typeof cr&&/native code/.test(lr(cr)),dr=createCommonjsModule((function(Tn){(Tn.exports=function(Tn,Un){return rr[Tn]||(rr[Tn]=void 0!==Un?Un:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})})),hr=0,pr=Math.random(),uid=function(Tn){return"Symbol("+String(void 0===Tn?"":Tn)+")_"+(++hr+pr).toString(36)},Ar=dr("keys"),sharedKey=function(Tn){return Ar[Tn]||(Ar[Tn]=uid(Tn))},fr={},gr=Un.WeakMap;if(ur){var mr=new gr,_r=mr.get,vr=mr.has,yr=mr.set;or=function(Tn,Un){return yr.call(mr,Tn,Un),Un},ar=function(Tn){return _r.call(mr,Tn)||{}},sr=function(Tn){return vr.call(mr,Tn)}}else{var wr=sharedKey("state");fr[wr]=!0,or=function(Tn,Un){return nr(Tn,wr,Un),Un},ar=function(Tn){return has(Tn,wr)?Tn[wr]:{}},sr=function(Tn){return has(Tn,wr)}}var br,xr,Sr={set:or,get:ar,has:sr,enforce:function(Tn){return sr(Tn)?ar(Tn):or(Tn,{})},getterFor:function(Tn){return function(Un){var Qn;if(!isObject(Un)||(Qn=ar(Un)).type!==Tn)throw TypeError("Incompatible receiver, "+Tn+" required");return Qn}}},kr=createCommonjsModule((function(Tn){var Qn=Sr.get,Dn=Sr.enforce,Hn=String(String).split("String");(Tn.exports=function(Tn,Qn,Gn,Vn){var zn=!!Vn&&!!Vn.unsafe,Kn=!!Vn&&!!Vn.enumerable,Wn=!!Vn&&!!Vn.noTargetGet;"function"==typeof Gn&&("string"!=typeof Qn||has(Gn,"name")||nr(Gn,"name",Qn),Dn(Gn).source=Hn.join("string"==typeof Qn?Qn:"")),Tn!==Un?(zn?!Wn&&Tn[Qn]&&(Kn=!0):delete Tn[Qn],Kn?Tn[Qn]=Gn:nr(Tn,Qn,Gn)):Kn?Tn[Qn]=Gn:setGlobal(Qn,Gn)})(Function.prototype,"toString",(function toString(){return"function"==typeof this&&Qn(this).source||lr(this)}))})),Cr=Un,aFunction=function(Tn){return"function"==typeof Tn?Tn:void 0},getBuiltIn=function(Tn,Qn){return arguments.length<2?aFunction(Cr[Tn])||aFunction(Un[Tn]):Cr[Tn]&&Cr[Tn][Qn]||Un[Tn]&&Un[Tn][Qn]},Br=Math.ceil,Er=Math.floor,toInteger=function(Tn){return isNaN(Tn=+Tn)?0:(Tn>0?Er:Br)(Tn)},Nr=Math.min,toLength=function(Tn){return Tn>0?Nr(toInteger(Tn),9007199254740991):0},Lr=Math.max,Tr=Math.min,toAbsoluteIndex=function(Tn,Un){var Qn=toInteger(Tn);return Qn<0?Lr(Qn+Un,0):Tr(Qn,Un)},createMethod=function(Tn){return function(Un,Qn,Dn){var Hn,Gn=toIndexedObject(Un),Vn=toLength(Gn.length),zn=toAbsoluteIndex(Dn,Vn);if(Tn&&Qn!=Qn){for(;Vn>zn;)if((Hn=Gn[zn++])!=Hn)return!0}else for(;Vn>zn;zn++)if((Tn||zn in Gn)&&Gn[zn]===Qn)return Tn||zn||0;return!Tn&&-1}},Pr={includes:createMethod(!0),indexOf:createMethod(!1)},Fr=Pr.indexOf,objectKeysInternal=function(Tn,Un){var Qn,Dn=toIndexedObject(Tn),Hn=0,Gn=[];for(Qn in Dn)!has(fr,Qn)&&has(Dn,Qn)&&Gn.push(Qn);for(;Un.length>Hn;)has(Dn,Qn=Un[Hn++])&&(~Fr(Gn,Qn)||Gn.push(Qn));return Gn},Ur=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ir=Ur.concat("length","prototype"),Rr={f:Object.getOwnPropertyNames||function getOwnPropertyNames(Tn){return objectKeysInternal(Tn,Ir)}},Mr={f:Object.getOwnPropertySymbols},Qr=getBuiltIn("Reflect","ownKeys")||function ownKeys(Tn){var Un=Rr.f(anObject(Tn)),Qn=Mr.f;return Qn?Un.concat(Qn(Tn)):Un},copyConstructorProperties=function(Tn,Un){for(var Qn=Qr(Un),Dn=tr.f,Hn=Zn.f,Gn=0;Gn=74)&&(br=Zr.match(/Chrome\/(\d+)/))&&(xr=br[1]);var ri=xr&&+xr,ii=wellKnownSymbol("species"),arrayMethodHasSpeciesSupport=function(Tn){return ri>=51||!fails((function(){var Un=[];return(Un.constructor={})[ii]=function(){return{foo:1}},1!==Un[Tn](Boolean).foo}))},oi=wellKnownSymbol("isConcatSpreadable"),ai=ri>=51||!fails((function(){var Tn=[];return Tn[oi]=!1,Tn.concat()[0]!==Tn})),si=arrayMethodHasSpeciesSupport("concat"),isConcatSpreadable=function(Tn){if(!isObject(Tn))return!1;var Un=Tn[oi];return void 0!==Un?!!Un:Kr(Tn)};_export({target:"Array",proto:!0,forced:!ai||!si},{concat:function concat(Tn){var Un,Qn,Dn,Hn,Gn,Vn=toObject(this),zn=arraySpeciesCreate(Vn,0),Kn=0;for(Un=-1,Dn=arguments.length;Un9007199254740991)throw TypeError("Maximum allowed index exceeded");for(Qn=0;Qn=9007199254740991)throw TypeError("Maximum allowed index exceeded");createProperty(zn,Kn++,Gn)}return zn.length=Kn,zn}});var aFunction$1=function(Tn){if("function"!=typeof Tn)throw TypeError(String(Tn)+" is not a function");return Tn},functionBindContext=function(Tn,Un,Qn){if(aFunction$1(Tn),void 0===Un)return Tn;switch(Qn){case 0:return function(){return Tn.call(Un)};case 1:return function(Qn){return Tn.call(Un,Qn)};case 2:return function(Qn,Dn){return Tn.call(Un,Qn,Dn)};case 3:return function(Qn,Dn,Hn){return Tn.call(Un,Qn,Dn,Hn)}}return function(){return Tn.apply(Un,arguments)}},li=[].push,createMethod$1=function(Tn){var Un=1==Tn,Qn=2==Tn,Dn=3==Tn,Hn=4==Tn,Gn=6==Tn,Vn=5==Tn||Gn;return function(zn,Wn,Xn,Yn){for(var Jn,$n,Zn=toObject(zn),er=Kn(Zn),tr=functionBindContext(Wn,Xn,3),nr=toLength(er.length),rr=0,ir=Yn||arraySpeciesCreate,or=Un?ir(zn,nr):Qn?ir(zn,0):void 0;nr>rr;rr++)if((Vn||rr in er)&&($n=tr(Jn=er[rr],rr,Zn),Tn))if(Un)or[rr]=$n;else if($n)switch(Tn){case 3:return!0;case 5:return Jn;case 6:return rr;case 2:li.call(or,Jn)}else if(Hn)return!1;return Gn?-1:Dn||Hn?Hn:or}},ui={forEach:createMethod$1(0),map:createMethod$1(1),filter:createMethod$1(2),some:createMethod$1(3),every:createMethod$1(4),find:createMethod$1(5),findIndex:createMethod$1(6)},di=Object.defineProperty,hi={},thrower=function(Tn){throw Tn},arrayMethodUsesToLength=function(Tn,Un){if(has(hi,Tn))return hi[Tn];Un||(Un={});var Dn=[][Tn],Hn=!!has(Un,"ACCESSORS")&&Un.ACCESSORS,Gn=has(Un,0)?Un[0]:thrower,Vn=has(Un,1)?Un[1]:void 0;return hi[Tn]=!!Dn&&!fails((function(){if(Hn&&!Qn)return!0;var Tn={length:-1};Hn?di(Tn,1,{enumerable:!0,get:thrower}):Tn[1]=1,Dn.call(Tn,Gn,Vn)}))},pi=ui.filter,Ai=arrayMethodHasSpeciesSupport("filter"),fi=arrayMethodUsesToLength("filter");_export({target:"Array",proto:!0,forced:!Ai||!fi},{filter:function filter(Tn){return pi(this,Tn,arguments.length>1?arguments[1]:void 0)}});var gi,mi=Object.keys||function keys(Tn){return objectKeysInternal(Tn,Ur)},_i=Qn?Object.defineProperties:function defineProperties(Tn,Un){anObject(Tn);for(var Qn,Dn=mi(Un),Hn=Dn.length,Gn=0;Hn>Gn;)tr.f(Tn,Qn=Dn[Gn++],Un[Qn]);return Tn},vi=getBuiltIn("document","documentElement"),yi=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(Tn){return" + + + + + + + +
+ + diff --git a/dist/editor/system/embedapi.js b/dist/editor/system/embedapi.js new file mode 100644 index 00000000..dd6459c4 --- /dev/null +++ b/dist/editor/system/embedapi.js @@ -0,0 +1,395 @@ +/** +* Handles underlying communication between the embedding window and the +* editor frame. +* @module EmbeddedSVGEdit +*/ + +let cbid = 0; + +/** +* @callback module:EmbeddedSVGEdit.CallbackSetter +* @param {GenericCallback} newCallback Callback to be stored (signature dependent on function) +* @returns {void} +*/ +/** +* @callback module:EmbeddedSVGEdit.CallbackSetGetter +* @param {...any} args Signature dependent on the function +* @returns {module:EmbeddedSVGEdit.CallbackSetter} +*/ + +/** +* @param {string} funcName +* @returns {module:EmbeddedSVGEdit.CallbackSetGetter} +*/ +function getCallbackSetter (funcName) { + return function (...args) { + const that = this, // New callback + callbackID = this.send(funcName, args, function () { /* */ }); // The callback (currently it's nothing, but will be set later) + + return function (newCallback) { + that.callbacks[callbackID] = newCallback; // Set callback + }; + }; +} + +/** +* Having this separate from messageListener allows us to +* avoid using JSON parsing (and its limitations) in the case +* of same domain control. +* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value +* @param {PlainObject} data +* @param {JSON} data.result +* @param {string} data.error +* @param {Integer} data.id +* @returns {void} +*/ +function addCallback (t, {result, error, id: callbackID}) { + if (typeof callbackID === 'number' && t.callbacks[callbackID]) { + // These should be safe both because we check `cbid` is numeric and + // because the calls are from trusted origins + if (result) { + t.callbacks[callbackID](result); // lgtm [js/unvalidated-dynamic-method-call] + } else { + t.callbacks[callbackID](error, 'error'); // lgtm [js/unvalidated-dynamic-method-call] + } + } +} + +/** +* @param {Event} e +* @returns {void} +*/ +function messageListener (e) { + // We accept and post strings as opposed to objects for the sake of IE9 support; this + // will most likely be changed in the future + if (!e.data || !['string', 'object'].includes(typeof e.data)) { + return; + } + const {allowedOrigins} = this, + data = typeof e.data === 'object' ? e.data : JSON.parse(e.data); + if (!data || typeof data !== 'object' || data.namespace !== 'svg-edit' || + e.source !== this.frame.contentWindow || + (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) + ) { + // eslint-disable-next-line no-console -- Info for developers + console.error( + `The origin ${e.origin} was not whitelisted as an origin from ` + + `which responses may be received by this ${window.origin} script.` + ); + return; + } + addCallback(this, data); +} + +/** +* @callback module:EmbeddedSVGEdit.MessageListener +* @param {MessageEvent} e +* @returns {void} +*/ +/** +* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value +* @returns {module:EmbeddedSVGEdit.MessageListener} Event listener +*/ +function getMessageListener (t) { + return function (e) { + messageListener.call(t, e); + }; +} + +/** +* Embedded SVG-edit API. +* General usage: +* - Have an iframe somewhere pointing to a version of svg-edit > r1000. +* @example +// Initialize the magic with: +const svgCanvas = new EmbeddedSVGEdit(window.frames.svgedit); + +// Pass functions in this format: +svgCanvas.setSvgString('string'); + +// Or if a callback is needed: +svgCanvas.setSvgString('string')(function (data, error) { + if (error) { + // There was an error + } else { + // Handle data + } +}); + +// Everything is done with the same API as the real svg-edit, +// and all documentation is unchanged. + +// However, this file depends on the postMessage API which +// can only support JSON-serializable arguments and +// return values, so, for example, arguments whose value is +// 'undefined', a function, a non-finite number, or a built-in +// object like Date(), RegExp(), etc. will most likely not behave +// as expected. In such a case one may need to host +// the SVG editor on the same domain and reference the +// JavaScript methods on the frame itself. + +// The only other difference is when handling returns: +// the callback notation is used instead. +const blah = new EmbeddedSVGEdit(window.frames.svgedit); +blah.clearSelection('woot', 'blah', 1337, [1, 2, 3, 4, 5, 'moo'], -42, { + a: 'tree', b: 6, c: 9 +})(function () { console.log('GET DATA', args); }); +* +* @memberof module:EmbeddedSVGEdit +*/ +class EmbeddedSVGEdit { + /** + * @param {HTMLIFrameElement} frame + * @param {string[]} [allowedOrigins=[]] Array of origins from which incoming + * messages will be allowed when same origin is not used; defaults to none. + * If supplied, it should probably be the same as svgEditor's allowedOrigins + */ + constructor (frame, allowedOrigins) { + const that = this; + this.allowedOrigins = allowedOrigins || []; + // Initialize communication + this.frame = frame; + this.callbacks = {}; + // List of functions extracted with this: + // Run in firebug on http://svg-edit.googlecode.com/svn/trunk/docs/files/svgcanvas-js.html + + // for (const i=0,q=[],f = document.querySelectorAll('div.CFunction h3.CTitle a'); i < f.length; i++) { q.push(f[i].name); }; q + // const functions = ['clearSelection', 'addToSelection', 'removeFromSelection', 'open', 'save', 'getSvgString', 'setSvgString', + // 'createLayer', 'deleteCurrentLayer', 'setCurrentLayer', 'renameCurrentLayer', 'setCurrentLayerPosition', 'setLayerVisibility', + // 'moveSelectedToLayer', 'clear']; + + // Newer, well, it extracts things that aren't documented as well. All functions accessible through the normal thingy can now be accessed though the API + // const {svgCanvas} = frame.contentWindow; + // const l = []; + // for (const i in svgCanvas) { if (typeof svgCanvas[i] === 'function') { l.push(i);} }; + // alert("['" + l.join("', '") + "']"); + // Run in svgedit itself + const functions = [ + 'addExtension', + 'addSVGElementFromJson', + 'addToSelection', + 'alignSelectedElements', + 'assignAttributes', + 'bind', + 'call', + 'changeSelectedAttribute', + 'cleanupElement', + 'clear', + 'clearSelection', + 'clearSvgContentElement', + 'cloneLayer', + 'cloneSelectedElements', + 'convertGradients', + 'convertToGroup', + 'convertToNum', + 'convertToPath', + 'copySelectedElements', + 'createLayer', + 'cutSelectedElements', + 'cycleElement', + 'deleteCurrentLayer', + 'deleteSelectedElements', + 'embedImage', + 'exportPDF', + 'findDefs', + 'getBBox', + 'getBlur', + 'getBold', + 'getColor', + 'getContentElem', + 'getCurrentDrawing', + 'getDocumentTitle', + 'getEditorNS', + 'getElem', + 'getFillOpacity', + 'getFontColor', + 'getFontFamily', + 'getFontSize', + 'getHref', + 'getId', + 'getIntersectionList', + 'getItalic', + 'getMode', + 'getMouseTarget', + 'getNextId', + 'getOffset', + 'getOpacity', + 'getPaintOpacity', + 'getPrivateMethods', + 'getRefElem', + 'getResolution', + 'getRootElem', + 'getRotationAngle', + 'getSelectedElems', + 'getStrokeOpacity', + 'getStrokeWidth', + 'getStrokedBBox', + 'getStyle', + 'getSvgString', + 'getText', + 'getTitle', + 'getTransformList', + 'getUIStrings', + 'getUrlFromAttr', + 'getVersion', + 'getVisibleElements', + 'getVisibleElementsAndBBoxes', + 'getZoom', + 'groupSelectedElements', + 'groupSvgElem', + 'hasMatrixTransform', + 'identifyLayers', + 'importSvgString', + 'leaveContext', + 'linkControlPoints', + 'makeHyperlink', + 'matrixMultiply', + 'mergeAllLayers', + 'mergeLayer', + 'moveSelectedElements', + 'moveSelectedToLayer', + 'moveToBottomSelectedElement', + 'moveToTopSelectedElement', + 'moveUpDownSelected', + 'open', + 'pasteElements', + 'prepareSvg', + 'pushGroupProperties', + 'randomizeIds', + 'rasterExport', + 'ready', + 'recalculateAllSelectedDimensions', + 'recalculateDimensions', + 'remapElement', + 'removeFromSelection', + 'removeHyperlink', + 'removeUnusedDefElems', + 'renameCurrentLayer', + 'round', + 'runExtensions', + 'sanitizeSvg', + 'save', + 'selectAllInCurrentLayer', + 'selectOnly', + 'setBBoxZoom', + 'setBackground', + 'setBlur', + 'setBlurNoUndo', + 'setBlurOffsets', + 'setBold', + 'setColor', + 'setConfig', + 'setContext', + 'setCurrentLayer', + 'setCurrentLayerPosition', + 'setDocumentTitle', + 'setFillPaint', + 'setFontColor', + 'setFontFamily', + 'setFontSize', + 'setGoodImage', + 'setGradient', + 'setGroupTitle', + 'setHref', + 'setIdPrefix', + 'setImageURL', + 'setItalic', + 'setLayerVisibility', + 'setLinkURL', + 'setMode', + 'setOpacity', + 'setPaint', + 'setPaintOpacity', + 'setRectRadius', + 'setResolution', + 'setRotationAngle', + 'setSegType', + 'setStrokeAttr', + 'setStrokePaint', + 'setStrokeWidth', + 'setSvgString', + 'setTextContent', + 'setUiStrings', + 'setUseData', + 'setZoom', + 'svgCanvasToString', + 'svgToString', + 'transformListToTransform', + 'ungroupSelectedElement', + 'uniquifyElems', + 'updateCanvas', + 'zoomChanged' + ]; + + // TODO: rewrite the following, it's pretty scary. + for (const func of functions) { + this[func] = getCallbackSetter(func); + } + + // Older IE may need a polyfill for addEventListener, but so it would for SVG + window.addEventListener('message', getMessageListener(this)); + window.addEventListener('keydown', (e) => { + const {type, key} = e; + if (key === 'Backspace') { + e.preventDefault(); + const keyboardEvent = new KeyboardEvent(type, {key}); + that.frame.contentDocument.dispatchEvent(keyboardEvent); + } + }); + } + + /** + * @param {string} name + * @param {ArgumentsArray} args Signature dependent on function + * @param {GenericCallback} callback (This may be better than a promise in case adding an event.) + * @returns {Integer} + */ + send (name, args, callback) { // eslint-disable-line promise/prefer-await-to-callbacks + const that = this; + cbid++; + + this.callbacks[cbid] = callback; + setTimeout((function (callbackID) { + return function () { // Delay for the callback to be set in case its synchronous + /* + * Todo: Handle non-JSON arguments and return values (undefined, + * nonfinite numbers, functions, and built-in objects like Date, + * RegExp), etc.? Allow promises instead of callbacks? Review + * SVG-Edit functions for whether JSON-able parameters can be + * made compatile with all API functionality + */ + // We accept and post strings for the sake of IE9 support + let sameOriginWithGlobal = false; + try { + sameOriginWithGlobal = window.location.origin === that.frame.contentWindow.location.origin && + that.frame.contentWindow.svgEditor.canvas; + } catch (err) {} + + if (sameOriginWithGlobal) { + // Although we do not really need this API if we are working same + // domain, it could allow us to write in a way that would work + // cross-domain as well, assuming we stick to the argument limitations + // of the current JSON-based communication API (e.g., not passing + // callbacks). We might be able to address these shortcomings; see + // the todo elsewhere in this file. + const message = {id: callbackID}, + {svgEditor: {canvas: svgCanvas}} = that.frame.contentWindow; + try { + message.result = svgCanvas[name](...args); + } catch (err) { + message.error = err.message; + } + addCallback(that, message); + } else { // Requires the ext-xdomain-messaging.js extension + that.frame.contentWindow.postMessage(JSON.stringify({ + namespace: 'svgCanvas', id: callbackID, name, args + }), '*'); + } + }; + }(cbid)), 0); + + return cbid; + } +} + +export default EmbeddedSVGEdit; diff --git a/dist/editor/system/extensions/ext-arrows/ext-arrows.js b/dist/editor/system/extensions/ext-arrows/ext-arrows.js new file mode 100644 index 00000000..6eb06ea7 --- /dev/null +++ b/dist/editor/system/extensions/ext-arrows/ext-arrows.js @@ -0,0 +1,9 @@ +System.register([],(function(t){"use strict";return{execute:function(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t,e,r){return t(r={path:e,exports:{},require:function(t,e){return function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==e&&r.path)}},r.exports),r.exports}var check=function(t){return t&&t.Math==Math&&t},r=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof e&&e)||Function("return this")(),fails=function(t){try{return!!t()}catch(t){return!0}},n=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),o={}.propertyIsEnumerable,i=Object.getOwnPropertyDescriptor,a={f:i&&!o.call({1:2},1)?function propertyIsEnumerable(t){var e=i(this,t);return!!e&&e.enumerable}:o},createPropertyDescriptor=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},c={}.toString,classofRaw=function(t){return c.call(t).slice(8,-1)},u="".split,f=fails((function(){return!Object("z").propertyIsEnumerable(0)}))?function(t){return"String"==classofRaw(t)?u.call(t,""):Object(t)}:Object,requireObjectCoercible=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t},toIndexedObject=function(t){return f(requireObjectCoercible(t))},isObject=function(t){return"object"==typeof t?null!==t:"function"==typeof t},toPrimitive=function(t,e){if(!isObject(t))return t;var r,n;if(e&&"function"==typeof(r=t.toString)&&!isObject(n=r.call(t)))return n;if("function"==typeof(r=t.valueOf)&&!isObject(n=r.call(t)))return n;if(!e&&"function"==typeof(r=t.toString)&&!isObject(n=r.call(t)))return n;throw TypeError("Can't convert object to primitive value")},l={}.hasOwnProperty,has=function(t,e){return l.call(t,e)},s=r.document,p=isObject(s)&&isObject(s.createElement),documentCreateElement=function(t){return p?s.createElement(t):{}},h=!n&&!fails((function(){return 7!=Object.defineProperty(documentCreateElement("div"),"a",{get:function(){return 7}}).a})),d=Object.getOwnPropertyDescriptor,v={f:n?d:function getOwnPropertyDescriptor(t,e){if(t=toIndexedObject(t),e=toPrimitive(e,!0),h)try{return d(t,e)}catch(t){}if(has(t,e))return createPropertyDescriptor(!a.f.call(t,e),t[e])}},anObject=function(t){if(!isObject(t))throw TypeError(String(t)+" is not an object");return t},y=Object.defineProperty,g={f:n?y:function defineProperty(t,e,r){if(anObject(t),e=toPrimitive(e,!0),anObject(r),h)try{return y(t,e,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported");return"value"in r&&(t[e]=r.value),t}},m=n?function(t,e,r){return g.f(t,e,createPropertyDescriptor(1,r))}:function(t,e,r){return t[e]=r,t},setGlobal=function(t,e){try{m(r,t,e)}catch(n){r[t]=e}return e},b="__core-js_shared__",w=r[b]||setGlobal(b,{}),S=Function.toString;"function"!=typeof w.inspectSource&&(w.inspectSource=function(t){return S.call(t)});var x,E,O,_=w.inspectSource,j=r.WeakMap,k="function"==typeof j&&/native code/.test(_(j)),P=createCommonjsModule((function(t){(t.exports=function(t,e){return w[t]||(w[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})})),A=0,T=Math.random(),uid=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++A+T).toString(36)},L=P("keys"),sharedKey=function(t){return L[t]||(L[t]=uid(t))},I={},R=r.WeakMap;if(k){var C=new R,M=C.get,G=C.has,N=C.set;x=function(t,e){return N.call(C,t,e),e},E=function(t){return M.call(C,t)||{}},O=function(t){return G.call(C,t)}}else{var D=sharedKey("state");I[D]=!0,x=function(t,e){return m(t,D,e),e},E=function(t){return has(t,D)?t[D]:{}},O=function(t){return has(t,D)}}var U,z={set:x,get:E,has:O,enforce:function(t){return O(t)?E(t):x(t,{})},getterFor:function(t){return function(e){var r;if(!isObject(e)||(r=E(e)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return r}}},W=createCommonjsModule((function(t){var e=z.get,n=z.enforce,o=String(String).split("String");(t.exports=function(t,e,i,a){var c=!!a&&!!a.unsafe,u=!!a&&!!a.enumerable,f=!!a&&!!a.noTargetGet;"function"==typeof i&&("string"!=typeof e||has(i,"name")||m(i,"name",e),n(i).source=o.join("string"==typeof e?e:"")),t!==r?(c?!f&&t[e]&&(u=!0):delete t[e],u?t[e]=i:m(t,e,i)):u?t[e]=i:setGlobal(e,i)})(Function.prototype,"toString",(function toString(){return"function"==typeof this&&e(this).source||_(this)}))})),$=r,aFunction=function(t){return"function"==typeof t?t:void 0},getBuiltIn=function(t,e){return arguments.length<2?aFunction($[t])||aFunction(r[t]):$[t]&&$[t][e]||r[t]&&r[t][e]},B=Math.ceil,V=Math.floor,toInteger=function(t){return isNaN(t=+t)?0:(t>0?V:B)(t)},Y=Math.min,toLength=function(t){return t>0?Y(toInteger(t),9007199254740991):0},q=Math.max,H=Math.min,toAbsoluteIndex=function(t,e){var r=toInteger(t);return r<0?q(r+e,0):H(r,e)},createMethod=function(t){return function(e,r,n){var o,i=toIndexedObject(e),a=toLength(i.length),c=toAbsoluteIndex(n,a);if(t&&r!=r){for(;a>c;)if((o=i[c++])!=o)return!0}else for(;a>c;c++)if((t||c in i)&&i[c]===r)return t||c||0;return!t&&-1}},K={includes:createMethod(!0),indexOf:createMethod(!1)},J=K.indexOf,objectKeysInternal=function(t,e){var r,n=toIndexedObject(t),o=0,i=[];for(r in n)!has(I,r)&&has(n,r)&&i.push(r);for(;e.length>o;)has(n,r=e[o++])&&(~J(i,r)||i.push(r));return i},X=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Q=X.concat("length","prototype"),Z={f:Object.getOwnPropertyNames||function getOwnPropertyNames(t){return objectKeysInternal(t,Q)}},tt={f:Object.getOwnPropertySymbols},et=getBuiltIn("Reflect","ownKeys")||function ownKeys(t){var e=Z.f(anObject(t)),r=tt.f;return r?e.concat(r(t)):e},copyConstructorProperties=function(t,e){for(var r=et(e),n=g.f,o=v.f,i=0;ii;)g.f(t,r=n[i++],e[r]);return t},yt=getBuiltIn("document","documentElement"),gt=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(t){return" + + + + + SVG-edit + + + + + + + + \ No newline at end of file diff --git a/dist/editor/system/index.js b/dist/editor/system/index.js new file mode 100644 index 00000000..0719809b --- /dev/null +++ b/dist/editor/system/index.js @@ -0,0 +1,588 @@ +System.register([],(function(Tn,Un){"use strict";return{execute:function(){var Tn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(Tn,Un,Qn){return Tn(Qn={path:Un,exports:{},require:function(Tn,Un){return function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==Un&&Qn.path)}},Qn.exports),Qn.exports}var check=function(Tn){return Tn&&Tn.Math==Math&&Tn},Qn=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof Tn&&Tn)||Function("return this")(),fails=function(Tn){try{return!!Tn()}catch(Tn){return!0}},Dn=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Hn={}.propertyIsEnumerable,Gn=Object.getOwnPropertyDescriptor,Vn={f:Gn&&!Hn.call({1:2},1)?function propertyIsEnumerable(Tn){var Un=Gn(this,Tn);return!!Un&&Un.enumerable}:Hn},createPropertyDescriptor=function(Tn,Un){return{enumerable:!(1&Tn),configurable:!(2&Tn),writable:!(4&Tn),value:Un}},zn={}.toString,classofRaw=function(Tn){return zn.call(Tn).slice(8,-1)},Kn="".split,Wn=fails((function(){return!Object("z").propertyIsEnumerable(0)}))?function(Tn){return"String"==classofRaw(Tn)?Kn.call(Tn,""):Object(Tn)}:Object,requireObjectCoercible=function(Tn){if(null==Tn)throw TypeError("Can't call method on "+Tn);return Tn},toIndexedObject=function(Tn){return Wn(requireObjectCoercible(Tn))},isObject=function(Tn){return"object"==typeof Tn?null!==Tn:"function"==typeof Tn},toPrimitive=function(Tn,Un){if(!isObject(Tn))return Tn;var Qn,Dn;if(Un&&"function"==typeof(Qn=Tn.toString)&&!isObject(Dn=Qn.call(Tn)))return Dn;if("function"==typeof(Qn=Tn.valueOf)&&!isObject(Dn=Qn.call(Tn)))return Dn;if(!Un&&"function"==typeof(Qn=Tn.toString)&&!isObject(Dn=Qn.call(Tn)))return Dn;throw TypeError("Can't convert object to primitive value")},Xn={}.hasOwnProperty,has=function(Tn,Un){return Xn.call(Tn,Un)},Yn=Qn.document,Jn=isObject(Yn)&&isObject(Yn.createElement),documentCreateElement=function(Tn){return Jn?Yn.createElement(Tn):{}},$n=!Dn&&!fails((function(){return 7!=Object.defineProperty(documentCreateElement("div"),"a",{get:function(){return 7}}).a})),Zn=Object.getOwnPropertyDescriptor,er={f:Dn?Zn:function getOwnPropertyDescriptor(Tn,Un){if(Tn=toIndexedObject(Tn),Un=toPrimitive(Un,!0),$n)try{return Zn(Tn,Un)}catch(Tn){}if(has(Tn,Un))return createPropertyDescriptor(!Vn.f.call(Tn,Un),Tn[Un])}},anObject=function(Tn){if(!isObject(Tn))throw TypeError(String(Tn)+" is not an object");return Tn},tr=Object.defineProperty,nr={f:Dn?tr:function defineProperty(Tn,Un,Qn){if(anObject(Tn),Un=toPrimitive(Un,!0),anObject(Qn),$n)try{return tr(Tn,Un,Qn)}catch(Tn){}if("get"in Qn||"set"in Qn)throw TypeError("Accessors not supported");return"value"in Qn&&(Tn[Un]=Qn.value),Tn}},rr=Dn?function(Tn,Un,Qn){return nr.f(Tn,Un,createPropertyDescriptor(1,Qn))}:function(Tn,Un,Qn){return Tn[Un]=Qn,Tn},setGlobal=function(Tn,Un){try{rr(Qn,Tn,Un)}catch(Dn){Qn[Tn]=Un}return Un},ir="__core-js_shared__",or=Qn[ir]||setGlobal(ir,{}),ar=Function.toString;"function"!=typeof or.inspectSource&&(or.inspectSource=function(Tn){return ar.call(Tn)});var sr,lr,cr,ur=or.inspectSource,dr=Qn.WeakMap,hr="function"==typeof dr&&/native code/.test(ur(dr)),pr=createCommonjsModule((function(Tn){(Tn.exports=function(Tn,Un){return or[Tn]||(or[Tn]=void 0!==Un?Un:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})})),Ar=0,fr=Math.random(),uid=function(Tn){return"Symbol("+String(void 0===Tn?"":Tn)+")_"+(++Ar+fr).toString(36)},gr=pr("keys"),sharedKey=function(Tn){return gr[Tn]||(gr[Tn]=uid(Tn))},mr={},_r=Qn.WeakMap;if(hr){var vr=new _r,yr=vr.get,wr=vr.has,br=vr.set;sr=function(Tn,Un){return br.call(vr,Tn,Un),Un},lr=function(Tn){return yr.call(vr,Tn)||{}},cr=function(Tn){return wr.call(vr,Tn)}}else{var xr=sharedKey("state");mr[xr]=!0,sr=function(Tn,Un){return rr(Tn,xr,Un),Un},lr=function(Tn){return has(Tn,xr)?Tn[xr]:{}},cr=function(Tn){return has(Tn,xr)}}var Sr,kr,Cr={set:sr,get:lr,has:cr,enforce:function(Tn){return cr(Tn)?lr(Tn):sr(Tn,{})},getterFor:function(Tn){return function(Un){var Qn;if(!isObject(Un)||(Qn=lr(Un)).type!==Tn)throw TypeError("Incompatible receiver, "+Tn+" required");return Qn}}},Br=createCommonjsModule((function(Tn){var Un=Cr.get,Dn=Cr.enforce,Hn=String(String).split("String");(Tn.exports=function(Tn,Un,Gn,Vn){var zn=!!Vn&&!!Vn.unsafe,Kn=!!Vn&&!!Vn.enumerable,Wn=!!Vn&&!!Vn.noTargetGet;"function"==typeof Gn&&("string"!=typeof Un||has(Gn,"name")||rr(Gn,"name",Un),Dn(Gn).source=Hn.join("string"==typeof Un?Un:"")),Tn!==Qn?(zn?!Wn&&Tn[Un]&&(Kn=!0):delete Tn[Un],Kn?Tn[Un]=Gn:rr(Tn,Un,Gn)):Kn?Tn[Un]=Gn:setGlobal(Un,Gn)})(Function.prototype,"toString",(function toString(){return"function"==typeof this&&Un(this).source||ur(this)}))})),Er=Qn,aFunction=function(Tn){return"function"==typeof Tn?Tn:void 0},getBuiltIn=function(Tn,Un){return arguments.length<2?aFunction(Er[Tn])||aFunction(Qn[Tn]):Er[Tn]&&Er[Tn][Un]||Qn[Tn]&&Qn[Tn][Un]},Nr=Math.ceil,Lr=Math.floor,toInteger=function(Tn){return isNaN(Tn=+Tn)?0:(Tn>0?Lr:Nr)(Tn)},Tr=Math.min,toLength=function(Tn){return Tn>0?Tr(toInteger(Tn),9007199254740991):0},Pr=Math.max,Fr=Math.min,toAbsoluteIndex=function(Tn,Un){var Qn=toInteger(Tn);return Qn<0?Pr(Qn+Un,0):Fr(Qn,Un)},createMethod=function(Tn){return function(Un,Qn,Dn){var Hn,Gn=toIndexedObject(Un),Vn=toLength(Gn.length),zn=toAbsoluteIndex(Dn,Vn);if(Tn&&Qn!=Qn){for(;Vn>zn;)if((Hn=Gn[zn++])!=Hn)return!0}else for(;Vn>zn;zn++)if((Tn||zn in Gn)&&Gn[zn]===Qn)return Tn||zn||0;return!Tn&&-1}},Ur={includes:createMethod(!0),indexOf:createMethod(!1)},Ir=Ur.indexOf,objectKeysInternal=function(Tn,Un){var Qn,Dn=toIndexedObject(Tn),Hn=0,Gn=[];for(Qn in Dn)!has(mr,Qn)&&has(Dn,Qn)&&Gn.push(Qn);for(;Un.length>Hn;)has(Dn,Qn=Un[Hn++])&&(~Ir(Gn,Qn)||Gn.push(Qn));return Gn},Rr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Mr=Rr.concat("length","prototype"),Qr={f:Object.getOwnPropertyNames||function getOwnPropertyNames(Tn){return objectKeysInternal(Tn,Mr)}},Or={f:Object.getOwnPropertySymbols},Dr=getBuiltIn("Reflect","ownKeys")||function ownKeys(Tn){var Un=Qr.f(anObject(Tn)),Qn=Or.f;return Qn?Un.concat(Qn(Tn)):Un},copyConstructorProperties=function(Tn,Un){for(var Qn=Dr(Un),Dn=nr.f,Hn=er.f,Gn=0;Gn=74)&&(Sr=ti.match(/Chrome\/(\d+)/))&&(kr=Sr[1]);var oi=kr&&+kr,ai=wellKnownSymbol("species"),arrayMethodHasSpeciesSupport=function(Tn){return oi>=51||!fails((function(){var Un=[];return(Un.constructor={})[ai]=function(){return{foo:1}},1!==Un[Tn](Boolean).foo}))},si=wellKnownSymbol("isConcatSpreadable"),li=9007199254740991,ui="Maximum allowed index exceeded",di=oi>=51||!fails((function(){var Tn=[];return Tn[si]=!1,Tn.concat()[0]!==Tn})),hi=arrayMethodHasSpeciesSupport("concat"),isConcatSpreadable=function(Tn){if(!isObject(Tn))return!1;var Un=Tn[si];return void 0!==Un?!!Un:Wr(Tn)};_export({target:"Array",proto:!0,forced:!di||!hi},{concat:function concat(Tn){var Un,Qn,Dn,Hn,Gn,Vn=toObject(this),zn=arraySpeciesCreate(Vn,0),Kn=0;for(Un=-1,Dn=arguments.length;Unli)throw TypeError(ui);for(Qn=0;Qn=li)throw TypeError(ui);createProperty(zn,Kn++,Gn)}return zn.length=Kn,zn}});var aFunction$1=function(Tn){if("function"!=typeof Tn)throw TypeError(String(Tn)+" is not a function");return Tn},functionBindContext=function(Tn,Un,Qn){if(aFunction$1(Tn),void 0===Un)return Tn;switch(Qn){case 0:return function(){return Tn.call(Un)};case 1:return function(Qn){return Tn.call(Un,Qn)};case 2:return function(Qn,Dn){return Tn.call(Un,Qn,Dn)};case 3:return function(Qn,Dn,Hn){return Tn.call(Un,Qn,Dn,Hn)}}return function(){return Tn.apply(Un,arguments)}},pi=[].push,createMethod$1=function(Tn){var Un=1==Tn,Qn=2==Tn,Dn=3==Tn,Hn=4==Tn,Gn=6==Tn,Vn=5==Tn||Gn;return function(zn,Kn,Xn,Yn){for(var Jn,$n,Zn=toObject(zn),er=Wn(Zn),tr=functionBindContext(Kn,Xn,3),nr=toLength(er.length),rr=0,ir=Yn||arraySpeciesCreate,or=Un?ir(zn,nr):Qn?ir(zn,0):void 0;nr>rr;rr++)if((Vn||rr in er)&&($n=tr(Jn=er[rr],rr,Zn),Tn))if(Un)or[rr]=$n;else if($n)switch(Tn){case 3:return!0;case 5:return Jn;case 6:return rr;case 2:pi.call(or,Jn)}else if(Hn)return!1;return Gn?-1:Dn||Hn?Hn:or}},Ai={forEach:createMethod$1(0),map:createMethod$1(1),filter:createMethod$1(2),some:createMethod$1(3),every:createMethod$1(4),find:createMethod$1(5),findIndex:createMethod$1(6)},fi=Object.defineProperty,gi={},thrower=function(Tn){throw Tn},arrayMethodUsesToLength=function(Tn,Un){if(has(gi,Tn))return gi[Tn];Un||(Un={});var Qn=[][Tn],Hn=!!has(Un,"ACCESSORS")&&Un.ACCESSORS,Gn=has(Un,0)?Un[0]:thrower,Vn=has(Un,1)?Un[1]:void 0;return gi[Tn]=!!Qn&&!fails((function(){if(Hn&&!Dn)return!0;var Tn={length:-1};Hn?fi(Tn,1,{enumerable:!0,get:thrower}):Tn[1]=1,Qn.call(Tn,Gn,Vn)}))},mi=Ai.filter,_i=arrayMethodHasSpeciesSupport("filter"),vi=arrayMethodUsesToLength("filter");_export({target:"Array",proto:!0,forced:!_i||!vi},{filter:function filter(Tn){return mi(this,Tn,arguments.length>1?arguments[1]:void 0)}});var yi,wi=Object.keys||function keys(Tn){return objectKeysInternal(Tn,Rr)},xi=Dn?Object.defineProperties:function defineProperties(Tn,Un){anObject(Tn);for(var Qn,Dn=wi(Un),Hn=Dn.length,Gn=0;Hn>Gn;)nr.f(Tn,Qn=Dn[Gn++],Un[Qn]);return Tn},Si=getBuiltIn("document","documentElement"),ki=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(Tn){return" + + + + + SVG-edit + + + + + + + + \ No newline at end of file diff --git a/dist/editor/xdomain-index.js b/dist/editor/xdomain-index.js new file mode 100644 index 00000000..413ac070 --- /dev/null +++ b/dist/editor/xdomain-index.js @@ -0,0 +1,581 @@ +var Tn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(Tn,Un,Qn){return Tn(Qn={path:Un,exports:{},require:function(Tn,Un){return function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==Un&&Qn.path)}},Qn.exports),Qn.exports}var check=function(Tn){return Tn&&Tn.Math==Math&&Tn},Un=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof Tn&&Tn)||Function("return this")(),fails=function(Tn){try{return!!Tn()}catch(Tn){return!0}},Qn=!fails((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Dn={}.propertyIsEnumerable,Hn=Object.getOwnPropertyDescriptor,Gn={f:Hn&&!Dn.call({1:2},1)?function propertyIsEnumerable(Tn){var Un=Hn(this,Tn);return!!Un&&Un.enumerable}:Dn},createPropertyDescriptor=function(Tn,Un){return{enumerable:!(1&Tn),configurable:!(2&Tn),writable:!(4&Tn),value:Un}},Vn={}.toString,classofRaw=function(Tn){return Vn.call(Tn).slice(8,-1)},zn="".split,Kn=fails((function(){return!Object("z").propertyIsEnumerable(0)}))?function(Tn){return"String"==classofRaw(Tn)?zn.call(Tn,""):Object(Tn)}:Object,requireObjectCoercible=function(Tn){if(null==Tn)throw TypeError("Can't call method on "+Tn);return Tn},toIndexedObject=function(Tn){return Kn(requireObjectCoercible(Tn))},isObject=function(Tn){return"object"==typeof Tn?null!==Tn:"function"==typeof Tn},toPrimitive=function(Tn,Un){if(!isObject(Tn))return Tn;var Qn,Dn;if(Un&&"function"==typeof(Qn=Tn.toString)&&!isObject(Dn=Qn.call(Tn)))return Dn;if("function"==typeof(Qn=Tn.valueOf)&&!isObject(Dn=Qn.call(Tn)))return Dn;if(!Un&&"function"==typeof(Qn=Tn.toString)&&!isObject(Dn=Qn.call(Tn)))return Dn;throw TypeError("Can't convert object to primitive value")},Wn={}.hasOwnProperty,has=function(Tn,Un){return Wn.call(Tn,Un)},Xn=Un.document,Yn=isObject(Xn)&&isObject(Xn.createElement),documentCreateElement=function(Tn){return Yn?Xn.createElement(Tn):{}},Jn=!Qn&&!fails((function(){return 7!=Object.defineProperty(documentCreateElement("div"),"a",{get:function(){return 7}}).a})),$n=Object.getOwnPropertyDescriptor,Zn={f:Qn?$n:function getOwnPropertyDescriptor(Tn,Un){if(Tn=toIndexedObject(Tn),Un=toPrimitive(Un,!0),Jn)try{return $n(Tn,Un)}catch(Tn){}if(has(Tn,Un))return createPropertyDescriptor(!Gn.f.call(Tn,Un),Tn[Un])}},anObject=function(Tn){if(!isObject(Tn))throw TypeError(String(Tn)+" is not an object");return Tn},er=Object.defineProperty,tr={f:Qn?er:function defineProperty(Tn,Un,Qn){if(anObject(Tn),Un=toPrimitive(Un,!0),anObject(Qn),Jn)try{return er(Tn,Un,Qn)}catch(Tn){}if("get"in Qn||"set"in Qn)throw TypeError("Accessors not supported");return"value"in Qn&&(Tn[Un]=Qn.value),Tn}},nr=Qn?function(Tn,Un,Qn){return tr.f(Tn,Un,createPropertyDescriptor(1,Qn))}:function(Tn,Un,Qn){return Tn[Un]=Qn,Tn},setGlobal=function(Tn,Qn){try{nr(Un,Tn,Qn)}catch(Dn){Un[Tn]=Qn}return Qn},rr=Un["__core-js_shared__"]||setGlobal("__core-js_shared__",{}),ir=Function.toString;"function"!=typeof rr.inspectSource&&(rr.inspectSource=function(Tn){return ir.call(Tn)});var or,ar,sr,lr=rr.inspectSource,cr=Un.WeakMap,ur="function"==typeof cr&&/native code/.test(lr(cr)),dr=createCommonjsModule((function(Tn){(Tn.exports=function(Tn,Un){return rr[Tn]||(rr[Tn]=void 0!==Un?Un:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})})),hr=0,pr=Math.random(),uid=function(Tn){return"Symbol("+String(void 0===Tn?"":Tn)+")_"+(++hr+pr).toString(36)},Ar=dr("keys"),sharedKey=function(Tn){return Ar[Tn]||(Ar[Tn]=uid(Tn))},fr={},gr=Un.WeakMap;if(ur){var mr=new gr,_r=mr.get,vr=mr.has,yr=mr.set;or=function(Tn,Un){return yr.call(mr,Tn,Un),Un},ar=function(Tn){return _r.call(mr,Tn)||{}},sr=function(Tn){return vr.call(mr,Tn)}}else{var wr=sharedKey("state");fr[wr]=!0,or=function(Tn,Un){return nr(Tn,wr,Un),Un},ar=function(Tn){return has(Tn,wr)?Tn[wr]:{}},sr=function(Tn){return has(Tn,wr)}}var br,xr,Sr={set:or,get:ar,has:sr,enforce:function(Tn){return sr(Tn)?ar(Tn):or(Tn,{})},getterFor:function(Tn){return function(Un){var Qn;if(!isObject(Un)||(Qn=ar(Un)).type!==Tn)throw TypeError("Incompatible receiver, "+Tn+" required");return Qn}}},kr=createCommonjsModule((function(Tn){var Qn=Sr.get,Dn=Sr.enforce,Hn=String(String).split("String");(Tn.exports=function(Tn,Qn,Gn,Vn){var zn=!!Vn&&!!Vn.unsafe,Kn=!!Vn&&!!Vn.enumerable,Wn=!!Vn&&!!Vn.noTargetGet;"function"==typeof Gn&&("string"!=typeof Qn||has(Gn,"name")||nr(Gn,"name",Qn),Dn(Gn).source=Hn.join("string"==typeof Qn?Qn:"")),Tn!==Un?(zn?!Wn&&Tn[Qn]&&(Kn=!0):delete Tn[Qn],Kn?Tn[Qn]=Gn:nr(Tn,Qn,Gn)):Kn?Tn[Qn]=Gn:setGlobal(Qn,Gn)})(Function.prototype,"toString",(function toString(){return"function"==typeof this&&Qn(this).source||lr(this)}))})),Cr=Un,aFunction=function(Tn){return"function"==typeof Tn?Tn:void 0},getBuiltIn=function(Tn,Qn){return arguments.length<2?aFunction(Cr[Tn])||aFunction(Un[Tn]):Cr[Tn]&&Cr[Tn][Qn]||Un[Tn]&&Un[Tn][Qn]},Br=Math.ceil,Er=Math.floor,toInteger=function(Tn){return isNaN(Tn=+Tn)?0:(Tn>0?Er:Br)(Tn)},Nr=Math.min,toLength=function(Tn){return Tn>0?Nr(toInteger(Tn),9007199254740991):0},Lr=Math.max,Tr=Math.min,toAbsoluteIndex=function(Tn,Un){var Qn=toInteger(Tn);return Qn<0?Lr(Qn+Un,0):Tr(Qn,Un)},createMethod=function(Tn){return function(Un,Qn,Dn){var Hn,Gn=toIndexedObject(Un),Vn=toLength(Gn.length),zn=toAbsoluteIndex(Dn,Vn);if(Tn&&Qn!=Qn){for(;Vn>zn;)if((Hn=Gn[zn++])!=Hn)return!0}else for(;Vn>zn;zn++)if((Tn||zn in Gn)&&Gn[zn]===Qn)return Tn||zn||0;return!Tn&&-1}},Pr={includes:createMethod(!0),indexOf:createMethod(!1)},Fr=Pr.indexOf,objectKeysInternal=function(Tn,Un){var Qn,Dn=toIndexedObject(Tn),Hn=0,Gn=[];for(Qn in Dn)!has(fr,Qn)&&has(Dn,Qn)&&Gn.push(Qn);for(;Un.length>Hn;)has(Dn,Qn=Un[Hn++])&&(~Fr(Gn,Qn)||Gn.push(Qn));return Gn},Ur=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ir=Ur.concat("length","prototype"),Rr={f:Object.getOwnPropertyNames||function getOwnPropertyNames(Tn){return objectKeysInternal(Tn,Ir)}},Mr={f:Object.getOwnPropertySymbols},Qr=getBuiltIn("Reflect","ownKeys")||function ownKeys(Tn){var Un=Rr.f(anObject(Tn)),Qn=Mr.f;return Qn?Un.concat(Qn(Tn)):Un},copyConstructorProperties=function(Tn,Un){for(var Qn=Qr(Un),Dn=tr.f,Hn=Zn.f,Gn=0;Gn=74)&&(br=Zr.match(/Chrome\/(\d+)/))&&(xr=br[1]);var ri=xr&&+xr,ii=wellKnownSymbol("species"),arrayMethodHasSpeciesSupport=function(Tn){return ri>=51||!fails((function(){var Un=[];return(Un.constructor={})[ii]=function(){return{foo:1}},1!==Un[Tn](Boolean).foo}))},oi=wellKnownSymbol("isConcatSpreadable"),ai=ri>=51||!fails((function(){var Tn=[];return Tn[oi]=!1,Tn.concat()[0]!==Tn})),si=arrayMethodHasSpeciesSupport("concat"),isConcatSpreadable=function(Tn){if(!isObject(Tn))return!1;var Un=Tn[oi];return void 0!==Un?!!Un:Kr(Tn)};_export({target:"Array",proto:!0,forced:!ai||!si},{concat:function concat(Tn){var Un,Qn,Dn,Hn,Gn,Vn=toObject(this),zn=arraySpeciesCreate(Vn,0),Kn=0;for(Un=-1,Dn=arguments.length;Un9007199254740991)throw TypeError("Maximum allowed index exceeded");for(Qn=0;Qn=9007199254740991)throw TypeError("Maximum allowed index exceeded");createProperty(zn,Kn++,Gn)}return zn.length=Kn,zn}});var aFunction$1=function(Tn){if("function"!=typeof Tn)throw TypeError(String(Tn)+" is not a function");return Tn},functionBindContext=function(Tn,Un,Qn){if(aFunction$1(Tn),void 0===Un)return Tn;switch(Qn){case 0:return function(){return Tn.call(Un)};case 1:return function(Qn){return Tn.call(Un,Qn)};case 2:return function(Qn,Dn){return Tn.call(Un,Qn,Dn)};case 3:return function(Qn,Dn,Hn){return Tn.call(Un,Qn,Dn,Hn)}}return function(){return Tn.apply(Un,arguments)}},li=[].push,createMethod$1=function(Tn){var Un=1==Tn,Qn=2==Tn,Dn=3==Tn,Hn=4==Tn,Gn=6==Tn,Vn=5==Tn||Gn;return function(zn,Wn,Xn,Yn){for(var Jn,$n,Zn=toObject(zn),er=Kn(Zn),tr=functionBindContext(Wn,Xn,3),nr=toLength(er.length),rr=0,ir=Yn||arraySpeciesCreate,or=Un?ir(zn,nr):Qn?ir(zn,0):void 0;nr>rr;rr++)if((Vn||rr in er)&&($n=tr(Jn=er[rr],rr,Zn),Tn))if(Un)or[rr]=$n;else if($n)switch(Tn){case 3:return!0;case 5:return Jn;case 6:return rr;case 2:li.call(or,Jn)}else if(Hn)return!1;return Gn?-1:Dn||Hn?Hn:or}},ui={forEach:createMethod$1(0),map:createMethod$1(1),filter:createMethod$1(2),some:createMethod$1(3),every:createMethod$1(4),find:createMethod$1(5),findIndex:createMethod$1(6)},di=Object.defineProperty,hi={},thrower=function(Tn){throw Tn},arrayMethodUsesToLength=function(Tn,Un){if(has(hi,Tn))return hi[Tn];Un||(Un={});var Dn=[][Tn],Hn=!!has(Un,"ACCESSORS")&&Un.ACCESSORS,Gn=has(Un,0)?Un[0]:thrower,Vn=has(Un,1)?Un[1]:void 0;return hi[Tn]=!!Dn&&!fails((function(){if(Hn&&!Qn)return!0;var Tn={length:-1};Hn?di(Tn,1,{enumerable:!0,get:thrower}):Tn[1]=1,Dn.call(Tn,Gn,Vn)}))},pi=ui.filter,Ai=arrayMethodHasSpeciesSupport("filter"),fi=arrayMethodUsesToLength("filter");_export({target:"Array",proto:!0,forced:!Ai||!fi},{filter:function filter(Tn){return pi(this,Tn,arguments.length>1?arguments[1]:void 0)}});var gi,mi=Object.keys||function keys(Tn){return objectKeysInternal(Tn,Ur)},_i=Qn?Object.defineProperties:function defineProperties(Tn,Un){anObject(Tn);for(var Qn,Dn=mi(Un),Hn=Dn.length,Gn=0;Hn>Gn;)tr.f(Tn,Qn=Dn[Gn++],Un[Qn]);return Tn},vi=getBuiltIn("document","documentElement"),yi=sharedKey("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(Tn){return"`, */ - // mathjaxSrc = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js', - // Had been on https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG.js - // Obtained Text-AMS-MML_SVG.js from https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.3/config/TeX-AMS-MML_SVG.js - mathjaxSrcSecure = 'mathjax/MathJax.min.js?config=TeX-AMS-MML_SVG.js', uiStrings = svgEditor.uiStrings; - mathjaxLoaded = false; // TODO: Implement language support. Move these uiStrings to the locale files and - // the code to the langReady callback. Also i18nize alert and HTML below - - $.extend(uiStrings, { - mathjax: { - embed_svg: 'Save as mathematics', - embed_mathml: 'Save as figure', - svg_save_warning: 'The math will be transformed into a figure is ' + 'manipulatable like everything else. You will not be able to ' + 'manipulate the TeX-code anymore.', - mathml_save_warning: 'Advised. The math will be saved as a figure.', - title: 'Mathematics code editor' - } - }); - /** - * - * @returns {void} - */ - - buttons = [{ - id: 'tool_mathjax', - type: 'mode', - icon: svgEditor.curConfig.extIconsPath + 'mathjax.png', - events: { - click: function click() { - return _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. - - if (!(mathjaxLoaded === false)) { - _context.next = 17; - break; - } - - $('
' + '' + '' + '
' + '
' + '
' + '' + '' + '
' + '
' + 'Mathematics Editor' + '' + '' + '
' + '
' + '
').insertAfter('#svg_prefs').hide(); // Make the MathEditor draggable. - - $('#mathjax_container').draggable({ - cancel: 'button,fieldset', - containment: 'window' - }); // Add functionality and picture to cancel button. - - $('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () { - $('#mathjax').hide(); - }); // Add functionality and picture to the save button. - - $('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () { - saveMath(); - $('#mathjax').hide(); - }); // MathJax preprocessing has to ignore most of the page. - - $('body').addClass('tex2jax_ignore'); // Now get (and run) the MathJax Library. - // Todo: insert script with modules once widely supported - // and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up - // providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998 - - /* - const modularVersion = !('svgEditor' in window) || - !window.svgEditor || - window.svgEditor.modules !== false; - // Add as second argument to `importScript` - { - type: modularVersion - ? 'module' // Make this the default when widely supported - : 'text/javascript' - } - // If only using modules, just use this: - const {default: MathJax} = await importModule( // or `import()` when widely supported - svgEditor.curConfig.extIconsPath + mathjaxSrcSecure - ); - */ - // We use `extIconsPath` here for now as it does not vary with - // the modular type as does `extPath` - - _context.prev = 7; - _context.next = 10; - return importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure); - - case 10: - // When MathJax is loaded get the div where the math will be rendered. - MathJax.Hub.queue.Push(function () { - math = MathJax.Hub.getAllJax('#mathjax_creator')[0]; - console.log(math); // eslint-disable-line no-console - - mathjaxLoaded = true; - console.log('MathJax Loaded'); // eslint-disable-line no-console - }); - _context.next = 17; - break; - - case 13: - _context.prev = 13; - _context.t0 = _context["catch"](7); - console.log('Failed loading MathJax.'); // eslint-disable-line no-console - - $.alert('Failed loading MathJax. You will not be able to change the mathematics.'); - - case 17: - case "end": - return _context.stop(); - } - } - }, _callee, null, [[7, 13]]); - }))(); - } - } - }]; - return _context2.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'mathjax-icons.xml', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - mouseDown: function mouseDown() { - if (svgCanvas.getMode() === 'mathjax') { - return { - started: true - }; - } - - return undefined; - }, - mouseUp: function mouseUp(opts) { - if (svgCanvas.getMode() === 'mathjax') { - // Get the coordinates from your mouse. - var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value - - locationX = opts.mouse_x / zoom; - locationY = opts.mouse_y / zoom; - $('#mathjax').show(); - return { - started: false - }; // Otherwise the last selected object dissapears. - } - - return undefined; - }, - callback: function callback() { - $('').appendTo('head'); - } - - fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }'); - $('#polygon_panel').toggle(on); - }; - - svgEditor = _this; - svgCanvas = svgEditor.canvas; - $ = S.$, importLocale = S.importLocale, editingitex = false; - _context.next = 9; - return importLocale(); - - case 9: - strings = _context.sent; - - /** - * Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3 - * This function sets the content of of the currently-selected foreignObject element, - * based on the itex contained in string. - * @param {string} tex The itex text. - * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise. - */ - - /* - function setItexString(tex) { - const mathns = 'http://www.w3.org/1998/Math/MathML', - xmlnsns = 'http://www.w3.org/2000/xmlns/', - ajaxEndpoint = '../../itex'; - const elt = selElems[0]; - try { - const math = svgdoc.createElementNS(mathns, 'math'); - math.setAttributeNS(xmlnsns, 'xmlns', mathns); - math.setAttribute('display', 'inline'); - const semantics = document.createElementNS(mathns, 'semantics'); - const annotation = document.createElementNS(mathns, 'annotation'); - annotation.setAttribute('encoding', 'application/x-tex'); - annotation.textContent = tex; - const mrow = document.createElementNS(mathns, 'mrow'); - semantics.append(mrow, annotation); - math.append(semantics); - // make an AJAX request to the server, to get the MathML - $.post(ajaxEndpoint, {tex, display: 'inline'}, function(data){ - const children = data.documentElement.childNodes; - while (children.length > 0) { - mrow.append(svgdoc.adoptNode(children[0], true)); - } - svgCanvas.sanitizeSvg(math); - svgCanvas.call('changed', [elt]); - }); - elt.firstChild.replaceWith(math); - svgCanvas.call('changed', [elt]); - svgCanvas.clearSelection(); - } catch(e) { - console.log(e); - return false; - } - return true; - } - */ - buttons = [{ - id: 'tool_polygon', - icon: svgEditor.curConfig.extIconsPath + 'polygon.png', - type: 'mode', - position: 11, - events: { - click: function click() { - svgCanvas.setMode('polygon'); - showPanel(true); - } - } - }]; - contextTools = [{ - type: 'input', - panel: 'polygon_panel', - id: 'polySides', - size: 3, - defval: 5, - events: { - change: function change() { - setAttr('sides', this.value); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - context_tools: strings.contextTools.map(function (contextTool, i) { - return Object.assign(contextTools[i], contextTool); - }), - callback: function callback() { - $('#polygon_panel').hide(); - - - setTimeout(function () { - // Create source save/cancel buttons - - /* const save = */ - $('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () { - if (!editingitex) { - return; - } // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint? - // setSelectMode(); - }); - /* const cancel = */ - - $('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () { - }); - }, 3000); - }, - mouseDown: function mouseDown(opts) { - if (svgCanvas.getMode() !== 'polygon') { - return undefined; - } // const e = opts.event; - - - var rgb = svgCanvas.getColor('fill'); // const ccRgbEl = rgb.substring(1, rgb.length); - - var sRgb = svgCanvas.getColor('stroke'); // ccSRgbEl = sRgb.substring(1, rgb.length); - - var sWidth = svgCanvas.getStrokeWidth(); - started = true; - newFO = svgCanvas.addSVGElementFromJson({ - element: 'polygon', - attr: { - cx: opts.start_x, - cy: opts.start_y, - id: svgCanvas.getNextId(), - shape: 'regularPoly', - sides: document.getElementById('polySides').value, - orient: 'x', - edge: 0, - fill: rgb, - strokecolor: sRgb, - strokeWidth: sWidth - } - }); - return { - started: true - }; - }, - mouseMove: function mouseMove(opts) { - if (!started || svgCanvas.getMode() !== 'polygon') { - return undefined; - } // const e = opts.event; - - - var c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']); - var x = opts.mouse_x; - var y = opts.mouse_y; - var cx = c.cx, - cy = c.cy, - fill = c.fill, - strokecolor = c.strokecolor, - strokeWidth = c.strokeWidth, - sides = c.sides, - edg = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5; - newFO.setAttribute('edge', edg); - var inradius = edg / 2 * cot(Math.PI / sides); - var circumradius = inradius * sec(Math.PI / sides); - var points = ''; - - for (var s = 0; sides >= s; s++) { - var angle = 2.0 * Math.PI * s / sides; - x = circumradius * Math.cos(angle) + cx; - y = circumradius * Math.sin(angle) + cy; - points += x + ',' + y + ' '; - } // const poly = newFO.createElementNS(NS.SVG, 'polygon'); - - - newFO.setAttribute('points', points); - newFO.setAttribute('fill', fill); - newFO.setAttribute('stroke', strokecolor); - newFO.setAttribute('stroke-width', strokeWidth); // newFO.setAttribute('transform', 'rotate(-90)'); - // const shape = newFO.getAttribute('shape'); - // newFO.append(poly); - // DrawPoly(cx, cy, sides, edg, orient); - - return { - started: true - }; - }, - mouseUp: function mouseUp(opts) { - if (svgCanvas.getMode() !== 'polygon') { - return undefined; - } - - var attrs = $(newFO).attr('edge'); - var keep = attrs.edge !== '0'; // svgCanvas.addToSelection([newFO], true); - - return { - keep: keep, - element: newFO - }; - }, - selectedChanged: function selectedChanged(opts) { - // Use this to update the current selected elements - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elem.getAttribute('shape') === 'regularPoly') { - if (opts.selectedElement && !opts.multiselected) { - $('#polySides').val(elem.getAttribute('sides')); - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - }, - elementChanged: function elementChanged(opts) {// const elem = opts.elems[0]; - } - }); - - case 13: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }; - - return extPolygon; - -}()); diff --git a/dist/extensions/ext-server_moinsave.js b/dist/extensions/ext-server_moinsave.js deleted file mode 100644 index ea4247e2..00000000 --- a/dist/extensions/ext-server_moinsave.js +++ /dev/null @@ -1,5000 +0,0 @@ -var svgEditorExtension_server_moinsave = (function () { - 'use strict'; - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; - } - - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - - return object; - } - - function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.get) { - return desc.get.call(receiver); - } - - return desc.value; - }; - } - - return _get(target, property, receiver || target); - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _iterableToArrayLimit(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - /** - * For parsing color values. - * @module RGBColor - * @author Stoyan Stefanov - * @see https://www.phpied.com/rgb-color-parser-in-javascript/ - * @license MIT - */ - var simpleColors = { - aliceblue: 'f0f8ff', - antiquewhite: 'faebd7', - aqua: '00ffff', - aquamarine: '7fffd4', - azure: 'f0ffff', - beige: 'f5f5dc', - bisque: 'ffe4c4', - black: '000000', - blanchedalmond: 'ffebcd', - blue: '0000ff', - blueviolet: '8a2be2', - brown: 'a52a2a', - burlywood: 'deb887', - cadetblue: '5f9ea0', - chartreuse: '7fff00', - chocolate: 'd2691e', - coral: 'ff7f50', - cornflowerblue: '6495ed', - cornsilk: 'fff8dc', - crimson: 'dc143c', - cyan: '00ffff', - darkblue: '00008b', - darkcyan: '008b8b', - darkgoldenrod: 'b8860b', - darkgray: 'a9a9a9', - darkgreen: '006400', - darkkhaki: 'bdb76b', - darkmagenta: '8b008b', - darkolivegreen: '556b2f', - darkorange: 'ff8c00', - darkorchid: '9932cc', - darkred: '8b0000', - darksalmon: 'e9967a', - darkseagreen: '8fbc8f', - darkslateblue: '483d8b', - darkslategray: '2f4f4f', - darkturquoise: '00ced1', - darkviolet: '9400d3', - deeppink: 'ff1493', - deepskyblue: '00bfff', - dimgray: '696969', - dodgerblue: '1e90ff', - feldspar: 'd19275', - firebrick: 'b22222', - floralwhite: 'fffaf0', - forestgreen: '228b22', - fuchsia: 'ff00ff', - gainsboro: 'dcdcdc', - ghostwhite: 'f8f8ff', - gold: 'ffd700', - goldenrod: 'daa520', - gray: '808080', - green: '008000', - greenyellow: 'adff2f', - honeydew: 'f0fff0', - hotpink: 'ff69b4', - indianred: 'cd5c5c', - indigo: '4b0082', - ivory: 'fffff0', - khaki: 'f0e68c', - lavender: 'e6e6fa', - lavenderblush: 'fff0f5', - lawngreen: '7cfc00', - lemonchiffon: 'fffacd', - lightblue: 'add8e6', - lightcoral: 'f08080', - lightcyan: 'e0ffff', - lightgoldenrodyellow: 'fafad2', - lightgrey: 'd3d3d3', - lightgreen: '90ee90', - lightpink: 'ffb6c1', - lightsalmon: 'ffa07a', - lightseagreen: '20b2aa', - lightskyblue: '87cefa', - lightslateblue: '8470ff', - lightslategray: '778899', - lightsteelblue: 'b0c4de', - lightyellow: 'ffffe0', - lime: '00ff00', - limegreen: '32cd32', - linen: 'faf0e6', - magenta: 'ff00ff', - maroon: '800000', - mediumaquamarine: '66cdaa', - mediumblue: '0000cd', - mediumorchid: 'ba55d3', - mediumpurple: '9370d8', - mediumseagreen: '3cb371', - mediumslateblue: '7b68ee', - mediumspringgreen: '00fa9a', - mediumturquoise: '48d1cc', - mediumvioletred: 'c71585', - midnightblue: '191970', - mintcream: 'f5fffa', - mistyrose: 'ffe4e1', - moccasin: 'ffe4b5', - navajowhite: 'ffdead', - navy: '000080', - oldlace: 'fdf5e6', - olive: '808000', - olivedrab: '6b8e23', - orange: 'ffa500', - orangered: 'ff4500', - orchid: 'da70d6', - palegoldenrod: 'eee8aa', - palegreen: '98fb98', - paleturquoise: 'afeeee', - palevioletred: 'd87093', - papayawhip: 'ffefd5', - peachpuff: 'ffdab9', - peru: 'cd853f', - pink: 'ffc0cb', - plum: 'dda0dd', - powderblue: 'b0e0e6', - purple: '800080', - red: 'ff0000', - rosybrown: 'bc8f8f', - royalblue: '4169e1', - saddlebrown: '8b4513', - salmon: 'fa8072', - sandybrown: 'f4a460', - seagreen: '2e8b57', - seashell: 'fff5ee', - sienna: 'a0522d', - silver: 'c0c0c0', - skyblue: '87ceeb', - slateblue: '6a5acd', - slategray: '708090', - snow: 'fffafa', - springgreen: '00ff7f', - steelblue: '4682b4', - tan: 'd2b48c', - teal: '008080', - thistle: 'd8bfd8', - tomato: 'ff6347', - turquoise: '40e0d0', - violet: 'ee82ee', - violetred: 'd02090', - wheat: 'f5deb3', - white: 'ffffff', - whitesmoke: 'f5f5f5', - yellow: 'ffff00', - yellowgreen: '9acd32' - }; // array of color definition objects - - var colorDefs = [{ - re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, - // 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(_) { - 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 Number.parseInt(b); - }); - } - }, { - re: /^(\w{2})(\w{2})(\w{2})$/, - // re: /^(?\w{2})(?\w{2})(?\w{2})$/, - example: ['#00ff00', '336699'], - 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 Number.parseInt(b, 16); - }); - } - }, { - re: /^(\w)(\w)(\w)$/, - // re: /^(?\w{1})(?\w{1})(?\w{1})$/, - example: ['#fb0', 'f0f'], - 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 Number.parseInt(b + b, 16); - }); - } - }]; - /** - * A class to parse color values. - */ - - var RGBColor = /*#__PURE__*/function () { - /** - * @param {string} colorString - */ - function RGBColor(colorString) { - var _this = this; - - _classCallCheck(this, RGBColor); - - this.ok = false; // strip any leading # - - if (colorString.charAt(0) === '#') { - // remove # if any - colorString = colorString.substr(1, 6); - } - - colorString = colorString.replace(/ /g, ''); - colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches - // and overwrite the input - - if (colorString in simpleColors) { - colorString = simpleColors[colorString]; - } // end of simple type-in colors - // search through the definitions to find a match - - - colorDefs.forEach(function (_ref) { - var re = _ref.re, - processor = _ref.process; - var bits = re.exec(colorString); - - if (bits) { - var _processor = processor.apply(void 0, _toConsumableArray(bits)), - _processor2 = _slicedToArray(_processor, 3), - r = _processor2[0], - g = _processor2[1], - b = _processor2[2]; - - Object.assign(_this, { - r: r, - g: g, - b: b - }); - _this.ok = true; - } - }); // validate/cleanup values - - this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r; - this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g; - this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b; - } // some getters - - /** - * @returns {string} - */ - - - _createClass(RGBColor, [{ - key: "toRGB", - value: function toRGB() { - return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; - } - /** - * @returns {string} - */ - - }, { - key: "toHex", - value: function toHex() { - var r = this.r.toString(16); - var g = this.g.toString(16); - var b = this.b.toString(16); - - if (r.length === 1) { - r = '0' + r; - } - - if (g.length === 1) { - g = '0' + g; - } - - if (b.length === 1) { - b = '0' + b; - } - - return '#' + r + g + b; - } - /** - * Offers a bulleted list of help. - * @returns {HTMLUListElement} - */ - - }], [{ - key: "getHelpXML", - value: function getHelpXML() { - var examples = [].concat(_toConsumableArray(colorDefs.flatMap(function (_ref2) { - var example = _ref2.example; - return example; - })), _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 = "\n margin: 3px;\n border: 1px solid black;\n background: ".concat(listColor.toHex(), ";\n color: ").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; - } - }]); - - return RGBColor; - }(); - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function _classCallCheck$1(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - /* eslint-disable no-bitwise, unicorn/prefer-query-selector */ - - /** - * 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: - * {@link https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript}. - * - * @module StackBlur - * @author Mario Klingemann - * 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. - */ - - /* eslint-disable max-len */ - - - 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]; - /** - * @param {string|HTMLCanvasElement} canvas - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @throws {Error|TypeError} - * @returns {ImageData} See {@link https://html.spec.whatwg.org/multipage/canvas.html#imagedata} - */ - - - function getImageDataFromCanvas(canvas, topX, topY, width, height) { - if (typeof canvas === 'string') { - canvas = document.getElementById(canvas); - } - - if (!canvas || _typeof(canvas) !== 'object' || !('getContext' in canvas)) { - throw new TypeError('Expecting canvas with `getContext` method ' + 'in processCanvasRGB(A) calls!'); - } - - var context = canvas.getContext('2d'); - - try { - return context.getImageData(topX, topY, width, height); - } catch (e) { - throw new Error('unable to access image data: ' + e); - } - } - /** - * @param {HTMLCanvasElement} canvas - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @param {Float} radius - * @returns {undefined} - */ - - - function processCanvasRGBA(canvas, topX, topY, width, height, radius) { - if (isNaN(radius) || radius < 1) { - return; - } - - radius |= 0; - var imageData = getImageDataFromCanvas(canvas, topX, topY, width, height); - imageData = processImageDataRGBA(imageData, topX, topY, width, height, radius); - canvas.getContext('2d').putImageData(imageData, topX, topY); - } - /** - * @param {ImageData} imageData - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @param {Float} radius - * @returns {ImageData} - */ - - - function processImageDataRGBA(imageData, topX, topY, width, height, radius) { - var pixels = imageData.data; - var x, y, i, p, yp, yi, yw, rSum, gSum, bSum, aSum, rOutSum, gOutSum, bOutSum, aOutSum, rInSum, gInSum, bInSum, aInSum, pr, pg, pb, pa, rbs; - var div = 2 * radius + 1; // const w4 = width << 2; - - var widthMinus1 = width - 1; - var heightMinus1 = height - 1; - var radiusPlus1 = radius + 1; - var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2; - var stackStart = new BlurStack(); - var stack = stackStart; - var stackEnd; - - for (i = 1; i < div; i++) { - stack = stack.next = new BlurStack(); - - if (i === radiusPlus1) { - stackEnd = stack; - } - } - - stack.next = stackStart; - var stackIn = null; - var stackOut = null; - yw = yi = 0; - var mulSum = mulTable[radius]; - var shgSum = shgTable[radius]; - - for (y = 0; y < height; y++) { - rInSum = gInSum = bInSum = aInSum = rSum = gSum = bSum = aSum = 0; - rOutSum = radiusPlus1 * (pr = pixels[yi]); - gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); - bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); - aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); - rSum += sumFactor * pr; - gSum += sumFactor * pg; - bSum += sumFactor * pb; - aSum += sumFactor * pa; - stack = stackStart; - - for (i = 0; i < radiusPlus1; i++) { - stack.r = pr; - stack.g = pg; - stack.b = pb; - stack.a = pa; - stack = stack.next; - } - - for (i = 1; i < radiusPlus1; i++) { - p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2); - rSum += (stack.r = pr = pixels[p]) * (rbs = radiusPlus1 - i); - gSum += (stack.g = pg = pixels[p + 1]) * rbs; - bSum += (stack.b = pb = pixels[p + 2]) * rbs; - aSum += (stack.a = pa = pixels[p + 3]) * rbs; - rInSum += pr; - gInSum += pg; - bInSum += pb; - aInSum += pa; - stack = stack.next; - } - - stackIn = stackStart; - stackOut = stackEnd; - - for (x = 0; x < width; x++) { - pixels[yi + 3] = pa = aSum * mulSum >> shgSum; - - if (pa !== 0) { - pa = 255 / pa; - pixels[yi] = (rSum * mulSum >> shgSum) * pa; - pixels[yi + 1] = (gSum * mulSum >> shgSum) * pa; - pixels[yi + 2] = (bSum * mulSum >> shgSum) * pa; - } else { - pixels[yi] = pixels[yi + 1] = pixels[yi + 2] = 0; - } - - rSum -= rOutSum; - gSum -= gOutSum; - bSum -= bOutSum; - aSum -= aOutSum; - rOutSum -= stackIn.r; - gOutSum -= stackIn.g; - bOutSum -= stackIn.b; - aOutSum -= stackIn.a; - p = yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1) << 2; - rInSum += stackIn.r = pixels[p]; - gInSum += stackIn.g = pixels[p + 1]; - bInSum += stackIn.b = pixels[p + 2]; - aInSum += stackIn.a = pixels[p + 3]; - rSum += rInSum; - gSum += gInSum; - bSum += bInSum; - aSum += aInSum; - stackIn = stackIn.next; - rOutSum += pr = stackOut.r; - gOutSum += pg = stackOut.g; - bOutSum += pb = stackOut.b; - aOutSum += pa = stackOut.a; - rInSum -= pr; - gInSum -= pg; - bInSum -= pb; - aInSum -= pa; - stackOut = stackOut.next; - yi += 4; - } - - yw += width; - } - - for (x = 0; x < width; x++) { - gInSum = bInSum = aInSum = rInSum = gSum = bSum = aSum = rSum = 0; - yi = x << 2; - rOutSum = radiusPlus1 * (pr = pixels[yi]); - gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); - bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); - aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); - rSum += sumFactor * pr; - gSum += sumFactor * pg; - bSum += sumFactor * pb; - aSum += sumFactor * pa; - stack = stackStart; - - for (i = 0; i < radiusPlus1; i++) { - stack.r = pr; - stack.g = pg; - stack.b = pb; - stack.a = pa; - stack = stack.next; - } - - yp = width; - - for (i = 1; i <= radius; i++) { - yi = yp + x << 2; - rSum += (stack.r = pr = pixels[yi]) * (rbs = radiusPlus1 - i); - gSum += (stack.g = pg = pixels[yi + 1]) * rbs; - bSum += (stack.b = pb = pixels[yi + 2]) * rbs; - aSum += (stack.a = pa = pixels[yi + 3]) * rbs; - rInSum += pr; - gInSum += pg; - bInSum += pb; - aInSum += pa; - stack = stack.next; - - if (i < heightMinus1) { - yp += width; - } - } - - yi = x; - stackIn = stackStart; - stackOut = stackEnd; - - for (y = 0; y < height; y++) { - p = yi << 2; - pixels[p + 3] = pa = aSum * mulSum >> shgSum; - - if (pa > 0) { - pa = 255 / pa; - pixels[p] = (rSum * mulSum >> shgSum) * pa; - pixels[p + 1] = (gSum * mulSum >> shgSum) * pa; - pixels[p + 2] = (bSum * mulSum >> shgSum) * pa; - } else { - pixels[p] = pixels[p + 1] = pixels[p + 2] = 0; - } - - rSum -= rOutSum; - gSum -= gOutSum; - bSum -= bOutSum; - aSum -= aOutSum; - rOutSum -= stackIn.r; - gOutSum -= stackIn.g; - bOutSum -= stackIn.b; - aOutSum -= stackIn.a; - p = x + ((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width << 2; - rSum += rInSum += stackIn.r = pixels[p]; - gSum += gInSum += stackIn.g = pixels[p + 1]; - bSum += bInSum += stackIn.b = pixels[p + 2]; - aSum += aInSum += stackIn.a = pixels[p + 3]; - stackIn = stackIn.next; - rOutSum += pr = stackOut.r; - gOutSum += pg = stackOut.g; - bOutSum += pb = stackOut.b; - aOutSum += pa = stackOut.a; - rInSum -= pr; - gInSum -= pg; - bInSum -= pb; - aInSum -= pa; - stackOut = stackOut.next; - yi += width; - } - } - - return imageData; - } - /** - * - */ - - - var BlurStack = - /** - * Set properties. - */ - function BlurStack() { - _classCallCheck$1(this, BlurStack); - - this.r = 0; - this.g = 0; - this.b = 0; - this.a = 0; - this.next = null; - }; - - /** - * 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} - */ - - /** - * @typedef {PlainObject} module:canvg.CanvgOptions - * @property {boolean} ignoreMouse true => ignore mouse events - * @property {boolean} ignoreAnimation true => ignore animations - * @property {boolean} ignoreDimensions true => does not try to resize canvas - * @property {boolean} ignoreClear true => does not clear canvas - * @property {Integer} offsetX int => draws at a x offset - * @property {Integer} offsetY int => draws at a y offset - * @property {Integer} scaleWidth int => scales horizontally to width - * @property {Integer} scaleHeight int => scales vertically to height - * @property {module:canvg.ForceRedraw} forceRedraw function => will call the function on every frame, if it returns true, will redraw - * @property {boolean} log Adds log function - * @property {boolean} useCORS Whether to set CORS `crossOrigin` for the image to `Anonymous` - */ - - /** - * If called with no arguments, it will replace all `` elements on the page - * 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 {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 (isNullish(target) && isNullish(s) && isNullish(opts)) { - var svgTags = document.querySelectorAll('svg'); - return Promise.all(_toConsumableArray(svgTags).map(function (svgTag) { - var c = document.createElement('canvas'); - c.width = svgTag.clientWidth; - c.height = svgTag.clientHeight; - svgTag.before(c); - svgTag.remove(); - var div = document.createElement('div'); - div.append(svgTag); - return canvg(c, div.innerHTML); - })); - } - - if (typeof target === 'string') { - target = document.getElementById(target); - } // store class on canvas - - - 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')) { - target.svg = svg; - } - - var ctx = target.getContext('2d'); - - if (typeof s.documentElement !== 'undefined') { - // load from xml doc - return svg.loadXmlDoc(ctx, s); - } - - if (s.substr(0, 1) === '<') { - // load from xml string - return svg.loadXml(ctx, s); - } // load from url - - - return svg.load(ctx, s); - }; - /* eslint-disable jsdoc/check-types */ - - /** - * @param {module:canvg.CanvgOptions} opts - * @returns {object} - * @todo Flesh out exactly what object is returned here (after updating to latest and reincluding our changes here and those of StackBlur) - */ - - function build(opts) { - /* eslint-enable jsdoc/check-types */ - var svg = { - opts: opts - }; - svg.FRAMERATE = 30; - svg.MAX_VIRTUAL_PIXELS = 30000; - - 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 - - - svg.init = function (ctx) { - var uniqueId = 0; - - svg.UniqueId = function () { - uniqueId++; - return 'canvg' + uniqueId; - }; - - svg.Definitions = {}; - svg.Styles = {}; - svg.Animations = []; - svg.Images = []; - svg.ctx = ctx; - svg.ViewPort = { - viewPorts: [], - Clear: function Clear() { - this.viewPorts = []; - }, - SetCurrent: function SetCurrent(width, height) { - this.viewPorts.push({ - width: width, - height: height - }); - }, - RemoveCurrent: function RemoveCurrent() { - this.viewPorts.pop(); - }, - Current: function Current() { - return this.viewPorts[this.viewPorts.length - 1]; - }, - width: function width() { - return this.Current().width; - }, - height: function height() { - return this.Current().height; - }, - ComputeSize: function ComputeSize(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); - } - }; - }; - - svg.init(); // images loaded - - svg.ImagesLoaded = function () { - return svg.Images.every(function (img) { - return img.loaded; - }); - }; // trim - - - svg.trim = function (s) { - return s.replace(/^\s+|\s+$/g, ''); - }; // compress spaces - - - svg.compressSpaces = function (s) { - return s.replace(/\s+/gm, ' '); - }; // ajax - // Todo: Replace with `fetch` and polyfill - - - svg.ajax = function (url, asynch) { - var AJAX = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP'); - - 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); - }); - AJAX.send(null); - }); - } - - AJAX.open('GET', url, false); - AJAX.send(null); - return AJAX.responseText; - }; // parse xml - - - svg.parseXml = function (xml) { - if (window.DOMParser) { - var parser = new DOMParser(); - return parser.parseFromString(xml, 'text/xml'); - } - - xml = xml.replace(/]*>/, ''); - var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM'); - xmlDoc.async = 'false'; - xmlDoc.loadXML(xml); - return xmlDoc; - }; // text extensions - // get the text baseline - - - var textBaselineMapping = { - baseline: 'alphabetic', - 'before-edge': 'top', - 'text-before-edge': 'top', - middle: 'middle', - central: 'middle', - 'after-edge': 'bottom', - 'text-after-edge': 'bottom', - ideographic: 'ideographic', - alphabetic: 'alphabetic', - hanging: 'hanging', - mathematical: 'alphabetic' - }; - - svg.Property = /*#__PURE__*/function () { - function Property(name, value) { - _classCallCheck(this, Property); - - this.name = name; - this.value = value; - } - - _createClass(Property, [{ - key: "getValue", - value: function getValue() { - return this.value; - } - }, { - key: "hasValue", - value: function hasValue() { - return !isNullish(this.value) && this.value !== ''; - } // return the numerical value of the property - - }, { - key: "numValue", - value: function numValue() { - if (!this.hasValue()) return 0; - var n = Number.parseFloat(this.value); - - if (String(this.value).endsWith('%')) { - n /= 100.0; - } - - return n; - } - }, { - key: "valueOrDefault", - value: function valueOrDefault(def) { - if (this.hasValue()) return this.value; - return def; - } - }, { - key: "numValueOrDefault", - value: function numValueOrDefault(def) { - if (this.hasValue()) return this.numValue(); - return def; - } // color extensions - // augment the current color value with the opacity - - }, { - key: "addOpacity", - value: function addOpacity(opacityProp) { - var newValue = this.value; - - if (!isNullish(opacityProp.value) && opacityProp.value !== '' && typeof this.value === 'string') { - // can only add opacity to colors, not patterns - var color = new RGBColor(this.value); - - if (color.ok) { - newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacityProp.numValue() + ')'; - } - } - - return new svg.Property(this.name, newValue); - } // definition extensions - // get the definition from the definitions table - - }, { - key: "getDefinition", - value: function getDefinition() { - var name = this.value.match(/#([^)'"]+)/); - - if (name) { - name = name[1]; - } - - if (!name) { - name = this.value; - } - - return svg.Definitions[name]; - } - }, { - key: "isUrlDefinition", - value: function isUrlDefinition() { - return this.value.startsWith('url('); - } - }, { - key: "getFillStyleDefinition", - value: function getFillStyleDefinition(e, opacityProp) { - var def = this.getDefinition(); // gradient - - if (!isNullish(def) && def.createGradient) { - return def.createGradient(svg.ctx, e, opacityProp); - } // pattern - - - if (!isNullish(def) && def.createPattern) { - if (def.getHrefAttribute().hasValue()) { - var pt = def.attribute('patternTransform'); - def = def.getHrefAttribute().getDefinition(); - - if (pt.hasValue()) { - def.attribute('patternTransform', true).value = pt.value; - } - } - - return def.createPattern(svg.ctx, e); - } - - return null; - } // length extensions - - }, { - key: "getDPI", - value: function getDPI(viewPort) { - return 96.0; // TODO: compute? - } - }, { - key: "getEM", - value: function getEM(viewPort) { - var em = 12; - var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); - if (fontSize.hasValue()) em = fontSize.toPixels(viewPort); - return em; - } - }, { - key: "getUnits", - value: function getUnits() { - return String(this.value).replace(/[\d.-]/g, ''); - } // get the length as pixels - - }, { - key: "toPixels", - value: function toPixels(viewPort, processPercent) { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('em')) return this.numValue() * this.getEM(viewPort); - if (s.endsWith('ex')) return this.numValue() * this.getEM(viewPort) / 2.0; - if (s.endsWith('px')) return this.numValue(); - if (s.endsWith('pt')) return this.numValue() * this.getDPI(viewPort) * (1.0 / 72.0); - if (s.endsWith('pc')) return this.numValue() * 15; - if (s.endsWith('cm')) return this.numValue() * this.getDPI(viewPort) / 2.54; - if (s.endsWith('mm')) return this.numValue() * this.getDPI(viewPort) / 25.4; - if (s.endsWith('in')) return this.numValue() * this.getDPI(viewPort); - if (s.endsWith('%')) return this.numValue() * svg.ViewPort.ComputeSize(viewPort); - var n = this.numValue(); - if (processPercent && n < 1.0) return n * svg.ViewPort.ComputeSize(viewPort); - return n; - } // time extensions - // get the time as milliseconds - - }, { - key: "toMilliseconds", - value: function toMilliseconds() { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('ms')) return this.numValue(); - if (s.endsWith('s')) return this.numValue() * 1000; - return this.numValue(); - } // angle extensions - // get the angle as radians - - }, { - key: "toRadians", - value: function toRadians() { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('deg')) return this.numValue() * (Math.PI / 180.0); - if (s.endsWith('grad')) return this.numValue() * (Math.PI / 200.0); - if (s.endsWith('rad')) return this.numValue(); - return this.numValue() * (Math.PI / 180.0); - } - }, { - key: "toTextBaseline", - value: function toTextBaseline() { - if (!this.hasValue()) return null; - return textBaselineMapping[this.value]; - } - }]); - - return Property; - }(); // fonts - - - svg.Font = { - Styles: 'normal|italic|oblique|inherit', - 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 = !isNullish(inherit) ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); - return { - fontFamily: fontFamily || f.fontFamily, - fontSize: fontSize || f.fontSize, - fontStyle: fontStyle || f.fontStyle, - fontWeight: fontWeight || f.fontWeight, - fontVariant: fontVariant || f.fontVariant, - toString: function toString() { - return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' '); - } - }; - }, - Parse: function Parse(s) { - var _this = this; - - var f = {}; - var ds = svg.trim(svg.compressSpaces(s || '')).split(' '); - var set = { - fontSize: false, - fontStyle: false, - fontWeight: false, - fontVariant: false - }; - var ff = ''; - ds.forEach(function (d) { - if (!set.fontStyle && _this.Styles.includes(d)) { - if (d !== 'inherit') { - f.fontStyle = d; - } - - set.fontStyle = true; - } else if (!set.fontVariant && _this.Variants.includes(d)) { - if (d !== 'inherit') { - f.fontVariant = d; - } - - set.fontStyle = set.fontVariant = true; - } else if (!set.fontWeight && _this.Weights.includes(d)) { - if (d !== 'inherit') { - f.fontWeight = d; - } - - set.fontStyle = set.fontVariant = set.fontWeight = true; - } else if (!set.fontSize) { - if (d !== 'inherit') { - f.fontSize = d.split('/')[0]; - } - - set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; - } else if (d !== 'inherit') { - ff += d; - } - }); - - if (ff !== '') { - f.fontFamily = ff; - } - - return f; - } - }; // points and paths - - svg.ToNumberArray = function (s) { - var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); - return a.map(function (_a) { - return Number.parseFloat(_a); - }); - }; - - svg.Point = /*#__PURE__*/function () { - function _class(x, y) { - _classCallCheck(this, _class); - - this.x = x; - this.y = y; - } - - _createClass(_class, [{ - key: "angleTo", - value: function angleTo(p) { - return Math.atan2(p.y - this.y, p.x - this.x); - } - }, { - key: "applyTransform", - value: function applyTransform(v) { - var xp = this.x * v[0] + this.y * v[2] + v[4]; - var yp = this.x * v[1] + this.y * v[3] + v[5]; - this.x = xp; - this.y = yp; - } - }]); - - return _class; - }(); - - svg.CreatePoint = function (s) { - var a = svg.ToNumberArray(s); - return new svg.Point(a[0], a[1]); - }; - - svg.CreatePath = function (s) { - var a = svg.ToNumberArray(s); - var path = []; - - for (var i = 0; i < a.length; i += 2) { - path.push(new svg.Point(a[i], a[i + 1])); - } - - return path; - }; // bounding box - - - svg.BoundingBox = /*#__PURE__*/function () { - function _class2(x1, y1, x2, y2) { - _classCallCheck(this, _class2); - - // pass in initial points if you want - this.x1 = Number.NaN; - this.y1 = Number.NaN; - this.x2 = Number.NaN; - this.y2 = Number.NaN; - this.addPoint(x1, y1); - this.addPoint(x2, y2); - } - - _createClass(_class2, [{ - key: "x", - value: function x() { - return this.x1; - } - }, { - key: "y", - value: function y() { - return this.y1; - } - }, { - key: "width", - value: function width() { - return this.x2 - this.x1; - } - }, { - key: "height", - value: function height() { - return this.y2 - this.y1; - } - }, { - key: "addPoint", - value: function addPoint(x, y) { - if (!isNullish(x)) { - if (isNaN(this.x1) || isNaN(this.x2)) { - this.x1 = x; - this.x2 = x; - } - - if (x < this.x1) this.x1 = x; - if (x > this.x2) this.x2 = x; - } - - if (!isNullish(y)) { - if (isNaN(this.y1) || isNaN(this.y2)) { - this.y1 = y; - this.y2 = y; - } - - if (y < this.y1) this.y1 = y; - if (y > this.y2) this.y2 = y; - } - } - }, { - key: "addX", - value: function addX(x) { - this.addPoint(x, null); - } - }, { - key: "addY", - value: function addY(y) { - this.addPoint(null, y); - } - }, { - key: "addBoundingBox", - value: function addBoundingBox(bb) { - this.addPoint(bb.x1, bb.y1); - this.addPoint(bb.x2, bb.y2); - } - }, { - key: "addQuadraticCurve", - value: function addQuadraticCurve(p0x, p0y, p1x, p1y, p2x, p2y) { - var cp1x = p0x + 2 / 3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) - - var cp1y = p0y + 2 / 3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) - - var cp2x = cp1x + 1 / 3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) - - var cp2y = cp1y + 1 / 3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) - - this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); - } - }, { - key: "addBezierCurve", - value: function addBezierCurve(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { - var _this2 = this; - - // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html - var p0 = [p0x, p0y], - p1 = [p1x, p1y], - p2 = [p2x, p2y], - p3 = [p3x, p3y]; - this.addPoint(p0[0], p0[1]); - this.addPoint(p3[0], p3[1]); - - var _loop = function _loop(i) { - var f = function f(t) { - return Math.pow(1 - t, 3) * p0[i] + 3 * Math.pow(1 - t, 2) * t * p1[i] + 3 * (1 - t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; - }; - - var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; - var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; - var c = 3 * p1[i] - 3 * p0[i]; - - if (a === 0) { - if (b === 0) return "continue"; - var t = -c / b; - - if (t > 0 && t < 1) { - if (i === 0) _this2.addX(f(t)); - if (i === 1) _this2.addY(f(t)); - } - - return "continue"; - } - - var b2ac = Math.pow(b, 2) - 4 * c * a; - if (b2ac < 0) return "continue"; - var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); - - if (t1 > 0 && t1 < 1) { - if (i === 0) _this2.addX(f(t1)); - if (i === 1) _this2.addY(f(t1)); - } - - var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); - - if (t2 > 0 && t2 < 1) { - if (i === 0) _this2.addX(f(t2)); - if (i === 1) _this2.addY(f(t2)); - } - }; - - for (var i = 0; i <= 1; i++) { - var _ret = _loop(i); - - if (_ret === "continue") continue; - } - } - }, { - key: "isPointInBox", - value: function isPointInBox(x, y) { - return this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2; - } - }]); - - return _class2; - }(); // transforms - - - svg.Transform = /*#__PURE__*/function () { - function _class3(v) { - var _this6 = this; - - _classCallCheck(this, _class3); - - this.Type = { - translate: function translate(s) { - _classCallCheck(this, translate); - - this.p = svg.CreatePoint(s); - - this.apply = function (ctx) { - ctx.translate(this.p.x || 0.0, this.p.y || 0.0); - }; - - this.unapply = function (ctx) { - ctx.translate(-1.0 * this.p.x || 0.0, -1.0 * this.p.y || 0.0); - }; - - this.applyToPoint = function (p) { - p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); - }; - }, - rotate: function rotate(s) { - _classCallCheck(this, rotate); - - var a = svg.ToNumberArray(s); - this.angle = new svg.Property('angle', a[0]); - this.cx = a[1] || 0; - this.cy = a[2] || 0; - - this.apply = function (ctx) { - ctx.translate(this.cx, this.cy); - ctx.rotate(this.angle.toRadians()); - ctx.translate(-this.cx, -this.cy); - }; - - this.unapply = function (ctx) { - ctx.translate(this.cx, this.cy); - ctx.rotate(-1.0 * this.angle.toRadians()); - ctx.translate(-this.cx, -this.cy); - }; - - this.applyToPoint = function (p) { - 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([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); - }; - }, - scale: function scale(s) { - _classCallCheck(this, scale); - - this.p = svg.CreatePoint(s); - - this.apply = function (ctx) { - ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); - }; - - this.unapply = function (ctx) { - ctx.scale(1.0 / this.p.x || 1.0, 1.0 / this.p.y || this.p.x || 1.0); - }; - - this.applyToPoint = function (p) { - p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); - }; - }, - matrix: function matrix(s) { - _classCallCheck(this, matrix); - - this.m = svg.ToNumberArray(s); - - this.apply = function (ctx) { - ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); - }; - - this.applyToPoint = function (p) { - p.applyTransform(this.m); - }; - } - }; - Object.assign(this.Type, { - SkewBase: /*#__PURE__*/function (_this$Type$matrix) { - _inherits(SkewBase, _this$Type$matrix); - - var _super = _createSuper(SkewBase); - - function SkewBase(s) { - var _this3; - - _classCallCheck(this, SkewBase); - - _this3 = _super.call(this, s); - _this3.angle = new svg.Property('angle', s); - return _this3; - } - - return SkewBase; - }(this.Type.matrix) - }); - Object.assign(this.Type, { - skewX: /*#__PURE__*/function (_this$Type$SkewBase) { - _inherits(skewX, _this$Type$SkewBase); - - var _super2 = _createSuper(skewX); - - function skewX(s) { - var _this4; - - _classCallCheck(this, skewX); - - _this4 = _super2.call(this, s); - _this4.m = [1, 0, Math.tan(_this4.angle.toRadians()), 1, 0, 0]; - return _this4; - } - - return skewX; - }(this.Type.SkewBase), - skewY: /*#__PURE__*/function (_this$Type$SkewBase2) { - _inherits(skewY, _this$Type$SkewBase2); - - var _super3 = _createSuper(skewY); - - function skewY(s) { - var _this5; - - _classCallCheck(this, skewY); - - _this5 = _super3.call(this, s); - _this5.m = [1, Math.tan(_this5.angle.toRadians()), 0, 1, 0, 0]; - return _this5; - } - - return skewY; - }(this.Type.SkewBase) - }); - var data = svg.trim(svg.compressSpaces(v)).replace(/\)([a-zA-Z])/g, ') $1').replace(/\)(\s?,\s?)/g, ') ').split(/\s(?=[a-z])/); - this.transforms = data.map(function (d) { - var type = svg.trim(d.split('(')[0]); - var s = d.split('(')[1].replace(')', ''); - var transform = new _this6.Type[type](s); - transform.type = type; - return transform; - }); - } - - _createClass(_class3, [{ - key: "apply", - value: function apply(ctx) { - this.transforms.forEach(function (transform) { - transform.apply(ctx); - }); - } - }, { - key: "unapply", - value: function unapply(ctx) { - for (var i = this.transforms.length - 1; i >= 0; i--) { - this.transforms[i].unapply(ctx); - } - } - }, { - key: "applyToPoint", - value: function applyToPoint(p) { - this.transforms.forEach(function (transform) { - transform.applyToPoint(p); - }); - } - }]); - - return _class3; - }(); // aspect ratio - - - svg.AspectRatio = function (ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { - // aspect ratio - https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute - aspectRatio = svg.compressSpaces(aspectRatio); - aspectRatio = aspectRatio.replace(/^defer\s/, ''); // ignore defer - - var align = aspectRatio.split(' ')[0] || 'xMidYMid'; - var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale - - var scaleX = width / desiredWidth; - var scaleY = height / desiredHeight; - var scaleMin = Math.min(scaleX, scaleY); - var scaleMax = Math.max(scaleX, scaleY); - - if (meetOrSlice === 'meet') { - desiredWidth *= scaleMin; - desiredHeight *= scaleMin; - } - - if (meetOrSlice === 'slice') { - desiredWidth *= scaleMax; - desiredHeight *= scaleMax; - } - - refX = new svg.Property('refX', refX); - refY = new svg.Property('refY', refY); - - if (refX.hasValue() && refY.hasValue()) { - ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y')); - } else { - // align - if (align.startsWith('xMid') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { - ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); - } - - if (align.endsWith('YMid') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { - ctx.translate(0, height / 2.0 - desiredHeight / 2.0); - } - - if (align.startsWith('xMax') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { - ctx.translate(width - desiredWidth, 0); - } - - if (align.endsWith('YMax') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { - ctx.translate(0, height - desiredHeight); - } - } // scale - - - 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(isNullish(minX) ? 0 : -minX, isNullish(minY) ? 0 : -minY); - }; // elements - - - svg.Element = {}; - svg.EmptyProperty = new svg.Property('EMPTY', ''); - - svg.Element.ElementBase = /*#__PURE__*/function () { - function _class4(node) { - var _this7 = this; - - _classCallCheck(this, _class4); - - // Argument from inheriting class - this.captureTextNodes = arguments[1]; // eslint-disable-line prefer-rest-params - - this.attributes = {}; - this.styles = {}; - this.children = []; - - if (!isNullish(node) && node.nodeType === 1) { - // ELEMENT_NODE - // add children - _toConsumableArray(node.childNodes).forEach(function (childNode) { - if (childNode.nodeType === 1) { - _this7.addChild(childNode, true); // ELEMENT_NODE - - } - - if (_this7.captureTextNodes && (childNode.nodeType === 3 || childNode.nodeType === 4)) { - var text = childNode.nodeValue || childNode.text || ''; - - if (svg.trim(svg.compressSpaces(text)) !== '') { - _this7.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE - - } - } - }); // add attributes - - - _toConsumableArray(node.attributes).forEach(function (_ref) { - var nodeName = _ref.nodeName, - nodeValue = _ref.nodeValue; - _this7.attributes[nodeName] = new svg.Property(nodeName, nodeValue); - }); // add tag styles - - - var styles = svg.Styles[node.nodeName]; - - 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 - - - if (this.attribute('class').hasValue()) { - var classes = svg.compressSpaces(this.attribute('class').value).split(' '); - classes.forEach(function (clss) { - styles = svg.Styles['.' + clss]; - - 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 (!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 - - - if (this.attribute('id').hasValue()) { - var _styles = svg.Styles['#' + this.attribute('id').value]; - - 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 - - - if (this.attribute('style').hasValue()) { - var _styles2 = this.attribute('style').value.split(';'); - - _styles2.forEach(function (style) { - if (svg.trim(style) !== '') { - var _style$split = style.split(':'), - name = _style$split.name, - value = _style$split.value; - - name = svg.trim(name); - value = svg.trim(value); - _this7.styles[name] = new svg.Property(name, value); - } - }); - } // add id - - - if (this.attribute('id').hasValue()) { - if (isNullish(svg.Definitions[this.attribute('id').value])) { - svg.Definitions[this.attribute('id').value] = this; - } - } - } - } // get or create attribute - - - _createClass(_class4, [{ - key: "attribute", - value: function attribute(name, createIfNotExists) { - var a = this.attributes[name]; - if (!isNullish(a)) return a; - - if (createIfNotExists === true) { - a = new svg.Property(name, ''); - this.attributes[name] = a; - } - - return a || svg.EmptyProperty; - } - }, { - key: "getHrefAttribute", - value: function getHrefAttribute() { - for (var a in this.attributes) { - if (a.endsWith(':href')) { - return this.attributes[a]; - } - } - - return svg.EmptyProperty; - } // get or create style, crawls up node tree - - }, { - key: "style", - value: function style(name, createIfNotExists, skipAncestors) { - var s = this.styles[name]; - if (!isNullish(s)) return s; - var a = this.attribute(name); - - if (!isNullish(a) && a.hasValue()) { - this.styles[name] = a; // move up to me to cache - - return a; - } - - if (skipAncestors !== true) { - var p = this.parent; - - if (!isNullish(p)) { - var ps = p.style(name); - - if (!isNullish(ps) && ps.hasValue()) { - return ps; - } - } - } - - if (createIfNotExists === true) { - s = new svg.Property(name, ''); - this.styles[name] = s; - } - - return s || svg.EmptyProperty; - } // base render - - }, { - key: "render", - value: function render(ctx) { - // don't render display=none - if (this.style('display').value === 'none') return; // don't render visibility=hidden - - if (this.style('visibility').value === 'hidden') return; - ctx.save(); - - if (this.attribute('mask').hasValue()) { - // mask - var mask = this.attribute('mask').getDefinition(); - if (!isNullish(mask)) mask.apply(ctx, this); - } else if (this.style('filter').hasValue()) { - // filter - var filter = this.style('filter').getDefinition(); - if (!isNullish(filter)) filter.apply(ctx, this); - } else { - this.setContext(ctx); - this.renderChildren(ctx); - this.clearContext(ctx); - } - - ctx.restore(); - } // base set context - - }, { - key: "setContext", - value: function setContext(ctx) {// OVERRIDE ME! - } // base clear context - - }, { - key: "clearContext", - value: function clearContext(ctx) {// OVERRIDE ME! - } // base render children - - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - this.children.forEach(function (child) { - child.render(ctx); - }); - } - }, { - key: "addChild", - value: function addChild(childNode, create) { - var child = create ? svg.CreateElement(childNode) : childNode; - child.parent = this; - - if (child.type !== 'title') { - this.children.push(child); - } - } - }]); - - return _class4; - }(); - - svg.Element.RenderedElementBase = /*#__PURE__*/function (_svg$Element$ElementB) { - _inherits(_class5, _svg$Element$ElementB); - - var _super4 = _createSuper(_class5); - - function _class5() { - _classCallCheck(this, _class5); - - return _super4.apply(this, arguments); - } - - _createClass(_class5, [{ - key: "setContext", - value: function setContext(ctx) { - // fill - if (this.style('fill').isUrlDefinition()) { - var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity')); - 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; - ctx.fillStyle = fillStyle.value === 'none' ? 'rgba(0,0,0,0)' : fillStyle.value; - } - - if (this.style('fill-opacity').hasValue()) { - var _fillStyle = new svg.Property('fill', ctx.fillStyle); - - _fillStyle = _fillStyle.addOpacity(this.style('fill-opacity')); - ctx.fillStyle = _fillStyle.value; - } // stroke - - - if (this.style('stroke').isUrlDefinition()) { - var _fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity')); - - 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; - ctx.strokeStyle = strokeStyle.value === 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value; - } - - if (this.style('stroke-opacity').hasValue()) { - var _strokeStyle = new svg.Property('stroke', ctx.strokeStyle); - - _strokeStyle = _strokeStyle.addOpacity(this.style('stroke-opacity')); - ctx.strokeStyle = _strokeStyle.value; - } - - if (this.style('stroke-width').hasValue()) { - var newLineWidth = this.style('stroke-width').toPixels(); - ctx.lineWidth = newLineWidth === 0 ? 0.001 : newLineWidth; // browsers don't respect 0 - } - - if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; - if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; - if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; - - if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value !== 'none') { - var gaps = svg.ToNumberArray(this.style('stroke-dasharray').value); - - if (typeof ctx.setLineDash !== 'undefined') { - ctx.setLineDash(gaps); - } else if (typeof ctx.webkitLineDash !== 'undefined') { - ctx.webkitLineDash = gaps; - } else if (typeof ctx.mozDash !== 'undefined' && !(gaps.length === 1 && gaps[0] === 0)) { - ctx.mozDash = gaps; - } - - var offset = this.style('stroke-dashoffset').numValueOrDefault(1); - - if (typeof ctx.lineDashOffset !== 'undefined') { - ctx.lineDashOffset = offset; - } else if (typeof ctx.webkitLineDashOffset !== 'undefined') { - ctx.webkitLineDashOffset = offset; - } else if (typeof ctx.mozDashOffset !== 'undefined') { - ctx.mozDashOffset = offset; - } - } // font - - - if (typeof ctx.font !== 'undefined') { - ctx.font = svg.Font.CreateFont(this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '', this.style('font-family').value).toString(); - } // transform - - - if (this.attribute('transform').hasValue()) { - var transform = new svg.Transform(this.attribute('transform').value); - transform.apply(ctx); - } // clip - - - if (this.style('clip-path', false, true).hasValue()) { - var clip = this.style('clip-path', false, true).getDefinition(); - if (!isNullish(clip)) clip.apply(ctx); - } // opacity - - - if (this.style('opacity').hasValue()) { - ctx.globalAlpha = this.style('opacity').numValue(); - } - } - }]); - - return _class5; - }(svg.Element.ElementBase); - - svg.Element.PathElementBase = /*#__PURE__*/function (_svg$Element$Rendered) { - _inherits(_class6, _svg$Element$Rendered); - - var _super5 = _createSuper(_class6); - - function _class6() { - _classCallCheck(this, _class6); - - return _super5.apply(this, arguments); - } - - _createClass(_class6, [{ - key: "path", - value: function path(ctx) { - if (!isNullish(ctx)) ctx.beginPath(); - return new svg.BoundingBox(); - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - this.path(ctx); - svg.Mouse.checkPath(this, ctx); - - if (ctx.fillStyle !== '') { - if (this.style('fill-rule').valueOrDefault('inherit') !== 'inherit') { - ctx.fill(this.style('fill-rule').value); - } else { - ctx.fill(); - } - } - - if (ctx.strokeStyle !== '') ctx.stroke(); - var markers = this.getMarkers(); - - 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]); - } - - if (this.style('marker-mid').isUrlDefinition()) { - var _marker = this.style('marker-mid').getDefinition(); - - for (var i = 1; i < markers.length - 1; i++) { - _marker.render(ctx, markers[i][0], markers[i][1]); - } - } - - if (this.style('marker-end').isUrlDefinition()) { - var _marker2 = this.style('marker-end').getDefinition(); - - _marker2.render(ctx, markers[markers.length - 1][0], markers[markers.length - 1][1]); - } - } - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - return this.path(); - } - }, { - key: "getMarkers", - value: function getMarkers() { - return null; - } - }]); - - return _class6; - }(svg.Element.RenderedElementBase); // svg element - - - svg.Element.svg = /*#__PURE__*/function (_svg$Element$Rendered2) { - _inherits(_class7, _svg$Element$Rendered2); - - var _super6 = _createSuper(_class7); - - function _class7() { - _classCallCheck(this, _class7); - - return _super6.apply(this, arguments); - } - - _createClass(_class7, [{ - key: "clearContext", - value: function clearContext(ctx) { - _get(_getPrototypeOf(_class7.prototype), "clearContext", this).call(this, ctx); - - svg.ViewPort.RemoveCurrent(); - } - }, { - key: "setContext", - value: function setContext(ctx) { - // initial values and defaults - ctx.strokeStyle = 'rgba(0,0,0,0)'; - ctx.lineCap = 'butt'; - ctx.lineJoin = 'miter'; - ctx.miterLimit = 4; - - if (typeof ctx.font !== 'undefined' && typeof window.getComputedStyle !== 'undefined') { - ctx.font = window.getComputedStyle(ctx.canvas).getPropertyValue('font'); - } - - _get(_getPrototypeOf(_class7.prototype), "setContext", this).call(this, ctx); // create new view port - - - if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0; - if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0; - ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y')); - var width = svg.ViewPort.width(); - var height = svg.ViewPort.height(); - if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%'; - if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%'; - - if (typeof this.root === 'undefined') { - width = this.attribute('width').toPixels('x'); - height = this.attribute('height').toPixels('y'); - var x = 0; - var y = 0; - - if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { - x = -this.attribute('refX').toPixels('x'); - y = -this.attribute('refY').toPixels('y'); - } - - if (this.attribute('overflow').valueOrDefault('hidden') !== 'visible') { - ctx.beginPath(); - ctx.moveTo(x, y); - ctx.lineTo(width, y); - ctx.lineTo(width, height); - ctx.lineTo(x, height); - ctx.closePath(); - ctx.clip(); - } - } - - svg.ViewPort.SetCurrent(width, height); // viewbox - - if (this.attribute('viewBox').hasValue()) { - var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); - var minX = viewBox[0]; - var minY = viewBox[1]; - width = viewBox[2]; - height = viewBox[3]; - svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); - svg.ViewPort.RemoveCurrent(); - svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); - } - } - }]); - - return _class7; - }(svg.Element.RenderedElementBase); // rect element - - - svg.Element.rect = /*#__PURE__*/function (_svg$Element$PathElem) { - _inherits(_class8, _svg$Element$PathElem); - - var _super7 = _createSuper(_class8); - - function _class8() { - _classCallCheck(this, _class8); - - return _super7.apply(this, arguments); - } - - _createClass(_class8, [{ - key: "path", - value: function path(ctx) { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - var rx = this.attribute('rx').toPixels('x'); - var ry = this.attribute('ry').toPixels('y'); - if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; - if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; - rx = Math.min(rx, width / 2.0); - ry = Math.min(ry, height / 2.0); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(x + rx, y); - ctx.lineTo(x + width - rx, y); - ctx.quadraticCurveTo(x + width, y, x + width, y + ry); - ctx.lineTo(x + width, y + height - ry); - ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height); - ctx.lineTo(x + rx, y + height); - ctx.quadraticCurveTo(x, y + height, x, y + height - ry); - ctx.lineTo(x, y + ry); - ctx.quadraticCurveTo(x, y, x + rx, y); - ctx.closePath(); - } - - return new svg.BoundingBox(x, y, x + width, y + height); - } - }]); - - return _class8; - }(svg.Element.PathElementBase); // circle element - - - svg.Element.circle = /*#__PURE__*/function (_svg$Element$PathElem2) { - _inherits(_class9, _svg$Element$PathElem2); - - var _super8 = _createSuper(_class9); - - function _class9() { - _classCallCheck(this, _class9); - - return _super8.apply(this, arguments); - } - - _createClass(_class9, [{ - key: "path", - value: function path(ctx) { - var cx = this.attribute('cx').toPixels('x'); - var cy = this.attribute('cy').toPixels('y'); - var r = this.attribute('r').toPixels(); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.arc(cx, cy, r, 0, Math.PI * 2, true); - ctx.closePath(); - } - - return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); - } - }]); - - return _class9; - }(svg.Element.PathElementBase); // ellipse element - - - var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); - - svg.Element.ellipse = /*#__PURE__*/function (_svg$Element$PathElem3) { - _inherits(_class10, _svg$Element$PathElem3); - - var _super9 = _createSuper(_class10); - - function _class10() { - _classCallCheck(this, _class10); - - return _super9.apply(this, arguments); - } - - _createClass(_class10, [{ - key: "path", - value: function path(ctx) { - var rx = this.attribute('rx').toPixels('x'); - var ry = this.attribute('ry').toPixels('y'); - var cx = this.attribute('cx').toPixels('x'); - var cy = this.attribute('cy').toPixels('y'); - - 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); - ctx.bezierCurveTo(cx + rx, cy + KAPPA * ry, cx + KAPPA * rx, cy + ry, cx, cy + ry); - ctx.bezierCurveTo(cx - KAPPA * rx, cy + ry, cx - rx, cy + KAPPA * ry, cx - rx, cy); - ctx.bezierCurveTo(cx - rx, cy - KAPPA * ry, cx - KAPPA * rx, cy - ry, cx, cy - ry); - ctx.closePath(); - } - - return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); - } - }]); - - return _class10; - }(svg.Element.PathElementBase); // line element - - - svg.Element.line = /*#__PURE__*/function (_svg$Element$PathElem4) { - _inherits(_class11, _svg$Element$PathElem4); - - var _super10 = _createSuper(_class11); - - function _class11() { - _classCallCheck(this, _class11); - - return _super10.apply(this, arguments); - } - - _createClass(_class11, [{ - key: "getPoints", - value: function getPoints() { - return [new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')), new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))]; - } - }, { - key: "path", - value: function path(ctx) { - var points = this.getPoints(); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(points[0].x, points[0].y); - ctx.lineTo(points[1].x, points[1].y); - } - - return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); - } - }, { - key: "getMarkers", - value: function getMarkers() { - var points = this.getPoints(); - var a = points[0].angleTo(points[1]); - return [[points[0], a], [points[1], a]]; - } - }]); - - return _class11; - }(svg.Element.PathElementBase); // polyline element - - - svg.Element.polyline = /*#__PURE__*/function (_svg$Element$PathElem5) { - _inherits(_class12, _svg$Element$PathElem5); - - var _super11 = _createSuper(_class12); - - function _class12(node) { - var _this8; - - _classCallCheck(this, _class12); - - _this8 = _super11.call(this, node); - _this8.points = svg.CreatePath(_this8.attribute('points').value); - return _this8; - } - - _createClass(_class12, [{ - key: "path", - value: function path(ctx) { - var _this$points$ = this.points[0], - x = _this$points$.x, - y = _this$points$.y; - var bb = new svg.BoundingBox(x, y); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(x, y); - } - - for (var i = 1; i < this.points.length; i++) { - var _this$points$i = this.points[i], - _x = _this$points$i.x, - _y = _this$points$i.y; - bb.addPoint(_x, _y); - if (!isNullish(ctx)) ctx.lineTo(_x, _y); - } - - return bb; - } - }, { - key: "getMarkers", - value: function getMarkers() { - var markers = []; - - for (var i = 0; i < this.points.length - 1; i++) { - markers.push([this.points[i], this.points[i].angleTo(this.points[i + 1])]); - } - - markers.push([this.points[this.points.length - 1], markers[markers.length - 1][1]]); - return markers; - } - }]); - - return _class12; - }(svg.Element.PathElementBase); // polygon element - - - svg.Element.polygon = /*#__PURE__*/function (_svg$Element$polyline) { - _inherits(_class13, _svg$Element$polyline); - - var _super12 = _createSuper(_class13); - - function _class13() { - _classCallCheck(this, _class13); - - return _super12.apply(this, arguments); - } - - _createClass(_class13, [{ - key: "path", - value: function path(ctx) { - var bb = _get(_getPrototypeOf(_class13.prototype), "path", this).call(this, ctx); - - if (!isNullish(ctx)) { - ctx.lineTo(this.points[0].x, this.points[0].y); - ctx.closePath(); - } - - return bb; - } - }]); - - return _class13; - }(svg.Element.polyline); // path element - - - svg.Element.path = /*#__PURE__*/function (_svg$Element$PathElem6) { - _inherits(_class14, _svg$Element$PathElem6); - - var _super13 = _createSuper(_class14); - - function _class14(node) { - var _this9; - - _classCallCheck(this, _class14); - - _this9 = _super13.call(this, node); - - var d = _this9.attribute('d').value // TODO: convert to real lexer based on https://www.w3.org/TR/SVG11/paths.html#PathDataBNF - .replace(/,/gm, ' ') // get rid of all commas - .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands - .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands - .replace(/([MmZzLlHhVvCcSsQqTtAa])(\S)/gm, '$1 $2') // separate commands from points - .replace(/(\S)([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from points - .replace(/(\d)([+-])/gm, '$1 $2') // separate digits when no comma - .replace(/(\.\d*)(\.)/gm, '$1 $2') // separate digits when no comma - .replace(/([Aa](\s+\d+)(\s+\d+)(\s+\d+))\s+([01])\s*([01])/gm, '$1 $5 $6 '); // shorthand elliptical arc path syntax - - - d = svg.compressSpaces(d); // compress multiple spaces - - d = svg.trim(d); - _this9.PathParser = { - tokens: d.split(' '), - reset: function reset() { - this.i = -1; - this.command = ''; - this.previousCommand = ''; - this.start = new svg.Point(0, 0); - this.control = new svg.Point(0, 0); - this.current = new svg.Point(0, 0); - this.points = []; - this.angles = []; - }, - isEnd: function isEnd() { - return this.i >= this.tokens.length - 1; - }, - isCommandOrEnd: function isCommandOrEnd() { - if (this.isEnd()) return true; - return !isNullish(this.tokens[this.i + 1].match(/^[A-Za-z]$/)); - }, - isRelativeCommand: function isRelativeCommand() { - switch (this.command) { - case 'm': - case 'l': - case 'h': - case 'v': - case 'c': - case 's': - case 'q': - case 't': - case 'a': - case 'z': - return true; - } - - return false; - }, - getToken: function getToken() { - this.i++; - return this.tokens[this.i]; - }, - getScalar: function getScalar() { - return Number.parseFloat(this.getToken()); - }, - nextCommand: function nextCommand() { - this.previousCommand = this.command; - this.command = this.getToken(); - }, - getPoint: function getPoint() { - var p = new svg.Point(this.getScalar(), this.getScalar()); - return this.makeAbsolute(p); - }, - getAsControlPoint: function getAsControlPoint() { - var p = this.getPoint(); - this.control = p; - return p; - }, - getAsCurrentPoint: function getAsCurrentPoint() { - var p = this.getPoint(); - this.current = p; - return p; - }, - getReflectedControlPoint: function getReflectedControlPoint() { - if (this.previousCommand.toLowerCase() !== 'c' && this.previousCommand.toLowerCase() !== 's' && this.previousCommand.toLowerCase() !== 'q' && this.previousCommand.toLowerCase() !== 't') { - return this.current; - } // reflect point - - - var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); - return p; - }, - makeAbsolute: function makeAbsolute(p) { - if (this.isRelativeCommand()) { - p.x += this.current.x; - p.y += this.current.y; - } - - return p; - }, - addMarker: function addMarker(p, from, priorTo) { - // if the last angle isn't filled in because we didn't have this point yet ... - 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, isNullish(from) ? null : from.angleTo(p)); - }, - addMarkerAngle: function addMarkerAngle(p, a) { - this.points.push(p); - this.angles.push(a); - }, - getMarkerPoints: function getMarkerPoints() { - return this.points; - }, - getMarkerAngles: function getMarkerAngles() { - for (var i = 0; i < this.angles.length; i++) { - if (isNullish(this.angles[i])) { - for (var j = i + 1; j < this.angles.length; j++) { - if (!isNullish(this.angles[j])) { - this.angles[i] = this.angles[j]; - break; - } - } - } - } - - return this.angles; - } - }; - return _this9; - } - - _createClass(_class14, [{ - key: "path", - value: function path(ctx) { - var pp = this.PathParser; - pp.reset(); - var bb = new svg.BoundingBox(); - if (!isNullish(ctx)) ctx.beginPath(); - - while (!pp.isEnd()) { - pp.nextCommand(); - - switch (pp.command) { - case 'M': - case 'm': - { - 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(); - - pp.addMarker(_p, pp.start); - bb.addPoint(_p.x, _p.y); - if (!isNullish(ctx)) ctx.lineTo(_p.x, _p.y); - } - - break; - } - - case 'L': - case 'l': - while (!pp.isCommandOrEnd()) { - var c = pp.current; - - var _p2 = pp.getAsCurrentPoint(); - - pp.addMarker(_p2, c); - bb.addPoint(_p2.x, _p2.y); - if (!isNullish(ctx)) ctx.lineTo(_p2.x, _p2.y); - } - - break; - - case 'H': - case 'h': - while (!pp.isCommandOrEnd()) { - var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); - pp.addMarker(newP, pp.current); - pp.current = newP; - bb.addPoint(pp.current.x, pp.current.y); - if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); - } - - break; - - case 'V': - case 'v': - while (!pp.isCommandOrEnd()) { - var _newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); - - pp.addMarker(_newP, pp.current); - pp.current = _newP; - bb.addPoint(pp.current.x, pp.current.y); - if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); - } - - break; - - case 'C': - case 'c': - while (!pp.isCommandOrEnd()) { - var curr = pp.current; - var p1 = pp.getPoint(); - var cntrl = pp.getAsControlPoint(); - 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 (!isNullish(ctx)) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); - } - - break; - - case 'S': - case 's': - while (!pp.isCommandOrEnd()) { - var _curr = pp.current; - - var _p3 = pp.getReflectedControlPoint(); - - var _cntrl = pp.getAsControlPoint(); - - var _cp = pp.getAsCurrentPoint(); - - pp.addMarker(_cp, _cntrl, _p3); - bb.addBezierCurve(_curr.x, _curr.y, _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; - - case 'Q': - case 'q': - while (!pp.isCommandOrEnd()) { - var _curr2 = pp.current; - - var _cntrl2 = pp.getAsControlPoint(); - - var _cp2 = pp.getAsCurrentPoint(); - - pp.addMarker(_cp2, _cntrl2, _cntrl2); - bb.addQuadraticCurve(_curr2.x, _curr2.y, _cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); - if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); - } - - break; - - case 'T': - case 't': - while (!pp.isCommandOrEnd()) { - var _curr3 = pp.current; - - var _cntrl3 = pp.getReflectedControlPoint(); - - pp.control = _cntrl3; - - var _cp3 = pp.getAsCurrentPoint(); - - pp.addMarker(_cp3, _cntrl3, _cntrl3); - bb.addQuadraticCurve(_curr3.x, _curr3.y, _cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); - if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); - } - - break; - - case 'A': - case 'a': - var _loop2 = function _loop2() { - var curr = pp.current; - var rx = pp.getScalar(); - var ry = pp.getScalar(); - var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); - var largeArcFlag = pp.getScalar(); - var sweepFlag = pp.getScalar(); - var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization - // https://www.w3.org/TR/SVG11/implnote.html#ArcConversionEndpointToCenter - // x1', y1' - - var currp = new svg.Point(Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0); // adjust radii - - var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2); - - if (l > 1) { - rx *= Math.sqrt(l); - ry *= Math.sqrt(l); - } // cx', cy' - - - var s = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt((Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(currp.y, 2) - Math.pow(ry, 2) * Math.pow(currp.x, 2)) / (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))); - if (isNaN(s)) s = 0; - var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy - - var centp = new svg.Point((curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y); // vector magnitude - - var m = function m(v) { - return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)); - }; // ratio between two vectors - - - var r = function r(u, v) { - return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v)); - }; // angle between two vectors - - - var a = function a(u, v) { - return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v)); - }; // initial angle - - - var a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]); // angle delta - - var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]; - var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry]; - var ad = a(u, v); - if (r(u, v) <= -1) ad = Math.PI; - if (r(u, v) >= 1) ad = 0; // for markers - - var dir = 1 - sweepFlag ? 1.0 : -1.0; - var ah = a1 + dir * (ad / 2.0); - var halfWay = new svg.Point(centp.x + rx * Math.cos(ah), centp.y + ry * Math.sin(ah)); - pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2); - pp.addMarkerAngle(cp, ah - dir * Math.PI); - bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better - - if (!isNullish(ctx)) { - var _r = rx > ry ? rx : ry; - - var sx = rx > ry ? 1 : rx / ry; - var sy = rx > ry ? ry / rx : 1; - ctx.translate(centp.x, centp.y); - ctx.rotate(xAxisRotation); - ctx.scale(sx, sy); - ctx.arc(0, 0, _r, a1, a1 + ad, 1 - sweepFlag); - ctx.scale(1 / sx, 1 / sy); - ctx.rotate(-xAxisRotation); - ctx.translate(-centp.x, -centp.y); - } - }; - - while (!pp.isCommandOrEnd()) { - _loop2(); - } - - break; - - case 'Z': - case 'z': - if (!isNullish(ctx)) ctx.closePath(); - pp.current = pp.start; - } - } - - return bb; - } - }, { - key: "getMarkers", - value: function getMarkers() { - var points = this.PathParser.getMarkerPoints(); - var angles = this.PathParser.getMarkerAngles(); - var markers = points.map(function (point, i) { - return [point, angles[i]]; - }); - return markers; - } - }]); - - return _class14; - }(svg.Element.PathElementBase); // pattern element - - - svg.Element.pattern = /*#__PURE__*/function (_svg$Element$ElementB2) { - _inherits(_class15, _svg$Element$ElementB2); - - var _super14 = _createSuper(_class15); - - function _class15() { - _classCallCheck(this, _class15); - - return _super14.apply(this, arguments); - } - - _createClass(_class15, [{ - key: "createPattern", - value: function createPattern(ctx, element) { - var width = this.attribute('width').toPixels('x', true); - 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.children = this.children; - var c = document.createElement('canvas'); - c.width = width; - c.height = height; - var cctx = c.getContext('2d'); - - if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { - cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true)); - } // render 3x3 grid so when we transform there's no white space on edges - - - for (var x = -1; x <= 1; x++) { - for (var y = -1; y <= 1; y++) { - cctx.save(); - cctx.translate(x * c.width, y * c.height); - tempSvg.render(cctx); - cctx.restore(); - } - } - - var pattern = ctx.createPattern(c, 'repeat'); - return pattern; - } - }]); - - return _class15; - }(svg.Element.ElementBase); // marker element - - - svg.Element.marker = /*#__PURE__*/function (_svg$Element$ElementB3) { - _inherits(_class16, _svg$Element$ElementB3); - - var _super15 = _createSuper(_class16); - - function _class16() { - _classCallCheck(this, _class16); - - return _super15.apply(this, arguments); - } - - _createClass(_class16, [{ - key: "render", - value: function render(ctx, point, angle) { - ctx.translate(point.x, point.y); - if (this.attribute('orient').valueOrDefault('auto') === 'auto') ctx.rotate(angle); - if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); - 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.children = this.children; - tempSvg.render(ctx); - ctx.restore(); - if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(1 / ctx.lineWidth, 1 / ctx.lineWidth); - - if (this.attribute('orient').valueOrDefault('auto') === 'auto') { - ctx.rotate(-angle); - } - - ctx.translate(-point.x, -point.y); - } - }]); - - return _class16; - }(svg.Element.ElementBase); // definitions element - - - svg.Element.defs = /*#__PURE__*/function (_svg$Element$ElementB4) { - _inherits(_class17, _svg$Element$ElementB4); - - var _super16 = _createSuper(_class17); - - function _class17() { - _classCallCheck(this, _class17); - - return _super16.apply(this, arguments); - } - - _createClass(_class17, [{ - key: "render", - value: function render(ctx) {// NOOP - } - }]); - - return _class17; - }(svg.Element.ElementBase); // base for gradients - - - svg.Element.GradientBase = /*#__PURE__*/function (_svg$Element$ElementB5) { - _inherits(_class18, _svg$Element$ElementB5); - - var _super17 = _createSuper(_class18); - - function _class18(node) { - var _this10; - - _classCallCheck(this, _class18); - - _this10 = _super17.call(this, node); - _this10.gradientUnits = _this10.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); - _this10.stops = []; - - _this10.children.forEach(function (child) { - if (child.type === 'stop') { - _this10.stops.push(child); - } - }); - - return _this10; - } - - _createClass(_class18, [{ - key: "getGradient", - value: function getGradient() {// OVERRIDE ME! - } - }, { - key: "createGradient", - value: function createGradient(ctx, element, parentOpacityProp) { - var stopsContainer = this.getHrefAttribute().hasValue() ? this.getHrefAttribute().getDefinition() : this; - - var addParentOpacity = function addParentOpacity(color) { - if (parentOpacityProp.hasValue()) { - var p = new svg.Property('color', color); - return p.addOpacity(parentOpacityProp).value; - } - - return color; - }; - - var g = this.getGradient(ctx, element); - 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)); - }); - - if (this.attribute('gradientTransform').hasValue()) { - // 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); - var group = new svg.Element.g(); - 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.children = [group]; - var c = document.createElement('canvas'); - c.width = rootView.width; - c.height = rootView.height; - var tempCtx = c.getContext('2d'); - tempCtx.fillStyle = g; - tempSvg.render(tempCtx); - return tempCtx.createPattern(c, 'no-repeat'); - } - - return g; - } - }]); - - return _class18; - }(svg.Element.ElementBase); // linear gradient element - - - svg.Element.linearGradient = /*#__PURE__*/function (_svg$Element$Gradient) { - _inherits(_class19, _svg$Element$Gradient); - - var _super18 = _createSuper(_class19); - - function _class19() { - _classCallCheck(this, _class19); - - return _super18.apply(this, arguments); - } - - _createClass(_class19, [{ - key: "getGradient", - value: function getGradient(ctx, element) { - var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; - var bb = useBB ? element.getBoundingBox() : null; - - if (!this.attribute('x1').hasValue() && !this.attribute('y1').hasValue() && !this.attribute('x2').hasValue() && !this.attribute('y2').hasValue()) { - this.attribute('x1', true).value = 0; - this.attribute('y1', true).value = 0; - this.attribute('x2', true).value = 1; - this.attribute('y2', true).value = 0; - } - - var x1 = useBB ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').toPixels('x'); - var y1 = useBB ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').toPixels('y'); - var x2 = useBB ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').toPixels('x'); - var y2 = useBB ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').toPixels('y'); - if (x1 === x2 && y1 === y2) return null; - return ctx.createLinearGradient(x1, y1, x2, y2); - } - }]); - - return _class19; - }(svg.Element.GradientBase); // radial gradient element - - - svg.Element.radialGradient = /*#__PURE__*/function (_svg$Element$Gradient2) { - _inherits(_class20, _svg$Element$Gradient2); - - var _super19 = _createSuper(_class20); - - function _class20() { - _classCallCheck(this, _class20); - - return _super19.apply(this, arguments); - } - - _createClass(_class20, [{ - key: "getGradient", - value: function getGradient(ctx, element) { - var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; - var bb = useBB ? element.getBoundingBox() : null; - if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%'; - if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%'; - if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%'; - var cx = useBB ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').toPixels('x'); - var cy = useBB ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').toPixels('y'); - var fx = cx; - var fy = cy; - - if (this.attribute('fx').hasValue()) { - fx = useBB ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').toPixels('x'); - } - - if (this.attribute('fy').hasValue()) { - fy = useBB ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').toPixels('y'); - } - - var r = useBB ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').toPixels(); - return ctx.createRadialGradient(fx, fy, 0, cx, cy, r); - } - }]); - - return _class20; - }(svg.Element.GradientBase); // gradient stop element - - - svg.Element.stop = /*#__PURE__*/function (_svg$Element$ElementB6) { - _inherits(_class21, _svg$Element$ElementB6); - - var _super20 = _createSuper(_class21); - - function _class21(node) { - var _this11; - - _classCallCheck(this, _class21); - - _this11 = _super20.call(this, node); - _this11.offset = _this11.attribute('offset').numValue(); - if (_this11.offset < 0) _this11.offset = 0; - if (_this11.offset > 1) _this11.offset = 1; - - var stopColor = _this11.style('stop-color'); - - if (_this11.style('stop-opacity').hasValue()) { - stopColor = stopColor.addOpacity(_this11.style('stop-opacity')); - } - - _this11.color = stopColor.value; - return _this11; - } - - return _class21; - }(svg.Element.ElementBase); // animation base element - - - svg.Element.AnimateBase = /*#__PURE__*/function (_svg$Element$ElementB7) { - _inherits(_class22, _svg$Element$ElementB7); - - var _super21 = _createSuper(_class22); - - function _class22(node) { - var _this12; - - _classCallCheck(this, _class22); - - _this12 = _super21.call(this, node); - svg.Animations.push(_assertThisInitialized(_this12)); - _this12.duration = 0.0; - _this12.begin = _this12.attribute('begin').toMilliseconds(); - _this12.maxDuration = _this12.begin + _this12.attribute('dur').toMilliseconds(); - _this12.initialValue = null; - _this12.initialUnits = ''; - _this12.removed = false; - _this12.from = _this12.attribute('from'); - _this12.to = _this12.attribute('to'); - _this12.values = _this12.attribute('values'); - if (_this12.values.hasValue()) _this12.values.value = _this12.values.value.split(';'); - return _this12; - } - - _createClass(_class22, [{ - key: "getProperty", - value: function getProperty() { - var attributeType = this.attribute('attributeType').value; - var attributeName = this.attribute('attributeName').value; - - if (attributeType === 'CSS') { - return this.parent.style(attributeName, true); - } - - return this.parent.attribute(attributeName, true); - } - }, { - key: "calcValue", - value: function calcValue() { - // OVERRIDE ME! - return ''; - } - }, { - key: "update", - value: function update(delta) { - // set initial value - if (isNullish(this.initialValue)) { - this.initialValue = this.getProperty().value; - this.initialUnits = this.getProperty().getUnits(); - } // if we're past the end time - - - if (this.duration > this.maxDuration) { - // loop for indefinitely repeating animations - if (this.attribute('repeatCount').value === 'indefinite' || this.attribute('repeatDur').value === 'indefinite') { - this.duration = 0.0; - } else if (this.attribute('fill').valueOrDefault('remove') === 'freeze' && !this.frozen) { - this.frozen = true; - this.parent.animationFrozen = true; - this.parent.animationFrozenValue = this.getProperty().value; - } else if (this.attribute('fill').valueOrDefault('remove') === 'remove' && !this.removed) { - this.removed = true; - this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue; - return true; - } - - return false; - } - - this.duration += delta; // if we're past the begin time - - var updated = false; - - if (this.begin < this.duration) { - var newValue = this.calcValue(); // tween - - if (this.attribute('type').hasValue()) { - // for transform, etc. - var type = this.attribute('type').value; - newValue = type + '(' + newValue + ')'; - } - - this.getProperty().value = newValue; - updated = true; - } - - return updated; - } // fraction of duration we've covered - - }, { - key: "progress", - value: function progress() { - var ret = { - progress: (this.duration - this.begin) / (this.maxDuration - this.begin) - }; - - if (this.values.hasValue()) { - var p = ret.progress * (this.values.value.length - 1); - var lb = Math.floor(p), - ub = Math.ceil(p); - ret.from = new svg.Property('from', Number.parseFloat(this.values.value[lb])); - ret.to = new svg.Property('to', Number.parseFloat(this.values.value[ub])); - ret.progress = (p - lb) / (ub - lb); - } else { - ret.from = this.from; - ret.to = this.to; - } - - return ret; - } - }]); - - return _class22; - }(svg.Element.ElementBase); // animate element - - - svg.Element.animate = /*#__PURE__*/function (_svg$Element$AnimateB) { - _inherits(_class23, _svg$Element$AnimateB); - - var _super22 = _createSuper(_class23); - - function _class23() { - _classCallCheck(this, _class23); - - return _super22.apply(this, arguments); - } - - _createClass(_class23, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); // tween value linearly - - var newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress; - return newValue + this.initialUnits; - } - }]); - - return _class23; - }(svg.Element.AnimateBase); // animate color element - - - svg.Element.animateColor = /*#__PURE__*/function (_svg$Element$AnimateB2) { - _inherits(_class24, _svg$Element$AnimateB2); - - var _super23 = _createSuper(_class24); - - function _class24() { - _classCallCheck(this, _class24); - - return _super23.apply(this, arguments); - } - - _createClass(_class24, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); - var from = new RGBColor(p.from.value); - var to = new RGBColor(p.to.value); - - if (from.ok && to.ok) { - // tween color linearly - 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(' + Number.parseInt(r) + ',' + Number.parseInt(g) + ',' + Number.parseInt(b) + ')'; - } - - return this.attribute('from').value; - } - }]); - - return _class24; - }(svg.Element.AnimateBase); // animate transform element - - - svg.Element.animateTransform = /*#__PURE__*/function (_svg$Element$animate) { - _inherits(_class25, _svg$Element$animate); - - var _super24 = _createSuper(_class25); - - function _class25() { - _classCallCheck(this, _class25); - - return _super24.apply(this, arguments); - } - - _createClass(_class25, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); // tween value linearly - - var from = svg.ToNumberArray(p.from.value); - var to = svg.ToNumberArray(p.to.value); - var newValue = ''; - from.forEach(function (fr, i) { - newValue += fr + (to[i] - fr) * p.progress + ' '; - }); - return newValue; - } - }]); - - return _class25; - }(svg.Element.animate); // font element - - - svg.Element.font = /*#__PURE__*/function (_svg$Element$ElementB8) { - _inherits(_class26, _svg$Element$ElementB8); - - var _super25 = _createSuper(_class26); - - function _class26(node) { - var _this13; - - _classCallCheck(this, _class26); - - _this13 = _super25.call(this, node); - _this13.horizAdvX = _this13.attribute('horiz-adv-x').numValue(); - _this13.isRTL = false; - _this13.isArabic = false; - _this13.fontFace = null; - _this13.missingGlyph = null; - _this13.glyphs = []; - - _this13.children.forEach(function (child) { - if (child.type === 'font-face') { - _this13.fontFace = child; - - if (child.style('font-family').hasValue()) { - svg.Definitions[child.style('font-family').value] = _assertThisInitialized(_this13); - } - } else if (child.type === 'missing-glyph') { - _this13.missingGlyph = child; - } else if (child.type === 'glyph') { - if (child.arabicForm !== '') { - _this13.isRTL = true; - _this13.isArabic = true; - - if (typeof _this13.glyphs[child.unicode] === 'undefined') { - _this13.glyphs[child.unicode] = []; - } - - _this13.glyphs[child.unicode][child.arabicForm] = child; - } else { - _this13.glyphs[child.unicode] = child; - } - } - }); - - return _this13; - } - - return _class26; - }(svg.Element.ElementBase); // font-face element - - - svg.Element.fontface = /*#__PURE__*/function (_svg$Element$ElementB9) { - _inherits(_class27, _svg$Element$ElementB9); - - var _super26 = _createSuper(_class27); - - function _class27(node) { - var _this14; - - _classCallCheck(this, _class27); - - _this14 = _super26.call(this, node); - _this14.ascent = _this14.attribute('ascent').value; - _this14.descent = _this14.attribute('descent').value; - _this14.unitsPerEm = _this14.attribute('units-per-em').numValue(); - return _this14; - } - - return _class27; - }(svg.Element.ElementBase); // missing-glyph element - - - svg.Element.missingglyph = /*#__PURE__*/function (_svg$Element$path) { - _inherits(_class28, _svg$Element$path); - - var _super27 = _createSuper(_class28); - - function _class28(node) { - var _this15; - - _classCallCheck(this, _class28); - - _this15 = _super27.call(this, node); - _this15.horizAdvX = 0; - return _this15; - } - - return _class28; - }(svg.Element.path); // glyph element - - - svg.Element.glyph = /*#__PURE__*/function (_svg$Element$path2) { - _inherits(_class29, _svg$Element$path2); - - var _super28 = _createSuper(_class29); - - function _class29(node) { - var _this16; - - _classCallCheck(this, _class29); - - _this16 = _super28.call(this, node); - _this16.horizAdvX = _this16.attribute('horiz-adv-x').numValue(); - _this16.unicode = _this16.attribute('unicode').value; - _this16.arabicForm = _this16.attribute('arabic-form').value; - return _this16; - } - - return _class29; - }(svg.Element.path); // text element - - - svg.Element.text = /*#__PURE__*/function (_svg$Element$Rendered3) { - _inherits(_class30, _svg$Element$Rendered3); - - var _super29 = _createSuper(_class30); - - function _class30(node) { - _classCallCheck(this, _class30); - - return _super29.call(this, node, true); - } - - _createClass(_class30, [{ - key: "setContext", - value: function setContext(ctx) { - _get(_getPrototypeOf(_class30.prototype), "setContext", this).call(this, ctx); - - var textBaseline = this.style('dominant-baseline').toTextBaseline(); - if (isNullish(textBaseline)) textBaseline = this.style('alignment-baseline').toTextBaseline(); - if (!isNullish(textBaseline)) ctx.textBaseline = textBaseline; - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); - return new svg.BoundingBox(x, y - fontSize, x + Math.floor(fontSize * 2.0 / 3.0) * this.children[0].getText().length, y); - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var _this17 = this; - - this.x = this.attribute('x').toPixels('x'); - this.y = this.attribute('y').toPixels('y'); - this.x += this.getAnchorDelta(ctx, this, 0); - this.children.forEach(function (child, i) { - _this17.renderChild(ctx, _this17, i); - }); - } - }, { - key: "getAnchorDelta", - value: function getAnchorDelta(ctx, parent, startI) { - var textAnchor = this.style('text-anchor').valueOrDefault('start'); - - if (textAnchor !== 'start') { - var width = 0; - - for (var i = startI; i < parent.children.length; i++) { - var child = parent.children[i]; - if (i > startI && child.attribute('x').hasValue()) break; // new group - - width += child.measureTextRecursive(ctx); - } - - return -1 * (textAnchor === 'end' ? width : width / 2.0); - } - - return 0; - } - }, { - key: "renderChild", - value: function renderChild(ctx, parent, i) { - var child = parent.children[i]; - - if (child.attribute('x').hasValue()) { - child.x = child.attribute('x').toPixels('x') + this.getAnchorDelta(ctx, parent, i); - if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x'); - } else { - if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x'); - if (child.attribute('dx').hasValue()) this.x += child.attribute('dx').toPixels('x'); - child.x = this.x; - } - - this.x = child.x + child.measureText(ctx); - - if (child.attribute('y').hasValue()) { - child.y = child.attribute('y').toPixels('y'); - if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y'); - } else { - if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y'); - if (child.attribute('dy').hasValue()) this.y += child.attribute('dy').toPixels('y'); - child.y = this.y; - } - - this.y = child.y; - child.render(ctx); - - for (var j = 0; j < child.children.length; j++) { - this.renderChild(ctx, child, j); - } - } - }]); - - return _class30; - }(svg.Element.RenderedElementBase); // text base - - - svg.Element.TextElementBase = /*#__PURE__*/function (_svg$Element$Rendered4) { - _inherits(_class31, _svg$Element$Rendered4); - - var _super30 = _createSuper(_class31); - - function _class31() { - _classCallCheck(this, _class31); - - return _super30.apply(this, arguments); - } - - _createClass(_class31, [{ - key: "getGlyph", - value: function getGlyph(font, text, i) { - var c = text[i]; - var glyph = null; - - if (font.isArabic) { - var arabicForm = 'isolated'; - if ((i === 0 || text[i - 1] === ' ') && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'terminal'; - if (i > 0 && text[i - 1] !== ' ' && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'medial'; - if (i > 0 && text[i - 1] !== ' ' && (i === text.length - 1 || text[i + 1] === ' ')) arabicForm = 'initial'; - - if (typeof font.glyphs[c] !== 'undefined') { - glyph = font.glyphs[c][arabicForm]; - if (isNullish(glyph) && font.glyphs[c].type === 'glyph') glyph = font.glyphs[c]; - } - } else { - glyph = font.glyphs[c]; - } - - if (isNullish(glyph)) glyph = font.missingGlyph; - return glyph; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var customFont = this.parent.style('font-family').getDefinition(); - - 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(); - if (customFont.isRTL) text = text.split('').reverse().join(''); - var dx = svg.ToNumberArray(this.parent.attribute('dx').value); - - for (var i = 0; i < text.length; i++) { - var glyph = this.getGlyph(customFont, text, i); - var scale = fontSize / customFont.fontFace.unitsPerEm; - ctx.translate(this.x, this.y); - ctx.scale(scale, -scale); - var lw = ctx.lineWidth; - ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize; - if (fontStyle === 'italic') ctx.transform(1, 0, 0.4, 1, 0, 0); - glyph.render(ctx); - if (fontStyle === 'italic') ctx.transform(1, 0, -0.4, 1, 0, 0); - ctx.lineWidth = lw; - ctx.scale(1 / scale, -1 / scale); - ctx.translate(-this.x, -this.y); - this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm; - - if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { - this.x += dx[i]; - } - } - - return; - } - - if (ctx.fillStyle !== '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); - if (ctx.strokeStyle !== '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y); - } - }, { - key: "getText", - value: function getText() {// OVERRIDE ME - } - }, { - key: "measureTextRecursive", - value: function measureTextRecursive(ctx) { - var width = this.measureText(ctx); - this.children.forEach(function (child) { - width += child.measureTextRecursive(ctx); - }); - return width; - } - }, { - key: "measureText", - value: function measureText(ctx) { - var customFont = this.parent.style('font-family').getDefinition(); - - 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(); - if (customFont.isRTL) text = text.split('').reverse().join(''); - var dx = svg.ToNumberArray(this.parent.attribute('dx').value); - - for (var i = 0; i < text.length; i++) { - var glyph = this.getGlyph(customFont, text, i); - measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm; - - if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { - measure += dx[i]; - } - } - - return measure; - } - - var textToMeasure = svg.compressSpaces(this.getText()); - if (!ctx.measureText) return textToMeasure.length * 10; - ctx.save(); - this.setContext(ctx); - - var _ctx$measureText = ctx.measureText(textToMeasure), - width = _ctx$measureText.width; - - ctx.restore(); - return width; - } - }]); - - return _class31; - }(svg.Element.RenderedElementBase); // tspan - - - svg.Element.tspan = /*#__PURE__*/function (_svg$Element$TextElem) { - _inherits(_class32, _svg$Element$TextElem); - - var _super31 = _createSuper(_class32); - - function _class32(node) { - var _this18; - - _classCallCheck(this, _class32); - - _this18 = _super31.call(this, node, true); - _this18.text = node.nodeValue || node.text || ''; - return _this18; - } - - _createClass(_class32, [{ - key: "getText", - value: function getText() { - return this.text; - } - }]); - - return _class32; - }(svg.Element.TextElementBase); // tref - - - svg.Element.tref = /*#__PURE__*/function (_svg$Element$TextElem2) { - _inherits(_class33, _svg$Element$TextElem2); - - var _super32 = _createSuper(_class33); - - function _class33() { - _classCallCheck(this, _class33); - - return _super32.apply(this, arguments); - } - - _createClass(_class33, [{ - key: "getText", - value: function getText() { - var element = this.getHrefAttribute().getDefinition(); - if (!isNullish(element)) return element.children[0].getText(); - return undefined; - } - }]); - - return _class33; - }(svg.Element.TextElementBase); // a element - - - svg.Element.a = /*#__PURE__*/function (_svg$Element$TextElem3) { - _inherits(_class34, _svg$Element$TextElem3); - - var _super33 = _createSuper(_class34); - - function _class34(node) { - var _this19; - - _classCallCheck(this, _class34); - - _this19 = _super33.call(this, node); - _this19.hasText = true; - - _toConsumableArray(node.childNodes).forEach(function (childNode) { - if (childNode.nodeType !== 3) { - _this19.hasText = false; - } - }); // this might contain text - - - _this19.text = _this19.hasText ? node.childNodes[0].nodeValue : ''; - return _this19; - } - - _createClass(_class34, [{ - key: "getText", - value: function getText() { - return this.text; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - if (this.hasText) { - // render as text element - _get(_getPrototypeOf(_class34.prototype), "renderChildren", this).call(this, ctx); - - var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); - svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y)); - } else { - // render as temporary group - var g = new svg.Element.g(); - g.children = this.children; - g.parent = this; - g.render(ctx); - } - } - }, { - key: "onclick", - value: function onclick() { - window.open(this.getHrefAttribute().value); - } - }, { - key: "onmousemove", - value: function onmousemove() { - svg.ctx.canvas.style.cursor = 'pointer'; - } - }]); - - return _class34; - }(svg.Element.TextElementBase); // image element - - - svg.Element.image = /*#__PURE__*/function (_svg$Element$Rendered5) { - _inherits(_class35, _svg$Element$Rendered5); - - var _super34 = _createSuper(_class35); - - function _class35(node) { - var _this20; - - _classCallCheck(this, _class35); - - _this20 = _super34.call(this, node); - - var href = _this20.getHrefAttribute().value; - - if (href === '') { - return _possibleConstructorReturn(_this20); - } - - _this20._isSvg = href.match(/\.svg$/); - svg.Images.push(_assertThisInitialized(_this20)); - _this20.loaded = false; - - if (!_this20._isSvg) { - _this20.img = document.createElement('img'); - - if (svg.opts.useCORS === true) { - _this20.img.crossOrigin = 'Anonymous'; - } - - _this20.img.addEventListener('load', function () { - _this20.loaded = true; - }); - - _this20.img.addEventListener('error', function () { - svg.log('ERROR: image "' + href + '" not found'); - _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 - }); - } - - return _this20; - } - - _createClass(_class35, [{ - key: "renderChildren", - value: function renderChildren(ctx) { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - if (width === 0 || height === 0) return; - ctx.save(); - - if (this._isSvg) { - ctx.drawSvg(this.img, x, y, width, height); - } else { - ctx.translate(x, y); - svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); - ctx.drawImage(this.img, 0, 0); - } - - ctx.restore(); - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - return new svg.BoundingBox(x, y, x + width, y + height); - } - }]); - - return _class35; - }(svg.Element.RenderedElementBase); // group element - - - svg.Element.g = /*#__PURE__*/function (_svg$Element$Rendered6) { - _inherits(_class36, _svg$Element$Rendered6); - - var _super35 = _createSuper(_class36); - - function _class36() { - _classCallCheck(this, _class36); - - return _super35.apply(this, arguments); - } - - _createClass(_class36, [{ - key: "getBoundingBox", - value: function getBoundingBox() { - var bb = new svg.BoundingBox(); - this.children.forEach(function (child) { - bb.addBoundingBox(child.getBoundingBox()); - }); - return bb; - } - }]); - - return _class36; - }(svg.Element.RenderedElementBase); // symbol element - - - svg.Element.symbol = /*#__PURE__*/function (_svg$Element$Rendered7) { - _inherits(_class37, _svg$Element$Rendered7); - - var _super36 = _createSuper(_class37); - - function _class37() { - _classCallCheck(this, _class37); - - return _super36.apply(this, arguments); - } - - _createClass(_class37, [{ - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class37; - }(svg.Element.RenderedElementBase); // style element - - - svg.Element.style = /*#__PURE__*/function (_svg$Element$ElementB10) { - _inherits(_class38, _svg$Element$ElementB10); - - var _super37 = _createSuper(_class38); - - function _class38(node) { - var _this21; - - _classCallCheck(this, _class38); - - _this21 = _super37.call(this, node); // text, or spaces then CDATA - - var css = ''; - - _toConsumableArray(node.childNodes).forEach(function (_ref11) { - var nodeValue = _ref11.nodeValue; - css += nodeValue; - }); // remove comments - - - css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(^\s*\/\/.*)/gm, ''); // eslint-disable-line unicorn/no-unsafe-regex - // replace whitespace - - css = svg.compressSpaces(css); - var cssDefs = css.split('}'); - cssDefs.forEach(function (cssDef) { - if (svg.trim(cssDef) !== '') { - var _cssDef$split = cssDef.split('{'), - _cssDef$split2 = _slicedToArray(_cssDef$split, 2), - cssClasses = _cssDef$split2[0], - cssProps = _cssDef$split2[1]; - - cssClasses = cssClasses.split(','); - cssProps = cssProps.split(';'); - cssClasses.forEach(function (cssClass) { - cssClass = svg.trim(cssClass); - - if (cssClass !== '') { - var props = {}; - cssProps.forEach(function (cssProp) { - var prop = cssProp.indexOf(':'); - var name = cssProp.substr(0, prop); - var value = cssProp.substr(prop + 1, cssProp.length - prop); - - if (!isNullish(name) && !isNullish(value)) { - props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value)); - } - }); - svg.Styles[cssClass] = props; - - if (cssClass === '@font-face') { - var fontFamily = props['font-family'].value.replace(/"/g, ''); - var srcs = props.src.value.split(','); - srcs.forEach(function (src) { - if (src.includes('format("svg")')) { - var urlStart = src.indexOf('url'); - var urlEnd = src.indexOf(')', urlStart); - var url = src.substr(urlStart + 5, urlEnd - urlStart - 6); // Can this ajax safely be converted to async? - - var doc = svg.parseXml(svg.ajax(url)); - var fonts = doc.getElementsByTagName('font'); - - _toConsumableArray(fonts).forEach(function (font) { - font = svg.CreateElement(font); - svg.Definitions[fontFamily] = font; - }); - } - }); - } - } - }); - } - }); - return _this21; - } - - return _class38; - }(svg.Element.ElementBase); // use element - - - svg.Element.use = /*#__PURE__*/function (_svg$Element$Rendered8) { - _inherits(_class39, _svg$Element$Rendered8); - - var _super38 = _createSuper(_class39); - - function _class39(node) { - var _this22; - - _classCallCheck(this, _class39); - - _this22 = _super38.call(this, node); - _this22._el = _this22.getHrefAttribute().getDefinition(); - return _this22; - } - - _createClass(_class39, [{ - key: "setContext", - value: function setContext(ctx) { - _get(_getPrototypeOf(_class39.prototype), "setContext", this).call(this, ctx); - - if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0); - if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y')); - } - }, { - key: "path", - value: function path(ctx) { - var element = this._el; - if (!isNullish(element)) element.path(ctx); - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var element = this._el; - if (!isNullish(element)) return element.getBoundingBox(); - return undefined; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var element = this._el; - - 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.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); - } - } - - var oldParent = tempSvg.parent; - tempSvg.parent = null; - tempSvg.render(ctx); - tempSvg.parent = oldParent; - } - } - }]); - - return _class39; - }(svg.Element.RenderedElementBase); // mask element - - - svg.Element.mask = /*#__PURE__*/function (_svg$Element$ElementB11) { - _inherits(_class40, _svg$Element$ElementB11); - - var _super39 = _createSuper(_class40); - - function _class40() { - _classCallCheck(this, _class40); - - return _super39.apply(this, arguments); - } - - _createClass(_class40, [{ - key: "apply", - value: function apply(ctx, element) { - // render as temp svg - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - - if (width === 0 && height === 0) { - var bb = new svg.BoundingBox(); - this.children.forEach(function (child) { - bb.addBoundingBox(child.getBoundingBox()); - }); - x = Math.floor(bb.x1); - y = Math.floor(bb.y1); - width = Math.floor(bb.width()); - height = Math.floor(bb.height()); - } // temporarily remove mask to avoid recursion - - - var mask = element.attribute('mask').value; - element.attribute('mask').value = ''; - var cMask = document.createElement('canvas'); - cMask.width = x + width; - cMask.height = y + height; - var maskCtx = cMask.getContext('2d'); - this.renderChildren(maskCtx); - var c = document.createElement('canvas'); - c.width = x + width; - c.height = y + height; - var tempCtx = c.getContext('2d'); - element.render(tempCtx); - tempCtx.globalCompositeOperation = 'destination-in'; - tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat'); - tempCtx.fillRect(0, 0, x + width, y + height); - ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat'); - ctx.fillRect(0, 0, x + width, y + height); // reassign mask - - element.attribute('mask').value = mask; - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class40; - }(svg.Element.ElementBase); // clip element - - - svg.Element.clipPath = /*#__PURE__*/function (_svg$Element$ElementB12) { - _inherits(_class41, _svg$Element$ElementB12); - - var _super40 = _createSuper(_class41); - - function _class41() { - _classCallCheck(this, _class41); - - return _super40.apply(this, arguments); - } - - _createClass(_class41, [{ - key: "apply", - value: function apply(ctx) { - this.children.forEach(function (child) { - if (typeof child.path !== 'undefined') { - var transform = null; - - if (child.attribute('transform').hasValue()) { - transform = new svg.Transform(child.attribute('transform').value); - transform.apply(ctx); - } - - child.path(ctx); - ctx.clip(); - - if (transform) { - transform.unapply(ctx); - } - } - }); - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class41; - }(svg.Element.ElementBase); // filters - - - svg.Element.filter = /*#__PURE__*/function (_svg$Element$ElementB13) { - _inherits(_class42, _svg$Element$ElementB13); - - var _super41 = _createSuper(_class42); - - function _class42() { - _classCallCheck(this, _class42); - - return _super41.apply(this, arguments); - } - - _createClass(_class42, [{ - key: "apply", - value: function apply(ctx, element) { - // render as temp svg - var bb = element.getBoundingBox(); - var x = Math.floor(bb.x1); - var y = Math.floor(bb.y1); - var width = Math.floor(bb.width()); - var height = Math.floor(bb.height()); // temporarily remove filter to avoid recursion - - var filter = element.style('filter').value; - element.style('filter').value = ''; - var px = 0, - py = 0; - this.children.forEach(function (child) { - var efd = child.extraFilterDistance || 0; - px = Math.max(px, efd); - py = Math.max(py, efd); - }); - var c = document.createElement('canvas'); - c.width = width + 2 * px; - c.height = height + 2 * py; - var tempCtx = c.getContext('2d'); - tempCtx.translate(-x + px, -y + py); - element.render(tempCtx); // apply filters - - this.children.forEach(function (child) { - child.apply(tempCtx, 0, 0, width + 2 * px, height + 2 * py); - }); // render on me - - ctx.drawImage(c, 0, 0, width + 2 * px, height + 2 * py, x - px, y - py, width + 2 * px, height + 2 * py); // reassign filter - - element.style('filter', true).value = filter; - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class42; - }(svg.Element.ElementBase); - - svg.Element.feMorphology = /*#__PURE__*/function (_svg$Element$ElementB14) { - _inherits(_class43, _svg$Element$ElementB14); - - var _super42 = _createSuper(_class43); - - function _class43() { - _classCallCheck(this, _class43); - - return _super42.apply(this, arguments); - } - - _createClass(_class43, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) {// TODO: implement - } - }]); - - return _class43; - }(svg.Element.ElementBase); - - svg.Element.feComposite = /*#__PURE__*/function (_svg$Element$ElementB15) { - _inherits(_class44, _svg$Element$ElementB15); - - var _super43 = _createSuper(_class44); - - function _class44() { - _classCallCheck(this, _class44); - - return _super43.apply(this, arguments); - } - - _createClass(_class44, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) {// TODO: implement - } - }]); - - return _class44; - }(svg.Element.ElementBase); - /** - * @param {Uint8ClampedArray} img - * @param {Integer} x - * @param {Integer} y - * @param {Float} width - * @param {Float} height - * @param {Integer} rgba - * @returns {Integer} - */ - - - 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 {void} - */ - - - function imSet(img, x, y, width, height, rgba, val) { - img[y * width * 4 + x * 4 + rgba] = val; - } - - svg.Element.feColorMatrix = /*#__PURE__*/function (_svg$Element$ElementB16) { - _inherits(_class45, _svg$Element$ElementB16); - - var _super44 = _createSuper(_class45); - - function _class45(node) { - var _this23; - - _classCallCheck(this, _class45); - - _this23 = _super44.call(this, node); - var matrix = svg.ToNumberArray(_this23.attribute('values').value); - - 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; - } - - case 'hueRotate': - { - 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; - }; - - 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]; - break; - } - - _this23.matrix = matrix; - - _this23._m = function (i, v) { - var mi = matrix[i]; - return mi * (mi < 0 ? v - 255 : v); - }; - - return _this23; - } - - _createClass(_class45, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) { - var m = this._m; // assuming x==0 && y==0 for now - - var srcData = ctx.getImageData(0, 0, width, height); - - 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)); - } - } - - ctx.clearRect(0, 0, width, height); - ctx.putImageData(srcData, 0, 0); - } - }]); - - return _class45; - }(svg.Element.ElementBase); - - svg.Element.feGaussianBlur = /*#__PURE__*/function (_svg$Element$ElementB17) { - _inherits(_class46, _svg$Element$ElementB17); - - var _super45 = _createSuper(_class46); - - function _class46(node) { - var _this24; - - _classCallCheck(this, _class46); - - _this24 = _super45.call(this, node); - _this24.blurRadius = Math.floor(_this24.attribute('stdDeviation').numValue()); - _this24.extraFilterDistance = _this24.blurRadius; - return _this24; - } - - _createClass(_class46, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) { - // 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); - processCanvasRGBA(ctx.canvas, x, y, width, height, this.blurRadius); - ctx.canvas.remove(); - } - }]); - - return _class46; - }(svg.Element.ElementBase); // title element, do nothing - - - svg.Element.title = /*#__PURE__*/function (_svg$Element$ElementB18) { - _inherits(_class47, _svg$Element$ElementB18); - - var _super46 = _createSuper(_class47); - - function _class47(node) { - _classCallCheck(this, _class47); - - return _super46.call(this); - } - - return _class47; - }(svg.Element.ElementBase); // desc element, do nothing - - - svg.Element.desc = /*#__PURE__*/function (_svg$Element$ElementB19) { - _inherits(_class48, _svg$Element$ElementB19); - - var _super47 = _createSuper(_class48); - - function _class48(node) { - _classCallCheck(this, _class48); - - return _super47.call(this); - } - - return _class48; - }(svg.Element.ElementBase); - - svg.Element.MISSING = /*#__PURE__*/function (_svg$Element$ElementB20) { - _inherits(_class49, _svg$Element$ElementB20); - - var _super48 = _createSuper(_class49); - - function _class49(node) { - var _this25; - - _classCallCheck(this, _class49); - - _this25 = _super48.call(this); - svg.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); - return _this25; - } - - return _class49; - }(svg.Element.ElementBase); // element factory - - - svg.CreateElement = function (node) { - var className = node.nodeName.replace(/^[^:]+:/, '') // remove namespace - .replace(/-/g, ''); // remove dashes - - var e; - - if (typeof svg.Element[className] !== 'undefined') { - e = new svg.Element[className](node); - } else { - e = new svg.Element.MISSING(node); - } - - e.type = node.nodeName; - return e; - }; // load from url - - - svg.load = /*#__PURE__*/function () { - var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(ctx, url) { - var dom; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return svg.ajax(url, true); - - case 2: - dom = _context.sent; - return _context.abrupt("return", svg.loadXml(ctx, dom)); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function (_x2, _x3) { - return _ref12.apply(this, arguments); - }; - }(); // load from xml - - - svg.loadXml = function (ctx, xml) { - return svg.loadXmlDoc(ctx, svg.parseXml(xml)); - }; - - svg.loadXmlDoc = function (ctx, dom) { - var res; - svg.init(ctx); - - var mapXY = function mapXY(p) { - var e = ctx.canvas; - - while (e) { - p.x -= e.offsetLeft; - p.y -= e.offsetTop; - e = e.offsetParent; - } - - if (window.scrollX) p.x += window.scrollX; - if (window.scrollY) p.y += window.scrollY; - return p; - }; // bind mouse - - - if (svg.opts.ignoreMouse !== true) { - ctx.canvas.addEventListener('click', function (e) { - 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, - y = _mapXY.y; - - svg.Mouse.onclick(x, y); - }); - ctx.canvas.addEventListener('mousemove', function (e) { - 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, - y = _mapXY2.y; - - svg.Mouse.onmousemove(x, y); - }); - } - - var e = svg.CreateElement(dom.documentElement); - e.root = true; // render loop - - var isFirstRender = true; - - var draw = function draw(resolve) { - svg.ViewPort.Clear(); - - if (ctx.canvas.parentNode) { - svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight); - } - - if (svg.opts.ignoreDimensions !== true) { - // set canvas size - if (e.style('width').hasValue()) { - ctx.canvas.width = e.style('width').toPixels('x'); - ctx.canvas.style.width = ctx.canvas.width + 'px'; - } - - if (e.style('height').hasValue()) { - ctx.canvas.height = e.style('height').toPixels('y'); - ctx.canvas.style.height = ctx.canvas.height + 'px'; - } - } - - var cWidth = ctx.canvas.clientWidth || ctx.canvas.width; - var cHeight = ctx.canvas.clientHeight || ctx.canvas.height; - - if (svg.opts.ignoreDimensions === true && e.style('width').hasValue() && e.style('height').hasValue()) { - cWidth = e.style('width').toPixels('x'); - cHeight = e.style('height').toPixels('y'); - } - - svg.ViewPort.SetCurrent(cWidth, cHeight); - - if (!isNullish(svg.opts.offsetX)) { - e.attribute('x', true).value = svg.opts.offsetX; - } - - if (!isNullish(svg.opts.offsetY)) { - e.attribute('y', true).value = svg.opts.offsetY; - } - - if (!isNullish(svg.opts.scaleWidth) || !isNullish(svg.opts.scaleHeight)) { - var viewBox = svg.ToNumberArray(e.attribute('viewBox').value); - var xRatio = null, - yRatio = 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])) { - xRatio = viewBox[2] / svg.opts.scaleWidth; - } - } - - if (!isNullish(svg.opts.scaleHeight)) { - if (e.attribute('height').hasValue()) { - yRatio = e.attribute('height').toPixels('y') / svg.opts.scaleHeight; - } else if (!isNaN(viewBox[3])) { - yRatio = viewBox[3] / svg.opts.scaleHeight; - } - } - - if (isNullish(xRatio)) { - xRatio = yRatio; - } - - if (isNullish(yRatio)) { - yRatio = xRatio; - } - - e.attribute('width', true).value = svg.opts.scaleWidth; - e.attribute('height', true).value = svg.opts.scaleHeight; - e.attribute('viewBox', true).value = '0 0 ' + cWidth * xRatio + ' ' + cHeight * yRatio; - e.attribute('preserveAspectRatio', true).value = 'none'; - } // clear and render - - - if (svg.opts.ignoreClear !== true) { - ctx.clearRect(0, 0, cWidth, cHeight); - } - - e.render(ctx); - - if (isFirstRender) { - isFirstRender = false; - resolve(dom); - } - }; - - var waitingForImages = true; - svg.intervalID = setInterval(function () { - var needUpdate = false; - - if (waitingForImages && svg.ImagesLoaded()) { - waitingForImages = false; - needUpdate = true; - } // need update from mouse events? - - - if (svg.opts.ignoreMouse !== true) { - needUpdate = needUpdate || svg.Mouse.hasEvents(); - } // need update from animations? - - - if (svg.opts.ignoreAnimation !== true) { - svg.Animations.forEach(function (animation) { - var needAnimationUpdate = animation.update(1000 / svg.FRAMERATE); - needUpdate = needUpdate || needAnimationUpdate; - }); - } // need update from redraw? - - - if (typeof svg.opts.forceRedraw === 'function') { - if (svg.opts.forceRedraw() === true) { - needUpdate = true; - } - } // render if needed - - - if (needUpdate) { - draw(res); - svg.Mouse.runEvents(); // run and clear our events - } - }, 1000 / svg.FRAMERATE); // Todo: Replace with an image loading Promise utility? - // eslint-disable-next-line promise/avoid-new - - return new Promise(function (resolve, reject) { - if (svg.ImagesLoaded()) { - waitingForImages = false; - draw(resolve); - return; - } - - res = resolve; - }); - }; - - svg.stop = function () { - if (svg.intervalID) { - clearInterval(svg.intervalID); - } - }; - - svg.Mouse = { - events: [], - hasEvents: function hasEvents() { - return this.events.length !== 0; - }, - onclick: function onclick(x, y) { - this.events.push({ - type: 'onclick', - x: x, - y: y, - run: function run(e) { - if (e.onclick) e.onclick(); - } - }); - }, - onmousemove: function onmousemove(x, y) { - this.events.push({ - type: 'onmousemove', - x: x, - y: y, - run: function run(e) { - if (e.onmousemove) e.onmousemove(); - } - }); - }, - eventElements: [], - checkPath: function checkPath(element, ctx) { - var _this26 = this; - - this.events.forEach(function (_ref13, i) { - var x = _ref13.x, - y = _ref13.y; - - if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { - _this26.eventElements[i] = element; - } - }); - }, - checkBoundingBox: function checkBoundingBox(element, bb) { - var _this27 = this; - - this.events.forEach(function (_ref14, i) { - var x = _ref14.x, - y = _ref14.y; - - if (bb.isPointInBox(x, y)) { - _this27.eventElements[i] = element; - } - }); - }, - runEvents: function runEvents() { - var _this28 = this; - - svg.ctx.canvas.style.cursor = ''; - this.events.forEach(function (e, i) { - var element = _this28.eventElements[i]; - - while (element) { - e.run(element); - element = element.parent; - } - }); // done running, clear - - this.events = []; - this.eventElements = []; - } - }; - return svg; - } - - if (typeof CanvasRenderingContext2D !== 'undefined') { - CanvasRenderingContext2D.prototype.drawSvg = function (s, dx, dy, dw, dh) { - canvg(this.canvas, s, { - ignoreMouse: true, - ignoreAnimation: true, - ignoreDimensions: true, - ignoreClear: true, - offsetX: dx, - offsetY: dy, - scaleWidth: dw, - scaleHeight: dh - }); - }; - } - - var extServer_moinsave = { - name: 'server_moinsave', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var $, encode64, importLocale, strings, svgEditor, svgCanvas, saveSvgAction; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - $ = _ref.$, encode64 = _ref.encode64, importLocale = _ref.importLocale; - _context2.next = 3; - return importLocale(); - - case 3: - strings = _context2.sent; - svgEditor = _this; - svgCanvas = svgEditor.canvas; - saveSvgAction = '/+modify'; // Create upload target (hidden iframe) - // Hiding by size instead of display to avoid FF console errors - // with `getBBox` in browser.js `supportsPathBBox_`) - - /* const target = */ - - $("\d{1,3})\)$/, - example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], - 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 Number.parseInt(b); - }); - } - }, { - re: /^(\w{2})(\w{2})(\w{2})$/, - // re: /^(?\w{2})(?\w{2})(?\w{2})$/, - example: ['#00ff00', '336699'], - 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 Number.parseInt(b, 16); - }); - } - }, { - re: /^(\w)(\w)(\w)$/, - // re: /^(?\w{1})(?\w{1})(?\w{1})$/, - example: ['#fb0', 'f0f'], - 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 Number.parseInt(b + b, 16); - }); - } - }]; - /** - * A class to parse color values. - */ - - var RGBColor = /*#__PURE__*/function () { - /** - * @param {string} colorString - */ - function RGBColor(colorString) { - var _this = this; - - _classCallCheck(this, RGBColor); - - this.ok = false; // strip any leading # - - if (colorString.charAt(0) === '#') { - // remove # if any - colorString = colorString.substr(1, 6); - } - - colorString = colorString.replace(/ /g, ''); - colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches - // and overwrite the input - - if (colorString in simpleColors) { - colorString = simpleColors[colorString]; - } // end of simple type-in colors - // search through the definitions to find a match - - - colorDefs.forEach(function (_ref) { - var re = _ref.re, - processor = _ref.process; - var bits = re.exec(colorString); - - if (bits) { - var _processor = processor.apply(void 0, _toConsumableArray(bits)), - _processor2 = _slicedToArray(_processor, 3), - r = _processor2[0], - g = _processor2[1], - b = _processor2[2]; - - Object.assign(_this, { - r: r, - g: g, - b: b - }); - _this.ok = true; - } - }); // validate/cleanup values - - this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r; - this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g; - this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b; - } // some getters - - /** - * @returns {string} - */ - - - _createClass(RGBColor, [{ - key: "toRGB", - value: function toRGB() { - return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; - } - /** - * @returns {string} - */ - - }, { - key: "toHex", - value: function toHex() { - var r = this.r.toString(16); - var g = this.g.toString(16); - var b = this.b.toString(16); - - if (r.length === 1) { - r = '0' + r; - } - - if (g.length === 1) { - g = '0' + g; - } - - if (b.length === 1) { - b = '0' + b; - } - - return '#' + r + g + b; - } - /** - * Offers a bulleted list of help. - * @returns {HTMLUListElement} - */ - - }], [{ - key: "getHelpXML", - value: function getHelpXML() { - var examples = [].concat(_toConsumableArray(colorDefs.flatMap(function (_ref2) { - var example = _ref2.example; - return example; - })), _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 = "\n margin: 3px;\n border: 1px solid black;\n background: ".concat(listColor.toHex(), ";\n color: ").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; - } - }]); - - return RGBColor; - }(); - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function _classCallCheck$1(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - /* eslint-disable no-bitwise, unicorn/prefer-query-selector */ - - /** - * 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: - * {@link https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript}. - * - * @module StackBlur - * @author Mario Klingemann - * 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. - */ - - /* eslint-disable max-len */ - - - 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]; - /** - * @param {string|HTMLCanvasElement} canvas - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @throws {Error|TypeError} - * @returns {ImageData} See {@link https://html.spec.whatwg.org/multipage/canvas.html#imagedata} - */ - - - function getImageDataFromCanvas(canvas, topX, topY, width, height) { - if (typeof canvas === 'string') { - canvas = document.getElementById(canvas); - } - - if (!canvas || _typeof(canvas) !== 'object' || !('getContext' in canvas)) { - throw new TypeError('Expecting canvas with `getContext` method ' + 'in processCanvasRGB(A) calls!'); - } - - var context = canvas.getContext('2d'); - - try { - return context.getImageData(topX, topY, width, height); - } catch (e) { - throw new Error('unable to access image data: ' + e); - } - } - /** - * @param {HTMLCanvasElement} canvas - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @param {Float} radius - * @returns {undefined} - */ - - - function processCanvasRGBA(canvas, topX, topY, width, height, radius) { - if (isNaN(radius) || radius < 1) { - return; - } - - radius |= 0; - var imageData = getImageDataFromCanvas(canvas, topX, topY, width, height); - imageData = processImageDataRGBA(imageData, topX, topY, width, height, radius); - canvas.getContext('2d').putImageData(imageData, topX, topY); - } - /** - * @param {ImageData} imageData - * @param {Integer} topX - * @param {Integer} topY - * @param {Integer} width - * @param {Integer} height - * @param {Float} radius - * @returns {ImageData} - */ - - - function processImageDataRGBA(imageData, topX, topY, width, height, radius) { - var pixels = imageData.data; - var x, y, i, p, yp, yi, yw, rSum, gSum, bSum, aSum, rOutSum, gOutSum, bOutSum, aOutSum, rInSum, gInSum, bInSum, aInSum, pr, pg, pb, pa, rbs; - var div = 2 * radius + 1; // const w4 = width << 2; - - var widthMinus1 = width - 1; - var heightMinus1 = height - 1; - var radiusPlus1 = radius + 1; - var sumFactor = radiusPlus1 * (radiusPlus1 + 1) / 2; - var stackStart = new BlurStack(); - var stack = stackStart; - var stackEnd; - - for (i = 1; i < div; i++) { - stack = stack.next = new BlurStack(); - - if (i === radiusPlus1) { - stackEnd = stack; - } - } - - stack.next = stackStart; - var stackIn = null; - var stackOut = null; - yw = yi = 0; - var mulSum = mulTable[radius]; - var shgSum = shgTable[radius]; - - for (y = 0; y < height; y++) { - rInSum = gInSum = bInSum = aInSum = rSum = gSum = bSum = aSum = 0; - rOutSum = radiusPlus1 * (pr = pixels[yi]); - gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); - bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); - aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); - rSum += sumFactor * pr; - gSum += sumFactor * pg; - bSum += sumFactor * pb; - aSum += sumFactor * pa; - stack = stackStart; - - for (i = 0; i < radiusPlus1; i++) { - stack.r = pr; - stack.g = pg; - stack.b = pb; - stack.a = pa; - stack = stack.next; - } - - for (i = 1; i < radiusPlus1; i++) { - p = yi + ((widthMinus1 < i ? widthMinus1 : i) << 2); - rSum += (stack.r = pr = pixels[p]) * (rbs = radiusPlus1 - i); - gSum += (stack.g = pg = pixels[p + 1]) * rbs; - bSum += (stack.b = pb = pixels[p + 2]) * rbs; - aSum += (stack.a = pa = pixels[p + 3]) * rbs; - rInSum += pr; - gInSum += pg; - bInSum += pb; - aInSum += pa; - stack = stack.next; - } - - stackIn = stackStart; - stackOut = stackEnd; - - for (x = 0; x < width; x++) { - pixels[yi + 3] = pa = aSum * mulSum >> shgSum; - - if (pa !== 0) { - pa = 255 / pa; - pixels[yi] = (rSum * mulSum >> shgSum) * pa; - pixels[yi + 1] = (gSum * mulSum >> shgSum) * pa; - pixels[yi + 2] = (bSum * mulSum >> shgSum) * pa; - } else { - pixels[yi] = pixels[yi + 1] = pixels[yi + 2] = 0; - } - - rSum -= rOutSum; - gSum -= gOutSum; - bSum -= bOutSum; - aSum -= aOutSum; - rOutSum -= stackIn.r; - gOutSum -= stackIn.g; - bOutSum -= stackIn.b; - aOutSum -= stackIn.a; - p = yw + ((p = x + radius + 1) < widthMinus1 ? p : widthMinus1) << 2; - rInSum += stackIn.r = pixels[p]; - gInSum += stackIn.g = pixels[p + 1]; - bInSum += stackIn.b = pixels[p + 2]; - aInSum += stackIn.a = pixels[p + 3]; - rSum += rInSum; - gSum += gInSum; - bSum += bInSum; - aSum += aInSum; - stackIn = stackIn.next; - rOutSum += pr = stackOut.r; - gOutSum += pg = stackOut.g; - bOutSum += pb = stackOut.b; - aOutSum += pa = stackOut.a; - rInSum -= pr; - gInSum -= pg; - bInSum -= pb; - aInSum -= pa; - stackOut = stackOut.next; - yi += 4; - } - - yw += width; - } - - for (x = 0; x < width; x++) { - gInSum = bInSum = aInSum = rInSum = gSum = bSum = aSum = rSum = 0; - yi = x << 2; - rOutSum = radiusPlus1 * (pr = pixels[yi]); - gOutSum = radiusPlus1 * (pg = pixels[yi + 1]); - bOutSum = radiusPlus1 * (pb = pixels[yi + 2]); - aOutSum = radiusPlus1 * (pa = pixels[yi + 3]); - rSum += sumFactor * pr; - gSum += sumFactor * pg; - bSum += sumFactor * pb; - aSum += sumFactor * pa; - stack = stackStart; - - for (i = 0; i < radiusPlus1; i++) { - stack.r = pr; - stack.g = pg; - stack.b = pb; - stack.a = pa; - stack = stack.next; - } - - yp = width; - - for (i = 1; i <= radius; i++) { - yi = yp + x << 2; - rSum += (stack.r = pr = pixels[yi]) * (rbs = radiusPlus1 - i); - gSum += (stack.g = pg = pixels[yi + 1]) * rbs; - bSum += (stack.b = pb = pixels[yi + 2]) * rbs; - aSum += (stack.a = pa = pixels[yi + 3]) * rbs; - rInSum += pr; - gInSum += pg; - bInSum += pb; - aInSum += pa; - stack = stack.next; - - if (i < heightMinus1) { - yp += width; - } - } - - yi = x; - stackIn = stackStart; - stackOut = stackEnd; - - for (y = 0; y < height; y++) { - p = yi << 2; - pixels[p + 3] = pa = aSum * mulSum >> shgSum; - - if (pa > 0) { - pa = 255 / pa; - pixels[p] = (rSum * mulSum >> shgSum) * pa; - pixels[p + 1] = (gSum * mulSum >> shgSum) * pa; - pixels[p + 2] = (bSum * mulSum >> shgSum) * pa; - } else { - pixels[p] = pixels[p + 1] = pixels[p + 2] = 0; - } - - rSum -= rOutSum; - gSum -= gOutSum; - bSum -= bOutSum; - aSum -= aOutSum; - rOutSum -= stackIn.r; - gOutSum -= stackIn.g; - bOutSum -= stackIn.b; - aOutSum -= stackIn.a; - p = x + ((p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1) * width << 2; - rSum += rInSum += stackIn.r = pixels[p]; - gSum += gInSum += stackIn.g = pixels[p + 1]; - bSum += bInSum += stackIn.b = pixels[p + 2]; - aSum += aInSum += stackIn.a = pixels[p + 3]; - stackIn = stackIn.next; - rOutSum += pr = stackOut.r; - gOutSum += pg = stackOut.g; - bOutSum += pb = stackOut.b; - aOutSum += pa = stackOut.a; - rInSum -= pr; - gInSum -= pg; - bInSum -= pb; - aInSum -= pa; - stackOut = stackOut.next; - yi += width; - } - } - - return imageData; - } - /** - * - */ - - - var BlurStack = - /** - * Set properties. - */ - function BlurStack() { - _classCallCheck$1(this, BlurStack); - - this.r = 0; - this.g = 0; - this.b = 0; - this.a = 0; - this.next = null; - }; - - /** - * 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} - */ - - /** - * @typedef {PlainObject} module:canvg.CanvgOptions - * @property {boolean} ignoreMouse true => ignore mouse events - * @property {boolean} ignoreAnimation true => ignore animations - * @property {boolean} ignoreDimensions true => does not try to resize canvas - * @property {boolean} ignoreClear true => does not clear canvas - * @property {Integer} offsetX int => draws at a x offset - * @property {Integer} offsetY int => draws at a y offset - * @property {Integer} scaleWidth int => scales horizontally to width - * @property {Integer} scaleHeight int => scales vertically to height - * @property {module:canvg.ForceRedraw} forceRedraw function => will call the function on every frame, if it returns true, will redraw - * @property {boolean} log Adds log function - * @property {boolean} useCORS Whether to set CORS `crossOrigin` for the image to `Anonymous` - */ - - /** - * If called with no arguments, it will replace all `` elements on the page - * 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 {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 (isNullish(target) && isNullish(s) && isNullish(opts)) { - var svgTags = document.querySelectorAll('svg'); - return Promise.all(_toConsumableArray(svgTags).map(function (svgTag) { - var c = document.createElement('canvas'); - c.width = svgTag.clientWidth; - c.height = svgTag.clientHeight; - svgTag.before(c); - svgTag.remove(); - var div = document.createElement('div'); - div.append(svgTag); - return canvg(c, div.innerHTML); - })); - } - - if (typeof target === 'string') { - target = document.getElementById(target); - } // store class on canvas - - - 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')) { - target.svg = svg; - } - - var ctx = target.getContext('2d'); - - if (typeof s.documentElement !== 'undefined') { - // load from xml doc - return svg.loadXmlDoc(ctx, s); - } - - if (s.substr(0, 1) === '<') { - // load from xml string - return svg.loadXml(ctx, s); - } // load from url - - - return svg.load(ctx, s); - }; - /* eslint-disable jsdoc/check-types */ - - /** - * @param {module:canvg.CanvgOptions} opts - * @returns {object} - * @todo Flesh out exactly what object is returned here (after updating to latest and reincluding our changes here and those of StackBlur) - */ - - function build(opts) { - /* eslint-enable jsdoc/check-types */ - var svg = { - opts: opts - }; - svg.FRAMERATE = 30; - svg.MAX_VIRTUAL_PIXELS = 30000; - - 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 - - - svg.init = function (ctx) { - var uniqueId = 0; - - svg.UniqueId = function () { - uniqueId++; - return 'canvg' + uniqueId; - }; - - svg.Definitions = {}; - svg.Styles = {}; - svg.Animations = []; - svg.Images = []; - svg.ctx = ctx; - svg.ViewPort = { - viewPorts: [], - Clear: function Clear() { - this.viewPorts = []; - }, - SetCurrent: function SetCurrent(width, height) { - this.viewPorts.push({ - width: width, - height: height - }); - }, - RemoveCurrent: function RemoveCurrent() { - this.viewPorts.pop(); - }, - Current: function Current() { - return this.viewPorts[this.viewPorts.length - 1]; - }, - width: function width() { - return this.Current().width; - }, - height: function height() { - return this.Current().height; - }, - ComputeSize: function ComputeSize(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); - } - }; - }; - - svg.init(); // images loaded - - svg.ImagesLoaded = function () { - return svg.Images.every(function (img) { - return img.loaded; - }); - }; // trim - - - svg.trim = function (s) { - return s.replace(/^\s+|\s+$/g, ''); - }; // compress spaces - - - svg.compressSpaces = function (s) { - return s.replace(/\s+/gm, ' '); - }; // ajax - // Todo: Replace with `fetch` and polyfill - - - svg.ajax = function (url, asynch) { - var AJAX = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP'); - - 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); - }); - AJAX.send(null); - }); - } - - AJAX.open('GET', url, false); - AJAX.send(null); - return AJAX.responseText; - }; // parse xml - - - svg.parseXml = function (xml) { - if (window.DOMParser) { - var parser = new DOMParser(); - return parser.parseFromString(xml, 'text/xml'); - } - - xml = xml.replace(/]*>/, ''); - var xmlDoc = new window.ActiveXObject('Microsoft.XMLDOM'); - xmlDoc.async = 'false'; - xmlDoc.loadXML(xml); - return xmlDoc; - }; // text extensions - // get the text baseline - - - var textBaselineMapping = { - baseline: 'alphabetic', - 'before-edge': 'top', - 'text-before-edge': 'top', - middle: 'middle', - central: 'middle', - 'after-edge': 'bottom', - 'text-after-edge': 'bottom', - ideographic: 'ideographic', - alphabetic: 'alphabetic', - hanging: 'hanging', - mathematical: 'alphabetic' - }; - - svg.Property = /*#__PURE__*/function () { - function Property(name, value) { - _classCallCheck(this, Property); - - this.name = name; - this.value = value; - } - - _createClass(Property, [{ - key: "getValue", - value: function getValue() { - return this.value; - } - }, { - key: "hasValue", - value: function hasValue() { - return !isNullish(this.value) && this.value !== ''; - } // return the numerical value of the property - - }, { - key: "numValue", - value: function numValue() { - if (!this.hasValue()) return 0; - var n = Number.parseFloat(this.value); - - if (String(this.value).endsWith('%')) { - n /= 100.0; - } - - return n; - } - }, { - key: "valueOrDefault", - value: function valueOrDefault(def) { - if (this.hasValue()) return this.value; - return def; - } - }, { - key: "numValueOrDefault", - value: function numValueOrDefault(def) { - if (this.hasValue()) return this.numValue(); - return def; - } // color extensions - // augment the current color value with the opacity - - }, { - key: "addOpacity", - value: function addOpacity(opacityProp) { - var newValue = this.value; - - if (!isNullish(opacityProp.value) && opacityProp.value !== '' && typeof this.value === 'string') { - // can only add opacity to colors, not patterns - var color = new RGBColor(this.value); - - if (color.ok) { - newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacityProp.numValue() + ')'; - } - } - - return new svg.Property(this.name, newValue); - } // definition extensions - // get the definition from the definitions table - - }, { - key: "getDefinition", - value: function getDefinition() { - var name = this.value.match(/#([^)'"]+)/); - - if (name) { - name = name[1]; - } - - if (!name) { - name = this.value; - } - - return svg.Definitions[name]; - } - }, { - key: "isUrlDefinition", - value: function isUrlDefinition() { - return this.value.startsWith('url('); - } - }, { - key: "getFillStyleDefinition", - value: function getFillStyleDefinition(e, opacityProp) { - var def = this.getDefinition(); // gradient - - if (!isNullish(def) && def.createGradient) { - return def.createGradient(svg.ctx, e, opacityProp); - } // pattern - - - if (!isNullish(def) && def.createPattern) { - if (def.getHrefAttribute().hasValue()) { - var pt = def.attribute('patternTransform'); - def = def.getHrefAttribute().getDefinition(); - - if (pt.hasValue()) { - def.attribute('patternTransform', true).value = pt.value; - } - } - - return def.createPattern(svg.ctx, e); - } - - return null; - } // length extensions - - }, { - key: "getDPI", - value: function getDPI(viewPort) { - return 96.0; // TODO: compute? - } - }, { - key: "getEM", - value: function getEM(viewPort) { - var em = 12; - var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); - if (fontSize.hasValue()) em = fontSize.toPixels(viewPort); - return em; - } - }, { - key: "getUnits", - value: function getUnits() { - return String(this.value).replace(/[\d.-]/g, ''); - } // get the length as pixels - - }, { - key: "toPixels", - value: function toPixels(viewPort, processPercent) { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('em')) return this.numValue() * this.getEM(viewPort); - if (s.endsWith('ex')) return this.numValue() * this.getEM(viewPort) / 2.0; - if (s.endsWith('px')) return this.numValue(); - if (s.endsWith('pt')) return this.numValue() * this.getDPI(viewPort) * (1.0 / 72.0); - if (s.endsWith('pc')) return this.numValue() * 15; - if (s.endsWith('cm')) return this.numValue() * this.getDPI(viewPort) / 2.54; - if (s.endsWith('mm')) return this.numValue() * this.getDPI(viewPort) / 25.4; - if (s.endsWith('in')) return this.numValue() * this.getDPI(viewPort); - if (s.endsWith('%')) return this.numValue() * svg.ViewPort.ComputeSize(viewPort); - var n = this.numValue(); - if (processPercent && n < 1.0) return n * svg.ViewPort.ComputeSize(viewPort); - return n; - } // time extensions - // get the time as milliseconds - - }, { - key: "toMilliseconds", - value: function toMilliseconds() { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('ms')) return this.numValue(); - if (s.endsWith('s')) return this.numValue() * 1000; - return this.numValue(); - } // angle extensions - // get the angle as radians - - }, { - key: "toRadians", - value: function toRadians() { - if (!this.hasValue()) return 0; - var s = String(this.value); - if (s.endsWith('deg')) return this.numValue() * (Math.PI / 180.0); - if (s.endsWith('grad')) return this.numValue() * (Math.PI / 200.0); - if (s.endsWith('rad')) return this.numValue(); - return this.numValue() * (Math.PI / 180.0); - } - }, { - key: "toTextBaseline", - value: function toTextBaseline() { - if (!this.hasValue()) return null; - return textBaselineMapping[this.value]; - } - }]); - - return Property; - }(); // fonts - - - svg.Font = { - Styles: 'normal|italic|oblique|inherit', - 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 = !isNullish(inherit) ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); - return { - fontFamily: fontFamily || f.fontFamily, - fontSize: fontSize || f.fontSize, - fontStyle: fontStyle || f.fontStyle, - fontWeight: fontWeight || f.fontWeight, - fontVariant: fontVariant || f.fontVariant, - toString: function toString() { - return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' '); - } - }; - }, - Parse: function Parse(s) { - var _this = this; - - var f = {}; - var ds = svg.trim(svg.compressSpaces(s || '')).split(' '); - var set = { - fontSize: false, - fontStyle: false, - fontWeight: false, - fontVariant: false - }; - var ff = ''; - ds.forEach(function (d) { - if (!set.fontStyle && _this.Styles.includes(d)) { - if (d !== 'inherit') { - f.fontStyle = d; - } - - set.fontStyle = true; - } else if (!set.fontVariant && _this.Variants.includes(d)) { - if (d !== 'inherit') { - f.fontVariant = d; - } - - set.fontStyle = set.fontVariant = true; - } else if (!set.fontWeight && _this.Weights.includes(d)) { - if (d !== 'inherit') { - f.fontWeight = d; - } - - set.fontStyle = set.fontVariant = set.fontWeight = true; - } else if (!set.fontSize) { - if (d !== 'inherit') { - f.fontSize = d.split('/')[0]; - } - - set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; - } else if (d !== 'inherit') { - ff += d; - } - }); - - if (ff !== '') { - f.fontFamily = ff; - } - - return f; - } - }; // points and paths - - svg.ToNumberArray = function (s) { - var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); - return a.map(function (_a) { - return Number.parseFloat(_a); - }); - }; - - svg.Point = /*#__PURE__*/function () { - function _class(x, y) { - _classCallCheck(this, _class); - - this.x = x; - this.y = y; - } - - _createClass(_class, [{ - key: "angleTo", - value: function angleTo(p) { - return Math.atan2(p.y - this.y, p.x - this.x); - } - }, { - key: "applyTransform", - value: function applyTransform(v) { - var xp = this.x * v[0] + this.y * v[2] + v[4]; - var yp = this.x * v[1] + this.y * v[3] + v[5]; - this.x = xp; - this.y = yp; - } - }]); - - return _class; - }(); - - svg.CreatePoint = function (s) { - var a = svg.ToNumberArray(s); - return new svg.Point(a[0], a[1]); - }; - - svg.CreatePath = function (s) { - var a = svg.ToNumberArray(s); - var path = []; - - for (var i = 0; i < a.length; i += 2) { - path.push(new svg.Point(a[i], a[i + 1])); - } - - return path; - }; // bounding box - - - svg.BoundingBox = /*#__PURE__*/function () { - function _class2(x1, y1, x2, y2) { - _classCallCheck(this, _class2); - - // pass in initial points if you want - this.x1 = Number.NaN; - this.y1 = Number.NaN; - this.x2 = Number.NaN; - this.y2 = Number.NaN; - this.addPoint(x1, y1); - this.addPoint(x2, y2); - } - - _createClass(_class2, [{ - key: "x", - value: function x() { - return this.x1; - } - }, { - key: "y", - value: function y() { - return this.y1; - } - }, { - key: "width", - value: function width() { - return this.x2 - this.x1; - } - }, { - key: "height", - value: function height() { - return this.y2 - this.y1; - } - }, { - key: "addPoint", - value: function addPoint(x, y) { - if (!isNullish(x)) { - if (isNaN(this.x1) || isNaN(this.x2)) { - this.x1 = x; - this.x2 = x; - } - - if (x < this.x1) this.x1 = x; - if (x > this.x2) this.x2 = x; - } - - if (!isNullish(y)) { - if (isNaN(this.y1) || isNaN(this.y2)) { - this.y1 = y; - this.y2 = y; - } - - if (y < this.y1) this.y1 = y; - if (y > this.y2) this.y2 = y; - } - } - }, { - key: "addX", - value: function addX(x) { - this.addPoint(x, null); - } - }, { - key: "addY", - value: function addY(y) { - this.addPoint(null, y); - } - }, { - key: "addBoundingBox", - value: function addBoundingBox(bb) { - this.addPoint(bb.x1, bb.y1); - this.addPoint(bb.x2, bb.y2); - } - }, { - key: "addQuadraticCurve", - value: function addQuadraticCurve(p0x, p0y, p1x, p1y, p2x, p2y) { - var cp1x = p0x + 2 / 3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) - - var cp1y = p0y + 2 / 3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) - - var cp2x = cp1x + 1 / 3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) - - var cp2y = cp1y + 1 / 3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) - - this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); - } - }, { - key: "addBezierCurve", - value: function addBezierCurve(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { - var _this2 = this; - - // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html - var p0 = [p0x, p0y], - p1 = [p1x, p1y], - p2 = [p2x, p2y], - p3 = [p3x, p3y]; - this.addPoint(p0[0], p0[1]); - this.addPoint(p3[0], p3[1]); - - var _loop = function _loop(i) { - var f = function f(t) { - return Math.pow(1 - t, 3) * p0[i] + 3 * Math.pow(1 - t, 2) * t * p1[i] + 3 * (1 - t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; - }; - - var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; - var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; - var c = 3 * p1[i] - 3 * p0[i]; - - if (a === 0) { - if (b === 0) return "continue"; - var t = -c / b; - - if (t > 0 && t < 1) { - if (i === 0) _this2.addX(f(t)); - if (i === 1) _this2.addY(f(t)); - } - - return "continue"; - } - - var b2ac = Math.pow(b, 2) - 4 * c * a; - if (b2ac < 0) return "continue"; - var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); - - if (t1 > 0 && t1 < 1) { - if (i === 0) _this2.addX(f(t1)); - if (i === 1) _this2.addY(f(t1)); - } - - var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); - - if (t2 > 0 && t2 < 1) { - if (i === 0) _this2.addX(f(t2)); - if (i === 1) _this2.addY(f(t2)); - } - }; - - for (var i = 0; i <= 1; i++) { - var _ret = _loop(i); - - if (_ret === "continue") continue; - } - } - }, { - key: "isPointInBox", - value: function isPointInBox(x, y) { - return this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2; - } - }]); - - return _class2; - }(); // transforms - - - svg.Transform = /*#__PURE__*/function () { - function _class3(v) { - var _this6 = this; - - _classCallCheck(this, _class3); - - this.Type = { - translate: function translate(s) { - _classCallCheck(this, translate); - - this.p = svg.CreatePoint(s); - - this.apply = function (ctx) { - ctx.translate(this.p.x || 0.0, this.p.y || 0.0); - }; - - this.unapply = function (ctx) { - ctx.translate(-1.0 * this.p.x || 0.0, -1.0 * this.p.y || 0.0); - }; - - this.applyToPoint = function (p) { - p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); - }; - }, - rotate: function rotate(s) { - _classCallCheck(this, rotate); - - var a = svg.ToNumberArray(s); - this.angle = new svg.Property('angle', a[0]); - this.cx = a[1] || 0; - this.cy = a[2] || 0; - - this.apply = function (ctx) { - ctx.translate(this.cx, this.cy); - ctx.rotate(this.angle.toRadians()); - ctx.translate(-this.cx, -this.cy); - }; - - this.unapply = function (ctx) { - ctx.translate(this.cx, this.cy); - ctx.rotate(-1.0 * this.angle.toRadians()); - ctx.translate(-this.cx, -this.cy); - }; - - this.applyToPoint = function (p) { - 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([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); - }; - }, - scale: function scale(s) { - _classCallCheck(this, scale); - - this.p = svg.CreatePoint(s); - - this.apply = function (ctx) { - ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); - }; - - this.unapply = function (ctx) { - ctx.scale(1.0 / this.p.x || 1.0, 1.0 / this.p.y || this.p.x || 1.0); - }; - - this.applyToPoint = function (p) { - p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); - }; - }, - matrix: function matrix(s) { - _classCallCheck(this, matrix); - - this.m = svg.ToNumberArray(s); - - this.apply = function (ctx) { - ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); - }; - - this.applyToPoint = function (p) { - p.applyTransform(this.m); - }; - } - }; - Object.assign(this.Type, { - SkewBase: /*#__PURE__*/function (_this$Type$matrix) { - _inherits(SkewBase, _this$Type$matrix); - - var _super = _createSuper(SkewBase); - - function SkewBase(s) { - var _this3; - - _classCallCheck(this, SkewBase); - - _this3 = _super.call(this, s); - _this3.angle = new svg.Property('angle', s); - return _this3; - } - - return SkewBase; - }(this.Type.matrix) - }); - Object.assign(this.Type, { - skewX: /*#__PURE__*/function (_this$Type$SkewBase) { - _inherits(skewX, _this$Type$SkewBase); - - var _super2 = _createSuper(skewX); - - function skewX(s) { - var _this4; - - _classCallCheck(this, skewX); - - _this4 = _super2.call(this, s); - _this4.m = [1, 0, Math.tan(_this4.angle.toRadians()), 1, 0, 0]; - return _this4; - } - - return skewX; - }(this.Type.SkewBase), - skewY: /*#__PURE__*/function (_this$Type$SkewBase2) { - _inherits(skewY, _this$Type$SkewBase2); - - var _super3 = _createSuper(skewY); - - function skewY(s) { - var _this5; - - _classCallCheck(this, skewY); - - _this5 = _super3.call(this, s); - _this5.m = [1, Math.tan(_this5.angle.toRadians()), 0, 1, 0, 0]; - return _this5; - } - - return skewY; - }(this.Type.SkewBase) - }); - var data = svg.trim(svg.compressSpaces(v)).replace(/\)([a-zA-Z])/g, ') $1').replace(/\)(\s?,\s?)/g, ') ').split(/\s(?=[a-z])/); - this.transforms = data.map(function (d) { - var type = svg.trim(d.split('(')[0]); - var s = d.split('(')[1].replace(')', ''); - var transform = new _this6.Type[type](s); - transform.type = type; - return transform; - }); - } - - _createClass(_class3, [{ - key: "apply", - value: function apply(ctx) { - this.transforms.forEach(function (transform) { - transform.apply(ctx); - }); - } - }, { - key: "unapply", - value: function unapply(ctx) { - for (var i = this.transforms.length - 1; i >= 0; i--) { - this.transforms[i].unapply(ctx); - } - } - }, { - key: "applyToPoint", - value: function applyToPoint(p) { - this.transforms.forEach(function (transform) { - transform.applyToPoint(p); - }); - } - }]); - - return _class3; - }(); // aspect ratio - - - svg.AspectRatio = function (ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { - // aspect ratio - https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute - aspectRatio = svg.compressSpaces(aspectRatio); - aspectRatio = aspectRatio.replace(/^defer\s/, ''); // ignore defer - - var align = aspectRatio.split(' ')[0] || 'xMidYMid'; - var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale - - var scaleX = width / desiredWidth; - var scaleY = height / desiredHeight; - var scaleMin = Math.min(scaleX, scaleY); - var scaleMax = Math.max(scaleX, scaleY); - - if (meetOrSlice === 'meet') { - desiredWidth *= scaleMin; - desiredHeight *= scaleMin; - } - - if (meetOrSlice === 'slice') { - desiredWidth *= scaleMax; - desiredHeight *= scaleMax; - } - - refX = new svg.Property('refX', refX); - refY = new svg.Property('refY', refY); - - if (refX.hasValue() && refY.hasValue()) { - ctx.translate(-scaleMin * refX.toPixels('x'), -scaleMin * refY.toPixels('y')); - } else { - // align - if (align.startsWith('xMid') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { - ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); - } - - if (align.endsWith('YMid') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { - ctx.translate(0, height / 2.0 - desiredHeight / 2.0); - } - - if (align.startsWith('xMax') && (meetOrSlice === 'meet' && scaleMin === scaleY || meetOrSlice === 'slice' && scaleMax === scaleY)) { - ctx.translate(width - desiredWidth, 0); - } - - if (align.endsWith('YMax') && (meetOrSlice === 'meet' && scaleMin === scaleX || meetOrSlice === 'slice' && scaleMax === scaleX)) { - ctx.translate(0, height - desiredHeight); - } - } // scale - - - 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(isNullish(minX) ? 0 : -minX, isNullish(minY) ? 0 : -minY); - }; // elements - - - svg.Element = {}; - svg.EmptyProperty = new svg.Property('EMPTY', ''); - - svg.Element.ElementBase = /*#__PURE__*/function () { - function _class4(node) { - var _this7 = this; - - _classCallCheck(this, _class4); - - // Argument from inheriting class - this.captureTextNodes = arguments[1]; // eslint-disable-line prefer-rest-params - - this.attributes = {}; - this.styles = {}; - this.children = []; - - if (!isNullish(node) && node.nodeType === 1) { - // ELEMENT_NODE - // add children - _toConsumableArray(node.childNodes).forEach(function (childNode) { - if (childNode.nodeType === 1) { - _this7.addChild(childNode, true); // ELEMENT_NODE - - } - - if (_this7.captureTextNodes && (childNode.nodeType === 3 || childNode.nodeType === 4)) { - var text = childNode.nodeValue || childNode.text || ''; - - if (svg.trim(svg.compressSpaces(text)) !== '') { - _this7.addChild(new svg.Element.tspan(childNode), false); // TEXT_NODE - - } - } - }); // add attributes - - - _toConsumableArray(node.attributes).forEach(function (_ref) { - var nodeName = _ref.nodeName, - nodeValue = _ref.nodeValue; - _this7.attributes[nodeName] = new svg.Property(nodeName, nodeValue); - }); // add tag styles - - - var styles = svg.Styles[node.nodeName]; - - 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 - - - if (this.attribute('class').hasValue()) { - var classes = svg.compressSpaces(this.attribute('class').value).split(' '); - classes.forEach(function (clss) { - styles = svg.Styles['.' + clss]; - - 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 (!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 - - - if (this.attribute('id').hasValue()) { - var _styles = svg.Styles['#' + this.attribute('id').value]; - - 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 - - - if (this.attribute('style').hasValue()) { - var _styles2 = this.attribute('style').value.split(';'); - - _styles2.forEach(function (style) { - if (svg.trim(style) !== '') { - var _style$split = style.split(':'), - name = _style$split.name, - value = _style$split.value; - - name = svg.trim(name); - value = svg.trim(value); - _this7.styles[name] = new svg.Property(name, value); - } - }); - } // add id - - - if (this.attribute('id').hasValue()) { - if (isNullish(svg.Definitions[this.attribute('id').value])) { - svg.Definitions[this.attribute('id').value] = this; - } - } - } - } // get or create attribute - - - _createClass(_class4, [{ - key: "attribute", - value: function attribute(name, createIfNotExists) { - var a = this.attributes[name]; - if (!isNullish(a)) return a; - - if (createIfNotExists === true) { - a = new svg.Property(name, ''); - this.attributes[name] = a; - } - - return a || svg.EmptyProperty; - } - }, { - key: "getHrefAttribute", - value: function getHrefAttribute() { - for (var a in this.attributes) { - if (a.endsWith(':href')) { - return this.attributes[a]; - } - } - - return svg.EmptyProperty; - } // get or create style, crawls up node tree - - }, { - key: "style", - value: function style(name, createIfNotExists, skipAncestors) { - var s = this.styles[name]; - if (!isNullish(s)) return s; - var a = this.attribute(name); - - if (!isNullish(a) && a.hasValue()) { - this.styles[name] = a; // move up to me to cache - - return a; - } - - if (skipAncestors !== true) { - var p = this.parent; - - if (!isNullish(p)) { - var ps = p.style(name); - - if (!isNullish(ps) && ps.hasValue()) { - return ps; - } - } - } - - if (createIfNotExists === true) { - s = new svg.Property(name, ''); - this.styles[name] = s; - } - - return s || svg.EmptyProperty; - } // base render - - }, { - key: "render", - value: function render(ctx) { - // don't render display=none - if (this.style('display').value === 'none') return; // don't render visibility=hidden - - if (this.style('visibility').value === 'hidden') return; - ctx.save(); - - if (this.attribute('mask').hasValue()) { - // mask - var mask = this.attribute('mask').getDefinition(); - if (!isNullish(mask)) mask.apply(ctx, this); - } else if (this.style('filter').hasValue()) { - // filter - var filter = this.style('filter').getDefinition(); - if (!isNullish(filter)) filter.apply(ctx, this); - } else { - this.setContext(ctx); - this.renderChildren(ctx); - this.clearContext(ctx); - } - - ctx.restore(); - } // base set context - - }, { - key: "setContext", - value: function setContext(ctx) {// OVERRIDE ME! - } // base clear context - - }, { - key: "clearContext", - value: function clearContext(ctx) {// OVERRIDE ME! - } // base render children - - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - this.children.forEach(function (child) { - child.render(ctx); - }); - } - }, { - key: "addChild", - value: function addChild(childNode, create) { - var child = create ? svg.CreateElement(childNode) : childNode; - child.parent = this; - - if (child.type !== 'title') { - this.children.push(child); - } - } - }]); - - return _class4; - }(); - - svg.Element.RenderedElementBase = /*#__PURE__*/function (_svg$Element$ElementB) { - _inherits(_class5, _svg$Element$ElementB); - - var _super4 = _createSuper(_class5); - - function _class5() { - _classCallCheck(this, _class5); - - return _super4.apply(this, arguments); - } - - _createClass(_class5, [{ - key: "setContext", - value: function setContext(ctx) { - // fill - if (this.style('fill').isUrlDefinition()) { - var fs = this.style('fill').getFillStyleDefinition(this, this.style('fill-opacity')); - 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; - ctx.fillStyle = fillStyle.value === 'none' ? 'rgba(0,0,0,0)' : fillStyle.value; - } - - if (this.style('fill-opacity').hasValue()) { - var _fillStyle = new svg.Property('fill', ctx.fillStyle); - - _fillStyle = _fillStyle.addOpacity(this.style('fill-opacity')); - ctx.fillStyle = _fillStyle.value; - } // stroke - - - if (this.style('stroke').isUrlDefinition()) { - var _fs = this.style('stroke').getFillStyleDefinition(this, this.style('stroke-opacity')); - - 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; - ctx.strokeStyle = strokeStyle.value === 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value; - } - - if (this.style('stroke-opacity').hasValue()) { - var _strokeStyle = new svg.Property('stroke', ctx.strokeStyle); - - _strokeStyle = _strokeStyle.addOpacity(this.style('stroke-opacity')); - ctx.strokeStyle = _strokeStyle.value; - } - - if (this.style('stroke-width').hasValue()) { - var newLineWidth = this.style('stroke-width').toPixels(); - ctx.lineWidth = newLineWidth === 0 ? 0.001 : newLineWidth; // browsers don't respect 0 - } - - if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; - if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; - if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; - - if (this.style('stroke-dasharray').hasValue() && this.style('stroke-dasharray').value !== 'none') { - var gaps = svg.ToNumberArray(this.style('stroke-dasharray').value); - - if (typeof ctx.setLineDash !== 'undefined') { - ctx.setLineDash(gaps); - } else if (typeof ctx.webkitLineDash !== 'undefined') { - ctx.webkitLineDash = gaps; - } else if (typeof ctx.mozDash !== 'undefined' && !(gaps.length === 1 && gaps[0] === 0)) { - ctx.mozDash = gaps; - } - - var offset = this.style('stroke-dashoffset').numValueOrDefault(1); - - if (typeof ctx.lineDashOffset !== 'undefined') { - ctx.lineDashOffset = offset; - } else if (typeof ctx.webkitLineDashOffset !== 'undefined') { - ctx.webkitLineDashOffset = offset; - } else if (typeof ctx.mozDashOffset !== 'undefined') { - ctx.mozDashOffset = offset; - } - } // font - - - if (typeof ctx.font !== 'undefined') { - ctx.font = svg.Font.CreateFont(this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').toPixels() + 'px' : '', this.style('font-family').value).toString(); - } // transform - - - if (this.attribute('transform').hasValue()) { - var transform = new svg.Transform(this.attribute('transform').value); - transform.apply(ctx); - } // clip - - - if (this.style('clip-path', false, true).hasValue()) { - var clip = this.style('clip-path', false, true).getDefinition(); - if (!isNullish(clip)) clip.apply(ctx); - } // opacity - - - if (this.style('opacity').hasValue()) { - ctx.globalAlpha = this.style('opacity').numValue(); - } - } - }]); - - return _class5; - }(svg.Element.ElementBase); - - svg.Element.PathElementBase = /*#__PURE__*/function (_svg$Element$Rendered) { - _inherits(_class6, _svg$Element$Rendered); - - var _super5 = _createSuper(_class6); - - function _class6() { - _classCallCheck(this, _class6); - - return _super5.apply(this, arguments); - } - - _createClass(_class6, [{ - key: "path", - value: function path(ctx) { - if (!isNullish(ctx)) ctx.beginPath(); - return new svg.BoundingBox(); - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - this.path(ctx); - svg.Mouse.checkPath(this, ctx); - - if (ctx.fillStyle !== '') { - if (this.style('fill-rule').valueOrDefault('inherit') !== 'inherit') { - ctx.fill(this.style('fill-rule').value); - } else { - ctx.fill(); - } - } - - if (ctx.strokeStyle !== '') ctx.stroke(); - var markers = this.getMarkers(); - - 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]); - } - - if (this.style('marker-mid').isUrlDefinition()) { - var _marker = this.style('marker-mid').getDefinition(); - - for (var i = 1; i < markers.length - 1; i++) { - _marker.render(ctx, markers[i][0], markers[i][1]); - } - } - - if (this.style('marker-end').isUrlDefinition()) { - var _marker2 = this.style('marker-end').getDefinition(); - - _marker2.render(ctx, markers[markers.length - 1][0], markers[markers.length - 1][1]); - } - } - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - return this.path(); - } - }, { - key: "getMarkers", - value: function getMarkers() { - return null; - } - }]); - - return _class6; - }(svg.Element.RenderedElementBase); // svg element - - - svg.Element.svg = /*#__PURE__*/function (_svg$Element$Rendered2) { - _inherits(_class7, _svg$Element$Rendered2); - - var _super6 = _createSuper(_class7); - - function _class7() { - _classCallCheck(this, _class7); - - return _super6.apply(this, arguments); - } - - _createClass(_class7, [{ - key: "clearContext", - value: function clearContext(ctx) { - _get(_getPrototypeOf(_class7.prototype), "clearContext", this).call(this, ctx); - - svg.ViewPort.RemoveCurrent(); - } - }, { - key: "setContext", - value: function setContext(ctx) { - // initial values and defaults - ctx.strokeStyle = 'rgba(0,0,0,0)'; - ctx.lineCap = 'butt'; - ctx.lineJoin = 'miter'; - ctx.miterLimit = 4; - - if (typeof ctx.font !== 'undefined' && typeof window.getComputedStyle !== 'undefined') { - ctx.font = window.getComputedStyle(ctx.canvas).getPropertyValue('font'); - } - - _get(_getPrototypeOf(_class7.prototype), "setContext", this).call(this, ctx); // create new view port - - - if (!this.attribute('x').hasValue()) this.attribute('x', true).value = 0; - if (!this.attribute('y').hasValue()) this.attribute('y', true).value = 0; - ctx.translate(this.attribute('x').toPixels('x'), this.attribute('y').toPixels('y')); - var width = svg.ViewPort.width(); - var height = svg.ViewPort.height(); - if (!this.attribute('width').hasValue()) this.attribute('width', true).value = '100%'; - if (!this.attribute('height').hasValue()) this.attribute('height', true).value = '100%'; - - if (typeof this.root === 'undefined') { - width = this.attribute('width').toPixels('x'); - height = this.attribute('height').toPixels('y'); - var x = 0; - var y = 0; - - if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { - x = -this.attribute('refX').toPixels('x'); - y = -this.attribute('refY').toPixels('y'); - } - - if (this.attribute('overflow').valueOrDefault('hidden') !== 'visible') { - ctx.beginPath(); - ctx.moveTo(x, y); - ctx.lineTo(width, y); - ctx.lineTo(width, height); - ctx.lineTo(x, height); - ctx.closePath(); - ctx.clip(); - } - } - - svg.ViewPort.SetCurrent(width, height); // viewbox - - if (this.attribute('viewBox').hasValue()) { - var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); - var minX = viewBox[0]; - var minY = viewBox[1]; - width = viewBox[2]; - height = viewBox[3]; - svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); - svg.ViewPort.RemoveCurrent(); - svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); - } - } - }]); - - return _class7; - }(svg.Element.RenderedElementBase); // rect element - - - svg.Element.rect = /*#__PURE__*/function (_svg$Element$PathElem) { - _inherits(_class8, _svg$Element$PathElem); - - var _super7 = _createSuper(_class8); - - function _class8() { - _classCallCheck(this, _class8); - - return _super7.apply(this, arguments); - } - - _createClass(_class8, [{ - key: "path", - value: function path(ctx) { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - var rx = this.attribute('rx').toPixels('x'); - var ry = this.attribute('ry').toPixels('y'); - if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; - if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; - rx = Math.min(rx, width / 2.0); - ry = Math.min(ry, height / 2.0); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(x + rx, y); - ctx.lineTo(x + width - rx, y); - ctx.quadraticCurveTo(x + width, y, x + width, y + ry); - ctx.lineTo(x + width, y + height - ry); - ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height); - ctx.lineTo(x + rx, y + height); - ctx.quadraticCurveTo(x, y + height, x, y + height - ry); - ctx.lineTo(x, y + ry); - ctx.quadraticCurveTo(x, y, x + rx, y); - ctx.closePath(); - } - - return new svg.BoundingBox(x, y, x + width, y + height); - } - }]); - - return _class8; - }(svg.Element.PathElementBase); // circle element - - - svg.Element.circle = /*#__PURE__*/function (_svg$Element$PathElem2) { - _inherits(_class9, _svg$Element$PathElem2); - - var _super8 = _createSuper(_class9); - - function _class9() { - _classCallCheck(this, _class9); - - return _super8.apply(this, arguments); - } - - _createClass(_class9, [{ - key: "path", - value: function path(ctx) { - var cx = this.attribute('cx').toPixels('x'); - var cy = this.attribute('cy').toPixels('y'); - var r = this.attribute('r').toPixels(); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.arc(cx, cy, r, 0, Math.PI * 2, true); - ctx.closePath(); - } - - return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); - } - }]); - - return _class9; - }(svg.Element.PathElementBase); // ellipse element - - - var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); - - svg.Element.ellipse = /*#__PURE__*/function (_svg$Element$PathElem3) { - _inherits(_class10, _svg$Element$PathElem3); - - var _super9 = _createSuper(_class10); - - function _class10() { - _classCallCheck(this, _class10); - - return _super9.apply(this, arguments); - } - - _createClass(_class10, [{ - key: "path", - value: function path(ctx) { - var rx = this.attribute('rx').toPixels('x'); - var ry = this.attribute('ry').toPixels('y'); - var cx = this.attribute('cx').toPixels('x'); - var cy = this.attribute('cy').toPixels('y'); - - 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); - ctx.bezierCurveTo(cx + rx, cy + KAPPA * ry, cx + KAPPA * rx, cy + ry, cx, cy + ry); - ctx.bezierCurveTo(cx - KAPPA * rx, cy + ry, cx - rx, cy + KAPPA * ry, cx - rx, cy); - ctx.bezierCurveTo(cx - rx, cy - KAPPA * ry, cx - KAPPA * rx, cy - ry, cx, cy - ry); - ctx.closePath(); - } - - return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); - } - }]); - - return _class10; - }(svg.Element.PathElementBase); // line element - - - svg.Element.line = /*#__PURE__*/function (_svg$Element$PathElem4) { - _inherits(_class11, _svg$Element$PathElem4); - - var _super10 = _createSuper(_class11); - - function _class11() { - _classCallCheck(this, _class11); - - return _super10.apply(this, arguments); - } - - _createClass(_class11, [{ - key: "getPoints", - value: function getPoints() { - return [new svg.Point(this.attribute('x1').toPixels('x'), this.attribute('y1').toPixels('y')), new svg.Point(this.attribute('x2').toPixels('x'), this.attribute('y2').toPixels('y'))]; - } - }, { - key: "path", - value: function path(ctx) { - var points = this.getPoints(); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(points[0].x, points[0].y); - ctx.lineTo(points[1].x, points[1].y); - } - - return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); - } - }, { - key: "getMarkers", - value: function getMarkers() { - var points = this.getPoints(); - var a = points[0].angleTo(points[1]); - return [[points[0], a], [points[1], a]]; - } - }]); - - return _class11; - }(svg.Element.PathElementBase); // polyline element - - - svg.Element.polyline = /*#__PURE__*/function (_svg$Element$PathElem5) { - _inherits(_class12, _svg$Element$PathElem5); - - var _super11 = _createSuper(_class12); - - function _class12(node) { - var _this8; - - _classCallCheck(this, _class12); - - _this8 = _super11.call(this, node); - _this8.points = svg.CreatePath(_this8.attribute('points').value); - return _this8; - } - - _createClass(_class12, [{ - key: "path", - value: function path(ctx) { - var _this$points$ = this.points[0], - x = _this$points$.x, - y = _this$points$.y; - var bb = new svg.BoundingBox(x, y); - - if (!isNullish(ctx)) { - ctx.beginPath(); - ctx.moveTo(x, y); - } - - for (var i = 1; i < this.points.length; i++) { - var _this$points$i = this.points[i], - _x = _this$points$i.x, - _y = _this$points$i.y; - bb.addPoint(_x, _y); - if (!isNullish(ctx)) ctx.lineTo(_x, _y); - } - - return bb; - } - }, { - key: "getMarkers", - value: function getMarkers() { - var markers = []; - - for (var i = 0; i < this.points.length - 1; i++) { - markers.push([this.points[i], this.points[i].angleTo(this.points[i + 1])]); - } - - markers.push([this.points[this.points.length - 1], markers[markers.length - 1][1]]); - return markers; - } - }]); - - return _class12; - }(svg.Element.PathElementBase); // polygon element - - - svg.Element.polygon = /*#__PURE__*/function (_svg$Element$polyline) { - _inherits(_class13, _svg$Element$polyline); - - var _super12 = _createSuper(_class13); - - function _class13() { - _classCallCheck(this, _class13); - - return _super12.apply(this, arguments); - } - - _createClass(_class13, [{ - key: "path", - value: function path(ctx) { - var bb = _get(_getPrototypeOf(_class13.prototype), "path", this).call(this, ctx); - - if (!isNullish(ctx)) { - ctx.lineTo(this.points[0].x, this.points[0].y); - ctx.closePath(); - } - - return bb; - } - }]); - - return _class13; - }(svg.Element.polyline); // path element - - - svg.Element.path = /*#__PURE__*/function (_svg$Element$PathElem6) { - _inherits(_class14, _svg$Element$PathElem6); - - var _super13 = _createSuper(_class14); - - function _class14(node) { - var _this9; - - _classCallCheck(this, _class14); - - _this9 = _super13.call(this, node); - - var d = _this9.attribute('d').value // TODO: convert to real lexer based on https://www.w3.org/TR/SVG11/paths.html#PathDataBNF - .replace(/,/gm, ' ') // get rid of all commas - .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands - .replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from commands - .replace(/([MmZzLlHhVvCcSsQqTtAa])(\S)/gm, '$1 $2') // separate commands from points - .replace(/(\S)([MmZzLlHhVvCcSsQqTtAa])/gm, '$1 $2') // separate commands from points - .replace(/(\d)([+-])/gm, '$1 $2') // separate digits when no comma - .replace(/(\.\d*)(\.)/gm, '$1 $2') // separate digits when no comma - .replace(/([Aa](\s+\d+)(\s+\d+)(\s+\d+))\s+([01])\s*([01])/gm, '$1 $5 $6 '); // shorthand elliptical arc path syntax - - - d = svg.compressSpaces(d); // compress multiple spaces - - d = svg.trim(d); - _this9.PathParser = { - tokens: d.split(' '), - reset: function reset() { - this.i = -1; - this.command = ''; - this.previousCommand = ''; - this.start = new svg.Point(0, 0); - this.control = new svg.Point(0, 0); - this.current = new svg.Point(0, 0); - this.points = []; - this.angles = []; - }, - isEnd: function isEnd() { - return this.i >= this.tokens.length - 1; - }, - isCommandOrEnd: function isCommandOrEnd() { - if (this.isEnd()) return true; - return !isNullish(this.tokens[this.i + 1].match(/^[A-Za-z]$/)); - }, - isRelativeCommand: function isRelativeCommand() { - switch (this.command) { - case 'm': - case 'l': - case 'h': - case 'v': - case 'c': - case 's': - case 'q': - case 't': - case 'a': - case 'z': - return true; - } - - return false; - }, - getToken: function getToken() { - this.i++; - return this.tokens[this.i]; - }, - getScalar: function getScalar() { - return Number.parseFloat(this.getToken()); - }, - nextCommand: function nextCommand() { - this.previousCommand = this.command; - this.command = this.getToken(); - }, - getPoint: function getPoint() { - var p = new svg.Point(this.getScalar(), this.getScalar()); - return this.makeAbsolute(p); - }, - getAsControlPoint: function getAsControlPoint() { - var p = this.getPoint(); - this.control = p; - return p; - }, - getAsCurrentPoint: function getAsCurrentPoint() { - var p = this.getPoint(); - this.current = p; - return p; - }, - getReflectedControlPoint: function getReflectedControlPoint() { - if (this.previousCommand.toLowerCase() !== 'c' && this.previousCommand.toLowerCase() !== 's' && this.previousCommand.toLowerCase() !== 'q' && this.previousCommand.toLowerCase() !== 't') { - return this.current; - } // reflect point - - - var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); - return p; - }, - makeAbsolute: function makeAbsolute(p) { - if (this.isRelativeCommand()) { - p.x += this.current.x; - p.y += this.current.y; - } - - return p; - }, - addMarker: function addMarker(p, from, priorTo) { - // if the last angle isn't filled in because we didn't have this point yet ... - 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, isNullish(from) ? null : from.angleTo(p)); - }, - addMarkerAngle: function addMarkerAngle(p, a) { - this.points.push(p); - this.angles.push(a); - }, - getMarkerPoints: function getMarkerPoints() { - return this.points; - }, - getMarkerAngles: function getMarkerAngles() { - for (var i = 0; i < this.angles.length; i++) { - if (isNullish(this.angles[i])) { - for (var j = i + 1; j < this.angles.length; j++) { - if (!isNullish(this.angles[j])) { - this.angles[i] = this.angles[j]; - break; - } - } - } - } - - return this.angles; - } - }; - return _this9; - } - - _createClass(_class14, [{ - key: "path", - value: function path(ctx) { - var pp = this.PathParser; - pp.reset(); - var bb = new svg.BoundingBox(); - if (!isNullish(ctx)) ctx.beginPath(); - - while (!pp.isEnd()) { - pp.nextCommand(); - - switch (pp.command) { - case 'M': - case 'm': - { - 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(); - - pp.addMarker(_p, pp.start); - bb.addPoint(_p.x, _p.y); - if (!isNullish(ctx)) ctx.lineTo(_p.x, _p.y); - } - - break; - } - - case 'L': - case 'l': - while (!pp.isCommandOrEnd()) { - var c = pp.current; - - var _p2 = pp.getAsCurrentPoint(); - - pp.addMarker(_p2, c); - bb.addPoint(_p2.x, _p2.y); - if (!isNullish(ctx)) ctx.lineTo(_p2.x, _p2.y); - } - - break; - - case 'H': - case 'h': - while (!pp.isCommandOrEnd()) { - var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); - pp.addMarker(newP, pp.current); - pp.current = newP; - bb.addPoint(pp.current.x, pp.current.y); - if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); - } - - break; - - case 'V': - case 'v': - while (!pp.isCommandOrEnd()) { - var _newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); - - pp.addMarker(_newP, pp.current); - pp.current = _newP; - bb.addPoint(pp.current.x, pp.current.y); - if (!isNullish(ctx)) ctx.lineTo(pp.current.x, pp.current.y); - } - - break; - - case 'C': - case 'c': - while (!pp.isCommandOrEnd()) { - var curr = pp.current; - var p1 = pp.getPoint(); - var cntrl = pp.getAsControlPoint(); - 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 (!isNullish(ctx)) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); - } - - break; - - case 'S': - case 's': - while (!pp.isCommandOrEnd()) { - var _curr = pp.current; - - var _p3 = pp.getReflectedControlPoint(); - - var _cntrl = pp.getAsControlPoint(); - - var _cp = pp.getAsCurrentPoint(); - - pp.addMarker(_cp, _cntrl, _p3); - bb.addBezierCurve(_curr.x, _curr.y, _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; - - case 'Q': - case 'q': - while (!pp.isCommandOrEnd()) { - var _curr2 = pp.current; - - var _cntrl2 = pp.getAsControlPoint(); - - var _cp2 = pp.getAsCurrentPoint(); - - pp.addMarker(_cp2, _cntrl2, _cntrl2); - bb.addQuadraticCurve(_curr2.x, _curr2.y, _cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); - if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl2.x, _cntrl2.y, _cp2.x, _cp2.y); - } - - break; - - case 'T': - case 't': - while (!pp.isCommandOrEnd()) { - var _curr3 = pp.current; - - var _cntrl3 = pp.getReflectedControlPoint(); - - pp.control = _cntrl3; - - var _cp3 = pp.getAsCurrentPoint(); - - pp.addMarker(_cp3, _cntrl3, _cntrl3); - bb.addQuadraticCurve(_curr3.x, _curr3.y, _cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); - if (!isNullish(ctx)) ctx.quadraticCurveTo(_cntrl3.x, _cntrl3.y, _cp3.x, _cp3.y); - } - - break; - - case 'A': - case 'a': - var _loop2 = function _loop2() { - var curr = pp.current; - var rx = pp.getScalar(); - var ry = pp.getScalar(); - var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); - var largeArcFlag = pp.getScalar(); - var sweepFlag = pp.getScalar(); - var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization - // https://www.w3.org/TR/SVG11/implnote.html#ArcConversionEndpointToCenter - // x1', y1' - - var currp = new svg.Point(Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0); // adjust radii - - var l = Math.pow(currp.x, 2) / Math.pow(rx, 2) + Math.pow(currp.y, 2) / Math.pow(ry, 2); - - if (l > 1) { - rx *= Math.sqrt(l); - ry *= Math.sqrt(l); - } // cx', cy' - - - var s = (largeArcFlag === sweepFlag ? -1 : 1) * Math.sqrt((Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(currp.y, 2) - Math.pow(ry, 2) * Math.pow(currp.x, 2)) / (Math.pow(rx, 2) * Math.pow(currp.y, 2) + Math.pow(ry, 2) * Math.pow(currp.x, 2))); - if (isNaN(s)) s = 0; - var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy - - var centp = new svg.Point((curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y); // vector magnitude - - var m = function m(v) { - return Math.sqrt(Math.pow(v[0], 2) + Math.pow(v[1], 2)); - }; // ratio between two vectors - - - var r = function r(u, v) { - return (u[0] * v[0] + u[1] * v[1]) / (m(u) * m(v)); - }; // angle between two vectors - - - var a = function a(u, v) { - return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(r(u, v)); - }; // initial angle - - - var a1 = a([1, 0], [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]); // angle delta - - var u = [(currp.x - cpp.x) / rx, (currp.y - cpp.y) / ry]; - var v = [(-currp.x - cpp.x) / rx, (-currp.y - cpp.y) / ry]; - var ad = a(u, v); - if (r(u, v) <= -1) ad = Math.PI; - if (r(u, v) >= 1) ad = 0; // for markers - - var dir = 1 - sweepFlag ? 1.0 : -1.0; - var ah = a1 + dir * (ad / 2.0); - var halfWay = new svg.Point(centp.x + rx * Math.cos(ah), centp.y + ry * Math.sin(ah)); - pp.addMarkerAngle(halfWay, ah - dir * Math.PI / 2); - pp.addMarkerAngle(cp, ah - dir * Math.PI); - bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better - - if (!isNullish(ctx)) { - var _r = rx > ry ? rx : ry; - - var sx = rx > ry ? 1 : rx / ry; - var sy = rx > ry ? ry / rx : 1; - ctx.translate(centp.x, centp.y); - ctx.rotate(xAxisRotation); - ctx.scale(sx, sy); - ctx.arc(0, 0, _r, a1, a1 + ad, 1 - sweepFlag); - ctx.scale(1 / sx, 1 / sy); - ctx.rotate(-xAxisRotation); - ctx.translate(-centp.x, -centp.y); - } - }; - - while (!pp.isCommandOrEnd()) { - _loop2(); - } - - break; - - case 'Z': - case 'z': - if (!isNullish(ctx)) ctx.closePath(); - pp.current = pp.start; - } - } - - return bb; - } - }, { - key: "getMarkers", - value: function getMarkers() { - var points = this.PathParser.getMarkerPoints(); - var angles = this.PathParser.getMarkerAngles(); - var markers = points.map(function (point, i) { - return [point, angles[i]]; - }); - return markers; - } - }]); - - return _class14; - }(svg.Element.PathElementBase); // pattern element - - - svg.Element.pattern = /*#__PURE__*/function (_svg$Element$ElementB2) { - _inherits(_class15, _svg$Element$ElementB2); - - var _super14 = _createSuper(_class15); - - function _class15() { - _classCallCheck(this, _class15); - - return _super14.apply(this, arguments); - } - - _createClass(_class15, [{ - key: "createPattern", - value: function createPattern(ctx, element) { - var width = this.attribute('width').toPixels('x', true); - 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.children = this.children; - var c = document.createElement('canvas'); - c.width = width; - c.height = height; - var cctx = c.getContext('2d'); - - if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { - cctx.translate(this.attribute('x').toPixels('x', true), this.attribute('y').toPixels('y', true)); - } // render 3x3 grid so when we transform there's no white space on edges - - - for (var x = -1; x <= 1; x++) { - for (var y = -1; y <= 1; y++) { - cctx.save(); - cctx.translate(x * c.width, y * c.height); - tempSvg.render(cctx); - cctx.restore(); - } - } - - var pattern = ctx.createPattern(c, 'repeat'); - return pattern; - } - }]); - - return _class15; - }(svg.Element.ElementBase); // marker element - - - svg.Element.marker = /*#__PURE__*/function (_svg$Element$ElementB3) { - _inherits(_class16, _svg$Element$ElementB3); - - var _super15 = _createSuper(_class16); - - function _class16() { - _classCallCheck(this, _class16); - - return _super15.apply(this, arguments); - } - - _createClass(_class16, [{ - key: "render", - value: function render(ctx, point, angle) { - ctx.translate(point.x, point.y); - if (this.attribute('orient').valueOrDefault('auto') === 'auto') ctx.rotate(angle); - if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); - 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.children = this.children; - tempSvg.render(ctx); - ctx.restore(); - if (this.attribute('markerUnits').valueOrDefault('strokeWidth') === 'strokeWidth') ctx.scale(1 / ctx.lineWidth, 1 / ctx.lineWidth); - - if (this.attribute('orient').valueOrDefault('auto') === 'auto') { - ctx.rotate(-angle); - } - - ctx.translate(-point.x, -point.y); - } - }]); - - return _class16; - }(svg.Element.ElementBase); // definitions element - - - svg.Element.defs = /*#__PURE__*/function (_svg$Element$ElementB4) { - _inherits(_class17, _svg$Element$ElementB4); - - var _super16 = _createSuper(_class17); - - function _class17() { - _classCallCheck(this, _class17); - - return _super16.apply(this, arguments); - } - - _createClass(_class17, [{ - key: "render", - value: function render(ctx) {// NOOP - } - }]); - - return _class17; - }(svg.Element.ElementBase); // base for gradients - - - svg.Element.GradientBase = /*#__PURE__*/function (_svg$Element$ElementB5) { - _inherits(_class18, _svg$Element$ElementB5); - - var _super17 = _createSuper(_class18); - - function _class18(node) { - var _this10; - - _classCallCheck(this, _class18); - - _this10 = _super17.call(this, node); - _this10.gradientUnits = _this10.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); - _this10.stops = []; - - _this10.children.forEach(function (child) { - if (child.type === 'stop') { - _this10.stops.push(child); - } - }); - - return _this10; - } - - _createClass(_class18, [{ - key: "getGradient", - value: function getGradient() {// OVERRIDE ME! - } - }, { - key: "createGradient", - value: function createGradient(ctx, element, parentOpacityProp) { - var stopsContainer = this.getHrefAttribute().hasValue() ? this.getHrefAttribute().getDefinition() : this; - - var addParentOpacity = function addParentOpacity(color) { - if (parentOpacityProp.hasValue()) { - var p = new svg.Property('color', color); - return p.addOpacity(parentOpacityProp).value; - } - - return color; - }; - - var g = this.getGradient(ctx, element); - 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)); - }); - - if (this.attribute('gradientTransform').hasValue()) { - // 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); - var group = new svg.Element.g(); - 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.children = [group]; - var c = document.createElement('canvas'); - c.width = rootView.width; - c.height = rootView.height; - var tempCtx = c.getContext('2d'); - tempCtx.fillStyle = g; - tempSvg.render(tempCtx); - return tempCtx.createPattern(c, 'no-repeat'); - } - - return g; - } - }]); - - return _class18; - }(svg.Element.ElementBase); // linear gradient element - - - svg.Element.linearGradient = /*#__PURE__*/function (_svg$Element$Gradient) { - _inherits(_class19, _svg$Element$Gradient); - - var _super18 = _createSuper(_class19); - - function _class19() { - _classCallCheck(this, _class19); - - return _super18.apply(this, arguments); - } - - _createClass(_class19, [{ - key: "getGradient", - value: function getGradient(ctx, element) { - var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; - var bb = useBB ? element.getBoundingBox() : null; - - if (!this.attribute('x1').hasValue() && !this.attribute('y1').hasValue() && !this.attribute('x2').hasValue() && !this.attribute('y2').hasValue()) { - this.attribute('x1', true).value = 0; - this.attribute('y1', true).value = 0; - this.attribute('x2', true).value = 1; - this.attribute('y2', true).value = 0; - } - - var x1 = useBB ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').toPixels('x'); - var y1 = useBB ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').toPixels('y'); - var x2 = useBB ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').toPixels('x'); - var y2 = useBB ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').toPixels('y'); - if (x1 === x2 && y1 === y2) return null; - return ctx.createLinearGradient(x1, y1, x2, y2); - } - }]); - - return _class19; - }(svg.Element.GradientBase); // radial gradient element - - - svg.Element.radialGradient = /*#__PURE__*/function (_svg$Element$Gradient2) { - _inherits(_class20, _svg$Element$Gradient2); - - var _super19 = _createSuper(_class20); - - function _class20() { - _classCallCheck(this, _class20); - - return _super19.apply(this, arguments); - } - - _createClass(_class20, [{ - key: "getGradient", - value: function getGradient(ctx, element) { - var useBB = this.gradientUnits === 'objectBoundingBox' && element.getBoundingBox; - var bb = useBB ? element.getBoundingBox() : null; - if (!this.attribute('cx').hasValue()) this.attribute('cx', true).value = '50%'; - if (!this.attribute('cy').hasValue()) this.attribute('cy', true).value = '50%'; - if (!this.attribute('r').hasValue()) this.attribute('r', true).value = '50%'; - var cx = useBB ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').toPixels('x'); - var cy = useBB ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').toPixels('y'); - var fx = cx; - var fy = cy; - - if (this.attribute('fx').hasValue()) { - fx = useBB ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').toPixels('x'); - } - - if (this.attribute('fy').hasValue()) { - fy = useBB ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').toPixels('y'); - } - - var r = useBB ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').toPixels(); - return ctx.createRadialGradient(fx, fy, 0, cx, cy, r); - } - }]); - - return _class20; - }(svg.Element.GradientBase); // gradient stop element - - - svg.Element.stop = /*#__PURE__*/function (_svg$Element$ElementB6) { - _inherits(_class21, _svg$Element$ElementB6); - - var _super20 = _createSuper(_class21); - - function _class21(node) { - var _this11; - - _classCallCheck(this, _class21); - - _this11 = _super20.call(this, node); - _this11.offset = _this11.attribute('offset').numValue(); - if (_this11.offset < 0) _this11.offset = 0; - if (_this11.offset > 1) _this11.offset = 1; - - var stopColor = _this11.style('stop-color'); - - if (_this11.style('stop-opacity').hasValue()) { - stopColor = stopColor.addOpacity(_this11.style('stop-opacity')); - } - - _this11.color = stopColor.value; - return _this11; - } - - return _class21; - }(svg.Element.ElementBase); // animation base element - - - svg.Element.AnimateBase = /*#__PURE__*/function (_svg$Element$ElementB7) { - _inherits(_class22, _svg$Element$ElementB7); - - var _super21 = _createSuper(_class22); - - function _class22(node) { - var _this12; - - _classCallCheck(this, _class22); - - _this12 = _super21.call(this, node); - svg.Animations.push(_assertThisInitialized(_this12)); - _this12.duration = 0.0; - _this12.begin = _this12.attribute('begin').toMilliseconds(); - _this12.maxDuration = _this12.begin + _this12.attribute('dur').toMilliseconds(); - _this12.initialValue = null; - _this12.initialUnits = ''; - _this12.removed = false; - _this12.from = _this12.attribute('from'); - _this12.to = _this12.attribute('to'); - _this12.values = _this12.attribute('values'); - if (_this12.values.hasValue()) _this12.values.value = _this12.values.value.split(';'); - return _this12; - } - - _createClass(_class22, [{ - key: "getProperty", - value: function getProperty() { - var attributeType = this.attribute('attributeType').value; - var attributeName = this.attribute('attributeName').value; - - if (attributeType === 'CSS') { - return this.parent.style(attributeName, true); - } - - return this.parent.attribute(attributeName, true); - } - }, { - key: "calcValue", - value: function calcValue() { - // OVERRIDE ME! - return ''; - } - }, { - key: "update", - value: function update(delta) { - // set initial value - if (isNullish(this.initialValue)) { - this.initialValue = this.getProperty().value; - this.initialUnits = this.getProperty().getUnits(); - } // if we're past the end time - - - if (this.duration > this.maxDuration) { - // loop for indefinitely repeating animations - if (this.attribute('repeatCount').value === 'indefinite' || this.attribute('repeatDur').value === 'indefinite') { - this.duration = 0.0; - } else if (this.attribute('fill').valueOrDefault('remove') === 'freeze' && !this.frozen) { - this.frozen = true; - this.parent.animationFrozen = true; - this.parent.animationFrozenValue = this.getProperty().value; - } else if (this.attribute('fill').valueOrDefault('remove') === 'remove' && !this.removed) { - this.removed = true; - this.getProperty().value = this.parent.animationFrozen ? this.parent.animationFrozenValue : this.initialValue; - return true; - } - - return false; - } - - this.duration += delta; // if we're past the begin time - - var updated = false; - - if (this.begin < this.duration) { - var newValue = this.calcValue(); // tween - - if (this.attribute('type').hasValue()) { - // for transform, etc. - var type = this.attribute('type').value; - newValue = type + '(' + newValue + ')'; - } - - this.getProperty().value = newValue; - updated = true; - } - - return updated; - } // fraction of duration we've covered - - }, { - key: "progress", - value: function progress() { - var ret = { - progress: (this.duration - this.begin) / (this.maxDuration - this.begin) - }; - - if (this.values.hasValue()) { - var p = ret.progress * (this.values.value.length - 1); - var lb = Math.floor(p), - ub = Math.ceil(p); - ret.from = new svg.Property('from', Number.parseFloat(this.values.value[lb])); - ret.to = new svg.Property('to', Number.parseFloat(this.values.value[ub])); - ret.progress = (p - lb) / (ub - lb); - } else { - ret.from = this.from; - ret.to = this.to; - } - - return ret; - } - }]); - - return _class22; - }(svg.Element.ElementBase); // animate element - - - svg.Element.animate = /*#__PURE__*/function (_svg$Element$AnimateB) { - _inherits(_class23, _svg$Element$AnimateB); - - var _super22 = _createSuper(_class23); - - function _class23() { - _classCallCheck(this, _class23); - - return _super22.apply(this, arguments); - } - - _createClass(_class23, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); // tween value linearly - - var newValue = p.from.numValue() + (p.to.numValue() - p.from.numValue()) * p.progress; - return newValue + this.initialUnits; - } - }]); - - return _class23; - }(svg.Element.AnimateBase); // animate color element - - - svg.Element.animateColor = /*#__PURE__*/function (_svg$Element$AnimateB2) { - _inherits(_class24, _svg$Element$AnimateB2); - - var _super23 = _createSuper(_class24); - - function _class24() { - _classCallCheck(this, _class24); - - return _super23.apply(this, arguments); - } - - _createClass(_class24, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); - var from = new RGBColor(p.from.value); - var to = new RGBColor(p.to.value); - - if (from.ok && to.ok) { - // tween color linearly - 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(' + Number.parseInt(r) + ',' + Number.parseInt(g) + ',' + Number.parseInt(b) + ')'; - } - - return this.attribute('from').value; - } - }]); - - return _class24; - }(svg.Element.AnimateBase); // animate transform element - - - svg.Element.animateTransform = /*#__PURE__*/function (_svg$Element$animate) { - _inherits(_class25, _svg$Element$animate); - - var _super24 = _createSuper(_class25); - - function _class25() { - _classCallCheck(this, _class25); - - return _super24.apply(this, arguments); - } - - _createClass(_class25, [{ - key: "calcValue", - value: function calcValue() { - var p = this.progress(); // tween value linearly - - var from = svg.ToNumberArray(p.from.value); - var to = svg.ToNumberArray(p.to.value); - var newValue = ''; - from.forEach(function (fr, i) { - newValue += fr + (to[i] - fr) * p.progress + ' '; - }); - return newValue; - } - }]); - - return _class25; - }(svg.Element.animate); // font element - - - svg.Element.font = /*#__PURE__*/function (_svg$Element$ElementB8) { - _inherits(_class26, _svg$Element$ElementB8); - - var _super25 = _createSuper(_class26); - - function _class26(node) { - var _this13; - - _classCallCheck(this, _class26); - - _this13 = _super25.call(this, node); - _this13.horizAdvX = _this13.attribute('horiz-adv-x').numValue(); - _this13.isRTL = false; - _this13.isArabic = false; - _this13.fontFace = null; - _this13.missingGlyph = null; - _this13.glyphs = []; - - _this13.children.forEach(function (child) { - if (child.type === 'font-face') { - _this13.fontFace = child; - - if (child.style('font-family').hasValue()) { - svg.Definitions[child.style('font-family').value] = _assertThisInitialized(_this13); - } - } else if (child.type === 'missing-glyph') { - _this13.missingGlyph = child; - } else if (child.type === 'glyph') { - if (child.arabicForm !== '') { - _this13.isRTL = true; - _this13.isArabic = true; - - if (typeof _this13.glyphs[child.unicode] === 'undefined') { - _this13.glyphs[child.unicode] = []; - } - - _this13.glyphs[child.unicode][child.arabicForm] = child; - } else { - _this13.glyphs[child.unicode] = child; - } - } - }); - - return _this13; - } - - return _class26; - }(svg.Element.ElementBase); // font-face element - - - svg.Element.fontface = /*#__PURE__*/function (_svg$Element$ElementB9) { - _inherits(_class27, _svg$Element$ElementB9); - - var _super26 = _createSuper(_class27); - - function _class27(node) { - var _this14; - - _classCallCheck(this, _class27); - - _this14 = _super26.call(this, node); - _this14.ascent = _this14.attribute('ascent').value; - _this14.descent = _this14.attribute('descent').value; - _this14.unitsPerEm = _this14.attribute('units-per-em').numValue(); - return _this14; - } - - return _class27; - }(svg.Element.ElementBase); // missing-glyph element - - - svg.Element.missingglyph = /*#__PURE__*/function (_svg$Element$path) { - _inherits(_class28, _svg$Element$path); - - var _super27 = _createSuper(_class28); - - function _class28(node) { - var _this15; - - _classCallCheck(this, _class28); - - _this15 = _super27.call(this, node); - _this15.horizAdvX = 0; - return _this15; - } - - return _class28; - }(svg.Element.path); // glyph element - - - svg.Element.glyph = /*#__PURE__*/function (_svg$Element$path2) { - _inherits(_class29, _svg$Element$path2); - - var _super28 = _createSuper(_class29); - - function _class29(node) { - var _this16; - - _classCallCheck(this, _class29); - - _this16 = _super28.call(this, node); - _this16.horizAdvX = _this16.attribute('horiz-adv-x').numValue(); - _this16.unicode = _this16.attribute('unicode').value; - _this16.arabicForm = _this16.attribute('arabic-form').value; - return _this16; - } - - return _class29; - }(svg.Element.path); // text element - - - svg.Element.text = /*#__PURE__*/function (_svg$Element$Rendered3) { - _inherits(_class30, _svg$Element$Rendered3); - - var _super29 = _createSuper(_class30); - - function _class30(node) { - _classCallCheck(this, _class30); - - return _super29.call(this, node, true); - } - - _createClass(_class30, [{ - key: "setContext", - value: function setContext(ctx) { - _get(_getPrototypeOf(_class30.prototype), "setContext", this).call(this, ctx); - - var textBaseline = this.style('dominant-baseline').toTextBaseline(); - if (isNullish(textBaseline)) textBaseline = this.style('alignment-baseline').toTextBaseline(); - if (!isNullish(textBaseline)) ctx.textBaseline = textBaseline; - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var fontSize = this.parent.style('font-size').numValueOrDefault(svg.Font.Parse(svg.ctx.font).fontSize); - return new svg.BoundingBox(x, y - fontSize, x + Math.floor(fontSize * 2.0 / 3.0) * this.children[0].getText().length, y); - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var _this17 = this; - - this.x = this.attribute('x').toPixels('x'); - this.y = this.attribute('y').toPixels('y'); - this.x += this.getAnchorDelta(ctx, this, 0); - this.children.forEach(function (child, i) { - _this17.renderChild(ctx, _this17, i); - }); - } - }, { - key: "getAnchorDelta", - value: function getAnchorDelta(ctx, parent, startI) { - var textAnchor = this.style('text-anchor').valueOrDefault('start'); - - if (textAnchor !== 'start') { - var width = 0; - - for (var i = startI; i < parent.children.length; i++) { - var child = parent.children[i]; - if (i > startI && child.attribute('x').hasValue()) break; // new group - - width += child.measureTextRecursive(ctx); - } - - return -1 * (textAnchor === 'end' ? width : width / 2.0); - } - - return 0; - } - }, { - key: "renderChild", - value: function renderChild(ctx, parent, i) { - var child = parent.children[i]; - - if (child.attribute('x').hasValue()) { - child.x = child.attribute('x').toPixels('x') + this.getAnchorDelta(ctx, parent, i); - if (child.attribute('dx').hasValue()) child.x += child.attribute('dx').toPixels('x'); - } else { - if (this.attribute('dx').hasValue()) this.x += this.attribute('dx').toPixels('x'); - if (child.attribute('dx').hasValue()) this.x += child.attribute('dx').toPixels('x'); - child.x = this.x; - } - - this.x = child.x + child.measureText(ctx); - - if (child.attribute('y').hasValue()) { - child.y = child.attribute('y').toPixels('y'); - if (child.attribute('dy').hasValue()) child.y += child.attribute('dy').toPixels('y'); - } else { - if (this.attribute('dy').hasValue()) this.y += this.attribute('dy').toPixels('y'); - if (child.attribute('dy').hasValue()) this.y += child.attribute('dy').toPixels('y'); - child.y = this.y; - } - - this.y = child.y; - child.render(ctx); - - for (var j = 0; j < child.children.length; j++) { - this.renderChild(ctx, child, j); - } - } - }]); - - return _class30; - }(svg.Element.RenderedElementBase); // text base - - - svg.Element.TextElementBase = /*#__PURE__*/function (_svg$Element$Rendered4) { - _inherits(_class31, _svg$Element$Rendered4); - - var _super30 = _createSuper(_class31); - - function _class31() { - _classCallCheck(this, _class31); - - return _super30.apply(this, arguments); - } - - _createClass(_class31, [{ - key: "getGlyph", - value: function getGlyph(font, text, i) { - var c = text[i]; - var glyph = null; - - if (font.isArabic) { - var arabicForm = 'isolated'; - if ((i === 0 || text[i - 1] === ' ') && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'terminal'; - if (i > 0 && text[i - 1] !== ' ' && i < text.length - 2 && text[i + 1] !== ' ') arabicForm = 'medial'; - if (i > 0 && text[i - 1] !== ' ' && (i === text.length - 1 || text[i + 1] === ' ')) arabicForm = 'initial'; - - if (typeof font.glyphs[c] !== 'undefined') { - glyph = font.glyphs[c][arabicForm]; - if (isNullish(glyph) && font.glyphs[c].type === 'glyph') glyph = font.glyphs[c]; - } - } else { - glyph = font.glyphs[c]; - } - - if (isNullish(glyph)) glyph = font.missingGlyph; - return glyph; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var customFont = this.parent.style('font-family').getDefinition(); - - 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(); - if (customFont.isRTL) text = text.split('').reverse().join(''); - var dx = svg.ToNumberArray(this.parent.attribute('dx').value); - - for (var i = 0; i < text.length; i++) { - var glyph = this.getGlyph(customFont, text, i); - var scale = fontSize / customFont.fontFace.unitsPerEm; - ctx.translate(this.x, this.y); - ctx.scale(scale, -scale); - var lw = ctx.lineWidth; - ctx.lineWidth = ctx.lineWidth * customFont.fontFace.unitsPerEm / fontSize; - if (fontStyle === 'italic') ctx.transform(1, 0, 0.4, 1, 0, 0); - glyph.render(ctx); - if (fontStyle === 'italic') ctx.transform(1, 0, -0.4, 1, 0, 0); - ctx.lineWidth = lw; - ctx.scale(1 / scale, -1 / scale); - ctx.translate(-this.x, -this.y); - this.x += fontSize * (glyph.horizAdvX || customFont.horizAdvX) / customFont.fontFace.unitsPerEm; - - if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { - this.x += dx[i]; - } - } - - return; - } - - if (ctx.fillStyle !== '') ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); - if (ctx.strokeStyle !== '') ctx.strokeText(svg.compressSpaces(this.getText()), this.x, this.y); - } - }, { - key: "getText", - value: function getText() {// OVERRIDE ME - } - }, { - key: "measureTextRecursive", - value: function measureTextRecursive(ctx) { - var width = this.measureText(ctx); - this.children.forEach(function (child) { - width += child.measureTextRecursive(ctx); - }); - return width; - } - }, { - key: "measureText", - value: function measureText(ctx) { - var customFont = this.parent.style('font-family').getDefinition(); - - 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(); - if (customFont.isRTL) text = text.split('').reverse().join(''); - var dx = svg.ToNumberArray(this.parent.attribute('dx').value); - - for (var i = 0; i < text.length; i++) { - var glyph = this.getGlyph(customFont, text, i); - measure += (glyph.horizAdvX || customFont.horizAdvX) * fontSize / customFont.fontFace.unitsPerEm; - - if (typeof dx[i] !== 'undefined' && !isNaN(dx[i])) { - measure += dx[i]; - } - } - - return measure; - } - - var textToMeasure = svg.compressSpaces(this.getText()); - if (!ctx.measureText) return textToMeasure.length * 10; - ctx.save(); - this.setContext(ctx); - - var _ctx$measureText = ctx.measureText(textToMeasure), - width = _ctx$measureText.width; - - ctx.restore(); - return width; - } - }]); - - return _class31; - }(svg.Element.RenderedElementBase); // tspan - - - svg.Element.tspan = /*#__PURE__*/function (_svg$Element$TextElem) { - _inherits(_class32, _svg$Element$TextElem); - - var _super31 = _createSuper(_class32); - - function _class32(node) { - var _this18; - - _classCallCheck(this, _class32); - - _this18 = _super31.call(this, node, true); - _this18.text = node.nodeValue || node.text || ''; - return _this18; - } - - _createClass(_class32, [{ - key: "getText", - value: function getText() { - return this.text; - } - }]); - - return _class32; - }(svg.Element.TextElementBase); // tref - - - svg.Element.tref = /*#__PURE__*/function (_svg$Element$TextElem2) { - _inherits(_class33, _svg$Element$TextElem2); - - var _super32 = _createSuper(_class33); - - function _class33() { - _classCallCheck(this, _class33); - - return _super32.apply(this, arguments); - } - - _createClass(_class33, [{ - key: "getText", - value: function getText() { - var element = this.getHrefAttribute().getDefinition(); - if (!isNullish(element)) return element.children[0].getText(); - return undefined; - } - }]); - - return _class33; - }(svg.Element.TextElementBase); // a element - - - svg.Element.a = /*#__PURE__*/function (_svg$Element$TextElem3) { - _inherits(_class34, _svg$Element$TextElem3); - - var _super33 = _createSuper(_class34); - - function _class34(node) { - var _this19; - - _classCallCheck(this, _class34); - - _this19 = _super33.call(this, node); - _this19.hasText = true; - - _toConsumableArray(node.childNodes).forEach(function (childNode) { - if (childNode.nodeType !== 3) { - _this19.hasText = false; - } - }); // this might contain text - - - _this19.text = _this19.hasText ? node.childNodes[0].nodeValue : ''; - return _this19; - } - - _createClass(_class34, [{ - key: "getText", - value: function getText() { - return this.text; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - if (this.hasText) { - // render as text element - _get(_getPrototypeOf(_class34.prototype), "renderChildren", this).call(this, ctx); - - var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); - svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.toPixels('y'), this.x + this.measureText(ctx), this.y)); - } else { - // render as temporary group - var g = new svg.Element.g(); - g.children = this.children; - g.parent = this; - g.render(ctx); - } - } - }, { - key: "onclick", - value: function onclick() { - window.open(this.getHrefAttribute().value); - } - }, { - key: "onmousemove", - value: function onmousemove() { - svg.ctx.canvas.style.cursor = 'pointer'; - } - }]); - - return _class34; - }(svg.Element.TextElementBase); // image element - - - svg.Element.image = /*#__PURE__*/function (_svg$Element$Rendered5) { - _inherits(_class35, _svg$Element$Rendered5); - - var _super34 = _createSuper(_class35); - - function _class35(node) { - var _this20; - - _classCallCheck(this, _class35); - - _this20 = _super34.call(this, node); - - var href = _this20.getHrefAttribute().value; - - if (href === '') { - return _possibleConstructorReturn(_this20); - } - - _this20._isSvg = href.match(/\.svg$/); - svg.Images.push(_assertThisInitialized(_this20)); - _this20.loaded = false; - - if (!_this20._isSvg) { - _this20.img = document.createElement('img'); - - if (svg.opts.useCORS === true) { - _this20.img.crossOrigin = 'Anonymous'; - } - - _this20.img.addEventListener('load', function () { - _this20.loaded = true; - }); - - _this20.img.addEventListener('error', function () { - svg.log('ERROR: image "' + href + '" not found'); - _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 - }); - } - - return _this20; - } - - _createClass(_class35, [{ - key: "renderChildren", - value: function renderChildren(ctx) { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - if (width === 0 || height === 0) return; - ctx.save(); - - if (this._isSvg) { - ctx.drawSvg(this.img, x, y, width, height); - } else { - ctx.translate(x, y); - svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); - ctx.drawImage(this.img, 0, 0); - } - - ctx.restore(); - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - return new svg.BoundingBox(x, y, x + width, y + height); - } - }]); - - return _class35; - }(svg.Element.RenderedElementBase); // group element - - - svg.Element.g = /*#__PURE__*/function (_svg$Element$Rendered6) { - _inherits(_class36, _svg$Element$Rendered6); - - var _super35 = _createSuper(_class36); - - function _class36() { - _classCallCheck(this, _class36); - - return _super35.apply(this, arguments); - } - - _createClass(_class36, [{ - key: "getBoundingBox", - value: function getBoundingBox() { - var bb = new svg.BoundingBox(); - this.children.forEach(function (child) { - bb.addBoundingBox(child.getBoundingBox()); - }); - return bb; - } - }]); - - return _class36; - }(svg.Element.RenderedElementBase); // symbol element - - - svg.Element.symbol = /*#__PURE__*/function (_svg$Element$Rendered7) { - _inherits(_class37, _svg$Element$Rendered7); - - var _super36 = _createSuper(_class37); - - function _class37() { - _classCallCheck(this, _class37); - - return _super36.apply(this, arguments); - } - - _createClass(_class37, [{ - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class37; - }(svg.Element.RenderedElementBase); // style element - - - svg.Element.style = /*#__PURE__*/function (_svg$Element$ElementB10) { - _inherits(_class38, _svg$Element$ElementB10); - - var _super37 = _createSuper(_class38); - - function _class38(node) { - var _this21; - - _classCallCheck(this, _class38); - - _this21 = _super37.call(this, node); // text, or spaces then CDATA - - var css = ''; - - _toConsumableArray(node.childNodes).forEach(function (_ref11) { - var nodeValue = _ref11.nodeValue; - css += nodeValue; - }); // remove comments - - - css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(^\s*\/\/.*)/gm, ''); // eslint-disable-line unicorn/no-unsafe-regex - // replace whitespace - - css = svg.compressSpaces(css); - var cssDefs = css.split('}'); - cssDefs.forEach(function (cssDef) { - if (svg.trim(cssDef) !== '') { - var _cssDef$split = cssDef.split('{'), - _cssDef$split2 = _slicedToArray(_cssDef$split, 2), - cssClasses = _cssDef$split2[0], - cssProps = _cssDef$split2[1]; - - cssClasses = cssClasses.split(','); - cssProps = cssProps.split(';'); - cssClasses.forEach(function (cssClass) { - cssClass = svg.trim(cssClass); - - if (cssClass !== '') { - var props = {}; - cssProps.forEach(function (cssProp) { - var prop = cssProp.indexOf(':'); - var name = cssProp.substr(0, prop); - var value = cssProp.substr(prop + 1, cssProp.length - prop); - - if (!isNullish(name) && !isNullish(value)) { - props[svg.trim(name)] = new svg.Property(svg.trim(name), svg.trim(value)); - } - }); - svg.Styles[cssClass] = props; - - if (cssClass === '@font-face') { - var fontFamily = props['font-family'].value.replace(/"/g, ''); - var srcs = props.src.value.split(','); - srcs.forEach(function (src) { - if (src.includes('format("svg")')) { - var urlStart = src.indexOf('url'); - var urlEnd = src.indexOf(')', urlStart); - var url = src.substr(urlStart + 5, urlEnd - urlStart - 6); // Can this ajax safely be converted to async? - - var doc = svg.parseXml(svg.ajax(url)); - var fonts = doc.getElementsByTagName('font'); - - _toConsumableArray(fonts).forEach(function (font) { - font = svg.CreateElement(font); - svg.Definitions[fontFamily] = font; - }); - } - }); - } - } - }); - } - }); - return _this21; - } - - return _class38; - }(svg.Element.ElementBase); // use element - - - svg.Element.use = /*#__PURE__*/function (_svg$Element$Rendered8) { - _inherits(_class39, _svg$Element$Rendered8); - - var _super38 = _createSuper(_class39); - - function _class39(node) { - var _this22; - - _classCallCheck(this, _class39); - - _this22 = _super38.call(this, node); - _this22._el = _this22.getHrefAttribute().getDefinition(); - return _this22; - } - - _createClass(_class39, [{ - key: "setContext", - value: function setContext(ctx) { - _get(_getPrototypeOf(_class39.prototype), "setContext", this).call(this, ctx); - - if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').toPixels('x'), 0); - if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').toPixels('y')); - } - }, { - key: "path", - value: function path(ctx) { - var element = this._el; - if (!isNullish(element)) element.path(ctx); - } - }, { - key: "getBoundingBox", - value: function getBoundingBox() { - var element = this._el; - if (!isNullish(element)) return element.getBoundingBox(); - return undefined; - } - }, { - key: "renderChildren", - value: function renderChildren(ctx) { - var element = this._el; - - 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.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); - } - } - - var oldParent = tempSvg.parent; - tempSvg.parent = null; - tempSvg.render(ctx); - tempSvg.parent = oldParent; - } - } - }]); - - return _class39; - }(svg.Element.RenderedElementBase); // mask element - - - svg.Element.mask = /*#__PURE__*/function (_svg$Element$ElementB11) { - _inherits(_class40, _svg$Element$ElementB11); - - var _super39 = _createSuper(_class40); - - function _class40() { - _classCallCheck(this, _class40); - - return _super39.apply(this, arguments); - } - - _createClass(_class40, [{ - key: "apply", - value: function apply(ctx, element) { - // render as temp svg - var x = this.attribute('x').toPixels('x'); - var y = this.attribute('y').toPixels('y'); - var width = this.attribute('width').toPixels('x'); - var height = this.attribute('height').toPixels('y'); - - if (width === 0 && height === 0) { - var bb = new svg.BoundingBox(); - this.children.forEach(function (child) { - bb.addBoundingBox(child.getBoundingBox()); - }); - x = Math.floor(bb.x1); - y = Math.floor(bb.y1); - width = Math.floor(bb.width()); - height = Math.floor(bb.height()); - } // temporarily remove mask to avoid recursion - - - var mask = element.attribute('mask').value; - element.attribute('mask').value = ''; - var cMask = document.createElement('canvas'); - cMask.width = x + width; - cMask.height = y + height; - var maskCtx = cMask.getContext('2d'); - this.renderChildren(maskCtx); - var c = document.createElement('canvas'); - c.width = x + width; - c.height = y + height; - var tempCtx = c.getContext('2d'); - element.render(tempCtx); - tempCtx.globalCompositeOperation = 'destination-in'; - tempCtx.fillStyle = maskCtx.createPattern(cMask, 'no-repeat'); - tempCtx.fillRect(0, 0, x + width, y + height); - ctx.fillStyle = tempCtx.createPattern(c, 'no-repeat'); - ctx.fillRect(0, 0, x + width, y + height); // reassign mask - - element.attribute('mask').value = mask; - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class40; - }(svg.Element.ElementBase); // clip element - - - svg.Element.clipPath = /*#__PURE__*/function (_svg$Element$ElementB12) { - _inherits(_class41, _svg$Element$ElementB12); - - var _super40 = _createSuper(_class41); - - function _class41() { - _classCallCheck(this, _class41); - - return _super40.apply(this, arguments); - } - - _createClass(_class41, [{ - key: "apply", - value: function apply(ctx) { - this.children.forEach(function (child) { - if (typeof child.path !== 'undefined') { - var transform = null; - - if (child.attribute('transform').hasValue()) { - transform = new svg.Transform(child.attribute('transform').value); - transform.apply(ctx); - } - - child.path(ctx); - ctx.clip(); - - if (transform) { - transform.unapply(ctx); - } - } - }); - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class41; - }(svg.Element.ElementBase); // filters - - - svg.Element.filter = /*#__PURE__*/function (_svg$Element$ElementB13) { - _inherits(_class42, _svg$Element$ElementB13); - - var _super41 = _createSuper(_class42); - - function _class42() { - _classCallCheck(this, _class42); - - return _super41.apply(this, arguments); - } - - _createClass(_class42, [{ - key: "apply", - value: function apply(ctx, element) { - // render as temp svg - var bb = element.getBoundingBox(); - var x = Math.floor(bb.x1); - var y = Math.floor(bb.y1); - var width = Math.floor(bb.width()); - var height = Math.floor(bb.height()); // temporarily remove filter to avoid recursion - - var filter = element.style('filter').value; - element.style('filter').value = ''; - var px = 0, - py = 0; - this.children.forEach(function (child) { - var efd = child.extraFilterDistance || 0; - px = Math.max(px, efd); - py = Math.max(py, efd); - }); - var c = document.createElement('canvas'); - c.width = width + 2 * px; - c.height = height + 2 * py; - var tempCtx = c.getContext('2d'); - tempCtx.translate(-x + px, -y + py); - element.render(tempCtx); // apply filters - - this.children.forEach(function (child) { - child.apply(tempCtx, 0, 0, width + 2 * px, height + 2 * py); - }); // render on me - - ctx.drawImage(c, 0, 0, width + 2 * px, height + 2 * py, x - px, y - py, width + 2 * px, height + 2 * py); // reassign filter - - element.style('filter', true).value = filter; - } - }, { - key: "render", - value: function render(ctx) {// NO RENDER - } - }]); - - return _class42; - }(svg.Element.ElementBase); - - svg.Element.feMorphology = /*#__PURE__*/function (_svg$Element$ElementB14) { - _inherits(_class43, _svg$Element$ElementB14); - - var _super42 = _createSuper(_class43); - - function _class43() { - _classCallCheck(this, _class43); - - return _super42.apply(this, arguments); - } - - _createClass(_class43, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) {// TODO: implement - } - }]); - - return _class43; - }(svg.Element.ElementBase); - - svg.Element.feComposite = /*#__PURE__*/function (_svg$Element$ElementB15) { - _inherits(_class44, _svg$Element$ElementB15); - - var _super43 = _createSuper(_class44); - - function _class44() { - _classCallCheck(this, _class44); - - return _super43.apply(this, arguments); - } - - _createClass(_class44, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) {// TODO: implement - } - }]); - - return _class44; - }(svg.Element.ElementBase); - /** - * @param {Uint8ClampedArray} img - * @param {Integer} x - * @param {Integer} y - * @param {Float} width - * @param {Float} height - * @param {Integer} rgba - * @returns {Integer} - */ - - - 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 {void} - */ - - - function imSet(img, x, y, width, height, rgba, val) { - img[y * width * 4 + x * 4 + rgba] = val; - } - - svg.Element.feColorMatrix = /*#__PURE__*/function (_svg$Element$ElementB16) { - _inherits(_class45, _svg$Element$ElementB16); - - var _super44 = _createSuper(_class45); - - function _class45(node) { - var _this23; - - _classCallCheck(this, _class45); - - _this23 = _super44.call(this, node); - var matrix = svg.ToNumberArray(_this23.attribute('values').value); - - 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; - } - - case 'hueRotate': - { - 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; - }; - - 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]; - break; - } - - _this23.matrix = matrix; - - _this23._m = function (i, v) { - var mi = matrix[i]; - return mi * (mi < 0 ? v - 255 : v); - }; - - return _this23; - } - - _createClass(_class45, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) { - var m = this._m; // assuming x==0 && y==0 for now - - var srcData = ctx.getImageData(0, 0, width, height); - - 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)); - } - } - - ctx.clearRect(0, 0, width, height); - ctx.putImageData(srcData, 0, 0); - } - }]); - - return _class45; - }(svg.Element.ElementBase); - - svg.Element.feGaussianBlur = /*#__PURE__*/function (_svg$Element$ElementB17) { - _inherits(_class46, _svg$Element$ElementB17); - - var _super45 = _createSuper(_class46); - - function _class46(node) { - var _this24; - - _classCallCheck(this, _class46); - - _this24 = _super45.call(this, node); - _this24.blurRadius = Math.floor(_this24.attribute('stdDeviation').numValue()); - _this24.extraFilterDistance = _this24.blurRadius; - return _this24; - } - - _createClass(_class46, [{ - key: "apply", - value: function apply(ctx, x, y, width, height) { - // 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); - processCanvasRGBA(ctx.canvas, x, y, width, height, this.blurRadius); - ctx.canvas.remove(); - } - }]); - - return _class46; - }(svg.Element.ElementBase); // title element, do nothing - - - svg.Element.title = /*#__PURE__*/function (_svg$Element$ElementB18) { - _inherits(_class47, _svg$Element$ElementB18); - - var _super46 = _createSuper(_class47); - - function _class47(node) { - _classCallCheck(this, _class47); - - return _super46.call(this); - } - - return _class47; - }(svg.Element.ElementBase); // desc element, do nothing - - - svg.Element.desc = /*#__PURE__*/function (_svg$Element$ElementB19) { - _inherits(_class48, _svg$Element$ElementB19); - - var _super47 = _createSuper(_class48); - - function _class48(node) { - _classCallCheck(this, _class48); - - return _super47.call(this); - } - - return _class48; - }(svg.Element.ElementBase); - - svg.Element.MISSING = /*#__PURE__*/function (_svg$Element$ElementB20) { - _inherits(_class49, _svg$Element$ElementB20); - - var _super48 = _createSuper(_class49); - - function _class49(node) { - var _this25; - - _classCallCheck(this, _class49); - - _this25 = _super48.call(this); - svg.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); - return _this25; - } - - return _class49; - }(svg.Element.ElementBase); // element factory - - - svg.CreateElement = function (node) { - var className = node.nodeName.replace(/^[^:]+:/, '') // remove namespace - .replace(/-/g, ''); // remove dashes - - var e; - - if (typeof svg.Element[className] !== 'undefined') { - e = new svg.Element[className](node); - } else { - e = new svg.Element.MISSING(node); - } - - e.type = node.nodeName; - return e; - }; // load from url - - - svg.load = /*#__PURE__*/function () { - var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(ctx, url) { - var dom; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return svg.ajax(url, true); - - case 2: - dom = _context.sent; - return _context.abrupt("return", svg.loadXml(ctx, dom)); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function (_x2, _x3) { - return _ref12.apply(this, arguments); - }; - }(); // load from xml - - - svg.loadXml = function (ctx, xml) { - return svg.loadXmlDoc(ctx, svg.parseXml(xml)); - }; - - svg.loadXmlDoc = function (ctx, dom) { - var res; - svg.init(ctx); - - var mapXY = function mapXY(p) { - var e = ctx.canvas; - - while (e) { - p.x -= e.offsetLeft; - p.y -= e.offsetTop; - e = e.offsetParent; - } - - if (window.scrollX) p.x += window.scrollX; - if (window.scrollY) p.y += window.scrollY; - return p; - }; // bind mouse - - - if (svg.opts.ignoreMouse !== true) { - ctx.canvas.addEventListener('click', function (e) { - 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, - y = _mapXY.y; - - svg.Mouse.onclick(x, y); - }); - ctx.canvas.addEventListener('mousemove', function (e) { - 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, - y = _mapXY2.y; - - svg.Mouse.onmousemove(x, y); - }); - } - - var e = svg.CreateElement(dom.documentElement); - e.root = true; // render loop - - var isFirstRender = true; - - var draw = function draw(resolve) { - svg.ViewPort.Clear(); - - if (ctx.canvas.parentNode) { - svg.ViewPort.SetCurrent(ctx.canvas.parentNode.clientWidth, ctx.canvas.parentNode.clientHeight); - } - - if (svg.opts.ignoreDimensions !== true) { - // set canvas size - if (e.style('width').hasValue()) { - ctx.canvas.width = e.style('width').toPixels('x'); - ctx.canvas.style.width = ctx.canvas.width + 'px'; - } - - if (e.style('height').hasValue()) { - ctx.canvas.height = e.style('height').toPixels('y'); - ctx.canvas.style.height = ctx.canvas.height + 'px'; - } - } - - var cWidth = ctx.canvas.clientWidth || ctx.canvas.width; - var cHeight = ctx.canvas.clientHeight || ctx.canvas.height; - - if (svg.opts.ignoreDimensions === true && e.style('width').hasValue() && e.style('height').hasValue()) { - cWidth = e.style('width').toPixels('x'); - cHeight = e.style('height').toPixels('y'); - } - - svg.ViewPort.SetCurrent(cWidth, cHeight); - - if (!isNullish(svg.opts.offsetX)) { - e.attribute('x', true).value = svg.opts.offsetX; - } - - if (!isNullish(svg.opts.offsetY)) { - e.attribute('y', true).value = svg.opts.offsetY; - } - - if (!isNullish(svg.opts.scaleWidth) || !isNullish(svg.opts.scaleHeight)) { - var viewBox = svg.ToNumberArray(e.attribute('viewBox').value); - var xRatio = null, - yRatio = 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])) { - xRatio = viewBox[2] / svg.opts.scaleWidth; - } - } - - if (!isNullish(svg.opts.scaleHeight)) { - if (e.attribute('height').hasValue()) { - yRatio = e.attribute('height').toPixels('y') / svg.opts.scaleHeight; - } else if (!isNaN(viewBox[3])) { - yRatio = viewBox[3] / svg.opts.scaleHeight; - } - } - - if (isNullish(xRatio)) { - xRatio = yRatio; - } - - if (isNullish(yRatio)) { - yRatio = xRatio; - } - - e.attribute('width', true).value = svg.opts.scaleWidth; - e.attribute('height', true).value = svg.opts.scaleHeight; - e.attribute('viewBox', true).value = '0 0 ' + cWidth * xRatio + ' ' + cHeight * yRatio; - e.attribute('preserveAspectRatio', true).value = 'none'; - } // clear and render - - - if (svg.opts.ignoreClear !== true) { - ctx.clearRect(0, 0, cWidth, cHeight); - } - - e.render(ctx); - - if (isFirstRender) { - isFirstRender = false; - resolve(dom); - } - }; - - var waitingForImages = true; - svg.intervalID = setInterval(function () { - var needUpdate = false; - - if (waitingForImages && svg.ImagesLoaded()) { - waitingForImages = false; - needUpdate = true; - } // need update from mouse events? - - - if (svg.opts.ignoreMouse !== true) { - needUpdate = needUpdate || svg.Mouse.hasEvents(); - } // need update from animations? - - - if (svg.opts.ignoreAnimation !== true) { - svg.Animations.forEach(function (animation) { - var needAnimationUpdate = animation.update(1000 / svg.FRAMERATE); - needUpdate = needUpdate || needAnimationUpdate; - }); - } // need update from redraw? - - - if (typeof svg.opts.forceRedraw === 'function') { - if (svg.opts.forceRedraw() === true) { - needUpdate = true; - } - } // render if needed - - - if (needUpdate) { - draw(res); - svg.Mouse.runEvents(); // run and clear our events - } - }, 1000 / svg.FRAMERATE); // Todo: Replace with an image loading Promise utility? - // eslint-disable-next-line promise/avoid-new - - return new Promise(function (resolve, reject) { - if (svg.ImagesLoaded()) { - waitingForImages = false; - draw(resolve); - return; - } - - res = resolve; - }); - }; - - svg.stop = function () { - if (svg.intervalID) { - clearInterval(svg.intervalID); - } - }; - - svg.Mouse = { - events: [], - hasEvents: function hasEvents() { - return this.events.length !== 0; - }, - onclick: function onclick(x, y) { - this.events.push({ - type: 'onclick', - x: x, - y: y, - run: function run(e) { - if (e.onclick) e.onclick(); - } - }); - }, - onmousemove: function onmousemove(x, y) { - this.events.push({ - type: 'onmousemove', - x: x, - y: y, - run: function run(e) { - if (e.onmousemove) e.onmousemove(); - } - }); - }, - eventElements: [], - checkPath: function checkPath(element, ctx) { - var _this26 = this; - - this.events.forEach(function (_ref13, i) { - var x = _ref13.x, - y = _ref13.y; - - if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { - _this26.eventElements[i] = element; - } - }); - }, - checkBoundingBox: function checkBoundingBox(element, bb) { - var _this27 = this; - - this.events.forEach(function (_ref14, i) { - var x = _ref14.x, - y = _ref14.y; - - if (bb.isPointInBox(x, y)) { - _this27.eventElements[i] = element; - } - }); - }, - runEvents: function runEvents() { - var _this28 = this; - - svg.ctx.canvas.style.cursor = ''; - this.events.forEach(function (e, i) { - var element = _this28.eventElements[i]; - - while (element) { - e.run(element); - element = element.parent; - } - }); // done running, clear - - this.events = []; - this.eventElements = []; - } - }; - return svg; - } - - if (typeof CanvasRenderingContext2D !== 'undefined') { - CanvasRenderingContext2D.prototype.drawSvg = function (s, dx, dy, dw, dh) { - canvg(this.canvas, s, { - ignoreMouse: true, - ignoreAnimation: true, - ignoreDimensions: true, - ignoreClear: true, - offsetX: dx, - offsetY: dy, - scaleWidth: dw, - scaleHeight: dh - }); - }; - } - - var extServer_opensave = { - name: 'server_opensave', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { - var $, decode64, encode64, importLocale, strings, svgEditor, _svgEditor$curConfig, extPath, avoidClientSide, avoidClientSideDownload, avoidClientSideOpen, svgCanvas, getFileNameFromTitle, xhtmlEscape, clientDownloadSupport, saveSvgAction, saveImgAction, cancelled, openSvgAction, importSvgAction, importImgAction, openSvgForm, importSvgForm, importImgForm, rebuildInput; - - return regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - rebuildInput = function _rebuildInput(form) { - form.empty(); - var inp = $('
').parent().attr({ - id: modeId + '_' + id, - title: id - }); // Store for later use - - return iconBtn[0]; - }); - }; - - loadIcons = function _loadIcons() { - $('#shape_buttons').empty().append(curLib.buttons); - }; - - $ = _ref.$, importLocale = _ref.importLocale; - _context.next = 6; - return importLocale(); - - case 6: - strings = _context.sent; - svgEditor = _this; - canv = svgEditor.canvas; - svgroot = canv.getRootElem(); - lastBBox = {}; // This populates the category list - - categories = strings.categories; - /* eslint-disable max-len */ - - library = { - basic: { - data: { - heart: 'm150,73c61,-175 300,0 0,225c-300,-225 -61,-400 0,-225z', - frame: 'm0,0l300,0l0,300l-300,0zm35,-265l0,230l230,0l0,-230z', - donut: 'm1,150l0,0c0,-82.29042 66.70958,-149 149,-149l0,0c39.51724,0 77.41599,15.69816 105.35889,43.64108c27.94293,27.94293 43.64111,65.84165 43.64111,105.35892l0,0c0,82.29041 -66.70958,149 -149,149l0,0c-82.29041,0 -149,-66.70959 -149,-149zm74.5,0l0,0c0,41.1452 33.35481,74.5 74.5,74.5c41.14522,0 74.5,-33.3548 74.5,-74.5c0,-41.1452 -33.3548,-74.5 -74.5,-74.5l0,0c-41.14519,0 -74.5,33.35481 -74.5,74.5z', - triangle: 'm1,280.375l149,-260.75l149,260.75z', - right_triangle: 'm1,299l0,-298l298,298z', - diamond: 'm1,150l149,-149l149,149l-149,149l-149,-149z', - pentagon: 'm1.00035,116.97758l148.99963,-108.4053l148.99998,108.4053l-56.91267,175.4042l-184.1741,0l-56.91284,-175.4042z', - hexagon: 'm1,149.99944l63.85715,-127.71428l170.28572,0l63.85713,127.71428l-63.85713,127.71428l-170.28572,0l-63.85715,-127.71428z', - septagon1: 'm0.99917,191.06511l29.51249,-127.7108l119.48833,-56.83673l119.48836,56.83673l29.51303,127.7108l-82.69087,102.41679l-132.62103,0l-82.69031,-102.41679z', - heptagon: 'm1,88.28171l87.28172,-87.28171l123.43653,0l87.28172,87.28171l0,123.43654l-87.28172,87.28172l-123.43653,0l-87.28172,-87.28172l0,-123.43654z', - decagon: 'm1,150.00093l28.45646,-88.40318l74.49956,-54.63682l92.08794,0l74.50002,54.63682l28.45599,88.40318l-28.45599,88.40318l-74.50002,54.63681l-92.08794,0l-74.49956,-54.63681l-28.45646,-88.40318z', - dodecagon: 'm1,110.07421l39.92579,-69.14842l69.14842,-39.92579l79.85159,0l69.14842,39.92579l39.92578,69.14842l0,79.85159l-39.92578,69.14842l-69.14842,39.92578l-79.85159,0l-69.14842,-39.92578l-39.92579,-69.14842l0,-79.85159z', - star_points_5: 'm1,116.58409l113.82668,0l35.17332,-108.13487l35.17334,108.13487l113.82666,0l-92.08755,66.83026l35.17514,108.13487l-92.08759,-66.83208l-92.08757,66.83208l35.17515,-108.13487l-92.08758,-66.83026z', - trapezoid: 'm1,299l55.875,-298l186.25001,0l55.87498,298z', - arrow_up: 'm1.49805,149.64304l148.50121,-148.00241l148.50121,148.00241l-74.25061,0l0,148.71457l-148.5012,0l0,-148.71457z', - vertical_scrool: 'm37.375,261.625l0,-242.9375l0,0c0,-10.32083 8.36669,-18.6875 18.6875,-18.6875l224.25,0c10.32083,0 18.6875,8.36667 18.6875,18.6875c0,10.32081 -8.36667,18.6875 -18.6875,18.6875l-18.6875,0l0,242.9375c0,10.32083 -8.36668,18.6875 -18.6875,18.6875l-224.25,0l0,0c-10.32083,0 -18.6875,-8.36667 -18.6875,-18.6875c0,-10.32083 8.36667,-18.6875 18.6875,-18.6875zm37.375,-261.625l0,0c10.32081,0 18.6875,8.36667 18.6875,18.6875c0,10.32081 -8.36669,18.6875 -18.6875,18.6875c-5.1604,0 -9.34375,-4.18335 -9.34375,-9.34375c0,-5.16041 4.18335,-9.34375 9.34375,-9.34375l18.6875,0m186.875,18.6875l-205.5625,0m-37.375,224.25l0,0c5.1604,0 9.34375,4.18335 9.34375,9.34375c0,5.1604 -4.18335,9.34375 -9.34375,9.34375l18.6875,0m-18.6875,18.6875l0,0c10.32081,0 18.6875,-8.36667 18.6875,-18.6875l0,-18.6875', - smiley: 'm68.49886,214.78838q81.06408,55.67332 161.93891,0m-144.36983,-109.9558c0,-8.60432 6.97517,-15.57949 15.57948,-15.57949c8.60431,0 15.57948,6.97517 15.57948,15.57949c0,8.60431 -6.97517,15.57947 -15.57948,15.57947c-8.60431,0 -15.57948,-6.97516 -15.57948,-15.57947m95.83109,0c0,-8.60432 6.97517,-15.57949 15.57948,-15.57949c8.60431,0 15.57947,6.97517 15.57947,15.57949c0,8.60431 -6.97516,15.57947 -15.57947,15.57947c-8.60429,0 -15.57948,-6.97516 -15.57948,-15.57947m-181.89903,44.73038l0,0c0,-82.60133 66.96162,-149.56296 149.56296,-149.56296c82.60135,0 149.56296,66.96162 149.56296,149.56296c0,82.60135 -66.96161,149.56296 -149.56296,149.56296c-82.60133,0 -149.56296,-66.96161 -149.56296,-149.56296zm0,0l0,0c0,-82.60133 66.96162,-149.56296 149.56296,-149.56296c82.60135,0 149.56296,66.96162 149.56296,149.56296c0,82.60135 -66.96161,149.56296 -149.56296,149.56296c-82.60133,0 -149.56296,-66.96161 -149.56296,-149.56296z', - left_braket: 'm174.24565,298.5c-13.39009,0 -24.24489,-1.80908 -24.24489,-4.04065l0,-140.4187c0,-2.23158 -10.85481,-4.04065 -24.2449,-4.04065l0,0c13.39009,0 24.2449,-1.80907 24.2449,-4.04065l0,-140.4187l0,0c0,-2.23159 10.8548,-4.04066 24.24489,-4.04066', - uml_actor: 'm40.5,100l219,0m-108.99991,94.00006l107,105m-107.00009,-106.00006l-100,106m99.5,-231l0,125m33.24219,-158.75781c0,18.35916 -14.88303,33.24219 -33.24219,33.24219c-18.35916,0 -33.2422,-14.88303 -33.2422,-33.24219c0.00002,-18.35915 14.88304,-33.24219 33.2422,-33.24219c18.35916,0 33.24219,14.88304 33.24219,33.24219z', - dialog_balloon_1: 'm0.99786,35.96579l0,0c0,-19.31077 15.28761,-34.96524 34.14583,-34.96524l15.52084,0l0,0l74.50001,0l139.68748,0c9.05606,0 17.74118,3.68382 24.14478,10.24108c6.40356,6.55726 10.00107,15.45081 10.00107,24.72416l0,87.41311l0,0l0,52.44785l0,0c0,19.31078 -15.2876,34.96524 -34.14584,34.96524l-139.68748,0l-97.32507,88.90848l22.82506,-88.90848l-15.52084,0c-18.85822,0 -34.14583,-15.65446 -34.14583,-34.96524l0,0l0,-52.44785l0,0z', - cloud: 'm182.05086,34.31005c-0.64743,0.02048 -1.27309,0.07504 -1.92319,0.13979c-10.40161,1.03605 -19.58215,7.63722 -24.24597,17.4734l-2.47269,7.44367c0.53346,-2.57959 1.35258,-5.08134 2.47269,-7.44367c-8.31731,-8.61741 -19.99149,-12.59487 -31.52664,-10.72866c-11.53516,1.8662 -21.55294,9.3505 -27.02773,20.19925c-15.45544,-9.51897 -34.72095,-8.94245 -49.62526,1.50272c-14.90431,10.44516 -22.84828,28.93916 -20.43393,47.59753l1.57977,7.58346c-0.71388,-2.48442 -1.24701,-5.01186 -1.57977,-7.58346l-0.2404,0.69894c-12.95573,1.4119 -23.58103,11.46413 -26.34088,24.91708c-2.75985,13.45294 2.9789,27.25658 14.21789,34.21291l17.54914,4.26352c-6.1277,0.50439 -12.24542,-0.9808 -17.54914,-4.26352c-8.66903,9.71078 -10.6639,24.08736 -4.94535,35.96027c5.71854,11.87289 17.93128,18.70935 30.53069,17.15887l7.65843,-2.02692c-2.46413,1.0314 -5.02329,1.70264 -7.65843,2.02692c7.15259,13.16728 19.01251,22.77237 32.93468,26.5945c13.92217,3.82214 28.70987,1.56322 41.03957,-6.25546c10.05858,15.86252 27.91113,24.19412 45.81322,21.38742c17.90208,-2.8067 32.66954,-16.26563 37.91438,-34.52742l1.82016,-10.20447c-0.27254,3.46677 -0.86394,6.87508 -1.82016,10.20447c12.31329,8.07489 27.80199,8.52994 40.52443,1.18819c12.72244,-7.34175 20.6609,-21.34155 20.77736,-36.58929l-4.56108,-22.7823l-17.96776,-15.41455c13.89359,8.70317 22.6528,21.96329 22.52884,38.19685c16.5202,0.17313 30.55292,-13.98268 36.84976,-30.22897c6.29684,-16.24631 3.91486,-34.76801 -6.2504,-48.68089c4.21637,-10.35873 3.96622,-22.14172 -0.68683,-32.29084c-4.65308,-10.14912 -13.23602,-17.69244 -23.55914,-20.65356c-2.31018,-13.45141 -11.83276,-24.27162 -24.41768,-27.81765c-12.58492,-3.54603 -25.98557,0.82654 -34.41142,11.25287l-5.11707,8.63186c1.30753,-3.12148 3.01521,-6.03101 5.11707,-8.63186c-5.93959,-8.19432 -15.2556,-12.8181 -24.96718,-12.51096z', - cylinder: 'm299.0007,83.77844c0,18.28676 -66.70958,33.11111 -149.00002,33.11111m149.00002,-33.11111l0,0c0,18.28676 -66.70958,33.11111 -149.00002,33.11111c-82.29041,0 -148.99997,-14.82432 -148.99997,-33.11111m0,0l0,0c0,-18.28674 66.70956,-33.1111 148.99997,-33.1111c82.29044,0 149.00002,14.82436 149.00002,33.1111l0,132.44449c0,18.28674 -66.70958,33.11105 -149.00002,33.11105c-82.29041,0 -148.99997,-14.82431 -148.99997,-33.11105z', - arrow_u_turn: 'm1.00059,299.00055l0,-167.62497l0,0c0,-72.00411 58.37087,-130.37499 130.375,-130.37499l0,0l0,0c34.57759,0 67.73898,13.7359 92.18906,38.18595c24.45006,24.45005 38.18593,57.61144 38.18593,92.18904l0,18.625l37.24997,0l-74.49995,74.50002l-74.50002,-74.50002l37.25,0l0,-18.625c0,-30.8589 -25.0161,-55.87498 -55.87498,-55.87498l0,0l0,0c-30.85892,0 -55.875,25.01608 -55.875,55.87498l0,167.62497z', - arrow_left_up: 'm0.99865,224.5l74.50004,-74.5l0,37.25l111.74991,0l0,-111.75l-37.25,0l74.5,-74.5l74.5,74.5l-37.25,0l0,186.25l-186.24989,0l0,37.25l-74.50005,-74.5z', - maximize: 'm1.00037,150.34581l55.30305,-55.30267l0,27.65093l22.17356,0l0,-44.21833l44.21825,0l0,-22.17357l-27.65095,0l55.30267,-55.30292l55.3035,55.30292l-27.65175,0l0,22.17357l44.21835,0l0,44.21833l22.17357,0l0,-27.65093l55.30345,55.30267l-55.30345,55.3035l0,-27.65175l-22.17357,0l0,44.21834l-44.21835,0l0,22.17355l27.65175,0l-55.3035,55.30348l-55.30267,-55.30348l27.65095,0l0,-22.17355l-44.21825,0l0,-44.21834l-22.17356,0l0,27.65175l-55.30305,-55.3035z', - cross: 'm0.99844,99.71339l98.71494,0l0,-98.71495l101.26279,0l0,98.71495l98.71495,0l0,101.2628l-98.71495,0l0,98.71494l-101.26279,0l0,-98.71494l-98.71494,0z', - plaque: 'm-0.00197,49.94376l0,0c27.5829,0 49.94327,-22.36036 49.94327,-49.94327l199.76709,0l0,0c0,27.5829 22.36037,49.94327 49.94325,49.94327l0,199.7671l0,0c-27.58289,0 -49.94325,22.36034 -49.94325,49.94325l-199.76709,0c0,-27.58292 -22.36037,-49.94325 -49.94327,-49.94325z', - page: 'm249.3298,298.99744l9.9335,-39.73413l39.73413,-9.93355l-49.66763,49.66768l-248.33237,0l0,-298.00001l298.00001,0l0,248.33234' - }, - buttons: [] - } - }; - /* eslint-enable max-len */ - - modeId = 'shapelib'; - startClientPos = {}; - curLib = library.basic; - /** - * - * @returns {void} - */ - - buttons = [{ - id: 'tool_shapelib', - icon: svgEditor.curConfig.extIconsPath + 'shapes.png', - type: 'mode_flyout', - // _flyout - position: 6, - events: { - click: function click() { - canv.setMode(modeId); - } - } - }]; - return _context.abrupt("return", { - svgicons: svgEditor.curConfig.extIconsPath + 'ext-shapes.xml', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - callback: function callback() { - $('').appendTo('head'); - } - - fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }'); - $('#star_panel').toggle(on); - }; - - svgEditor = _this; - svgCanvas = svgEditor.canvas; - $ = S.$, importLocale = S.importLocale; // {svgcontent}, - - _context.next = 7; - return importLocale(); - - case 7: - strings = _context.sent; - - /* - function cot(n){ - return 1 / Math.tan(n); - } - function sec(n){ - return 1 / Math.cos(n); - } - */ - buttons = [{ - id: 'tool_star', - icon: svgEditor.curConfig.extIconsPath + 'star.png', - type: 'mode', - position: 12, - events: { - click: function click() { - showPanel(true); - svgCanvas.setMode('star'); - } - } - }]; - contextTools = [{ - type: 'input', - panel: 'star_panel', - id: 'starNumPoints', - size: 3, - defval: 5, - events: { - change: function change() { - setAttr('point', this.value); - } - } - }, { - type: 'input', - panel: 'star_panel', - id: 'starRadiusMulitplier', - size: 3, - defval: 2.5 - }, { - type: 'input', - panel: 'star_panel', - id: 'radialShift', - size: 3, - defval: 0, - events: { - change: function change() { - setAttr('radialshift', this.value); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'star-icons.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - context_tools: strings.contextTools.map(function (contextTool, i) { - return Object.assign(contextTools[i], contextTool); - }), - callback: function callback() { - $('#star_panel').hide(); // const endChanges = function(){}; - }, - mouseDown: function mouseDown(opts) { - var rgb = svgCanvas.getColor('fill'); // const ccRgbEl = rgb.substring(1, rgb.length); - - var sRgb = svgCanvas.getColor('stroke'); // const ccSRgbEl = sRgb.substring(1, rgb.length); - - var sWidth = svgCanvas.getStrokeWidth(); - - if (svgCanvas.getMode() === 'star') { - started = true; - newFO = svgCanvas.addSVGElementFromJson({ - element: 'polygon', - attr: { - cx: opts.start_x, - cy: opts.start_y, - id: svgCanvas.getNextId(), - shape: 'star', - point: document.getElementById('starNumPoints').value, - r: 0, - radialshift: document.getElementById('radialShift').value, - r2: 0, - orient: 'point', - fill: rgb, - strokecolor: sRgb, - strokeWidth: sWidth - } - }); - return { - started: true - }; - } - - return undefined; - }, - mouseMove: function mouseMove(opts) { - if (!started) { - return undefined; - } - - if (svgCanvas.getMode() === 'star') { - var c = $(newFO).attr(['cx', 'cy', 'point', 'orient', 'fill', 'strokecolor', 'strokeWidth', 'radialshift']); - var x = opts.mouse_x; - var y = opts.mouse_y; - var cx = c.cx, - cy = c.cy, - fill = c.fill, - strokecolor = c.strokecolor, - strokeWidth = c.strokeWidth, - radialshift = c.radialshift, - point = c.point, - orient = c.orient, - circumradius = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5, - inradius = circumradius / document.getElementById('starRadiusMulitplier').value; - newFO.setAttribute('r', circumradius); - newFO.setAttribute('r2', inradius); - var polyPoints = ''; - - for (var s = 0; point >= s; s++) { - var angle = 2.0 * Math.PI * (s / point); - - if (orient === 'point') { - angle -= Math.PI / 2; - } else if (orient === 'edge') { - angle = angle + Math.PI / point - Math.PI / 2; - } - - x = circumradius * Math.cos(angle) + cx; - y = circumradius * Math.sin(angle) + cy; - polyPoints += x + ',' + y + ' '; - - if (!isNaN(inradius)) { - angle = 2.0 * Math.PI * (s / point) + Math.PI / point; - - if (orient === 'point') { - angle -= Math.PI / 2; - } else if (orient === 'edge') { - angle = angle + Math.PI / point - Math.PI / 2; - } - - angle += radialshift; - x = inradius * Math.cos(angle) + cx; - y = inradius * Math.sin(angle) + cy; - polyPoints += x + ',' + y + ' '; - } - } - - newFO.setAttribute('points', polyPoints); - newFO.setAttribute('fill', fill); - newFO.setAttribute('stroke', strokecolor); - newFO.setAttribute('stroke-width', strokeWidth); - /* const shape = */ - - newFO.getAttribute('shape'); - return { - started: true - }; - } - - return undefined; - }, - mouseUp: function mouseUp() { - if (svgCanvas.getMode() === 'star') { - var attrs = $(newFO).attr(['r']); // svgCanvas.addToSelection([newFO], true); - - return { - keep: attrs.r !== '0', - element: newFO - }; - } - - return undefined; - }, - selectedChanged: function selectedChanged(opts) { - // Use this to update the current selected elements - selElems = opts.elems; - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (elem && elem.getAttribute('shape') === 'star') { - if (opts.selectedElement && !opts.multiselected) { - // $('#starRadiusMulitplier').val(elem.getAttribute('r2')); - $('#starNumPoints').val(elem.getAttribute('point')); - $('#radialShift').val(elem.getAttribute('radialshift')); - showPanel(true); - } else { - showPanel(false); - } - } else { - showPanel(false); - } - } - }, - elementChanged: function elementChanged(opts) {// const elem = opts.elems[0]; - } - }); - - case 11: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }; - - return extStar; - -}()); diff --git a/dist/extensions/ext-storage.js b/dist/extensions/ext-storage.js deleted file mode 100644 index 50dfa718..00000000 --- a/dist/extensions/ext-storage.js +++ /dev/null @@ -1,444 +0,0 @@ -var svgEditorExtension_storage = (function () { - 'use strict'; - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - - function _iterableToArrayLimit(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - /** - * @file ext-storage.js - * - * This extension allows automatic saving of the SVG canvas contents upon - * page unload (which can later be automatically retrieved upon future - * editor loads). - * - * The functionality was originally part of the SVG Editor, but moved to a - * separate extension to make the setting behavior optional, and adapted - * to inform the user of its setting of local data. - * - * @license MIT - * - * @copyright 2010 Brett Zamir - * @todo Revisit on whether to use `svgEditor.pref` over directly setting - * `curConfig` in all extensions for a more public API (not only for `extPath` - * and `imagePath`, but other currently used config in the extensions) - * @todo We might provide control of storage settings through the UI besides the - * initial (or URL-forced) dialog. * - */ - var extStorage = { - name: 'storage', - init: function init(_ref) { - var $ = _ref.$; - var svgEditor = this; - var svgCanvas = svgEditor.canvas; // We could empty any already-set data for users when they decline storage, - // but it would be a risk for users who wanted to store but accidentally - // said "no"; instead, we'll let those who already set it, delete it themselves; - // to change, set the "emptyStorageOnDecline" config setting to true - // in svgedit-config-iife.js/svgedit-config-es.js. - - var _svgEditor$curConfig = svgEditor.curConfig, - emptyStorageOnDecline = _svgEditor$curConfig.emptyStorageOnDecline, - noStorageOnLoad = _svgEditor$curConfig.noStorageOnLoad, - forceStorage = _svgEditor$curConfig.forceStorage; - var storage = svgEditor.storage, - updateCanvas = svgEditor.updateCanvas; - /** - * Replace `storagePrompt` parameter within URL. - * @param {string} val - * @returns {void} - * @todo Replace the string manipulation with `searchParams.set` - */ - - function replaceStoragePrompt(val) { - val = val ? 'storagePrompt=' + val : ''; - var loc = top.location; // Allow this to work with the embedded editor as well - - if (loc.href.includes('storagePrompt=')) { - /* - loc.href = loc.href.replace(/(?[&?])storagePrompt=[^&]*(?&?)/, function (n0, sep, amp) { - return (val ? sep : '') + val + (!val && amp ? sep : (amp || '')); - }); - */ - loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) { - return (val ? n1 : '') + val + (!val && amp ? n1 : amp || ''); - }); - } else { - loc.href += (loc.href.includes('?') ? '&' : '?') + val; - } - } - /** - * Sets SVG content as a string with "svgedit-" and the current - * canvas name as namespace. - * @param {string} val - * @returns {void} - */ - - - function setSVGContentStorage(val) { - if (storage) { - var name = 'svgedit-' + svgEditor.curConfig.canvasName; - - if (!val) { - storage.removeItem(name); - } else { - storage.setItem(name, val); - } - } - } - /** - * Set the cookie to expire. - * @param {string} cookie - * @returns {void} - */ - - - function expireCookie(cookie) { - document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'; - } - /** - * Expire the storage cookie. - * @returns {void} - */ - - - function removeStoragePrefCookie() { - expireCookie('svgeditstore'); - } - /** - * Empties storage for each of the current preferences. - * @returns {void} - */ - - - function emptyStorage() { - setSVGContentStorage(''); - Object.keys(svgEditor.curPrefs).forEach(function (name) { - name = 'svg-edit-' + name; - - if (storage) { - storage.removeItem(name); - } - - expireCookie(name); - }); - } // emptyStorage(); - - /** - * Listen for unloading: If and only if opted in by the user, set the content - * document and preferences into storage: - * 1. Prevent save warnings (since we're automatically saving unsaved - * content into storage) - * 2. Use localStorage to set SVG contents (potentially too large to allow in cookies) - * 3. Use localStorage (where available) or cookies to set preferences. - * @returns {void} - */ - - - function setupBeforeUnloadListener() { - window.addEventListener('beforeunload', function (e) { - // Don't save anything unless the user opted in to storage - if (!document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/)) { - return; - } - - if (document.cookie.match(/(?:^|;\s*)svgeditstore=prefsAndContent/)) { - setSVGContentStorage(svgCanvas.getSvgString()); - } - - svgEditor.setConfig({ - no_save_warning: true - }); // No need for explicit saving at all once storage is on - // svgEditor.showSaveWarning = false; - - var curPrefs = svgEditor.curPrefs; - Object.entries(curPrefs).forEach(function (_ref2) { - var _ref3 = _slicedToArray(_ref2, 2), - key = _ref3[0], - val = _ref3[1]; - - var store = val !== undefined; - key = 'svg-edit-' + key; - - if (!store) { - return; - } - - if (storage) { - storage.setItem(key, val); - } else if (window.widget) { - window.widget.setPreferenceForKey(val, key); - } else { - val = encodeURIComponent(val); - document.cookie = encodeURIComponent(key) + '=' + val + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; - } - }); - }); - } - - var loaded = false; - return { - name: 'storage', - langReady: function langReady(_ref4) { - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var importLocale, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight, _yield$$$select, pref, checked; - - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - importLocale = _ref4.importLocale; - storagePrompt = new URL(top.location).searchParams.get('storagePrompt'); - _context.next = 4; - return importLocale(); - - case 4: - confirmSetStorage = _context.sent; - message = confirmSetStorage.message, storagePrefsAndContent = confirmSetStorage.storagePrefsAndContent, storagePrefsOnly = confirmSetStorage.storagePrefsOnly, storagePrefs = confirmSetStorage.storagePrefs, storageNoPrefsOrContent = confirmSetStorage.storageNoPrefsOrContent, storageNoPrefs = confirmSetStorage.storageNoPrefs, rememberLabel = confirmSetStorage.rememberLabel, rememberTooltip = confirmSetStorage.rememberTooltip; // No need to run this one-time dialog again just because the user - // changes the language - - if (!loaded) { - _context.next = 8; - break; - } - - return _context.abrupt("return"); - - case 8: - loaded = true; // Note that the following can load even if "noStorageOnLoad" is - // set to false; to avoid any chance of storage, avoid this - // extension! (and to avoid using any prior storage, set the - // config option "noStorageOnLoad" to true). - - if (!(!forceStorage && ( // If the URL has been explicitly set to always prompt the - // user (e.g., so one can be pointed to a URL where one - // can alter one's settings, say to prevent future storage)... - storagePrompt === 'true' || // ...or...if the URL at least doesn't explicitly prevent a - // storage prompt (as we use for users who - // don't want to set cookies at all but who don't want - // continual prompts about it)... - storagePrompt !== 'false' && // ...and this user hasn't previously indicated a desire for storage - !document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/) // ...then show the storage prompt. - ))) { - _context.next = 44; - break; - } - - options = []; - - if (storage) { - options.unshift({ - value: 'prefsAndContent', - text: storagePrefsAndContent - }, { - value: 'prefsOnly', - text: storagePrefsOnly - }, { - value: 'noPrefsOrContent', - text: storageNoPrefsOrContent - }); - } else { - options.unshift({ - value: 'prefsOnly', - text: storagePrefs - }, { - value: 'noPrefsOrContent', - text: storageNoPrefs - }); - } // Hack to temporarily provide a wide and high enough dialog - - - oldContainerWidth = $('#dialog_container')[0].style.width, oldContainerMarginLeft = $('#dialog_container')[0].style.marginLeft, oldContentHeight = $('#dialog_content')[0].style.height, oldContainerHeight = $('#dialog_container')[0].style.height; - $('#dialog_content')[0].style.height = '120px'; - $('#dialog_container')[0].style.height = '170px'; - $('#dialog_container')[0].style.width = '800px'; - $('#dialog_container')[0].style.marginLeft = '-400px'; // Open select-with-checkbox dialog - // From svg-editor.js - - svgEditor.storagePromptState = 'waiting'; - _context.next = 20; - return $.select(message, options, null, null, { - label: rememberLabel, - checked: true, - tooltip: rememberTooltip - }); - - case 20: - _yield$$$select = _context.sent; - pref = _yield$$$select.response; - checked = _yield$$$select.checked; - - if (!(pref && pref !== 'noPrefsOrContent')) { - _context.next = 30; - break; - } - - // Regardless of whether the user opted - // to remember the choice (and move to a URL which won't - // ask them again), we have to assume the user - // doesn't even want to remember their not wanting - // storage, so we don't set the cookie or continue on with - // setting storage on beforeunload - document.cookie = 'svgeditstore=' + encodeURIComponent(pref) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; // 'prefsAndContent' | 'prefsOnly' - // If the URL was configured to always insist on a prompt, if - // the user does indicate a wish to store their info, we - // don't want ask them again upon page refresh so move - // them instead to a URL which does not always prompt - - if (!(storagePrompt === 'true' && checked)) { - _context.next = 28; - break; - } - - replaceStoragePrompt(); - return _context.abrupt("return"); - - case 28: - _context.next = 35; - break; - - case 30: - // The user does not wish storage (or cancelled, which we treat equivalently) - removeStoragePrefCookie(); - - if (pref && // If the user explicitly expresses wish for no storage - emptyStorageOnDecline) { - emptyStorage(); - } - - if (!(pref && checked)) { - _context.next = 35; - break; - } - - // Open a URL which won't set storage and won't prompt user about storage - replaceStoragePrompt('false'); - return _context.abrupt("return"); - - case 35: - // Reset width/height of dialog (e.g., for use by Export) - $('#dialog_container')[0].style.width = oldContainerWidth; - $('#dialog_container')[0].style.marginLeft = oldContainerMarginLeft; - $('#dialog_content')[0].style.height = oldContentHeight; - $('#dialog_container')[0].style.height = oldContainerHeight; // It should be enough to (conditionally) add to storage on - // beforeunload, but if we wished to update immediately, - // we might wish to try setting: - // svgEditor.setConfig({noStorageOnLoad: true}); - // and then call: - // svgEditor.loadContentAndPrefs(); - // We don't check for noStorageOnLoad here because - // the prompt gives the user the option to store data - - setupBeforeUnloadListener(); - svgEditor.storagePromptState = 'closed'; - updateCanvas(true); - _context.next = 45; - break; - - case 44: - if (!noStorageOnLoad || forceStorage) { - setupBeforeUnloadListener(); - } - - case 45: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }; - } - }; - - return extStorage; - -}()); diff --git a/dist/extensions/ext-webappfind.js b/dist/extensions/ext-webappfind.js deleted file mode 100644 index 728e0f3c..00000000 --- a/dist/extensions/ext-webappfind.js +++ /dev/null @@ -1,178 +0,0 @@ -var svgEditorExtension_webappfind = (function () { - 'use strict'; - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - /** - * Depends on Firefox add-on and executables from - * {@link https://github.com/brettz9/webappfind}. - * @author Brett Zamir - * @license MIT - * @todo See WebAppFind Readme for SVG-related todos - */ - var extWebappfind = { - name: 'webappfind', - init: function init(_ref) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var importLocale, $, strings, svgEditor, saveMessage, readMessage, excludedMessages, pathID, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - importLocale = _ref.importLocale, $ = _ref.$; - _context.next = 3; - return importLocale(); - - case 3: - strings = _context.sent; - svgEditor = _this; - saveMessage = 'save', readMessage = 'read', excludedMessages = [readMessage, saveMessage]; - - _this.canvas.bind('message', - /** - * @param {external:Window} win - * @param {PlainObject} info - * @param {module:svgcanvas.SvgCanvas#event:message} info.data - * @param {string} info.origin - * @listens module:svgcanvas.SvgCanvas#event:message - * @throws {Error} Unexpected event type - * @returns {void} - */ - function (win, _ref2) { - var data = _ref2.data, - origin = _ref2.origin; - // eslint-disable-line no-shadow - // console.log('data, origin', data, origin); - var type, content; - - try { - var _data$webappfind = data.webappfind; - type = _data$webappfind.type; - pathID = _data$webappfind.pathID; - content = _data$webappfind.content; - - // May throw if data is not an object - if (origin !== location.origin || // We are only interested in a message sent as though within this URL by our browser add-on - excludedMessages.includes(type) // Avoid our post below (other messages might be possible in the future which may also need to be excluded if your subsequent code makes assumptions on the type of message this is) - ) { - return; - } - } catch (err) { - return; - } - - switch (type) { - case 'view': - // Populate the contents - svgEditor.loadFromString(content); - /* if ($('#tool_save_file')) { - $('#tool_save_file').disabled = false; - } */ - - break; - - case 'save-end': - $.alert("save complete for pathID ".concat(pathID, "!")); - break; - - default: - throw new Error('Unexpected WebAppFind event type'); - } - }); - /* - window.postMessage({ - webappfind: { - type: readMessage - } - }, window.location.origin === 'null' - // Avoid "null" string error for `file:` protocol (even though - // file protocol not currently supported by Firefox) - ? '*' - : window.location.origin - ); - */ - - - buttons = [{ - id: 'webappfind_save', - // - icon: svgEditor.curConfig.extIconsPath + 'webappfind.png', - type: 'app_menu', - position: 4, - // Before 0-based index position 4 (after the regular "Save Image (S)") - events: { - click: function click() { - if (!pathID) { - // Not ready yet as haven't received first payload - return; - } - - window.postMessage({ - webappfind: { - type: saveMessage, - pathID: pathID, - content: svgEditor.canvas.getSvgString() - } - }, window.location.origin === 'null' // Avoid "null" string error for `file:` protocol (even - // though file protocol not currently supported by add-on) - ? '*' : window.location.origin); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.extIconsPath + 'webappfind-icon.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }) - }); - - case 9: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }; - - return extWebappfind; - -}()); diff --git a/dist/extensions/ext-xdomain-messaging.js b/dist/extensions/ext-xdomain-messaging.js deleted file mode 100644 index caca2fa1..00000000 --- a/dist/extensions/ext-xdomain-messaging.js +++ /dev/null @@ -1,114 +0,0 @@ -var svgEditorExtension_xdomain_messaging = (function () { - 'use strict'; - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - /** - * Should not be needed for same domain control (just call via child frame), - * but an API common for cross-domain and same domain use can be found - * in embedapi.js with a demo at embedapi.html. - */ - var extXdomainMessaging = { - name: 'xdomain-messaging', - init: function init() { - var svgEditor = this; - var svgCanvas = svgEditor.canvas; - - try { - window.addEventListener('message', function (e) { - // We accept and post strings for the sake of IE9 support - if (!e.data || !['string', 'object'].includes(_typeof(e.data)) || e.data.charAt() === '|') { - return; - } - - var data = _typeof(e.data) === 'object' ? e.data : JSON.parse(e.data); - - if (!data || _typeof(data) !== 'object' || data.namespace !== 'svgCanvas') { - return; - } // The default is not to allow any origins, including even the same domain or - // if run on a `file:///` URL. See `svgedit-config-es.js` for an example of how - // to configure - - - var allowedOrigins = svgEditor.curConfig.allowedOrigins; - - if (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) { - console.log("Origin ".concat(e.origin, " not whitelisted for posting to ").concat(window.origin)); // eslint-disable-line no-console - - return; - } - - var cbid = data.id; - var name = data.name, - args = data.args; - var message = { - namespace: 'svg-edit', - id: cbid - }; - - try { - // Now that we know the origin is trusted, we perform otherwise - // unsafe arbitrary canvas method execution - message.result = svgCanvas[name].apply(svgCanvas, _toConsumableArray(args)); // lgtm [js/remote-property-injection] - } catch (err) { - message.error = err.message; - } - - e.source.postMessage(JSON.stringify(message), '*'); - }); - } catch (err) { - console.log('Error with xdomain message listener: ' + err); // eslint-disable-line no-console - } - } - }; - - return extXdomainMessaging; - -}()); diff --git a/dist/extensions/imagelib/index.js b/dist/extensions/imagelib/index.js deleted file mode 100644 index 47afc0f6..00000000 --- a/dist/extensions/imagelib/index.js +++ /dev/null @@ -1,84 +0,0 @@ -(function () { - 'use strict'; - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - /* globals jQuery */ - var $ = jQuery; - $('a').click(function () { - var href = this.href; - var target = window.parent; - - var post = function post(message) { - // Todo: Make origin customizable as set by opening window - // Todo: If dropping IE9, avoid stringifying - target.postMessage(JSON.stringify(_extends({ - namespace: 'imagelib' - }, message)), '*'); - }; // Convert Non-SVG images to data URL first - // (this could also have been done server-side by the library) - // Send metadata (also indicates file is about to be sent) - - - post({ - name: $(this).text(), - id: href - }); - - if (!href.includes('.svg')) { - var img = new Image(); - img.addEventListener('load', function () { - var canvas = document.createElement('canvas'); - canvas.width = this.width; - canvas.height = this.height; // load the raster image into the canvas - - canvas.getContext('2d').drawImage(this, 0, 0); // retrieve the data: URL - - var data; - - try { - data = canvas.toDataURL(); - } catch (err) { - // This fails in Firefox with `file:///` URLs :( - // Todo: This could use a generic alert library instead - alert('Data URL conversion failed: ' + err); // eslint-disable-line no-alert - - data = ''; - } - - post({ - href: href, - data: data - }); - }); - img.src = href; - } else { - // Do ajax request for image's href value - $.get(href, function (data) { - post({ - href: href, - data: data - }); - }, 'html'); // 'html' is necessary to keep returned data as a string - } - - return false; - }); - -}()); diff --git a/dist/extensions/imagelib/openclipart.js b/dist/extensions/imagelib/openclipart.js deleted file mode 100644 index 3206b4c2..00000000 --- a/dist/extensions/imagelib/openclipart.js +++ /dev/null @@ -1,3468 +0,0 @@ -(function () { - 'use strict'; - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - - function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); - } - - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; - } - - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - - return object; - } - - function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.get) { - return desc.get.call(receiver); - } - - return desc.value; - }; - } - - return _get(target, property, receiver || target); - } - - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); - } - - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; - } - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _iterableToArrayLimit(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - /* - Possible todos: - 0. Add XSLT to JML-string stylesheet (or even vice versa) - 0. IE problem: Add JsonML code to handle name attribute (during element creation) - 0. Element-specific: IE object-param handling - - Todos inspired by JsonML: https://github.com/mckamey/jsonml/blob/master/jsonml-html.js - - 0. duplicate attributes? - 0. expand ATTR_MAP - 0. equivalent of markup, to allow strings to be embedded within an object (e.g., {$value: '
id
'}); advantage over innerHTML in that it wouldn't need to work as the entire contents (nor destroy any existing content or handlers) - 0. More validation? - 0. JsonML DOM Level 0 listener - 0. Whitespace trimming? - - JsonML element-specific: - 0. table appending - 0. canHaveChildren necessary? (attempts to append to script and img) - - Other Todos: - 0. Note to self: Integrate research from other jml notes - 0. Allow Jamilih to be seeded with an existing element, so as to be able to add/modify attributes and children - 0. Allow array as single first argument - 0. Settle on whether need to use null as last argument to return array (or fragment) or other way to allow appending? Options object at end instead to indicate whether returning array, fragment, first element, etc.? - 0. Allow building of generic XML (pass configuration object) - 0. Allow building content internally as a string (though allowing DOM methods, etc.?) - 0. Support JsonML empty string element name to represent fragments? - 0. Redo browser testing of jml (including ensuring IE7 can work even if test framework can't work) - */ - // istanbul ignore next - var win = typeof window !== 'undefined' && window; // istanbul ignore next - - var doc = typeof document !== 'undefined' && document || win && win.document; // STATIC PROPERTIES - - var possibleOptions = ['$plugins', // '$mode', // Todo (SVG/XML) - // '$state', // Used internally - '$map' // Add any other options here - ]; - var NS_HTML = 'http://www.w3.org/1999/xhtml', - hyphenForCamelCase = /\x2D([a-z])/g; - var ATTR_MAP = { - maxlength: 'maxLength', - minlength: 'minLength', - readonly: 'readOnly' - }; // We define separately from ATTR_DOM for clarity (and parity with JsonML) but no current need - // We don't set attribute esp. for boolean atts as we want to allow setting of `undefined` - // (e.g., from an empty variable) on templates to have no effect - - var BOOL_ATTS = ['checked', 'defaultChecked', 'defaultSelected', 'disabled', 'indeterminate', 'open', // Dialog elements - 'readOnly', 'selected']; // From JsonML - - var ATTR_DOM = BOOL_ATTS.concat(['accessKey', // HTMLElement - 'async', 'autocapitalize', // HTMLElement - 'autofocus', 'contentEditable', // HTMLElement through ElementContentEditable - 'defaultValue', 'defer', 'draggable', // HTMLElement - 'formnovalidate', 'hidden', // HTMLElement - 'innerText', // HTMLElement - 'inputMode', // HTMLElement through ElementContentEditable - 'ismap', 'multiple', 'novalidate', 'pattern', 'required', 'spellcheck', // HTMLElement - 'translate', // HTMLElement - 'value', 'willvalidate']); // Todo: Add more to this as useful for templating - // to avoid setting through nullish value - - var NULLABLES = ['autocomplete', 'dir', // HTMLElement - 'integrity', // script, link - 'lang', // HTMLElement - 'max', 'min', 'minLength', 'maxLength', 'title' // HTMLElement - ]; - - var $ = function $(sel) { - return doc.querySelector(sel); - }; - /** - * Retrieve the (lower-cased) HTML name of a node. - * @static - * @param {Node} node The HTML node - * @returns {string} The lower-cased node name - */ - - - function _getHTMLNodeName(node) { - return node.nodeName && node.nodeName.toLowerCase(); - } - /** - * Apply styles if this is a style tag. - * @static - * @param {Node} node The element to check whether it is a style tag - * @returns {void} - */ - - - function _applyAnyStylesheet(node) { - // Only used in IE - // istanbul ignore else - if (!doc.createStyleSheet) { - return; - } // istanbul ignore next - - - if (_getHTMLNodeName(node) === 'style') { - // IE - var ss = doc.createStyleSheet(); // Create a stylesheet to actually do something useful - - ss.cssText = node.cssText; // We continue to add the style tag, however - } - } - /** - * Need this function for IE since options weren't otherwise getting added. - * @private - * @static - * @param {Element} parent The parent to which to append the element - * @param {Node} child The element or other node to append to the parent - * @returns {void} - */ - - - function _appendNode(parent, child) { - var parentName = _getHTMLNodeName(parent); // IE only - // istanbul ignore if - - - if (doc.createStyleSheet) { - if (parentName === 'script') { - parent.text = child.nodeValue; - return; - } - - if (parentName === 'style') { - parent.cssText = child.nodeValue; // This will not apply it--just make it available within the DOM cotents - - return; - } - } - - if (parentName === 'template') { - parent.content.append(child); - return; - } - - try { - parent.append(child); // IE9 is now ok with this - } catch (e) { - // istanbul ignore next - var childName = _getHTMLNodeName(child); // istanbul ignore next - - - if (parentName === 'select' && childName === 'option') { - try { - // Since this is now DOM Level 4 standard behavior (and what IE7+ can handle), we try it first - parent.add(child); - } catch (err) { - // DOM Level 2 did require a second argument, so we try it too just in case the user is using an older version of Firefox, etc. - parent.add(child, null); // IE7 has a problem with this, but IE8+ is ok - } - - return; - } // istanbul ignore next - - - throw e; - } - } - /** - * Attach event in a cross-browser fashion. - * @static - * @param {Element} el DOM element to which to attach the event - * @param {string} type The DOM event (without 'on') to attach to the element - * @param {EventListener} handler The event handler to attach to the element - * @param {boolean} [capturing] Whether or not the event should be - * capturing (W3C-browsers only); default is false; NOT IN USE - * @returns {void} - */ - - - function _addEvent(el, type, handler, capturing) { - el.addEventListener(type, handler, Boolean(capturing)); - } - /** - * Creates a text node of the result of resolving an entity or character reference. - * @param {'entity'|'decimal'|'hexadecimal'} type Type of reference - * @param {string} prefix Text to prefix immediately after the "&" - * @param {string} arg The body of the reference - * @returns {Text} The text node of the resolved reference - */ - - - function _createSafeReference(type, prefix, arg) { - // For security reasons related to innerHTML, we ensure this string only - // contains potential entity characters - if (!arg.match(/^[0-9A-Z_a-z]+$/)) { - throw new TypeError("Bad ".concat(type, " reference; with prefix \"").concat(prefix, "\" and arg \"").concat(arg, "\"")); - } - - var elContainer = doc.createElement('div'); // Todo: No workaround for XML? - // eslint-disable-next-line no-unsanitized/property - - elContainer.innerHTML = '&' + prefix + arg + ';'; - return doc.createTextNode(elContainer.innerHTML); - } - /** - * @param {string} n0 Whole expression match (including "-") - * @param {string} n1 Lower-case letter match - * @returns {string} Uppercased letter - */ - - - function _upperCase(n0, n1) { - return n1.toUpperCase(); - } // Todo: Make as public utility - - /** - * @param {any} o - * @returns {boolean} - */ - - - function _isNullish(o) { - return o === null || o === undefined; - } // Todo: Make as public utility, but also return types for undefined, boolean, number, document, etc. - - /** - * @private - * @static - * @param {string|JamilihAttributes|JamilihArray|Element|DocumentFragment} item - * @returns {"string"|"null"|"array"|"element"|"fragment"|"object"|"symbol"|"function"|"number"|"boolean"} - */ - - - function _getType(item) { - var type = _typeof(item); - - switch (type) { - case 'object': - if (item === null) { - return 'null'; - } - - if (Array.isArray(item)) { - return 'array'; - } - - if ('nodeType' in item) { - switch (item.nodeType) { - case 1: - return 'element'; - - case 9: - return 'document'; - - case 11: - return 'fragment'; - - default: - return 'non-container node'; - } - } - - // Fallthrough - - default: - return type; - } - } - /** - * @private - * @static - * @param {DocumentFragment} frag - * @param {Node} node - * @returns {DocumentFragment} - */ - - - function _fragReducer(frag, node) { - frag.append(node); - return frag; - } - /** - * @private - * @static - * @param {Object<{string:string}>} xmlnsObj - * @returns {string} - */ - - - function _replaceDefiner(xmlnsObj) { - return function (n0) { - var retStr = xmlnsObj[''] ? ' xmlns="' + xmlnsObj[''] + '"' : n0; // Preserve XHTML - - for (var _i = 0, _Object$entries = Object.entries(xmlnsObj); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), - ns = _Object$entries$_i[0], - xmlnsVal = _Object$entries$_i[1]; - - if (ns !== '') { - retStr += ' xmlns:' + ns + '="' + xmlnsVal + '"'; - } - } - - return retStr; - }; - } - /** - * @typedef {JamilihAttributes} AttributeArray - * @property {string} 0 The key - * @property {string} 1 The value - */ - - /** - * @callback ChildrenToJMLCallback - * @param {JamilihArray|Jamilih} childNodeJML - * @param {Integer} i - * @returns {void} - */ - - /** - * @private - * @static - * @param {Node} node - * @returns {ChildrenToJMLCallback} - */ - - - function _childrenToJML(node) { - return function (childNodeJML, i) { - var cn = node.childNodes[i]; - var j = Array.isArray(childNodeJML) ? jml.apply(void 0, _toConsumableArray(childNodeJML)) : jml(childNodeJML); - cn.replaceWith(j); - }; - } - /** - * @callback JamilihAppender - * @param {JamilihArray} childJML - * @returns {void} - */ - - /** - * @private - * @static - * @param {Node} node - * @returns {JamilihAppender} - */ - - - function _appendJML(node) { - return function (childJML) { - if (Array.isArray(childJML)) { - node.append(jml.apply(void 0, _toConsumableArray(childJML))); - } else { - node.append(jml(childJML)); - } - }; - } - /** - * @callback appender - * @param {string|JamilihArray} childJML - * @returns {void} - */ - - /** - * @private - * @static - * @param {Node} node - * @returns {appender} - */ - - - function _appendJMLOrText(node) { - return function (childJML) { - if (typeof childJML === 'string') { - node.append(childJML); - } else if (Array.isArray(childJML)) { - node.append(jml.apply(void 0, _toConsumableArray(childJML))); - } else { - node.append(jml(childJML)); - } - }; - } - /** - * @private - * @static - */ - - /* - function _DOMfromJMLOrString (childNodeJML) { - if (typeof childNodeJML === 'string') { - return doc.createTextNode(childNodeJML); - } - return jml(...childNodeJML); - } - */ - - /** - * @typedef {Element|DocumentFragment} JamilihReturn - */ - - /** - * @typedef {PlainObject} JamilihAttributes - */ - - /** - * @typedef {GenericArray} JamilihArray - * @property {string} 0 The element to create (by lower-case name) - * @property {JamilihAttributes} [1] Attributes to add with the key as the - * attribute name and value as the attribute value; important for IE where - * the input element's type cannot be added later after already added to the page - * @param {Element[]} [children] The optional children of this element - * (but raw DOM elements required to be specified within arrays since - * could not otherwise be distinguished from siblings being added) - * @param {Element} [parent] The optional parent to which to attach the element - * (always the last unless followed by null, in which case it is the - * second-to-last) - * @param {null} [returning] Can use null to indicate an array of elements - * should be returned - */ - - /** - * @typedef {PlainObject} JamilihOptions - * @property {"root"|"attributeValue"|"fragment"|"children"|"fragmentChildren"} $state - */ - - /** - * @param {Element} elem - * @param {string} att - * @param {string} attVal - * @param {JamilihOptions} opts - * @returns {void} - */ - - - function checkPluginValue(elem, att, attVal, opts) { - opts.$state = 'attributeValue'; - - if (attVal && _typeof(attVal) === 'object') { - var matchingPlugin = getMatchingPlugin(opts, Object.keys(attVal)[0]); - - if (matchingPlugin) { - return matchingPlugin.set({ - opts: opts, - element: elem, - attribute: { - name: att, - value: attVal - } - }); - } - } - - return attVal; - } - /** - * @param {JamilihOptions} opts - * @param {string} item - * @returns {JamilihPlugin} - */ - - - function getMatchingPlugin(opts, item) { - return opts.$plugins && opts.$plugins.find(function (p) { - return p.name === item; - }); - } - /** - * Creates an XHTML or HTML element (XHTML is preferred, but only in browsers - * that support); any element after element can be omitted, and any subsequent - * type or types added afterwards. - * @param {...JamilihArray} args - * @returns {JamilihReturn} The newly created (and possibly already appended) - * element or array of elements - */ - - - var jml = function jml() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var elem = doc.createDocumentFragment(); - /** - * - * @param {Object<{string: string}>} atts - * @returns {void} - */ - - function _checkAtts(atts) { - for (var _i2 = 0, _Object$entries2 = Object.entries(atts); _i2 < _Object$entries2.length; _i2++) { - var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2), - att = _Object$entries2$_i[0], - attVal = _Object$entries2$_i[1]; - - att = att in ATTR_MAP ? ATTR_MAP[att] : att; - - if (NULLABLES.includes(att)) { - attVal = checkPluginValue(elem, att, attVal, opts); - - if (!_isNullish(attVal)) { - elem[att] = attVal; - } - - continue; - } else if (ATTR_DOM.includes(att)) { - attVal = checkPluginValue(elem, att, attVal, opts); - elem[att] = attVal; - continue; - } - - switch (att) { - /* - Todos: - 0. JSON mode to prevent event addition - 0. {$xmlDocument: []} // doc.implementation.createDocument - 0. Accept array for any attribute with first item as prefix and second as value? - 0. {$: ['xhtml', 'div']} for prefixed elements - case '$': // Element with prefix? - nodes[nodes.length] = elem = doc.createElementNS(attVal[0], attVal[1]); - break; - */ - case '#': - { - // Document fragment - opts.$state = 'fragmentChilden'; - nodes[nodes.length] = jml(opts, attVal); - break; - } - - case '$shadow': - { - var _attVal = attVal, - open = _attVal.open, - closed = _attVal.closed; - var _attVal2 = attVal, - content = _attVal2.content, - template = _attVal2.template; - var shadowRoot = elem.attachShadow({ - mode: closed || open === false ? 'closed' : 'open' - }); - - if (template) { - if (Array.isArray(template)) { - if (_getType(template[0]) === 'object') { - // Has attributes - template = jml.apply(void 0, ['template'].concat(_toConsumableArray(template), [doc.body])); - } else { - // Array is for the children - template = jml('template', template, doc.body); - } - } else if (typeof template === 'string') { - template = $(template); - } - - jml(template.content.cloneNode(true), shadowRoot); - } else { - if (!content) { - content = open || closed; - } - - if (content && typeof content !== 'boolean') { - if (Array.isArray(content)) { - jml({ - '#': content - }, shadowRoot); - } else { - jml(content, shadowRoot); - } - } - } - - break; - } - - case '$state': - { - // Handled internally - break; - } - - case 'is': - { - // Currently only in Chrome - // Handled during element creation - break; - } - - case '$custom': - { - Object.assign(elem, attVal); - break; - } - - /* istanbul ignore next */ - - case '$define': - { - var _ret = function () { - var localName = elem.localName.toLowerCase(); // Note: customized built-ins sadly not working yet - - var customizedBuiltIn = !localName.includes('-'); // We check attribute in case this is a preexisting DOM element - // const {is} = atts; - - var is = void 0; - - if (customizedBuiltIn) { - is = elem.getAttribute('is'); - - if (!is) { - if (!{}.hasOwnProperty.call(atts, 'is')) { - throw new TypeError("Expected `is` with `$define` on built-in; args: ".concat(JSON.stringify(args))); - } - - atts.is = checkPluginValue(elem, 'is', atts.is, opts); - elem.setAttribute('is', atts.is); - is = atts.is; - } - } - - var def = customizedBuiltIn ? is : localName; - - if (window.customElements.get(def)) { - return "break"; - } - - var getConstructor = function getConstructor(cnstrct) { - var baseClass = options && options["extends"] ? doc.createElement(options["extends"]).constructor : customizedBuiltIn ? doc.createElement(localName).constructor : window.HTMLElement; - /** - * Class wrapping base class. - */ - - return cnstrct ? /*#__PURE__*/function (_baseClass) { - _inherits(_class, _baseClass); - - var _super = _createSuper(_class); - - /** - * Calls user constructor. - */ - function _class() { - var _this; - - _classCallCheck(this, _class); - - _this = _super.call(this); - cnstrct.call(_assertThisInitialized(_this)); - return _this; - } - - return _class; - }(baseClass) : /*#__PURE__*/function (_baseClass2) { - _inherits(_class2, _baseClass2); - - var _super2 = _createSuper(_class2); - - function _class2() { - _classCallCheck(this, _class2); - - return _super2.apply(this, arguments); - } - - return _class2; - }(baseClass); - }; - - var cnstrctr = void 0, - options = void 0, - mixin = void 0; - - if (Array.isArray(attVal)) { - if (attVal.length <= 2) { - var _attVal3 = attVal; - - var _attVal4 = _slicedToArray(_attVal3, 2); - - cnstrctr = _attVal4[0]; - options = _attVal4[1]; - - if (typeof options === 'string') { - // Todo: Allow creating a definition without using it; - // that may be the only reason to have a string here which - // differs from the `localName` anyways - options = { - "extends": options - }; - } else if (options && !{}.hasOwnProperty.call(options, 'extends')) { - mixin = options; - } - - if (_typeof(cnstrctr) === 'object') { - mixin = cnstrctr; - cnstrctr = getConstructor(); - } - } else { - var _attVal5 = attVal; - - var _attVal6 = _slicedToArray(_attVal5, 3); - - cnstrctr = _attVal6[0]; - mixin = _attVal6[1]; - options = _attVal6[2]; - - if (typeof options === 'string') { - options = { - "extends": options - }; - } - } - } else if (typeof attVal === 'function') { - cnstrctr = attVal; - } else { - mixin = attVal; - cnstrctr = getConstructor(); - } - - if (!cnstrctr.toString().startsWith('class')) { - cnstrctr = getConstructor(cnstrctr); - } - - if (!options && customizedBuiltIn) { - options = { - "extends": localName - }; - } - - if (mixin) { - Object.entries(mixin).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - methodName = _ref2[0], - method = _ref2[1]; - - cnstrctr.prototype[methodName] = method; - }); - } // console.log('def', def, '::', typeof options === 'object' ? options : undefined); - - - window.customElements.define(def, cnstrctr, _typeof(options) === 'object' ? options : undefined); - return "break"; - }(); - - if (_ret === "break") break; - } - - case '$symbol': - { - var _attVal7 = attVal, - _attVal8 = _slicedToArray(_attVal7, 2), - symbol = _attVal8[0], - func = _attVal8[1]; - - if (typeof func === 'function') { - var funcBound = func.bind(elem); - - if (typeof symbol === 'string') { - elem[Symbol["for"](symbol)] = funcBound; - } else { - elem[symbol] = funcBound; - } - } else { - var obj = func; - obj.elem = elem; - - if (typeof symbol === 'string') { - elem[Symbol["for"](symbol)] = obj; - } else { - elem[symbol] = obj; - } - } - - break; - } - - case '$data': - { - setMap(attVal); - break; - } - - case '$attribute': - { - // Attribute node - var node = attVal.length === 3 ? doc.createAttributeNS(attVal[0], attVal[1]) : doc.createAttribute(attVal[0]); - node.value = attVal[attVal.length - 1]; - nodes[nodes.length] = node; - break; - } - - case '$text': - { - // Todo: Also allow as jml(['a text node']) (or should that become a fragment)? - var _node = doc.createTextNode(attVal); - - nodes[nodes.length] = _node; - break; - } - - case '$document': - { - // Todo: Conditionally create XML document - var _node2 = doc.implementation.createHTMLDocument(); - - if (attVal.childNodes) { - // Remove any extra nodes created by createHTMLDocument(). - var j = attVal.childNodes.length; - - while (_node2.childNodes[j]) { - var cn = _node2.childNodes[j]; - cn.remove(); // `j` should stay the same as removing will cause node to be present - } // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - - - attVal.childNodes.forEach(_childrenToJML(_node2)); - } else { - if (attVal.$DOCTYPE) { - var dt = { - $DOCTYPE: attVal.$DOCTYPE - }; - var doctype = jml(dt); - - _node2.firstChild.replaceWith(doctype); - } - - var html = _node2.childNodes[1]; - var head = html.childNodes[0]; - var _body = html.childNodes[1]; - - if (attVal.title || attVal.head) { - var meta = doc.createElement('meta'); - meta.setAttribute('charset', 'utf-8'); - head.append(meta); - - if (attVal.title) { - _node2.title = attVal.title; // Appends after meta - } - - if (attVal.head) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - attVal.head.forEach(_appendJML(head)); - } - } - - if (attVal.body) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - attVal.body.forEach(_appendJMLOrText(_body)); - } - } - - nodes[nodes.length] = _node2; - break; - } - - case '$DOCTYPE': - { - var _node3 = doc.implementation.createDocumentType(attVal.name, attVal.publicId || '', attVal.systemId || ''); - - nodes[nodes.length] = _node3; - break; - } - - case '$on': - { - // Events - // Allow for no-op by defaulting to `{}` - for (var _i3 = 0, _Object$entries3 = Object.entries(attVal || {}); _i3 < _Object$entries3.length; _i3++) { - var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2), - p2 = _Object$entries3$_i[0], - val = _Object$entries3$_i[1]; - - if (typeof val === 'function') { - val = [val, false]; - } - - if (typeof val[0] !== 'function') { - throw new TypeError("Expect a function for `$on`; args: ".concat(JSON.stringify(args))); - } - - _addEvent(elem, p2, val[0], val[1]); // element, event name, handler, capturing - - } - - break; - } - - case 'className': - case 'class': - attVal = checkPluginValue(elem, att, attVal, opts); - - if (!_isNullish(attVal)) { - elem.className = attVal; - } - - break; - - case 'dataset': - { - var _ret2 = function () { - // Map can be keyed with hyphenated or camel-cased properties - var recurse = function recurse(atVal, startProp) { - var prop = ''; - var pastInitialProp = startProp !== ''; - Object.keys(atVal).forEach(function (key) { - var value = atVal[key]; - - if (pastInitialProp) { - prop = startProp + key.replace(hyphenForCamelCase, _upperCase).replace(/^([a-z])/, _upperCase); - } else { - prop = startProp + key.replace(hyphenForCamelCase, _upperCase); - } - - if (value === null || _typeof(value) !== 'object') { - if (!_isNullish(value)) { - elem.dataset[prop] = value; - } - - prop = startProp; - return; - } - - recurse(value, prop); - }); - }; - - recurse(attVal, ''); - return "break"; // Todo: Disable this by default unless configuration explicitly allows (for security) - }(); - - if (_ret2 === "break") break; - } - // #if IS_REMOVE - // Don't remove this `if` block (for sake of no-innerHTML build) - - case 'innerHTML': - if (!_isNullish(attVal)) { - // eslint-disable-next-line no-unsanitized/property - elem.innerHTML = attVal; - } - - break; - // #endif - - case 'htmlFor': - case 'for': - if (elStr === 'label') { - attVal = checkPluginValue(elem, att, attVal, opts); - - if (!_isNullish(attVal)) { - elem.htmlFor = attVal; - } - - break; - } - - attVal = checkPluginValue(elem, att, attVal, opts); - elem.setAttribute(att, attVal); - break; - - case 'xmlns': - // Already handled - break; - - default: - { - if (att.startsWith('on')) { - attVal = checkPluginValue(elem, att, attVal, opts); - elem[att] = attVal; // _addEvent(elem, att.slice(2), attVal, false); // This worked, but perhaps the user wishes only one event - - break; - } - - if (att === 'style') { - attVal = checkPluginValue(elem, att, attVal, opts); - - if (_isNullish(attVal)) { - break; - } - - if (_typeof(attVal) === 'object') { - for (var _i4 = 0, _Object$entries4 = Object.entries(attVal); _i4 < _Object$entries4.length; _i4++) { - var _Object$entries4$_i = _slicedToArray(_Object$entries4[_i4], 2), - _p = _Object$entries4$_i[0], - styleVal = _Object$entries4$_i[1]; - - if (!_isNullish(styleVal)) { - // Todo: Handle aggregate properties like "border" - if (_p === 'float') { - elem.style.cssFloat = styleVal; - elem.style.styleFloat = styleVal; // Harmless though we could make conditional on older IE instead - } else { - elem.style[_p.replace(hyphenForCamelCase, _upperCase)] = styleVal; - } - } - } - - break; - } // setAttribute unfortunately erases any existing styles - - - elem.setAttribute(att, attVal); - /* - // The following reorders which is troublesome for serialization, e.g., as used in our testing - if (elem.style.cssText !== undefined) { - elem.style.cssText += attVal; - } else { // Opera - elem.style += attVal; - } - */ - - break; - } - - var matchingPlugin = getMatchingPlugin(opts, att); - - if (matchingPlugin) { - matchingPlugin.set({ - opts: opts, - element: elem, - attribute: { - name: att, - value: attVal - } - }); - break; - } - - attVal = checkPluginValue(elem, att, attVal, opts); - elem.setAttribute(att, attVal); - break; - } - } - } - } - - var nodes = []; - var elStr; - var opts; - var isRoot = false; - - if (_getType(args[0]) === 'object' && Object.keys(args[0]).some(function (key) { - return possibleOptions.includes(key); - })) { - opts = args[0]; - - if (opts.$state === undefined) { - isRoot = true; - opts.$state = 'root'; - } - - if (opts.$map && !opts.$map.root && opts.$map.root !== false) { - opts.$map = { - root: opts.$map - }; - } - - if ('$plugins' in opts) { - if (!Array.isArray(opts.$plugins)) { - throw new TypeError("`$plugins` must be an array; args: ".concat(JSON.stringify(args))); - } - - opts.$plugins.forEach(function (pluginObj) { - if (!pluginObj || _typeof(pluginObj) !== 'object') { - throw new TypeError("Plugin must be an object; args: ".concat(JSON.stringify(args))); - } - - if (!pluginObj.name || !pluginObj.name.startsWith('$_')) { - throw new TypeError("Plugin object name must be present and begin with `$_`; args: ".concat(JSON.stringify(args))); - } - - if (typeof pluginObj.set !== 'function') { - throw new TypeError("Plugin object must have a `set` method; args: ".concat(JSON.stringify(args))); - } - }); - } - - args = args.slice(1); - } else { - opts = { - $state: undefined - }; - } - - var argc = args.length; - var defaultMap = opts.$map && opts.$map.root; - - var setMap = function setMap(dataVal) { - var map, obj; // Boolean indicating use of default map and object - - if (dataVal === true) { - var _defaultMap = _slicedToArray(defaultMap, 2); - - map = _defaultMap[0]; - obj = _defaultMap[1]; - } else if (Array.isArray(dataVal)) { - // Array of strings mapping to default - if (typeof dataVal[0] === 'string') { - dataVal.forEach(function (dVal) { - setMap(opts.$map[dVal]); - }); - return; // Array of Map and non-map data object - } - - map = dataVal[0] || defaultMap[0]; - obj = dataVal[1] || defaultMap[1]; // Map - } else if (/^\[object (?:Weak)?Map\]$/.test([].toString.call(dataVal))) { - map = dataVal; - obj = defaultMap[1]; // Non-map data object - } else { - map = defaultMap[0]; - obj = dataVal; - } - - map.set(elem, obj); - }; - - for (var i = 0; i < argc; i++) { - var arg = args[i]; - - var type = _getType(arg); - - switch (type) { - default: - throw new TypeError("Unexpected type: ".concat(type, "; arg: ").concat(arg, "; index ").concat(i, " on args: ").concat(JSON.stringify(args))); - - case 'null': - // null always indicates a place-holder (only needed for last argument if want array returned) - if (i === argc - 1) { - _applyAnyStylesheet(nodes[0]); // We have to execute any stylesheets even if not appending or otherwise IE will never apply them - // Todo: Fix to allow application of stylesheets of style tags within fragments? - - - return nodes.length <= 1 ? nodes[0] // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - : nodes.reduce(_fragReducer, doc.createDocumentFragment()); // nodes; - } - - throw new TypeError("`null` values not allowed except as final Jamilih argument; index ".concat(i, " on args: ").concat(JSON.stringify(args))); - - case 'string': - // Strings normally indicate elements - switch (arg) { - case '!': - nodes[nodes.length] = doc.createComment(args[++i]); - break; - - case '?': - { - arg = args[++i]; - var procValue = args[++i]; - var val = procValue; - - if (val && _typeof(val) === 'object') { - procValue = []; - - for (var _i5 = 0, _Object$entries5 = Object.entries(val); _i5 < _Object$entries5.length; _i5++) { - var _Object$entries5$_i = _slicedToArray(_Object$entries5[_i5], 2), - p = _Object$entries5$_i[0], - procInstVal = _Object$entries5$_i[1]; - - procValue.push(p + '=' + '"' + // https://www.w3.org/TR/xml-stylesheet/#NT-PseudoAttValue - procInstVal.replace(/"/g, '"') + '"'); - } - - procValue = procValue.join(' '); - } // Firefox allows instructions with ">" in this method, but not if placed directly! - - - try { - nodes[nodes.length] = doc.createProcessingInstruction(arg, procValue); - } catch (e) { - // Getting NotSupportedError in IE, so we try to imitate a processing instruction with a comment - // innerHTML didn't work - // var elContainer = doc.createElement('div'); - // elContainer.innerHTML = ''; - // nodes[nodes.length] = elContainer.innerHTML; - // Todo: any other way to resolve? Just use XML? - nodes[nodes.length] = doc.createComment('?' + arg + ' ' + procValue + '?'); - } - - break; // Browsers don't support doc.createEntityReference, so we just use this as a convenience - } - - case '&': - nodes[nodes.length] = _createSafeReference('entity', '', args[++i]); - break; - - case '#': - // // Decimal character reference - ['#', '01234'] // Ӓ // probably easier to use JavaScript Unicode escapes - nodes[nodes.length] = _createSafeReference('decimal', arg, String(args[++i])); - break; - - case '#x': - // Hex character reference - ['#x', '123a'] // ሺ // probably easier to use JavaScript Unicode escapes - nodes[nodes.length] = _createSafeReference('hexadecimal', arg, args[++i]); - break; - - case '![': - // '![', ['escaped <&> text'] // text]]> - // CDATA valid in XML only, so we'll just treat as text for mutual compatibility - // Todo: config (or detection via some kind of doc.documentType property?) of whether in XML - try { - nodes[nodes.length] = doc.createCDATASection(args[++i]); - } catch (e2) { - nodes[nodes.length] = doc.createTextNode(args[i]); // i already incremented - } - - break; - - case '': - nodes[nodes.length] = elem = doc.createDocumentFragment(); // Todo: Report to plugins - - opts.$state = 'fragment'; - break; - - default: - { - // An element - elStr = arg; - var atts = args[i + 1]; - - if (_getType(atts) === 'object' && atts.is) { - var is = atts.is; // istanbul ignore else - - if (doc.createElementNS) { - elem = doc.createElementNS(NS_HTML, elStr, { - is: is - }); - } else { - elem = doc.createElement(elStr, { - is: is - }); - } - } else - /* istanbul ignore else */ - if (doc.createElementNS) { - elem = doc.createElementNS(NS_HTML, elStr); - } else { - elem = doc.createElement(elStr); - } // Todo: Report to plugins - - - opts.$state = 'element'; - nodes[nodes.length] = elem; // Add to parent - - break; - } - } - - break; - - case 'object': - { - // Non-DOM-element objects indicate attribute-value pairs - var _atts = arg; - - if (_atts.xmlns !== undefined) { - // We handle this here, as otherwise may lose events, etc. - // As namespace of element already set as XHTML, we need to change the namespace - // elem.setAttribute('xmlns', atts.xmlns); // Doesn't work - // Can't set namespaceURI dynamically, renameNode() is not supported, and setAttribute() doesn't work to change the namespace, so we resort to this hack - var replacer = void 0; - - if (_typeof(_atts.xmlns) === 'object') { - replacer = _replaceDefiner(_atts.xmlns); - } else { - replacer = ' xmlns="' + _atts.xmlns + '"'; - } // try { - // Also fix DOMParser to work with text/html - - - elem = nodes[nodes.length - 1] = new win.DOMParser().parseFromString(new win.XMLSerializer().serializeToString(elem) // Mozilla adds XHTML namespace - .replace(' xmlns="' + NS_HTML + '"', replacer), 'application/xml').documentElement; // Todo: Report to plugins - - opts.$state = 'element'; // }catch(e) {alert(elem.outerHTML);throw e;} - } - - _checkAtts(_atts); - - break; - } - - case 'document': - case 'fragment': - case 'element': - /* - 1) Last element always the parent (put null if don't want parent and want to return array) unless only atts and children (no other elements) - 2) Individual elements (DOM elements or sequences of string[/object/array]) get added to parent first-in, first-added - */ - if (i === 0) { - // Allow wrapping of element, fragment, or document - elem = arg; // Todo: Report to plugins - - opts.$state = 'element'; - } - - if (i === argc - 1 || i === argc - 2 && args[i + 1] === null) { - // parent - var elsl = nodes.length; - - for (var k = 0; k < elsl; k++) { - _appendNode(arg, nodes[k]); - } // Todo: Apply stylesheets if any style tags were added elsewhere besides the first element? - - - _applyAnyStylesheet(nodes[0]); // We have to execute any stylesheets even if not appending or otherwise IE will never apply them - - } else { - nodes[nodes.length] = arg; - } - - break; - - case 'array': - { - // Arrays or arrays of arrays indicate child nodes - var child = arg; - var cl = child.length; - - for (var j = 0; j < cl; j++) { - // Go through children array container to handle elements - var childContent = child[j]; - - var childContentType = _typeof(childContent); - - if (_isNullish(childContent)) { - throw new TypeError("Bad children (parent array: ".concat(JSON.stringify(args), "; index ").concat(j, " of child: ").concat(JSON.stringify(child), ")")); - } - - switch (childContentType) { - // Todo: determine whether null or function should have special handling or be converted to text - case 'string': - case 'number': - case 'boolean': - _appendNode(elem, doc.createTextNode(childContent)); - - break; - - default: - if (Array.isArray(childContent)) { - // Arrays representing child elements - opts.$state = 'children'; - - _appendNode(elem, jml.apply(void 0, [opts].concat(_toConsumableArray(childContent)))); - } else if (childContent['#']) { - // Fragment - opts.$state = 'fragmentChildren'; - - _appendNode(elem, jml(opts, childContent['#'])); - } else { - // Single DOM element children - var newChildContent = checkPluginValue(elem, null, childContent, opts); - - _appendNode(elem, newChildContent); - } - - break; - } - } - - break; - } - } - } - - var ret = nodes[0] || elem; - - if (isRoot && opts.$map && opts.$map.root) { - setMap(true); - } - - return ret; - }; - /** - * Converts a DOM object or a string of HTML into a Jamilih object (or string). - * @param {string|HTMLElement} dom If a string, will parse as document - * @param {PlainObject} [config] Configuration object - * @param {boolean} [config.stringOutput=false] Whether to output the Jamilih object as a string. - * @param {boolean} [config.reportInvalidState=true] If true (the default), will report invalid state errors - * @param {boolean} [config.stripWhitespace=false] Strip whitespace for text nodes - * @returns {JamilihArray|string} Array containing the elements which represent - * a Jamilih object, or, if `stringOutput` is true, it will be the stringified - * version of such an object - */ - - - jml.toJML = function (dom) { - var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref3$stringOutput = _ref3.stringOutput, - stringOutput = _ref3$stringOutput === void 0 ? false : _ref3$stringOutput, - _ref3$reportInvalidSt = _ref3.reportInvalidState, - reportInvalidState = _ref3$reportInvalidSt === void 0 ? true : _ref3$reportInvalidSt, - _ref3$stripWhitespace = _ref3.stripWhitespace, - stripWhitespace = _ref3$stripWhitespace === void 0 ? false : _ref3$stripWhitespace; - - if (typeof dom === 'string') { - dom = new win.DOMParser().parseFromString(dom, 'text/html'); // todo: Give option for XML once implemented and change JSDoc to allow for Element - } - - var ret = []; - var parent = ret; - var parentIdx = 0; - /** - * @param {string} msg - * @throws {DOMException} - * @returns {void} - */ - - function invalidStateError(msg) { - // These are probably only necessary if working with text/html - - /* eslint-disable no-shadow, unicorn/custom-error-definition */ - - /** - * Polyfill for `DOMException`. - */ - var DOMException = /*#__PURE__*/function (_Error) { - _inherits(DOMException, _Error); - - var _super3 = _createSuper(DOMException); - - /* eslint-enable no-shadow, unicorn/custom-error-definition */ - - /** - * @param {string} message - * @param {string} name - */ - function DOMException(message, name) { - var _this2; - - _classCallCheck(this, DOMException); - - _this2 = _super3.call(this, message); // eslint-disable-next-line unicorn/custom-error-definition - - _this2.name = name; - return _this2; - } - - return DOMException; - }( /*#__PURE__*/_wrapNativeSuper(Error)); - - if (reportInvalidState) { - // INVALID_STATE_ERR per section 9.3 XHTML 5: http://www.w3.org/TR/html5/the-xhtml-syntax.html - var e = new DOMException(msg, 'INVALID_STATE_ERR'); - e.code = 11; - throw e; - } - } - /** - * - * @param {DocumentType|Entity} obj - * @param {Node} node - * @returns {void} - */ - - - function addExternalID(obj, node) { - if (node.systemId.includes('"') && node.systemId.includes("'")) { - invalidStateError('systemId cannot have both single and double quotes.'); - } - - var publicId = node.publicId, - systemId = node.systemId; - - if (systemId) { - obj.systemId = systemId; - } - - if (publicId) { - obj.publicId = publicId; - } - } - /** - * - * @param {any} val - * @returns {void} - */ - - - function set(val) { - parent[parentIdx] = val; - parentIdx++; - } - /** - * @returns {void} - */ - - - function setChildren() { - set([]); - parent = parent[parentIdx - 1]; - parentIdx = 0; - } - /** - * - * @param {string} prop1 - * @param {string} prop2 - * @returns {void} - */ - - - function setObj(prop1, prop2) { - parent = parent[parentIdx - 1][prop1]; - parentIdx = 0; - - if (prop2) { - parent = parent[prop2]; - } - } - /** - * - * @param {Node} node - * @param {object<{string: string}>} namespaces - * @returns {void} - */ - - - function parseDOM(node, namespaces) { - // namespaces = clone(namespaces) || {}; // Ensure we're working with a copy, so different levels in the hierarchy can treat it differently - - /* - if ((node.prefix && node.prefix.includes(':')) || (node.localName && node.localName.includes(':'))) { - invalidStateError('Prefix cannot have a colon'); - } - */ - var type = 'nodeType' in node ? node.nodeType : null; - namespaces = _extends({}, namespaces); - var xmlChars = /^([\t\n\r -\uD7FF\uE000-\uFFFD]|(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))(?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))*$/; // eslint-disable-line no-control-regex - - if ([2, 3, 4, 7, 8].includes(type) && !xmlChars.test(node.nodeValue)) { - invalidStateError('Node has bad XML character value'); - } - - var tmpParent, tmpParentIdx; - /** - * @returns {void} - */ - - function setTemp() { - tmpParent = parent; - tmpParentIdx = parentIdx; - } - /** - * @returns {void} - */ - - - function resetTemp() { - parent = tmpParent; - parentIdx = tmpParentIdx; - parentIdx++; // Increment index in parent container of this element - } - - switch (type) { - case 1: - { - // ELEMENT - setTemp(); - var nodeName = node.nodeName.toLowerCase(); // Todo: for XML, should not lower-case - - setChildren(); // Build child array since elements are, except at the top level, encapsulated in arrays - - set(nodeName); - var start = {}; - var hasNamespaceDeclaration = false; - - if (namespaces[node.prefix || ''] !== node.namespaceURI) { - namespaces[node.prefix || ''] = node.namespaceURI; - - if (node.prefix) { - start['xmlns:' + node.prefix] = node.namespaceURI; - } else if (node.namespaceURI) { - start.xmlns = node.namespaceURI; - } else { - start.xmlns = null; - } - - hasNamespaceDeclaration = true; - } - - if (node.attributes.length) { - set(_toConsumableArray(node.attributes).reduce(function (obj, att) { - obj[att.name] = att.value; // Attr.nodeName and Attr.nodeValue are deprecated as of DOM4 as Attr no longer inherits from Node, so we can safely use name and value - - return obj; - }, start)); - } else if (hasNamespaceDeclaration) { - set(start); - } - - var childNodes = node.childNodes; - - if (childNodes.length) { - setChildren(); // Element children array container - - _toConsumableArray(childNodes).forEach(function (childNode) { - parseDOM(childNode, namespaces); - }); - } - - resetTemp(); - break; - } - - case undefined: // Treat as attribute node until this is fixed: https://github.com/jsdom/jsdom/issues/1641 / https://github.com/jsdom/jsdom/pull/1822 - - case 2: - // ATTRIBUTE (should only get here if passing in an attribute node) - set({ - $attribute: [node.namespaceURI, node.name, node.value] - }); - break; - - case 3: - // TEXT - if (stripWhitespace && /^[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+$/.test(node.nodeValue)) { - set(''); - return; - } - - set(node.nodeValue); - break; - - case 4: - // CDATA - if (node.nodeValue.includes(']]' + '>')) { - invalidStateError('CDATA cannot end with closing ]]>'); - } - - set(['![', node.nodeValue]); - break; - - case 5: - // ENTITY REFERENCE (though not in browsers (was already resolved - // anyways), ok to keep for parity with our "entity" shorthand) - set(['&', node.nodeName]); - break; - - case 7: - // PROCESSING INSTRUCTION - if (/^xml$/i.test(node.target)) { - invalidStateError('Processing instructions cannot be "xml".'); - } - - if (node.target.includes('?>')) { - invalidStateError('Processing instruction targets cannot include ?>'); - } - - if (node.target.includes(':')) { - invalidStateError('The processing instruction target cannot include ":"'); - } - - if (node.data.includes('?>')) { - invalidStateError('Processing instruction data cannot include ?>'); - } - - set(['?', node.target, node.data]); // Todo: Could give option to attempt to convert value back into object if has pseudo-attributes - - break; - - case 8: - // COMMENT - if (node.nodeValue.includes('--') || node.nodeValue.length && node.nodeValue.lastIndexOf('-') === node.nodeValue.length - 1) { - invalidStateError('Comments cannot include --'); - } - - set(['!', node.nodeValue]); - break; - - case 9: - { - // DOCUMENT - setTemp(); - var docObj = { - $document: { - childNodes: [] - } - }; - set(docObj); // doc.implementation.createHTMLDocument - // Set position to fragment's array children - - setObj('$document', 'childNodes'); - var _childNodes = node.childNodes; - - if (!_childNodes.length) { - invalidStateError('Documents must have a child node'); - } // set({$xmlDocument: []}); // doc.implementation.createDocument // Todo: use this conditionally - - - _toConsumableArray(_childNodes).forEach(function (childNode) { - // Can't just do documentElement as there may be doctype, comments, etc. - // No need for setChildren, as we have already built the container array - parseDOM(childNode, namespaces); - }); - - resetTemp(); - break; - } - - case 10: - { - // DOCUMENT TYPE - setTemp(); // Can create directly by doc.implementation.createDocumentType - - var _start = { - $DOCTYPE: { - name: node.name - } - }; - var pubIdChar = /^( |\r|\n|[0-9A-Za-z]|[!#-%'-\/:;=\?@_])*$/; // eslint-disable-line no-control-regex - - if (!pubIdChar.test(node.publicId)) { - invalidStateError('A publicId must have valid characters.'); - } - - addExternalID(_start.$DOCTYPE, node); // Fit in internal subset along with entities?: probably don't need as these would only differ if from DTD, and we're not rebuilding the DTD - - set(_start); // Auto-generate the internalSubset instead? - - resetTemp(); - break; - } - - case 11: - { - // DOCUMENT FRAGMENT - setTemp(); - set({ - '#': [] - }); // Set position to fragment's array children - - setObj('#'); - var _childNodes2 = node.childNodes; - - _toConsumableArray(_childNodes2).forEach(function (childNode) { - // No need for setChildren, as we have already built the container array - parseDOM(childNode, namespaces); - }); - - resetTemp(); - break; - } - - default: - throw new TypeError('Not an XML type'); - } - } - - parseDOM(dom, {}); - - if (stringOutput) { - return JSON.stringify(ret[0]); - } - - return ret[0]; - }; - - jml.toJMLString = function (dom, config) { - return jml.toJML(dom, Object.assign(config || {}, { - stringOutput: true - })); - }; - /** - * - * @param {...JamilihArray} args - * @returns {JamilihReturn} - */ - - - jml.toDOM = function () { - // Alias for jml() - return jml.apply(void 0, arguments); - }; - /** - * - * @param {...JamilihArray} args - * @returns {string} - */ - - - jml.toHTML = function () { - // Todo: Replace this with version of jml() that directly builds a string - var ret = jml.apply(void 0, arguments); // Todo: deal with serialization of properties like 'selected', - // 'checked', 'value', 'defaultValue', 'for', 'dataset', 'on*', - // 'style'! (i.e., need to build a string ourselves) - - return ret.outerHTML; - }; - /** - * - * @param {...JamilihArray} args - * @returns {string} - */ - - - jml.toDOMString = function () { - // Alias for jml.toHTML for parity with jml.toJMLString - return jml.toHTML.apply(jml, arguments); - }; - /** - * - * @param {...JamilihArray} args - * @returns {string} - */ - - - jml.toXML = function () { - var ret = jml.apply(void 0, arguments); - return new win.XMLSerializer().serializeToString(ret); - }; - /** - * - * @param {...JamilihArray} args - * @returns {string} - */ - - - jml.toXMLDOMString = function () { - // Alias for jml.toXML for parity with jml.toJMLString - return jml.toXML.apply(jml, arguments); - }; - /** - * Element-aware wrapper for `Map`. - */ - - - var JamilihMap = /*#__PURE__*/function (_Map) { - _inherits(JamilihMap, _Map); - - var _super4 = _createSuper(JamilihMap); - - function JamilihMap() { - _classCallCheck(this, JamilihMap); - - return _super4.apply(this, arguments); - } - - _createClass(JamilihMap, [{ - key: "get", - - /** - * @param {string|Element} elem - * @returns {any} - */ - value: function get(elem) { - elem = typeof elem === 'string' ? $(elem) : elem; - return _get(_getPrototypeOf(JamilihMap.prototype), "get", this).call(this, elem); - } - /** - * @param {string|Element} elem - * @param {any} value - * @returns {any} - */ - - }, { - key: "set", - value: function set(elem, value) { - elem = typeof elem === 'string' ? $(elem) : elem; - return _get(_getPrototypeOf(JamilihMap.prototype), "set", this).call(this, elem, value); - } - /** - * @param {string|Element} elem - * @param {string} methodName - * @param {...any} args - * @returns {any} - */ - - }, { - key: "invoke", - value: function invoke(elem, methodName) { - var _this$get; - - elem = typeof elem === 'string' ? $(elem) : elem; - - for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { - args[_key2 - 2] = arguments[_key2]; - } - - return (_this$get = this.get(elem))[methodName].apply(_this$get, [elem].concat(args)); - } - }]); - - return JamilihMap; - }( /*#__PURE__*/_wrapNativeSuper(Map)); - /** - * Element-aware wrapper for `WeakMap`. - */ - - - var JamilihWeakMap = /*#__PURE__*/function (_WeakMap) { - _inherits(JamilihWeakMap, _WeakMap); - - var _super5 = _createSuper(JamilihWeakMap); - - function JamilihWeakMap() { - _classCallCheck(this, JamilihWeakMap); - - return _super5.apply(this, arguments); - } - - _createClass(JamilihWeakMap, [{ - key: "get", - - /** - * @param {string|Element} elem - * @returns {any} - */ - value: function get(elem) { - elem = typeof elem === 'string' ? $(elem) : elem; - return _get(_getPrototypeOf(JamilihWeakMap.prototype), "get", this).call(this, elem); - } - /** - * @param {string|Element} elem - * @param {any} value - * @returns {any} - */ - - }, { - key: "set", - value: function set(elem, value) { - elem = typeof elem === 'string' ? $(elem) : elem; - return _get(_getPrototypeOf(JamilihWeakMap.prototype), "set", this).call(this, elem, value); - } - /** - * @param {string|Element} elem - * @param {string} methodName - * @param {...any} args - * @returns {any} - */ - - }, { - key: "invoke", - value: function invoke(elem, methodName) { - var _this$get2; - - elem = typeof elem === 'string' ? $(elem) : elem; - - for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { - args[_key3 - 2] = arguments[_key3]; - } - - return (_this$get2 = this.get(elem))[methodName].apply(_this$get2, [elem].concat(args)); - } - }]); - - return JamilihWeakMap; - }( /*#__PURE__*/_wrapNativeSuper(WeakMap)); - - jml.Map = JamilihMap; - jml.WeakMap = JamilihWeakMap; - /** - * @typedef {GenericArray} MapAndElementArray - * @property {JamilihWeakMap|JamilihMap} 0 - * @property {Element} 1 - */ - - /** - * @param {GenericObject} obj - * @param {...JamilihArray} args - * @returns {MapAndElementArray} - */ - - jml.weak = function (obj) { - var map = new JamilihWeakMap(); - - for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - var elem = jml.apply(void 0, [{ - $map: [map, obj] - }].concat(args)); - return [map, elem]; - }; - /** - * @param {any} obj - * @param {...JamilihArray} args - * @returns {MapAndElementArray} - */ - - - jml.strong = function (obj) { - var map = new JamilihMap(); - - for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - args[_key5 - 1] = arguments[_key5]; - } - - var elem = jml.apply(void 0, [{ - $map: [map, obj] - }].concat(args)); - return [map, elem]; - }; - /** - * @param {string|Element} elem If a string, will be interpreted as a selector - * @param {symbol|string} sym If a string, will be used with `Symbol.for` - * @returns {any} The value associated with the symbol - */ - - - jml.symbol = jml.sym = jml["for"] = function (elem, sym) { - elem = typeof elem === 'string' ? $(elem) : elem; - return elem[_typeof(sym) === 'symbol' ? sym : Symbol["for"](sym)]; - }; - /** - * @param {string|Element} elem If a string, will be interpreted as a selector - * @param {symbol|string|Map|WeakMap} symOrMap If a string, will be used with `Symbol.for` - * @param {string|any} methodName Can be `any` if the symbol or map directly - * points to a function (it is then used as the first argument). - * @param {any[]} args - * @returns {any} - */ - - - jml.command = function (elem, symOrMap, methodName) { - var _func3; - - elem = typeof elem === 'string' ? $(elem) : elem; - var func; - - for (var _len6 = arguments.length, args = new Array(_len6 > 3 ? _len6 - 3 : 0), _key6 = 3; _key6 < _len6; _key6++) { - args[_key6 - 3] = arguments[_key6]; - } - - if (['symbol', 'string'].includes(_typeof(symOrMap))) { - var _func; - - func = jml.sym(elem, symOrMap); - - if (typeof func === 'function') { - return func.apply(void 0, [methodName].concat(args)); // Already has `this` bound to `elem` - } - - return (_func = func)[methodName].apply(_func, args); - } - - func = symOrMap.get(elem); - - if (typeof func === 'function') { - var _func2; - - return (_func2 = func).call.apply(_func2, [elem, methodName].concat(args)); - } - - return (_func3 = func)[methodName].apply(_func3, [elem].concat(args)); // return func[methodName].call(elem, ...args); - }; - /** - * Expects properties `document`, `XMLSerializer`, and `DOMParser`. - * Also updates `body` with `document.body`. - * @param {Window} wind - * @returns {void} - */ - - - jml.setWindow = function (wind) { - win = wind; - doc = win.document; - - if (doc && doc.body) { - var _doc = doc; - body = _doc.body; - } - }; - /** - * @returns {Window} - */ - - - jml.getWindow = function () { - return win; - }; - - - var body = doc && doc.body; // eslint-disable-line import/no-mutable-exports - - var nbsp = "\xA0"; // Very commonly needed in templates - - /** - * ISC License - * - * Copyright (c) 2018, Andrea Giammarchi, @WebReflection - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE - * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ - var QueryResult = /*#__PURE__*/function (_Array) { - _inherits(QueryResult, _Array); - - var _super = _createSuper(QueryResult); - - function QueryResult() { - _classCallCheck(this, QueryResult); - - return _super.apply(this, arguments); - } - - return QueryResult; - }( /*#__PURE__*/_wrapNativeSuper(Array)); - - var create = Object.create, - defineProperty = Object.defineProperty; - var AP = Array.prototype; - var DOM_CONTENT_LOADED = 'DOMContentLoaded'; - var LOAD = 'load'; - var NO_TRANSPILER_ISSUES = new QueryResult() instanceof QueryResult; - var QRP = QueryResult.prototype; // fixes methods returning non QueryResult - - /* istanbul ignore if */ - - if (!NO_TRANSPILER_ISSUES) Object.getOwnPropertyNames(AP).forEach(function (name) { - var desc = Object.getOwnPropertyDescriptor(AP, name); - - if (typeof desc.value === 'function') { - var fn = desc.value; - - desc.value = function () { - var result = fn.apply(this, arguments); - return result instanceof Array ? patch(result) : result; - }; - } - - defineProperty(QRP, name, desc); - }); // fixes badly transpiled classes - - var patch = NO_TRANSPILER_ISSUES ? function (qr) { - return qr; - } : - /* istanbul ignore next */ - function (qr) { - var nqr = create(QRP); - push.apply(nqr, slice(qr)); - return nqr; - }; - var push = AP.push; - - var search = function search(list, el) { - var nodes = []; - var length = list.length; - - for (var i = 0; i < length; i++) { - var css = list[i].trim(); - - if (css.slice(-6) === ':first') { - var node = el.querySelector(css.slice(0, -6)); - if (node) push.call(nodes, node); - } else push.apply(nodes, slice(el.querySelectorAll(css))); - } - - return _construct(QueryResult, nodes); - }; - - var slice = NO_TRANSPILER_ISSUES ? patch : - /* istanbul ignore next */ - function (all) { - // do not use slice.call(...) due old IE gotcha - var nodes = []; - var length = all.length; - - for (var i = 0; i < length; i++) { - nodes[i] = all[i]; - } - - return nodes; - }; // use function to avoid usage of Symbol.hasInstance - // (broken in older browsers anyway) - - var $$1 = function $(CSS) { - var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; - - switch (_typeof(CSS)) { - case 'string': - return patch(search(CSS.split(','), parent)); - - case 'object': - // needed to avoid iterator dance (breaks in older IEs) - var nodes = []; - var all = 'nodeType' in CSS || 'postMessage' in CSS ? [CSS] : CSS; - push.apply(nodes, slice(all)); - return patch(_construct(QueryResult, nodes)); - - case 'function': - var $parent = $(parent); - var $window = $(parent.defaultView); - var handler = { - handleEvent: function handleEvent(event) { - $parent.off(DOM_CONTENT_LOADED, handler); - $window.off(LOAD, handler); - CSS(event); - } - }; - $parent.on(DOM_CONTENT_LOADED, handler); - $window.on(LOAD, handler); - var rs = parent.readyState; - if (rs == 'complete' || rs != 'loading' && !parent.documentElement.doScroll) setTimeout(function () { - return $parent.dispatch(DOM_CONTENT_LOADED); - }); - return $; - } - }; - - $$1.prototype = QRP; - - $$1.extend = function (key, value) { - return defineProperty(QRP, key, { - configurable: true, - value: value - }), $$1; - }; // dropped usage of for-of to avoid broken iteration dance in older IEs - - - $$1.extend('dispatch', function dispatch(type) { - var init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var event = new CustomEvent(type, init); - var length = this.length; - - for (var i = 0; i < length; i++) { - this[i].dispatchEvent(event); - } - - return this; - }).extend('off', function off(type, handler) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var length = this.length; - - for (var i = 0; i < length; i++) { - this[i].removeEventListener(type, handler, options); - } - - return this; - }).extend('on', function on(type, handler) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var length = this.length; - - for (var i = 0; i < length; i++) { - this[i].addEventListener(type, handler, options); - } - - return this; - }); - - function _typeof$1(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof$1 = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof$1 = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof$1(obj); - } - - function _slicedToArray$1(arr, i) { - return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest$1(); - } - - function _toConsumableArray$1(arr) { - return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1(); - } - - function _arrayWithoutHoles$1(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); - } - - function _arrayWithHoles$1(arr) { - if (Array.isArray(arr)) return arr; - } - - function _iterableToArray$1(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _iterableToArrayLimit$1(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - function _unsupportedIterableToArray$1(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); - } - - function _arrayLikeToArray$1(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } - - function _nonIterableSpread$1() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function _nonIterableRest$1() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function convertToString(content, type) { - switch (_typeof$1(content)) { - case 'object': - { - if (!content) { - throw new TypeError('Cannot supply `null`'); - } - - switch (content.nodeType) { - case 1: - { - // ELEMENT - return content.outerHTML; - } - - case 3: - { - // TEXT - return content.nodeValue; - } - - case 11: - { - // DOCUMENT_FRAGMENT_NODE - return _toConsumableArray$1(content.childNodes).reduce(function (s, node) { - return s + convertToString(node, type); - }, ''); - } - - case undefined: - // Array of nodes, QueryResult objects - // if (Array.isArray(content)) { - if (typeof content.reduce === 'function') { - return content.reduce(function (s, node) { - return s + convertToString(node, type); - }, ''); - } - - break; - } - - return undefined; - } - - case 'string': - { - return content; - } - - default: - throw new TypeError('Bad content for ' + type + '; type: ' + _typeof$1(content)); - } - } - - function convertToDOM(content, type, avoidClone) { - switch (_typeof$1(content)) { - case 'object': - { - if (!content) { - throw new TypeError('Cannot supply `null`'); - } - - if ([1, // ELEMENT - 3, // TEXT - 11 // Document fragment - ].includes(content.nodeType)) { - return avoidClone ? content : content.cloneNode(true); - } - - if (typeof content.reduce !== 'function') { - throw new TypeError('Unrecognized type of object for conversion to DOM'); - } // Array of nodes, QueryResult objects - - - return avoidClone ? content : content.map(function (node) { - if (!node || !node.cloneNode) { - // Allows for arrays of HTML strings - return convertToDOM(node, type, false); - } - - return node.cloneNode(true); - }); - } - - case 'string': - { - var div = document.createElement('div'); // eslint-disable-next-line no-unsanitized/property - - div.innerHTML = content; - return div.firstElementChild || div.firstChild; - } - - default: - throw new TypeError('Bad content for ' + type + '; type: ' + _typeof$1(content)); - } - } - - function insert(type) { - return function () { - var _this = this; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var cbOrContent = args[0]; - - switch (_typeof$1(cbOrContent)) { - case 'function': - { - this.forEach(function (node, i) { - var ret = cbOrContent.call(_this, i, node.textContent); - node[type](ret); - }); - break; - } - - default: - { - this.forEach(function (node, i, arr) { - node[type].apply(node, _toConsumableArray$1(args.flatMap(function (content) { - return convertToDOM(content, type, i === arr.length - 1); - }))); - }); - break; - } - } - - return this; - }; - } - - function insertText(type) { - return function (cbOrContent) { - var _this2 = this; - - switch (_typeof$1(cbOrContent)) { - case 'function': - { - this.forEach(function (node, i) { - var ret = cbOrContent.call(_this2, i, node[type]); - node[type] = convertToString(ret, type); - }); - break; - } - - default: - { - this.forEach(function (node) { - node[type] = convertToString(cbOrContent, type); - }); - break; - } - } - - return this; - }; - } - - var after = insert('after'); - var before = insert('before'); - var append = insert('append'); - var prepend = insert('prepend'); - var html = insertText('innerHTML'); - var text = insertText('textContent'); - /* - // Todo: - export const val = function (valueOrFunc) { - - }; - */ - // Given that these types require a selector engine and - // in order to avoid the absence of optimization of `document.querySelectorAll` - // for `:first-child` and different behavior in different contexts, - // and to avoid making a mutual dependency with query-result, - // exports of this type accept a QueryResult instance; - // if selected without a second argument, we do default to - // `document.querySelectorAll`, however. - - var insertTo = function insertTo(method) { - var $ = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (sel) { - return _toConsumableArray$1(document.querySelectorAll(sel)); - }; - var type = { - appendTo: 'append', - prependTo: 'prepend', - insertAfter: 'after', - insertBefore: 'before' - }[method] || 'append'; - return function (target) { - var toType = type + 'To'; - this.forEach(function (node, i, arr) { - if (typeof target === 'string' && target.charAt(0) !== '<') { - target = $(target); - } - - target = Array.isArray(target) ? target : [target]; - node[type].apply(node, _toConsumableArray$1(target.flatMap(function (content) { - return convertToDOM(content, toType, i === arr.length - 1); - }))); - }); - return this; - }; - }; // Todo: optional `withDataAndEvents` and `deepWithDataAndEvents` arguments? - - - var clone = function clone() { - return this.map(function (node) { - // Still a QueryResult with such a map - return node.cloneNode(true); - }); - }; - - var empty = function empty() { - this.forEach(function (node) { - node.textContent = ''; - }); - }; - - var remove = function remove(selector) { - if (selector) { - this.forEach(function (node) { - if (node.matches(selector)) { - // Todo: Use query-result instead? - node.remove(); - } - }); - } else { - this.forEach(function (node) { - node.remove(); - }); - } - - return this; - }; - /* - // Todo: - export const detach = function (selector) { - // Should preserve attached data - return remove(selector); - }; - */ - - - var attr = function attr(attributeNameOrAtts, valueOrCb) { - var _this3 = this; - - if (valueOrCb === undefined) { - switch (_typeof$1(attributeNameOrAtts)) { - case 'string': - { - return this[0].hasAttribute(attributeNameOrAtts) ? this[0].getAttribute(attributeNameOrAtts) : undefined; - } - - case 'object': - { - if (attributeNameOrAtts) { - this.forEach(function (node, i) { - Object.entries(attributeNameOrAtts).forEach(function (_ref) { - var _ref2 = _slicedToArray$1(_ref, 2), - att = _ref2[0], - val = _ref2[1]; - - node.setAttribute(att, val); - }); - }); - return this; - } - } - // Fallthrough - - default: - { - throw new TypeError('Unexpected type for attribute name: ' + _typeof$1(attributeNameOrAtts)); - } - } - } - - switch (_typeof$1(valueOrCb)) { - case 'function': - { - this.forEach(function (node, i) { - var ret = valueOrCb.call(_this3, i, node.getAttribute(valueOrCb)); - - if (ret === null) { - node.removeAttribute(attributeNameOrAtts); - } else { - node.setAttribute(attributeNameOrAtts, ret); - } - }); - break; - } - - case 'string': - { - this.forEach(function (node, i) { - node.setAttribute(attributeNameOrAtts, valueOrCb); - }); - break; - } - - case 'object': - { - if (!valueOrCb) { - // `null` - return removeAttr.call(this, attributeNameOrAtts); - } - } - // Fallthrough - - default: - { - throw new TypeError('Unexpected type for attribute name: ' + _typeof$1(attributeNameOrAtts)); - } - } - - return this; - }; - - var removeAttr = function removeAttr(attributeName) { - if (typeof attributeName !== 'string') { - throw new TypeError('Unexpected type for attribute name: ' + _typeof$1(attributeName)); - } - - this.forEach(function (node) { - node.removeAttribute(attributeName); - }); - }; - - function classAttManipulation(type) { - return function (cbOrContent) { - var _this4 = this; - - switch (_typeof$1(cbOrContent)) { - case 'function': - { - this.forEach(function (node, i) { - var _node$classList; - - var ret = cbOrContent.call(_this4, i, node.className); - - (_node$classList = node.classList)[type].apply(_node$classList, _toConsumableArray$1(ret.split(' '))); - }); - break; - } - - default: - { - if (type === 'remove' && !cbOrContent) { - this.forEach(function (node) { - node.className = ''; - }); - break; - } - - this.forEach(function (node) { - var _node$classList2; - - (_node$classList2 = node.classList)[type].apply(_node$classList2, _toConsumableArray$1(cbOrContent.split(' '))); - }); - break; - } - } - - return this; - }; - } - - var addClass = classAttManipulation('add'); - var removeClass = classAttManipulation('remove'); - - var hasClass = function hasClass(className) { - return this.some(function (node) { - return node.classList.contains(className); - }); - }; - - var toggleClass = function toggleClass(classNameOrCb, state) { - var _this5 = this; - - switch (typeof cbOrContent === "undefined" ? "undefined" : _typeof$1(cbOrContent)) { - case 'function': - { - if (typeof state === 'boolean') { - this.forEach(function (node, i) { - var _node$classList3; - - var ret = classNameOrCb.call(_this5, i, node.className, state); - - (_node$classList3 = node.classList).toggle.apply(_node$classList3, _toConsumableArray$1(ret.split(' ')).concat([state])); - }); - } else { - this.forEach(function (node, i) { - var _node$classList4; - - var ret = classNameOrCb.call(_this5, i, node.className, state); - - (_node$classList4 = node.classList).toggle.apply(_node$classList4, _toConsumableArray$1(ret.split(' '))); - }); - } - - break; - } - - case 'string': - { - if (typeof state === 'boolean') { - this.forEach(function (node) { - var _node$classList5; - - (_node$classList5 = node.classList).toggle.apply(_node$classList5, _toConsumableArray$1(classNameOrCb.split(' ')).concat([state])); - }); - } else { - this.forEach(function (node) { - var _node$classList6; - - (_node$classList6 = node.classList).toggle.apply(_node$classList6, _toConsumableArray$1(classNameOrCb.split(' '))); - }); - } - - break; - } - } - }; - - var methods = { - after: after, - before: before, - append: append, - prepend: prepend, - html: html, - text: text, - clone: clone, - empty: empty, - remove: remove, - // detach - attr: attr, - removeAttr: removeAttr, - addClass: addClass, - hasClass: hasClass, - removeClass: removeClass, - toggleClass: toggleClass - }; - - var manipulation = function manipulation($, jml) { - ['after', 'before', 'append', 'prepend', 'html', 'text', 'clone', 'empty', 'remove', // 'detach' - 'attr', 'removeAttr', 'addClass', 'hasClass', 'removeClass', 'toggleClass'].forEach(function (method) { - $.extend(method, methods[method]); - }); - ['appendTo', 'prependTo', 'insertAfter', 'insertBefore'].forEach(function (method) { - $.extend(method, insertTo(method, $)); - }); - - if (jml) { - $.extend('jml', function () { - var _this6 = this; - - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - this.forEach(function (node) { - while (node.hasChildNodes()) { - node.firstChild.remove(); - } - - var n = jml.apply(void 0, args); - return append.call(_this6, n); - }); - }); - } - - return $; - }; - - manipulation($$1, jml); - var baseAPIURL = 'https://openclipart.org/search/json/'; - var jsVoid = 'javascript: void(0);'; // eslint-disable-line no-script-url - - /** - * Shows results after query submission. - * @param {string} url - * @returns {Promise} - */ - - function processResults(_x) { - return _processResults.apply(this, arguments); - } - - function _processResults() { - _processResults = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(url) { - var queryLink, r, json, payload, _json$info, numResults, pages, currentPage, semiColonSep; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - queryLink = function _queryLink(query) { - return ['a', { - href: jsVoid, - dataset: { - value: query - }, - $on: { - click: function click(e) { - e.preventDefault(); - var value = this.dataset.value; - $$1('#query')[0].$set(value); - $$1('#openclipart')[0].$submit(); - } - } - }, [query]]; - }; - - _context3.next = 3; - return fetch(url); - - case 3: - r = _context3.sent; - _context3.next = 6; - return r.json(); - - case 6: - json = _context3.sent; - - if (!(!json || json.msg !== 'success')) { - _context3.next = 10; - break; - } - - // Todo: This could use a generic alert library instead - alert('There was a problem downloading the results'); // eslint-disable-line no-alert - - return _context3.abrupt("return"); - - case 10: - payload = json.payload, _json$info = json.info, numResults = _json$info.results, pages = _json$info.pages, currentPage = _json$info.current_page; // $('#page')[0].value = currentPage; - // $('#page')[0].max = pages; - // Unused properties: - // - `svg_filesize` always 0? - // - `dimensions: { - // png_thumb: {width, height}, - // png_full_lossy: {width, height} - // }` object of relevance? - // - No need for `tags` with `tags_array` - // - `svg`'s: `png_thumb`, `png_full_lossy`, `png_2400px` - - semiColonSep = '; ' + nbsp; - $$1('#results').jml('div', [['span', ['Number of results: ', numResults]], semiColonSep, ['span', ['page ', currentPage, ' out of ', pages]]].concat(_toConsumableArray(payload.map(function (_ref3) { - var title = _ref3.title, - description = _ref3.description, - id = _ref3.id, - uploader = _ref3.uploader, - created = _ref3.created, - svgURL = _ref3.svg.url, - detailLink = _ref3.detail_link, - tagsArray = _ref3.tags_array, - downloadedBy = _ref3.downloaded_by, - totalFavorites = _ref3.total_favorites; - var imgHW = '100px'; - var colonSep = ': ' + nbsp; - return ['div', [['button', { - style: 'margin-right: 8px; border: 2px solid black;', - dataset: { - id: id, - value: svgURL - }, - $on: { - click: function click(e) { - var _this = this; - - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var svgurl, post, result, svg; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - e.preventDefault(); - svgurl = _this.dataset.value; // console.log('this', id, svgurl); - - post = function post(message) { - // Todo: Make origin customizable as set by opening window - // Todo: If dropping IE9, avoid stringifying - window.parent.postMessage(JSON.stringify(_extends({ - namespace: 'imagelib' - }, message)), '*'); - }; // Send metadata (also indicates file is about to be sent) - - - post({ - name: title, - id: svgurl - }); - _context2.next = 6; - return fetch(svgurl); - - case 6: - result = _context2.sent; - _context2.next = 9; - return result.text(); - - case 9: - svg = _context2.sent; - // console.log('url and svg', svgurl, svg); - post({ - href: svgurl, - data: svg - }); - - case 11: - case "end": - return _context2.stop(); - } - } - }, _callee2); - }))(); - } - } - }, [// If we wanted interactive versions despite security risk: - // ['object', {data: svgURL, type: 'image/svg+xml'}] - ['img', { - src: svgURL, - style: "width: ".concat(imgHW, "; height: ").concat(imgHW, ";") - }]]], ['b', [title]], ' ', ['i', [description]], ' ', ['span', ['(ID: ', ['a', { - href: jsVoid, - dataset: { - value: id - }, - $on: { - click: function click(e) { - e.preventDefault(); - var value = this.dataset.value; - $$1('#byids')[0].$set(value); - $$1('#openclipart')[0].$submit(); - } - } - }, [id]], ')']], ' ', ['i', [['a', { - href: detailLink, - target: '_blank' - }, ['Details']]]], ['br'], ['span', [['u', ['Uploaded by']], colonSep, queryLink(uploader), semiColonSep]], ['span', [['u', ['Download count']], colonSep, downloadedBy, semiColonSep]], ['span', [['u', ['Times used as favorite']], colonSep, totalFavorites, semiColonSep]], ['span', [['u', ['Created date']], colonSep, created]], ['br'], ['u', ['Tags']], colonSep].concat(_toConsumableArray(tagsArray.map(function (tag) { - return ['span', [' ', queryLink(tag)]]; - })))]; - })), [['br'], ['br'], currentPage === 1 || pages <= 2 ? '' : ['span', [['a', { - href: jsVoid, - $on: { - click: function click(e) { - e.preventDefault(); - $$1('#page')[0].value = 1; - $$1('#openclipart')[0].$submit(); - } - } - }, ['First']], ' ']], currentPage === 1 ? '' : ['span', [['a', { - href: jsVoid, - $on: { - click: function click(e) { - e.preventDefault(); - $$1('#page')[0].value = currentPage - 1; - $$1('#openclipart')[0].$submit(); - } - } - }, ['Prev']], ' ']], currentPage === pages ? '' : ['span', [['a', { - href: jsVoid, - $on: { - click: function click(e) { - e.preventDefault(); - $$1('#page')[0].value = currentPage + 1; - $$1('#openclipart')[0].$submit(); - } - } - }, ['Next']], ' ']], currentPage === pages || pages <= 2 ? '' : ['span', [['a', { - href: jsVoid, - $on: { - click: function click(e) { - e.preventDefault(); - $$1('#page')[0].value = pages; - $$1('#openclipart')[0].$submit(); - } - } - }, ['Last']], ' ']]])); - - case 13: - case "end": - return _context3.stop(); - } - } - }, _callee3); - })); - return _processResults.apply(this, arguments); - } - - jml('div', [['style', [".control {\n padding-top: 10px;\n }"]], ['form', { - id: 'openclipart', - $custom: { - $submit: function $submit() { - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var url; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - url = new URL(baseAPIURL); - ['query', 'sort', 'amount', 'page', 'byids'].forEach(function (prop) { - var value = $$1('#' + prop)[0].value; - - if (value) { - url.searchParams.set(prop, value); - } - }); - _context.next = 4; - return processResults(url); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee); - }))(); - } - }, - $on: { - submit: function submit(e) { - e.preventDefault(); - this.$submit(); - } - } - }, [// Todo: i18nize - ['fieldset', [['legend', ['Search terms']], ['div', { - "class": 'control' - }, [['label', ['Query (Title, description, uploader, or tag): ', ['input', { - id: 'query', - name: 'query', - placeholder: 'cat', - $custom: { - $set: function $set(value) { - $$1('#byids')[0].value = ''; - this.value = value; - } - }, - $on: { - change: function change() { - $$1('#byids')[0].value = ''; - } - } - }]]]]], ['br'], ' OR ', ['br'], ['div', { - "class": 'control' - }, [['label', ['IDs (single or comma-separated): ', ['input', { - id: 'byids', - name: 'ids', - placeholder: '271380, 265741', - $custom: { - $set: function $set(value) { - $$1('#query')[0].value = ''; - this.value = value; - } - }, - $on: { - change: function change() { - $$1('#query')[0].value = ''; - } - } - }]]]]]]], ['fieldset', [['legend', ['Configuring results']], ['div', { - "class": 'control' - }, [['label', ['Sort by: ', ['select', { - id: 'sort' - }, [// Todo: i18nize first values - ['Date', 'date'], ['Downloads', 'downloads'], ['Favorited', 'favorites']].map(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - text = _ref2[0], - _ref2$ = _ref2[1], - value = _ref2$ === void 0 ? text : _ref2$; - - return ['option', { - value: value - }, [text]]; - })]]]]], ['div', { - "class": 'control' - }, [['label', ['Results per page: ', ['input', { - id: 'amount', - name: 'amount', - value: 10, - type: 'number', - min: 1, - max: 200, - step: 1, - pattern: '\\d+' - }]]]]], ['div', { - "class": 'control' - }, [['label', ['Page number: ', ['input', { - // max: 1, // We'll change this based on available results - id: 'page', - name: 'page', - value: 1, - style: 'width: 40px;', - type: 'number', - min: 1, - step: 1, - pattern: '\\d+' - }]]]]]]], ['div', { - "class": 'control' - }, [['input', { - type: 'submit' - }]]]]], ['div', { - id: 'results' - }]], body); - -}()); diff --git a/dist/index-es.js b/dist/index-es.js deleted file mode 100644 index faa69cbe..00000000 --- a/dist/index-es.js +++ /dev/null @@ -1,36613 +0,0 @@ -function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); -} - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } -} - -function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; -} - -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} - -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); -} - -function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); -} - -function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); -} - -function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } -} - -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); -} - -function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; -} - -function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - - return object; -} - -function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.get) { - return desc.get.call(receiver); - } - - return desc.value; - }; - } - - return _get(target, property, receiver || target); -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); -} - -function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); -} - -function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; -} - -function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); -} - -function _iterableToArrayLimit(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; -} - -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); -} - -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; -} - -function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} - -function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} - -function _createForOfIteratorHelper(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - - var F = function () {}; - - return { - s: F, - n: function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function (e) { - throw e; - }, - f: F - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var normalCompletion = true, - didErr = false, - err; - return { - s: function () { - it = o[Symbol.iterator](); - }, - n: function () { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function (e) { - didErr = true; - err = e; - }, - f: function () { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; -} - -// http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/ - -/** - * - * @param {Event} ev - * @returns {void} - */ -function touchHandler(ev) { - var changedTouches = ev.changedTouches, - first = changedTouches[0]; - var type = ''; - - switch (ev.type) { - case 'touchstart': - type = 'mousedown'; - break; - - case 'touchmove': - type = 'mousemove'; - break; - - case 'touchend': - type = 'mouseup'; - break; - - default: - return; - } - - var screenX = first.screenX, - screenY = first.screenY, - clientX = first.clientX, - clientY = first.clientY; // eslint-disable-line no-shadow - - var simulatedEvent = new MouseEvent(type, { - // Event interface - bubbles: true, - cancelable: true, - // UIEvent interface - view: window, - detail: 1, - // click count - // MouseEvent interface (customized) - screenX: screenX, - screenY: screenY, - clientX: clientX, - clientY: clientY, - // MouseEvent interface (defaults) - these could be removed - ctrlKey: false, - altKey: false, - shiftKey: false, - metaKey: false, - button: 0, - // main button (usually left) - relatedTarget: null - }); - - if (changedTouches.length < 2) { - first.target.dispatchEvent(simulatedEvent); - ev.preventDefault(); - } -} - -document.addEventListener('touchstart', touchHandler, true); -document.addEventListener('touchmove', touchHandler, true); -document.addEventListener('touchend', touchHandler, true); -document.addEventListener('touchcancel', touchHandler, true); - -/** - * Namespaces or tools therefor. - * @module namespaces - * @license MIT -*/ - -/** -* Common namepaces constants in alpha order. -* @enum {string} -* @type {PlainObject} -* @memberof module:namespaces -*/ -var NS = { - HTML: 'http://www.w3.org/1999/xhtml', - MATH: 'http://www.w3.org/1998/Math/MathML', - SE: 'http://svg-edit.googlecode.com', - SVG: 'http://www.w3.org/2000/svg', - XLINK: 'http://www.w3.org/1999/xlink', - XML: 'http://www.w3.org/XML/1998/namespace', - XMLNS: 'http://www.w3.org/2000/xmlns/' // see http://www.w3.org/TR/REC-xml-names/#xmlReserved - -}; -/** -* @function module:namespaces.getReverseNS -* @returns {string} The NS with key values switched and lowercase -*/ - -var getReverseNS = function getReverseNS() { - var reverseNS = {}; - Object.entries(NS).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - name = _ref2[0], - URI = _ref2[1]; - - reverseNS[URI] = name.toLowerCase(); - }); - return reverseNS; -}; - -/* eslint-disable import/unambiguous, max-len */ - -/* globals SVGPathSeg, SVGPathSegMovetoRel, SVGPathSegMovetoAbs, - SVGPathSegMovetoRel, SVGPathSegLinetoRel, SVGPathSegLinetoAbs, - SVGPathSegLinetoHorizontalRel, SVGPathSegLinetoHorizontalAbs, - SVGPathSegLinetoVerticalRel, SVGPathSegLinetoVerticalAbs, - SVGPathSegClosePath, SVGPathSegCurvetoCubicRel, - SVGPathSegCurvetoCubicAbs, SVGPathSegCurvetoCubicSmoothRel, - SVGPathSegCurvetoCubicSmoothAbs, SVGPathSegCurvetoQuadraticRel, - SVGPathSegCurvetoQuadraticAbs, SVGPathSegCurvetoQuadraticSmoothRel, - SVGPathSegCurvetoQuadraticSmoothAbs, SVGPathSegArcRel, SVGPathSegArcAbs */ - -/** -* SVGPathSeg API polyfill -* https://github.com/progers/pathseg -* -* This is a drop-in replacement for the `SVGPathSeg` and `SVGPathSegList` APIs -* that were removed from SVG2 ({@link https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html}), -* including the latest spec changes which were implemented in Firefox 43 and -* Chrome 46. -*/ - -/* eslint-disable no-shadow, class-methods-use-this, jsdoc/require-jsdoc */ -// Linting: We avoid `no-shadow` as ESLint thinks these are still available globals -// Linting: We avoid `class-methods-use-this` as this is a polyfill that must -// follow the conventions -(function () { - if (!('SVGPathSeg' in window)) { - // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg - var _SVGPathSeg = /*#__PURE__*/function () { - function _SVGPathSeg(type, typeAsLetter, owningPathSegList) { - _classCallCheck(this, _SVGPathSeg); - - this.pathSegType = type; - this.pathSegTypeAsLetter = typeAsLetter; - this._owningPathSegList = owningPathSegList; - } // Notify owning PathSegList on any changes so they can be synchronized back to the path element. - - - _createClass(_SVGPathSeg, [{ - key: "_segmentChanged", - value: function _segmentChanged() { - if (this._owningPathSegList) { - this._owningPathSegList.segmentChanged(this); - } - } - }]); - - return _SVGPathSeg; - }(); - - _SVGPathSeg.prototype.classname = 'SVGPathSeg'; - _SVGPathSeg.PATHSEG_UNKNOWN = 0; - _SVGPathSeg.PATHSEG_CLOSEPATH = 1; - _SVGPathSeg.PATHSEG_MOVETO_ABS = 2; - _SVGPathSeg.PATHSEG_MOVETO_REL = 3; - _SVGPathSeg.PATHSEG_LINETO_ABS = 4; - _SVGPathSeg.PATHSEG_LINETO_REL = 5; - _SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6; - _SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7; - _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8; - _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9; - _SVGPathSeg.PATHSEG_ARC_ABS = 10; - _SVGPathSeg.PATHSEG_ARC_REL = 11; - _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12; - _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13; - _SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14; - _SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15; - _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16; - _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17; - _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18; - _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19; - - var _SVGPathSegClosePath = /*#__PURE__*/function (_SVGPathSeg2) { - _inherits(_SVGPathSegClosePath, _SVGPathSeg2); - - var _super = _createSuper(_SVGPathSegClosePath); - - function _SVGPathSegClosePath(owningPathSegList) { - _classCallCheck(this, _SVGPathSegClosePath); - - return _super.call(this, _SVGPathSeg.PATHSEG_CLOSEPATH, 'z', owningPathSegList); - } - - _createClass(_SVGPathSegClosePath, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegClosePath]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegClosePath(undefined); - } - }]); - - return _SVGPathSegClosePath; - }(_SVGPathSeg); - - var _SVGPathSegMovetoAbs = /*#__PURE__*/function (_SVGPathSeg3) { - _inherits(_SVGPathSegMovetoAbs, _SVGPathSeg3); - - var _super2 = _createSuper(_SVGPathSegMovetoAbs); - - function _SVGPathSegMovetoAbs(owningPathSegList, x, y) { - var _this; - - _classCallCheck(this, _SVGPathSegMovetoAbs); - - _this = _super2.call(this, _SVGPathSeg.PATHSEG_MOVETO_ABS, 'M', owningPathSegList); - _this._x = x; - _this._y = y; - return _this; - } - - _createClass(_SVGPathSegMovetoAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegMovetoAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegMovetoAbs(undefined, this._x, this._y); - } - }]); - - return _SVGPathSegMovetoAbs; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegMovetoAbs.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegMovetoRel = /*#__PURE__*/function (_SVGPathSeg4) { - _inherits(_SVGPathSegMovetoRel, _SVGPathSeg4); - - var _super3 = _createSuper(_SVGPathSegMovetoRel); - - function _SVGPathSegMovetoRel(owningPathSegList, x, y) { - var _this2; - - _classCallCheck(this, _SVGPathSegMovetoRel); - - _this2 = _super3.call(this, _SVGPathSeg.PATHSEG_MOVETO_REL, 'm', owningPathSegList); - _this2._x = x; - _this2._y = y; - return _this2; - } - - _createClass(_SVGPathSegMovetoRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegMovetoRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegMovetoRel(undefined, this._x, this._y); - } - }]); - - return _SVGPathSegMovetoRel; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegMovetoRel.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegLinetoAbs = /*#__PURE__*/function (_SVGPathSeg5) { - _inherits(_SVGPathSegLinetoAbs, _SVGPathSeg5); - - var _super4 = _createSuper(_SVGPathSegLinetoAbs); - - function _SVGPathSegLinetoAbs(owningPathSegList, x, y) { - var _this3; - - _classCallCheck(this, _SVGPathSegLinetoAbs); - - _this3 = _super4.call(this, _SVGPathSeg.PATHSEG_LINETO_ABS, 'L', owningPathSegList); - _this3._x = x; - _this3._y = y; - return _this3; - } - - _createClass(_SVGPathSegLinetoAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegLinetoAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegLinetoAbs(undefined, this._x, this._y); - } - }]); - - return _SVGPathSegLinetoAbs; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegLinetoAbs.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegLinetoRel = /*#__PURE__*/function (_SVGPathSeg6) { - _inherits(_SVGPathSegLinetoRel, _SVGPathSeg6); - - var _super5 = _createSuper(_SVGPathSegLinetoRel); - - function _SVGPathSegLinetoRel(owningPathSegList, x, y) { - var _this4; - - _classCallCheck(this, _SVGPathSegLinetoRel); - - _this4 = _super5.call(this, _SVGPathSeg.PATHSEG_LINETO_REL, 'l', owningPathSegList); - _this4._x = x; - _this4._y = y; - return _this4; - } - - _createClass(_SVGPathSegLinetoRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegLinetoRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegLinetoRel(undefined, this._x, this._y); - } - }]); - - return _SVGPathSegLinetoRel; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegLinetoRel.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegCurvetoCubicAbs = /*#__PURE__*/function (_SVGPathSeg7) { - _inherits(_SVGPathSegCurvetoCubicAbs, _SVGPathSeg7); - - var _super6 = _createSuper(_SVGPathSegCurvetoCubicAbs); - - function _SVGPathSegCurvetoCubicAbs(owningPathSegList, x, y, x1, y1, x2, y2) { - var _this5; - - _classCallCheck(this, _SVGPathSegCurvetoCubicAbs); - - _this5 = _super6.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, 'C', owningPathSegList); - _this5._x = x; - _this5._y = y; - _this5._x1 = x1; - _this5._y1 = y1; - _this5._x2 = x2; - _this5._y2 = y2; - return _this5; - } - - _createClass(_SVGPathSegCurvetoCubicAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoCubicAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoCubicAbs(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); - } - }]); - - return _SVGPathSegCurvetoCubicAbs; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoCubicAbs.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - x1: { - get: function get() { - return this._x1; - }, - set: function set(x1) { - this._x1 = x1; - - this._segmentChanged(); - }, - enumerable: true - }, - y1: { - get: function get() { - return this._y1; - }, - set: function set(y1) { - this._y1 = y1; - - this._segmentChanged(); - }, - enumerable: true - }, - x2: { - get: function get() { - return this._x2; - }, - set: function set(x2) { - this._x2 = x2; - - this._segmentChanged(); - }, - enumerable: true - }, - y2: { - get: function get() { - return this._y2; - }, - set: function set(y2) { - this._y2 = y2; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegCurvetoCubicRel = /*#__PURE__*/function (_SVGPathSeg8) { - _inherits(_SVGPathSegCurvetoCubicRel, _SVGPathSeg8); - - var _super7 = _createSuper(_SVGPathSegCurvetoCubicRel); - - function _SVGPathSegCurvetoCubicRel(owningPathSegList, x, y, x1, y1, x2, y2) { - var _this6; - - _classCallCheck(this, _SVGPathSegCurvetoCubicRel); - - _this6 = _super7.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, 'c', owningPathSegList); - _this6._x = x; - _this6._y = y; - _this6._x1 = x1; - _this6._y1 = y1; - _this6._x2 = x2; - _this6._y2 = y2; - return _this6; - } - - _createClass(_SVGPathSegCurvetoCubicRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoCubicRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoCubicRel(undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2); - } - }]); - - return _SVGPathSegCurvetoCubicRel; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoCubicRel.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - x1: { - get: function get() { - return this._x1; - }, - set: function set(x1) { - this._x1 = x1; - - this._segmentChanged(); - }, - enumerable: true - }, - y1: { - get: function get() { - return this._y1; - }, - set: function set(y1) { - this._y1 = y1; - - this._segmentChanged(); - }, - enumerable: true - }, - x2: { - get: function get() { - return this._x2; - }, - set: function set(x2) { - this._x2 = x2; - - this._segmentChanged(); - }, - enumerable: true - }, - y2: { - get: function get() { - return this._y2; - }, - set: function set(y2) { - this._y2 = y2; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegCurvetoQuadraticAbs = /*#__PURE__*/function (_SVGPathSeg9) { - _inherits(_SVGPathSegCurvetoQuadraticAbs, _SVGPathSeg9); - - var _super8 = _createSuper(_SVGPathSegCurvetoQuadraticAbs); - - function _SVGPathSegCurvetoQuadraticAbs(owningPathSegList, x, y, x1, y1) { - var _this7; - - _classCallCheck(this, _SVGPathSegCurvetoQuadraticAbs); - - _this7 = _super8.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, 'Q', owningPathSegList); - _this7._x = x; - _this7._y = y; - _this7._x1 = x1; - _this7._y1 = y1; - return _this7; - } - - _createClass(_SVGPathSegCurvetoQuadraticAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoQuadraticAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoQuadraticAbs(undefined, this._x, this._y, this._x1, this._y1); - } - }]); - - return _SVGPathSegCurvetoQuadraticAbs; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoQuadraticAbs.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - x1: { - get: function get() { - return this._x1; - }, - set: function set(x1) { - this._x1 = x1; - - this._segmentChanged(); - }, - enumerable: true - }, - y1: { - get: function get() { - return this._y1; - }, - set: function set(y1) { - this._y1 = y1; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegCurvetoQuadraticRel = /*#__PURE__*/function (_SVGPathSeg10) { - _inherits(_SVGPathSegCurvetoQuadraticRel, _SVGPathSeg10); - - var _super9 = _createSuper(_SVGPathSegCurvetoQuadraticRel); - - function _SVGPathSegCurvetoQuadraticRel(owningPathSegList, x, y, x1, y1) { - var _this8; - - _classCallCheck(this, _SVGPathSegCurvetoQuadraticRel); - - _this8 = _super9.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, 'q', owningPathSegList); - _this8._x = x; - _this8._y = y; - _this8._x1 = x1; - _this8._y1 = y1; - return _this8; - } - - _createClass(_SVGPathSegCurvetoQuadraticRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoQuadraticRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoQuadraticRel(undefined, this._x, this._y, this._x1, this._y1); - } - }]); - - return _SVGPathSegCurvetoQuadraticRel; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoQuadraticRel.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - x1: { - get: function get() { - return this._x1; - }, - set: function set(x1) { - this._x1 = x1; - - this._segmentChanged(); - }, - enumerable: true - }, - y1: { - get: function get() { - return this._y1; - }, - set: function set(y1) { - this._y1 = y1; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegArcAbs = /*#__PURE__*/function (_SVGPathSeg11) { - _inherits(_SVGPathSegArcAbs, _SVGPathSeg11); - - var _super10 = _createSuper(_SVGPathSegArcAbs); - - function _SVGPathSegArcAbs(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { - var _this9; - - _classCallCheck(this, _SVGPathSegArcAbs); - - _this9 = _super10.call(this, _SVGPathSeg.PATHSEG_ARC_ABS, 'A', owningPathSegList); - _this9._x = x; - _this9._y = y; - _this9._r1 = r1; - _this9._r2 = r2; - _this9._angle = angle; - _this9._largeArcFlag = largeArcFlag; - _this9._sweepFlag = sweepFlag; - return _this9; - } - - _createClass(_SVGPathSegArcAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegArcAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegArcAbs(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); - } - }]); - - return _SVGPathSegArcAbs; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegArcAbs.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - r1: { - get: function get() { - return this._r1; - }, - set: function set(r1) { - this._r1 = r1; - - this._segmentChanged(); - }, - enumerable: true - }, - r2: { - get: function get() { - return this._r2; - }, - set: function set(r2) { - this._r2 = r2; - - this._segmentChanged(); - }, - enumerable: true - }, - angle: { - get: function get() { - return this._angle; - }, - set: function set(angle) { - this._angle = angle; - - this._segmentChanged(); - }, - enumerable: true - }, - largeArcFlag: { - get: function get() { - return this._largeArcFlag; - }, - set: function set(largeArcFlag) { - this._largeArcFlag = largeArcFlag; - - this._segmentChanged(); - }, - enumerable: true - }, - sweepFlag: { - get: function get() { - return this._sweepFlag; - }, - set: function set(sweepFlag) { - this._sweepFlag = sweepFlag; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegArcRel = /*#__PURE__*/function (_SVGPathSeg12) { - _inherits(_SVGPathSegArcRel, _SVGPathSeg12); - - var _super11 = _createSuper(_SVGPathSegArcRel); - - function _SVGPathSegArcRel(owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag) { - var _this10; - - _classCallCheck(this, _SVGPathSegArcRel); - - _this10 = _super11.call(this, _SVGPathSeg.PATHSEG_ARC_REL, 'a', owningPathSegList); - _this10._x = x; - _this10._y = y; - _this10._r1 = r1; - _this10._r2 = r2; - _this10._angle = angle; - _this10._largeArcFlag = largeArcFlag; - _this10._sweepFlag = sweepFlag; - return _this10; - } - - _createClass(_SVGPathSegArcRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegArcRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegArcRel(undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag); - } - }]); - - return _SVGPathSegArcRel; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegArcRel.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - r1: { - get: function get() { - return this._r1; - }, - set: function set(r1) { - this._r1 = r1; - - this._segmentChanged(); - }, - enumerable: true - }, - r2: { - get: function get() { - return this._r2; - }, - set: function set(r2) { - this._r2 = r2; - - this._segmentChanged(); - }, - enumerable: true - }, - angle: { - get: function get() { - return this._angle; - }, - set: function set(angle) { - this._angle = angle; - - this._segmentChanged(); - }, - enumerable: true - }, - largeArcFlag: { - get: function get() { - return this._largeArcFlag; - }, - set: function set(largeArcFlag) { - this._largeArcFlag = largeArcFlag; - - this._segmentChanged(); - }, - enumerable: true - }, - sweepFlag: { - get: function get() { - return this._sweepFlag; - }, - set: function set(sweepFlag) { - this._sweepFlag = sweepFlag; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegLinetoHorizontalAbs = /*#__PURE__*/function (_SVGPathSeg13) { - _inherits(_SVGPathSegLinetoHorizontalAbs, _SVGPathSeg13); - - var _super12 = _createSuper(_SVGPathSegLinetoHorizontalAbs); - - function _SVGPathSegLinetoHorizontalAbs(owningPathSegList, x) { - var _this11; - - _classCallCheck(this, _SVGPathSegLinetoHorizontalAbs); - - _this11 = _super12.call(this, _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, 'H', owningPathSegList); - _this11._x = x; - return _this11; - } - - _createClass(_SVGPathSegLinetoHorizontalAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegLinetoHorizontalAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegLinetoHorizontalAbs(undefined, this._x); - } - }]); - - return _SVGPathSegLinetoHorizontalAbs; - }(_SVGPathSeg); - - Object.defineProperty(_SVGPathSegLinetoHorizontalAbs.prototype, 'x', { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }); - - var _SVGPathSegLinetoHorizontalRel = /*#__PURE__*/function (_SVGPathSeg14) { - _inherits(_SVGPathSegLinetoHorizontalRel, _SVGPathSeg14); - - var _super13 = _createSuper(_SVGPathSegLinetoHorizontalRel); - - function _SVGPathSegLinetoHorizontalRel(owningPathSegList, x) { - var _this12; - - _classCallCheck(this, _SVGPathSegLinetoHorizontalRel); - - _this12 = _super13.call(this, _SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, 'h', owningPathSegList); - _this12._x = x; - return _this12; - } - - _createClass(_SVGPathSegLinetoHorizontalRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegLinetoHorizontalRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegLinetoHorizontalRel(undefined, this._x); - } - }]); - - return _SVGPathSegLinetoHorizontalRel; - }(_SVGPathSeg); - - Object.defineProperty(_SVGPathSegLinetoHorizontalRel.prototype, 'x', { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }); - - var _SVGPathSegLinetoVerticalAbs = /*#__PURE__*/function (_SVGPathSeg15) { - _inherits(_SVGPathSegLinetoVerticalAbs, _SVGPathSeg15); - - var _super14 = _createSuper(_SVGPathSegLinetoVerticalAbs); - - function _SVGPathSegLinetoVerticalAbs(owningPathSegList, y) { - var _this13; - - _classCallCheck(this, _SVGPathSegLinetoVerticalAbs); - - _this13 = _super14.call(this, _SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, 'V', owningPathSegList); - _this13._y = y; - return _this13; - } - - _createClass(_SVGPathSegLinetoVerticalAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegLinetoVerticalAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegLinetoVerticalAbs(undefined, this._y); - } - }]); - - return _SVGPathSegLinetoVerticalAbs; - }(_SVGPathSeg); - - Object.defineProperty(_SVGPathSegLinetoVerticalAbs.prototype, 'y', { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }); - - var _SVGPathSegLinetoVerticalRel = /*#__PURE__*/function (_SVGPathSeg16) { - _inherits(_SVGPathSegLinetoVerticalRel, _SVGPathSeg16); - - var _super15 = _createSuper(_SVGPathSegLinetoVerticalRel); - - function _SVGPathSegLinetoVerticalRel(owningPathSegList, y) { - var _this14; - - _classCallCheck(this, _SVGPathSegLinetoVerticalRel); - - _this14 = _super15.call(this, _SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, 'v', owningPathSegList); - _this14._y = y; - return _this14; - } - - _createClass(_SVGPathSegLinetoVerticalRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegLinetoVerticalRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegLinetoVerticalRel(undefined, this._y); - } - }]); - - return _SVGPathSegLinetoVerticalRel; - }(_SVGPathSeg); - - Object.defineProperty(_SVGPathSegLinetoVerticalRel.prototype, 'y', { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }); - - var _SVGPathSegCurvetoCubicSmoothAbs = /*#__PURE__*/function (_SVGPathSeg17) { - _inherits(_SVGPathSegCurvetoCubicSmoothAbs, _SVGPathSeg17); - - var _super16 = _createSuper(_SVGPathSegCurvetoCubicSmoothAbs); - - function _SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, x, y, x2, y2) { - var _this15; - - _classCallCheck(this, _SVGPathSegCurvetoCubicSmoothAbs); - - _this15 = _super16.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, 'S', owningPathSegList); - _this15._x = x; - _this15._y = y; - _this15._x2 = x2; - _this15._y2 = y2; - return _this15; - } - - _createClass(_SVGPathSegCurvetoCubicSmoothAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoCubicSmoothAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoCubicSmoothAbs(undefined, this._x, this._y, this._x2, this._y2); - } - }]); - - return _SVGPathSegCurvetoCubicSmoothAbs; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoCubicSmoothAbs.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - x2: { - get: function get() { - return this._x2; - }, - set: function set(x2) { - this._x2 = x2; - - this._segmentChanged(); - }, - enumerable: true - }, - y2: { - get: function get() { - return this._y2; - }, - set: function set(y2) { - this._y2 = y2; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegCurvetoCubicSmoothRel = /*#__PURE__*/function (_SVGPathSeg18) { - _inherits(_SVGPathSegCurvetoCubicSmoothRel, _SVGPathSeg18); - - var _super17 = _createSuper(_SVGPathSegCurvetoCubicSmoothRel); - - function _SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, x, y, x2, y2) { - var _this16; - - _classCallCheck(this, _SVGPathSegCurvetoCubicSmoothRel); - - _this16 = _super17.call(this, _SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, 's', owningPathSegList); - _this16._x = x; - _this16._y = y; - _this16._x2 = x2; - _this16._y2 = y2; - return _this16; - } - - _createClass(_SVGPathSegCurvetoCubicSmoothRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoCubicSmoothRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoCubicSmoothRel(undefined, this._x, this._y, this._x2, this._y2); - } - }]); - - return _SVGPathSegCurvetoCubicSmoothRel; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoCubicSmoothRel.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - }, - x2: { - get: function get() { - return this._x2; - }, - set: function set(x2) { - this._x2 = x2; - - this._segmentChanged(); - }, - enumerable: true - }, - y2: { - get: function get() { - return this._y2; - }, - set: function set(y2) { - this._y2 = y2; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegCurvetoQuadraticSmoothAbs = /*#__PURE__*/function (_SVGPathSeg19) { - _inherits(_SVGPathSegCurvetoQuadraticSmoothAbs, _SVGPathSeg19); - - var _super18 = _createSuper(_SVGPathSegCurvetoQuadraticSmoothAbs); - - function _SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, x, y) { - var _this17; - - _classCallCheck(this, _SVGPathSegCurvetoQuadraticSmoothAbs); - - _this17 = _super18.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, 'T', owningPathSegList); - _this17._x = x; - _this17._y = y; - return _this17; - } - - _createClass(_SVGPathSegCurvetoQuadraticSmoothAbs, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoQuadraticSmoothAbs]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoQuadraticSmoothAbs(undefined, this._x, this._y); - } - }]); - - return _SVGPathSegCurvetoQuadraticSmoothAbs; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoQuadraticSmoothAbs.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - } - }); - - var _SVGPathSegCurvetoQuadraticSmoothRel = /*#__PURE__*/function (_SVGPathSeg20) { - _inherits(_SVGPathSegCurvetoQuadraticSmoothRel, _SVGPathSeg20); - - var _super19 = _createSuper(_SVGPathSegCurvetoQuadraticSmoothRel); - - function _SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, x, y) { - var _this18; - - _classCallCheck(this, _SVGPathSegCurvetoQuadraticSmoothRel); - - _this18 = _super19.call(this, _SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, 't', owningPathSegList); - _this18._x = x; - _this18._y = y; - return _this18; - } - - _createClass(_SVGPathSegCurvetoQuadraticSmoothRel, [{ - key: "toString", - value: function toString() { - return '[object SVGPathSegCurvetoQuadraticSmoothRel]'; - } - }, { - key: "_asPathString", - value: function _asPathString() { - return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y; - } - }, { - key: "clone", - value: function clone() { - return new _SVGPathSegCurvetoQuadraticSmoothRel(undefined, this._x, this._y); - } - }]); - - return _SVGPathSegCurvetoQuadraticSmoothRel; - }(_SVGPathSeg); - - Object.defineProperties(_SVGPathSegCurvetoQuadraticSmoothRel.prototype, { - x: { - get: function get() { - return this._x; - }, - set: function set(x) { - this._x = x; - - this._segmentChanged(); - }, - enumerable: true - }, - y: { - get: function get() { - return this._y; - }, - set: function set(y) { - this._y = y; - - this._segmentChanged(); - }, - enumerable: true - } - }); // Add createSVGPathSeg* functions to SVGPathElement. - // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathElement. - - SVGPathElement.prototype.createSVGPathSegClosePath = function () { - return new _SVGPathSegClosePath(undefined); - }; - - SVGPathElement.prototype.createSVGPathSegMovetoAbs = function (x, y) { - return new _SVGPathSegMovetoAbs(undefined, x, y); - }; - - SVGPathElement.prototype.createSVGPathSegMovetoRel = function (x, y) { - return new _SVGPathSegMovetoRel(undefined, x, y); - }; - - SVGPathElement.prototype.createSVGPathSegLinetoAbs = function (x, y) { - return new _SVGPathSegLinetoAbs(undefined, x, y); - }; - - SVGPathElement.prototype.createSVGPathSegLinetoRel = function (x, y) { - return new _SVGPathSegLinetoRel(undefined, x, y); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function (x, y, x1, y1, x2, y2) { - return new _SVGPathSegCurvetoCubicAbs(undefined, x, y, x1, y1, x2, y2); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function (x, y, x1, y1, x2, y2) { - return new _SVGPathSegCurvetoCubicRel(undefined, x, y, x1, y1, x2, y2); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function (x, y, x1, y1) { - return new _SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function (x, y, x1, y1) { - return new _SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1); - }; - - SVGPathElement.prototype.createSVGPathSegArcAbs = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { - return new _SVGPathSegArcAbs(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); - }; - - SVGPathElement.prototype.createSVGPathSegArcRel = function (x, y, r1, r2, angle, largeArcFlag, sweepFlag) { - return new _SVGPathSegArcRel(undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag); - }; - - SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function (x) { - return new _SVGPathSegLinetoHorizontalAbs(undefined, x); - }; - - SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function (x) { - return new _SVGPathSegLinetoHorizontalRel(undefined, x); - }; - - SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function (y) { - return new _SVGPathSegLinetoVerticalAbs(undefined, y); - }; - - SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function (y) { - return new _SVGPathSegLinetoVerticalRel(undefined, y); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function (x, y, x2, y2) { - return new _SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function (x, y, x2, y2) { - return new _SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function (x, y) { - return new _SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y); - }; - - SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function (x, y) { - return new _SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y); - }; - - if (!('getPathSegAtLength' in SVGPathElement.prototype)) { - // Add getPathSegAtLength to SVGPathElement. - // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-__svg__SVGPathElement__getPathSegAtLength - // This polyfill requires SVGPathElement.getTotalLength to implement the distance-along-a-path algorithm. - SVGPathElement.prototype.getPathSegAtLength = function (distance) { - if (distance === undefined || !isFinite(distance)) { - throw new Error('Invalid arguments.'); - } - - var measurementElement = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - measurementElement.setAttribute('d', this.getAttribute('d')); - var lastPathSegment = measurementElement.pathSegList.numberOfItems - 1; // If the path is empty, return 0. - - if (lastPathSegment <= 0) { - return 0; - } - - do { - measurementElement.pathSegList.removeItem(lastPathSegment); - - if (distance > measurementElement.getTotalLength()) { - break; - } - - lastPathSegment--; - } while (lastPathSegment > 0); - - return lastPathSegment; - }; - } - - window.SVGPathSeg = _SVGPathSeg; - window.SVGPathSegClosePath = _SVGPathSegClosePath; - window.SVGPathSegMovetoAbs = _SVGPathSegMovetoAbs; - window.SVGPathSegMovetoRel = _SVGPathSegMovetoRel; - window.SVGPathSegLinetoAbs = _SVGPathSegLinetoAbs; - window.SVGPathSegLinetoRel = _SVGPathSegLinetoRel; - window.SVGPathSegCurvetoCubicAbs = _SVGPathSegCurvetoCubicAbs; - window.SVGPathSegCurvetoCubicRel = _SVGPathSegCurvetoCubicRel; - window.SVGPathSegCurvetoQuadraticAbs = _SVGPathSegCurvetoQuadraticAbs; - window.SVGPathSegCurvetoQuadraticRel = _SVGPathSegCurvetoQuadraticRel; - window.SVGPathSegArcAbs = _SVGPathSegArcAbs; - window.SVGPathSegArcRel = _SVGPathSegArcRel; - window.SVGPathSegLinetoHorizontalAbs = _SVGPathSegLinetoHorizontalAbs; - window.SVGPathSegLinetoHorizontalRel = _SVGPathSegLinetoHorizontalRel; - window.SVGPathSegLinetoVerticalAbs = _SVGPathSegLinetoVerticalAbs; - window.SVGPathSegLinetoVerticalRel = _SVGPathSegLinetoVerticalRel; - window.SVGPathSegCurvetoCubicSmoothAbs = _SVGPathSegCurvetoCubicSmoothAbs; - window.SVGPathSegCurvetoCubicSmoothRel = _SVGPathSegCurvetoCubicSmoothRel; - window.SVGPathSegCurvetoQuadraticSmoothAbs = _SVGPathSegCurvetoQuadraticSmoothAbs; - window.SVGPathSegCurvetoQuadraticSmoothRel = _SVGPathSegCurvetoQuadraticSmoothRel; - } // Checking for SVGPathSegList in window checks for the case of an implementation without the - // SVGPathSegList API. - // The second check for appendItem is specific to Firefox 59+ which removed only parts of the - // SVGPathSegList API (e.g., appendItem). In this case we need to re-implement the entire API - // so the polyfill data (i.e., _list) is used throughout. - - - if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.prototype)) { - // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList - var SVGPathSegList = /*#__PURE__*/function () { - function SVGPathSegList(pathElement) { - _classCallCheck(this, SVGPathSegList); - - this._pathElement = pathElement; - this._list = this._parsePath(this._pathElement.getAttribute('d')); // Use a MutationObserver to catch changes to the path's "d" attribute. - - this._mutationObserverConfig = { - attributes: true, - attributeFilter: ['d'] - }; - this._pathElementMutationObserver = new MutationObserver(this._updateListFromPathMutations.bind(this)); - - this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig); - } // Process any pending mutations to the path element and update the list as needed. - // This should be the first call of all public functions and is needed because - // MutationObservers are not synchronous so we can have pending asynchronous mutations. - - - _createClass(SVGPathSegList, [{ - key: "_checkPathSynchronizedToList", - value: function _checkPathSynchronizedToList() { - this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords()); - } - }, { - key: "_updateListFromPathMutations", - value: function _updateListFromPathMutations(mutationRecords) { - if (!this._pathElement) { - return; - } - - var hasPathMutations = false; - mutationRecords.forEach(function (record) { - if (record.attributeName === 'd') { - hasPathMutations = true; - } - }); - - if (hasPathMutations) { - this._list = this._parsePath(this._pathElement.getAttribute('d')); - } - } // Serialize the list and update the path's 'd' attribute. - - }, { - key: "_writeListToPath", - value: function _writeListToPath() { - this._pathElementMutationObserver.disconnect(); - - this._pathElement.setAttribute('d', SVGPathSegList._pathSegArrayAsString(this._list)); - - this._pathElementMutationObserver.observe(this._pathElement, this._mutationObserverConfig); - } // When a path segment changes the list needs to be synchronized back to the path element. - - }, { - key: "segmentChanged", - value: function segmentChanged(pathSeg) { - this._writeListToPath(); - } - }, { - key: "clear", - value: function clear() { - this._checkPathSynchronizedToList(); - - this._list.forEach(function (pathSeg) { - pathSeg._owningPathSegList = null; - }); - - this._list = []; - - this._writeListToPath(); - } - }, { - key: "initialize", - value: function initialize(newItem) { - this._checkPathSynchronizedToList(); - - this._list = [newItem]; - newItem._owningPathSegList = this; - - this._writeListToPath(); - - return newItem; - } - }, { - key: "_checkValidIndex", - value: function _checkValidIndex(index) { - if (isNaN(index) || index < 0 || index >= this.numberOfItems) { - throw new Error('INDEX_SIZE_ERR'); - } - } - }, { - key: "getItem", - value: function getItem(index) { - this._checkPathSynchronizedToList(); - - this._checkValidIndex(index); - - return this._list[index]; - } - }, { - key: "insertItemBefore", - value: function insertItemBefore(newItem, index) { - this._checkPathSynchronizedToList(); // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list. - - - if (index > this.numberOfItems) { - index = this.numberOfItems; - } - - if (newItem._owningPathSegList) { - // SVG2 spec says to make a copy. - newItem = newItem.clone(); - } - - this._list.splice(index, 0, newItem); - - newItem._owningPathSegList = this; - - this._writeListToPath(); - - return newItem; - } - }, { - key: "replaceItem", - value: function replaceItem(newItem, index) { - this._checkPathSynchronizedToList(); - - if (newItem._owningPathSegList) { - // SVG2 spec says to make a copy. - newItem = newItem.clone(); - } - - this._checkValidIndex(index); - - this._list[index] = newItem; - newItem._owningPathSegList = this; - - this._writeListToPath(); - - return newItem; - } - }, { - key: "removeItem", - value: function removeItem(index) { - this._checkPathSynchronizedToList(); - - this._checkValidIndex(index); - - var item = this._list[index]; - - this._list.splice(index, 1); - - this._writeListToPath(); - - return item; - } - }, { - key: "appendItem", - value: function appendItem(newItem) { - this._checkPathSynchronizedToList(); - - if (newItem._owningPathSegList) { - // SVG2 spec says to make a copy. - newItem = newItem.clone(); - } - - this._list.push(newItem); - - newItem._owningPathSegList = this; // TODO: Optimize this to just append to the existing attribute. - - this._writeListToPath(); - - return newItem; - } // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp. - - }, { - key: "_parsePath", - value: function _parsePath(string) { - if (!string || !string.length) { - return []; - } - - var owningPathSegList = this; - - var Builder = /*#__PURE__*/function () { - function Builder() { - _classCallCheck(this, Builder); - - this.pathSegList = []; - } - - _createClass(Builder, [{ - key: "appendSegment", - value: function appendSegment(pathSeg) { - this.pathSegList.push(pathSeg); - } - }]); - - return Builder; - }(); - - var Source = /*#__PURE__*/function () { - function Source(string) { - _classCallCheck(this, Source); - - this._string = string; - this._currentIndex = 0; - this._endIndex = this._string.length; - this._previousCommand = SVGPathSeg.PATHSEG_UNKNOWN; - - this._skipOptionalSpaces(); - } - - _createClass(Source, [{ - key: "_isCurrentSpace", - value: function _isCurrentSpace() { - var character = this._string[this._currentIndex]; - return character <= ' ' && (character === ' ' || character === '\n' || character === '\t' || character === '\r' || character === '\f'); - } - }, { - key: "_skipOptionalSpaces", - value: function _skipOptionalSpaces() { - while (this._currentIndex < this._endIndex && this._isCurrentSpace()) { - this._currentIndex++; - } - - return this._currentIndex < this._endIndex; - } - }, { - key: "_skipOptionalSpacesOrDelimiter", - value: function _skipOptionalSpacesOrDelimiter() { - if (this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) !== ',') { - return false; - } - - if (this._skipOptionalSpaces()) { - if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === ',') { - this._currentIndex++; - - this._skipOptionalSpaces(); - } - } - - return this._currentIndex < this._endIndex; - } - }, { - key: "hasMoreData", - value: function hasMoreData() { - return this._currentIndex < this._endIndex; - } - }, { - key: "peekSegmentType", - value: function peekSegmentType() { - var lookahead = this._string[this._currentIndex]; - return this._pathSegTypeFromChar(lookahead); - } - }, { - key: "_pathSegTypeFromChar", - value: function _pathSegTypeFromChar(lookahead) { - switch (lookahead) { - case 'Z': - case 'z': - return SVGPathSeg.PATHSEG_CLOSEPATH; - - case 'M': - return SVGPathSeg.PATHSEG_MOVETO_ABS; - - case 'm': - return SVGPathSeg.PATHSEG_MOVETO_REL; - - case 'L': - return SVGPathSeg.PATHSEG_LINETO_ABS; - - case 'l': - return SVGPathSeg.PATHSEG_LINETO_REL; - - case 'C': - return SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS; - - case 'c': - return SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL; - - case 'Q': - return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS; - - case 'q': - return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL; - - case 'A': - return SVGPathSeg.PATHSEG_ARC_ABS; - - case 'a': - return SVGPathSeg.PATHSEG_ARC_REL; - - case 'H': - return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS; - - case 'h': - return SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL; - - case 'V': - return SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS; - - case 'v': - return SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL; - - case 'S': - return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS; - - case 's': - return SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL; - - case 'T': - return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS; - - case 't': - return SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL; - - default: - return SVGPathSeg.PATHSEG_UNKNOWN; - } - } - }, { - key: "_nextCommandHelper", - value: function _nextCommandHelper(lookahead, previousCommand) { - // Check for remaining coordinates in the current command. - if ((lookahead === '+' || lookahead === '-' || lookahead === '.' || lookahead >= '0' && lookahead <= '9') && previousCommand !== SVGPathSeg.PATHSEG_CLOSEPATH) { - if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_ABS) { - return SVGPathSeg.PATHSEG_LINETO_ABS; - } - - if (previousCommand === SVGPathSeg.PATHSEG_MOVETO_REL) { - return SVGPathSeg.PATHSEG_LINETO_REL; - } - - return previousCommand; - } - - return SVGPathSeg.PATHSEG_UNKNOWN; - } - }, { - key: "initialCommandIsMoveTo", - value: function initialCommandIsMoveTo() { - // If the path is empty it is still valid, so return true. - if (!this.hasMoreData()) { - return true; - } - - var command = this.peekSegmentType(); // Path must start with moveTo. - - return command === SVGPathSeg.PATHSEG_MOVETO_ABS || command === SVGPathSeg.PATHSEG_MOVETO_REL; - } // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp. - // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF - - }, { - key: "_parseNumber", - value: function _parseNumber() { - var exponent = 0; - var integer = 0; - var frac = 1; - var decimal = 0; - var sign = 1; - var expsign = 1; - var startIndex = this._currentIndex; - - this._skipOptionalSpaces(); // Read the sign. - - - if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '+') { - this._currentIndex++; - } else if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '-') { - this._currentIndex++; - sign = -1; - } - - if (this._currentIndex === this._endIndex || (this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') && this._string.charAt(this._currentIndex) !== '.') { - // The first character of a number must be one of [0-9+-.]. - return undefined; - } // Read the integer part, build right-to-left. - - - var startIntPartIndex = this._currentIndex; - - while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') { - this._currentIndex++; // Advance to first non-digit. - } - - if (this._currentIndex !== startIntPartIndex) { - var scanIntPartIndex = this._currentIndex - 1; - var multiplier = 1; - - while (scanIntPartIndex >= startIntPartIndex) { - integer += multiplier * (this._string.charAt(scanIntPartIndex--) - '0'); - multiplier *= 10; - } - } // Read the decimals. - - - if (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) === '.') { - this._currentIndex++; // There must be a least one digit following the . - - if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') { - return undefined; - } - - while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') { - frac *= 10; - decimal += (this._string.charAt(this._currentIndex) - '0') / frac; - this._currentIndex += 1; - } - } // Read the exponent part. - - - if (this._currentIndex !== startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) === 'e' || this._string.charAt(this._currentIndex) === 'E') && this._string.charAt(this._currentIndex + 1) !== 'x' && this._string.charAt(this._currentIndex + 1) !== 'm') { - this._currentIndex++; // Read the sign of the exponent. - - if (this._string.charAt(this._currentIndex) === '+') { - this._currentIndex++; - } else if (this._string.charAt(this._currentIndex) === '-') { - this._currentIndex++; - expsign = -1; - } // There must be an exponent. - - - if (this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') { - return undefined; - } - - while (this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9') { - exponent *= 10; - exponent += this._string.charAt(this._currentIndex) - '0'; - this._currentIndex++; - } - } - - var number = integer + decimal; - number *= sign; - - if (exponent) { - number *= Math.pow(10, expsign * exponent); - } - - if (startIndex === this._currentIndex) { - return undefined; - } - - this._skipOptionalSpacesOrDelimiter(); - - return number; - } - }, { - key: "_parseArcFlag", - value: function _parseArcFlag() { - if (this._currentIndex >= this._endIndex) { - return undefined; - } - - var flag = false; - - var flagChar = this._string.charAt(this._currentIndex++); - - if (flagChar === '0') { - flag = false; - } else if (flagChar === '1') { - flag = true; - } else { - return undefined; - } - - this._skipOptionalSpacesOrDelimiter(); - - return flag; - } - }, { - key: "parseSegment", - value: function parseSegment() { - var lookahead = this._string[this._currentIndex]; - - var command = this._pathSegTypeFromChar(lookahead); - - if (command === SVGPathSeg.PATHSEG_UNKNOWN) { - // Possibly an implicit command. Not allowed if this is the first command. - if (this._previousCommand === SVGPathSeg.PATHSEG_UNKNOWN) { - return null; - } - - command = this._nextCommandHelper(lookahead, this._previousCommand); - - if (command === SVGPathSeg.PATHSEG_UNKNOWN) { - return null; - } - } else { - this._currentIndex++; - } - - this._previousCommand = command; - - switch (command) { - case SVGPathSeg.PATHSEG_MOVETO_REL: - return new SVGPathSegMovetoRel(owningPathSegList, this._parseNumber(), this._parseNumber()); - - case SVGPathSeg.PATHSEG_MOVETO_ABS: - return new SVGPathSegMovetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); - - case SVGPathSeg.PATHSEG_LINETO_REL: - return new SVGPathSegLinetoRel(owningPathSegList, this._parseNumber(), this._parseNumber()); - - case SVGPathSeg.PATHSEG_LINETO_ABS: - return new SVGPathSegLinetoAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); - - case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL: - return new SVGPathSegLinetoHorizontalRel(owningPathSegList, this._parseNumber()); - - case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS: - return new SVGPathSegLinetoHorizontalAbs(owningPathSegList, this._parseNumber()); - - case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL: - return new SVGPathSegLinetoVerticalRel(owningPathSegList, this._parseNumber()); - - case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS: - return new SVGPathSegLinetoVerticalAbs(owningPathSegList, this._parseNumber()); - - case SVGPathSeg.PATHSEG_CLOSEPATH: - this._skipOptionalSpaces(); - - return new SVGPathSegClosePath(owningPathSegList); - - case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: - { - var points = { - x1: this._parseNumber(), - y1: this._parseNumber(), - x2: this._parseNumber(), - y2: this._parseNumber(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegCurvetoCubicRel(owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2); - } - - case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: - { - var _points = { - x1: this._parseNumber(), - y1: this._parseNumber(), - x2: this._parseNumber(), - y2: this._parseNumber(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegCurvetoCubicAbs(owningPathSegList, _points.x, _points.y, _points.x1, _points.y1, _points.x2, _points.y2); - } - - case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: - { - var _points2 = { - x2: this._parseNumber(), - y2: this._parseNumber(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegCurvetoCubicSmoothRel(owningPathSegList, _points2.x, _points2.y, _points2.x2, _points2.y2); - } - - case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: - { - var _points3 = { - x2: this._parseNumber(), - y2: this._parseNumber(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegCurvetoCubicSmoothAbs(owningPathSegList, _points3.x, _points3.y, _points3.x2, _points3.y2); - } - - case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: - { - var _points4 = { - x1: this._parseNumber(), - y1: this._parseNumber(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegCurvetoQuadraticRel(owningPathSegList, _points4.x, _points4.y, _points4.x1, _points4.y1); - } - - case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: - { - var _points5 = { - x1: this._parseNumber(), - y1: this._parseNumber(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegCurvetoQuadraticAbs(owningPathSegList, _points5.x, _points5.y, _points5.x1, _points5.y1); - } - - case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: - return new SVGPathSegCurvetoQuadraticSmoothRel(owningPathSegList, this._parseNumber(), this._parseNumber()); - - case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: - return new SVGPathSegCurvetoQuadraticSmoothAbs(owningPathSegList, this._parseNumber(), this._parseNumber()); - - case SVGPathSeg.PATHSEG_ARC_REL: - { - var _points6 = { - x1: this._parseNumber(), - y1: this._parseNumber(), - arcAngle: this._parseNumber(), - arcLarge: this._parseArcFlag(), - arcSweep: this._parseArcFlag(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegArcRel(owningPathSegList, _points6.x, _points6.y, _points6.x1, _points6.y1, _points6.arcAngle, _points6.arcLarge, _points6.arcSweep); - } - - case SVGPathSeg.PATHSEG_ARC_ABS: - { - var _points7 = { - x1: this._parseNumber(), - y1: this._parseNumber(), - arcAngle: this._parseNumber(), - arcLarge: this._parseArcFlag(), - arcSweep: this._parseArcFlag(), - x: this._parseNumber(), - y: this._parseNumber() - }; - return new SVGPathSegArcAbs(owningPathSegList, _points7.x, _points7.y, _points7.x1, _points7.y1, _points7.arcAngle, _points7.arcLarge, _points7.arcSweep); - } - - default: - throw new Error('Unknown path seg type.'); - } - } - }]); - - return Source; - }(); - - var builder = new Builder(); - var source = new Source(string); - - if (!source.initialCommandIsMoveTo()) { - return []; - } - - while (source.hasMoreData()) { - var pathSeg = source.parseSegment(); - - if (!pathSeg) { - return []; - } - - builder.appendSegment(pathSeg); - } - - return builder.pathSegList; - } // STATIC - - }], [{ - key: "_pathSegArrayAsString", - value: function _pathSegArrayAsString(pathSegArray) { - var string = ''; - var first = true; - pathSegArray.forEach(function (pathSeg) { - if (first) { - first = false; - string += pathSeg._asPathString(); - } else { - string += ' ' + pathSeg._asPathString(); - } - }); - return string; - } - }]); - - return SVGPathSegList; - }(); - - SVGPathSegList.prototype.classname = 'SVGPathSegList'; - Object.defineProperty(SVGPathSegList.prototype, 'numberOfItems', { - get: function get() { - this._checkPathSynchronizedToList(); - - return this._list.length; - }, - enumerable: true - }); // Add the pathSegList accessors to SVGPathElement. - // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData - - Object.defineProperties(SVGPathElement.prototype, { - pathSegList: { - get: function get() { - if (!this._pathSegList) { - this._pathSegList = new SVGPathSegList(this); - } - - return this._pathSegList; - }, - enumerable: true - }, - // TODO: The following are not implemented and simply return SVGPathElement.pathSegList. - normalizedPathSegList: { - get: function get() { - return this.pathSegList; - }, - enumerable: true - }, - animatedPathSegList: { - get: function get() { - return this.pathSegList; - }, - enumerable: true - }, - animatedNormalizedPathSegList: { - get: function get() { - return this.pathSegList; - }, - enumerable: true - } - }); - window.SVGPathSegList = SVGPathSegList; - } -})(); - -var $ = jQuery; - -var supportsSVG_ = function () { - return Boolean(document.createElementNS && document.createElementNS(NS.SVG, 'svg').createSVGRect); -}(); -var _navigator = navigator, - userAgent = _navigator.userAgent; -var svg = document.createElementNS(NS.SVG, 'svg'); // Note: Browser sniffing should only be used if no other detection method is possible - -var isOpera_ = Boolean(window.opera); -var isWebkit_ = userAgent.includes('AppleWebKit'); -var isGecko_ = userAgent.includes('Gecko/'); -var isIE_ = userAgent.includes('MSIE'); -var isChrome_ = userAgent.includes('Chrome/'); -var isWindows_ = userAgent.includes('Windows'); -var isMac_ = userAgent.includes('Macintosh'); -var isTouch_ = ('ontouchstart' in window); - -var supportsSelectors_ = function () { - return Boolean(svg.querySelector); -}(); - -var supportsXpath_ = function () { - return Boolean(document.evaluate); -}(); // segList functions (for FF1.5 and 2.0) - - -var supportsPathReplaceItem_ = function () { - var path = document.createElementNS(NS.SVG, 'path'); - path.setAttribute('d', 'M0,0 10,10'); - var seglist = path.pathSegList; - var seg = path.createSVGPathSegLinetoAbs(5, 5); - - try { - seglist.replaceItem(seg, 1); - return true; - } catch (err) {} - - return false; -}(); - -var supportsPathInsertItemBefore_ = function () { - var path = document.createElementNS(NS.SVG, 'path'); - path.setAttribute('d', 'M0,0 10,10'); - var seglist = path.pathSegList; - var seg = path.createSVGPathSegLinetoAbs(5, 5); - - try { - seglist.insertItemBefore(seg, 1); - return true; - } catch (err) {} - - return false; -}(); // text character positioning (for IE9 and now Chrome) - - -var supportsGoodTextCharPos_ = function () { - var svgroot = document.createElementNS(NS.SVG, 'svg'); - var svgcontent = document.createElementNS(NS.SVG, 'svg'); - document.documentElement.append(svgroot); - svgcontent.setAttribute('x', 5); - svgroot.append(svgcontent); - var text = document.createElementNS(NS.SVG, 'text'); - text.textContent = 'a'; - svgcontent.append(text); - - try { - // Chrome now fails here - var pos = text.getStartPositionOfChar(0).x; - return pos === 0; - } catch (err) { - return false; - } finally { - svgroot.remove(); - } -}(); - -var supportsPathBBox_ = function () { - var svgcontent = document.createElementNS(NS.SVG, 'svg'); - document.documentElement.append(svgcontent); - var path = document.createElementNS(NS.SVG, 'path'); - path.setAttribute('d', 'M0,0 C0,0 10,10 10,0'); - svgcontent.append(path); - var bbox = path.getBBox(); - svgcontent.remove(); - return bbox.height > 4 && bbox.height < 5; -}(); // Support for correct bbox sizing on groups with horizontal/vertical lines - - -var supportsHVLineContainerBBox_ = function () { - var svgcontent = document.createElementNS(NS.SVG, 'svg'); - document.documentElement.append(svgcontent); - var path = document.createElementNS(NS.SVG, 'path'); - path.setAttribute('d', 'M0,0 10,0'); - var path2 = document.createElementNS(NS.SVG, 'path'); - path2.setAttribute('d', 'M5,0 15,0'); - var g = document.createElementNS(NS.SVG, 'g'); - g.append(path, path2); - svgcontent.append(g); - var bbox = g.getBBox(); - svgcontent.remove(); // Webkit gives 0, FF gives 10, Opera (correctly) gives 15 - - return bbox.width === 15; -}(); - -var supportsGoodDecimals_ = function () { - // Correct decimals on clone attributes (Opera < 10.5/win/non-en) - var rect = document.createElementNS(NS.SVG, 'rect'); - rect.setAttribute('x', 0.1); - var crect = rect.cloneNode(false); - var retValue = !crect.getAttribute('x').includes(','); - - if (!retValue) { - // Todo: i18nize or remove - $.alert('NOTE: This version of Opera is known to contain bugs in SVG-edit.\n' + 'Please upgrade to the latest version in which the problems have been fixed.'); - } - - return retValue; -}(); - -var supportsNonScalingStroke_ = function () { - var rect = document.createElementNS(NS.SVG, 'rect'); - rect.setAttribute('style', 'vector-effect:non-scaling-stroke'); - return rect.style.vectorEffect === 'non-scaling-stroke'; -}(); - -var supportsNativeSVGTransformLists_ = function () { - var rect = document.createElementNS(NS.SVG, 'rect'); - var rxform = rect.transform.baseVal; - var t1 = svg.createSVGTransform(); - rxform.appendItem(t1); - var r1 = rxform.getItem(0); - - var isSVGTransform = function isSVGTransform(o) { - // https://developer.mozilla.org/en-US/docs/Web/API/SVGTransform - return o && _typeof(o) === 'object' && typeof o.setMatrix === 'function' && 'angle' in o; - }; - - return isSVGTransform(r1) && isSVGTransform(t1) && r1.type === t1.type && r1.angle === t1.angle && r1.matrix.a === t1.matrix.a && r1.matrix.b === t1.matrix.b && r1.matrix.c === t1.matrix.c && r1.matrix.d === t1.matrix.d && r1.matrix.e === t1.matrix.e && r1.matrix.f === t1.matrix.f; -}(); // Public API - -/** - * @function module:browser.isOpera - * @returns {boolean} -*/ - - -var isOpera = function isOpera() { - return isOpera_; -}; -/** - * @function module:browser.isWebkit - * @returns {boolean} -*/ - -var isWebkit = function isWebkit() { - return isWebkit_; -}; -/** - * @function module:browser.isGecko - * @returns {boolean} -*/ - -var isGecko = function isGecko() { - return isGecko_; -}; -/** - * @function module:browser.isIE - * @returns {boolean} -*/ - -var isIE = function isIE() { - return isIE_; -}; -/** - * @function module:browser.isChrome - * @returns {boolean} -*/ - -var isChrome = function isChrome() { - return isChrome_; -}; -/** - * @function module:browser.isMac - * @returns {boolean} -*/ - -var isMac = function isMac() { - return isMac_; -}; -/** - * @function module:browser.isTouch - * @returns {boolean} -*/ - -var isTouch = function isTouch() { - return isTouch_; -}; -/** - * @function module:browser.supportsSelectors - * @returns {boolean} -*/ - -var supportsSelectors = function supportsSelectors() { - return supportsSelectors_; -}; -/** - * @function module:browser.supportsXpath - * @returns {boolean} -*/ - -var supportsXpath = function supportsXpath() { - return supportsXpath_; -}; -/** - * @function module:browser.supportsPathReplaceItem - * @returns {boolean} -*/ - -var supportsPathReplaceItem = function supportsPathReplaceItem() { - return supportsPathReplaceItem_; -}; -/** - * @function module:browser.supportsPathInsertItemBefore - * @returns {boolean} -*/ - -var supportsPathInsertItemBefore = function supportsPathInsertItemBefore() { - return supportsPathInsertItemBefore_; -}; -/** - * @function module:browser.supportsPathBBox - * @returns {boolean} -*/ - -var supportsPathBBox = function supportsPathBBox() { - return supportsPathBBox_; -}; -/** - * @function module:browser.supportsHVLineContainerBBox - * @returns {boolean} -*/ - -var supportsHVLineContainerBBox = function supportsHVLineContainerBBox() { - return supportsHVLineContainerBBox_; -}; -/** - * @function module:browser.supportsGoodTextCharPos - * @returns {boolean} -*/ - -var supportsGoodTextCharPos = function supportsGoodTextCharPos() { - return supportsGoodTextCharPos_; -}; -/** -* @function module:browser.supportsNonScalingStroke -* @returns {boolean} -*/ - -var supportsNonScalingStroke = function supportsNonScalingStroke() { - return supportsNonScalingStroke_; -}; -/** -* @function module:browser.supportsNativeTransformLists -* @returns {boolean} -*/ - -var supportsNativeTransformLists = function supportsNativeTransformLists() { - return supportsNativeSVGTransformLists_; -}; - -/** - * A jQuery module to work with SVG attributes. - * @module jQueryAttr - * @license MIT - */ - -/** -* This fixes `$(...).attr()` to work as expected with SVG elements. -* Does not currently use `*AttributeNS()` since we rarely need that. -* Adds {@link external:jQuery.fn.attr}. -* See {@link https://api.jquery.com/attr/} for basic documentation of `.attr()`. -* -* Additional functionality: -* - When getting attributes, a string that's a number is returned as type number. -* - If an array is supplied as the first parameter, multiple values are returned -* as an object with values for each given attribute. -* @function module:jQueryAttr.jQueryAttr -* @param {external:jQuery} $ The jQuery object to which to add the plug-in -* @returns {external:jQuery} -*/ -function jQueryPluginSVG($) { - var proxied = $.fn.attr, - svgns = 'http://www.w3.org/2000/svg'; - /** - * @typedef {PlainObject} module:jQueryAttr.Attributes - */ - - /** - * @function external:jQuery.fn.attr - * @param {string|string[]|PlainObject} key - * @param {string} value - * @returns {external:jQuery|module:jQueryAttr.Attributes} - */ - - $.fn.attr = function (key, value) { - var len = this.length; - - if (!len) { - return proxied.call(this, key, value); - } - - for (var i = 0; i < len; ++i) { - var elem = this[i]; // set/get SVG attribute - - if (elem.namespaceURI === svgns) { - // Setting attribute - if (value !== undefined) { - elem.setAttribute(key, value); - } else if (Array.isArray(key)) { - // Getting attributes from array - var obj = {}; - var j = key.length; - - while (j--) { - var aname = key[j]; - var attr = elem.getAttribute(aname); // This returns a number when appropriate - - if (attr || attr === '0') { - attr = isNaN(attr) ? attr : attr - 0; - } - - obj[aname] = attr; - } - - return obj; - } - - if (_typeof(key) === 'object') { - // Setting attributes from object - for (var _i = 0, _Object$entries = Object.entries(key); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), - name = _Object$entries$_i[0], - val = _Object$entries$_i[1]; - - elem.setAttribute(name, val); - } // Getting attribute - - } else { - var _attr = elem.getAttribute(key); - - if (_attr || _attr === '0') { - _attr = isNaN(_attr) ? _attr : _attr - 0; - } - - return _attr; - } - } else { - return proxied.call(this, key, value); - } - } - - return this; - }; - - return $; -} - -var svgroot = document.createElementNS(NS.SVG, 'svg'); -/** - * Helper function to convert `SVGTransform` to a string. - * @param {SVGTransform} xform - * @returns {string} - */ - -function transformToString(xform) { - var m = xform.matrix; - var text = ''; - - switch (xform.type) { - case 1: - // MATRIX - text = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')'; - break; - - case 2: - // TRANSLATE - text = 'translate(' + m.e + ',' + m.f + ')'; - break; - - case 3: - // SCALE - if (m.a === m.d) { - text = 'scale(' + m.a + ')'; - } else { - text = 'scale(' + m.a + ',' + m.d + ')'; - } - - break; - - case 4: - { - // ROTATE - var cx = 0; - var cy = 0; // this prevents divide by zero - - if (xform.angle !== 0) { - var K = 1 - m.a; - cy = (K * m.f + m.b * m.e) / (K * K + m.b * m.b); - cx = (m.e - m.b * cy) / K; - } - - text = 'rotate(' + xform.angle + ' ' + cx + ',' + cy + ')'; - break; - } - } - - return text; -} -/** - * Map of SVGTransformList objects. - */ - - -var listMap_ = {}; -/** -* @interface module:SVGTransformList.SVGEditTransformList -* @property {Integer} numberOfItems unsigned long -*/ - -/** -* @function module:SVGTransformList.SVGEditTransformList#clear -* @returns {void} -*/ - -/** -* @function module:SVGTransformList.SVGEditTransformList#initialize -* @param {SVGTransform} newItem -* @returns {SVGTransform} -*/ - -/** -* DOES NOT THROW DOMException, INDEX_SIZE_ERR. -* @function module:SVGTransformList.SVGEditTransformList#getItem -* @param {Integer} index unsigned long -* @returns {SVGTransform} -*/ - -/** -* DOES NOT THROW DOMException, INDEX_SIZE_ERR. -* @function module:SVGTransformList.SVGEditTransformList#insertItemBefore -* @param {SVGTransform} newItem -* @param {Integer} index unsigned long -* @returns {SVGTransform} -*/ - -/** -* DOES NOT THROW DOMException, INDEX_SIZE_ERR. -* @function module:SVGTransformList.SVGEditTransformList#replaceItem -* @param {SVGTransform} newItem -* @param {Integer} index unsigned long -* @returns {SVGTransform} -*/ - -/** -* DOES NOT THROW DOMException, INDEX_SIZE_ERR. -* @function module:SVGTransformList.SVGEditTransformList#removeItem -* @param {Integer} index unsigned long -* @returns {SVGTransform} -*/ - -/** -* @function module:SVGTransformList.SVGEditTransformList#appendItem -* @param {SVGTransform} newItem -* @returns {SVGTransform} -*/ - -/** -* NOT IMPLEMENTED. -* @ignore -* @function module:SVGTransformList.SVGEditTransformList#createSVGTransformFromMatrix -* @param {SVGMatrix} matrix -* @returns {SVGTransform} -*/ - -/** -* NOT IMPLEMENTED. -* @ignore -* @function module:SVGTransformList.SVGEditTransformList#consolidate -* @returns {SVGTransform} -*/ - -/** -* SVGTransformList implementation for Webkit. -* These methods do not currently raise any exceptions. -* These methods also do not check that transforms are being inserted. This is basically -* implementing as much of SVGTransformList that we need to get the job done. -* @implements {module:SVGTransformList.SVGEditTransformList} -*/ - -var SVGTransformList = /*#__PURE__*/function () { - // eslint-disable-line no-shadow - - /** - * @param {Element} elem - * @returns {SVGTransformList} - */ - function SVGTransformList(elem) { - _classCallCheck(this, SVGTransformList); - - this._elem = elem || null; - this._xforms = []; // TODO: how do we capture the undo-ability in the changed transform list? - - this._update = function () { - var tstr = ''; // /* const concatMatrix = */ svgroot.createSVGMatrix(); - - for (var i = 0; i < this.numberOfItems; ++i) { - var xform = this._list.getItem(i); - - tstr += transformToString(xform) + ' '; - } - - this._elem.setAttribute('transform', tstr); - }; - - this._list = this; - - this._init = function () { - var _this = this; - - // Transform attribute parser - var str = this._elem.getAttribute('transform'); - - if (!str) { - return; - } // TODO: Add skew support in future - - - var re = /\s*((scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/; // const re = /\s*(?(?:scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/; - - var m = true; - - while (m) { - m = str.match(re); - str = str.replace(re, ''); - - if (m && m[1]) { - (function () { - var x = m[1]; - var bits = x.split(/\s*\(/); - var name = bits[0]; - var valBits = bits[1].match(/\s*(.*?)\s*\)/); - valBits[1] = valBits[1].replace(/(\d)-/g, '$1 -'); - var valArr = valBits[1].split(/[, ]+/); - var letters = 'abcdef'.split(''); - /* - if (m && m.groups.xform) { - const x = m.groups.xform; - const [name, bits] = x.split(/\s*\(/); - const valBits = bits.match(/\s*(?.*?)\s*\)/); - valBits.groups.nonWhitespace = valBits.groups.nonWhitespace.replace( - /(?\d)-/g, '$ -' - ); - const valArr = valBits.groups.nonWhitespace.split(/[, ]+/); - const letters = [...'abcdef']; - */ - - var mtx = svgroot.createSVGMatrix(); - Object.values(valArr).forEach(function (item, i) { - valArr[i] = Number.parseFloat(item); - - if (name === 'matrix') { - mtx[letters[i]] = valArr[i]; - } - }); - var xform = svgroot.createSVGTransform(); - var fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1); - var values = name === 'matrix' ? [mtx] : valArr; - - if (name === 'scale' && values.length === 1) { - values.push(values[0]); - } else if (name === 'translate' && values.length === 1) { - values.push(0); - } else if (name === 'rotate' && values.length === 1) { - values.push(0, 0); - } - - xform[fname].apply(xform, _toConsumableArray(values)); - - _this._list.appendItem(xform); - })(); - } - } - }; - - this._removeFromOtherLists = function (item) { - if (item) { - // Check if this transform is already in a transformlist, and - // remove it if so. - Object.values(listMap_).some(function (tl) { - for (var i = 0, len = tl._xforms.length; i < len; ++i) { - if (tl._xforms[i] === item) { - tl.removeItem(i); - return true; - } - } - - return false; - }); - } - }; - - this.numberOfItems = 0; - } - /** - * @returns {void} - */ - - - _createClass(SVGTransformList, [{ - key: "clear", - value: function clear() { - this.numberOfItems = 0; - this._xforms = []; - } - /** - * @param {SVGTransform} newItem - * @returns {void} - */ - - }, { - key: "initialize", - value: function initialize(newItem) { - this.numberOfItems = 1; - - this._removeFromOtherLists(newItem); - - this._xforms = [newItem]; - } - /** - * @param {Integer} index unsigned long - * @throws {Error} - * @returns {SVGTransform} - */ - - }, { - key: "getItem", - value: function getItem(index) { - if (index < this.numberOfItems && index >= 0) { - return this._xforms[index]; - } - - var err = new Error('DOMException with code=INDEX_SIZE_ERR'); - err.code = 1; - throw err; - } - /** - * @param {SVGTransform} newItem - * @param {Integer} index unsigned long - * @returns {SVGTransform} - */ - - }, { - key: "insertItemBefore", - value: function insertItemBefore(newItem, index) { - var retValue = null; - - if (index >= 0) { - if (index < this.numberOfItems) { - this._removeFromOtherLists(newItem); - - var newxforms = new Array(this.numberOfItems + 1); // TODO: use array copying and slicing - - var i; - - for (i = 0; i < index; ++i) { - newxforms[i] = this._xforms[i]; - } - - newxforms[i] = newItem; - - for (var j = i + 1; i < this.numberOfItems; ++j, ++i) { - newxforms[j] = this._xforms[i]; - } - - this.numberOfItems++; - this._xforms = newxforms; - retValue = newItem; - - this._list._update(); - } else { - retValue = this._list.appendItem(newItem); - } - } - - return retValue; - } - /** - * @param {SVGTransform} newItem - * @param {Integer} index unsigned long - * @returns {SVGTransform} - */ - - }, { - key: "replaceItem", - value: function replaceItem(newItem, index) { - var retValue = null; - - if (index < this.numberOfItems && index >= 0) { - this._removeFromOtherLists(newItem); - - this._xforms[index] = newItem; - retValue = newItem; - - this._list._update(); - } - - return retValue; - } - /** - * @param {Integer} index unsigned long - * @throws {Error} - * @returns {SVGTransform} - */ - - }, { - key: "removeItem", - value: function removeItem(index) { - if (index < this.numberOfItems && index >= 0) { - var retValue = this._xforms[index]; - var newxforms = new Array(this.numberOfItems - 1); - var i; - - for (i = 0; i < index; ++i) { - newxforms[i] = this._xforms[i]; - } - - for (var j = i; j < this.numberOfItems - 1; ++j, ++i) { - newxforms[j] = this._xforms[i + 1]; - } - - this.numberOfItems--; - this._xforms = newxforms; - - this._list._update(); - - return retValue; - } - - var err = new Error('DOMException with code=INDEX_SIZE_ERR'); - err.code = 1; - throw err; - } - /** - * @param {SVGTransform} newItem - * @returns {SVGTransform} - */ - - }, { - key: "appendItem", - value: function appendItem(newItem) { - this._removeFromOtherLists(newItem); - - this._xforms.push(newItem); - - this.numberOfItems++; - - this._list._update(); - - return newItem; - } - }]); - - return SVGTransformList; -}(); -/** -* @function module:SVGTransformList.resetListMap -* @returns {void} -*/ - -var resetListMap = function resetListMap() { - listMap_ = {}; -}; -/** - * Removes transforms of the given element from the map. - * @function module:SVGTransformList.removeElementFromListMap - * @param {Element} elem - a DOM Element - * @returns {void} - */ - -var removeElementFromListMap = function removeElementFromListMap(elem) { - // eslint-disable-line import/no-mutable-exports - if (elem.id && listMap_[elem.id]) { - delete listMap_[elem.id]; - } -}; -/** -* Returns an object that behaves like a `SVGTransformList` for the given DOM element. -* @function module:SVGTransformList.getTransformList -* @param {Element} elem - DOM element to get a transformlist from -* @todo The polyfill should have `SVGAnimatedTransformList` and this should use it -* @returns {SVGAnimatedTransformList|SVGTransformList} -*/ - -var getTransformList = function getTransformList(elem) { - if (!supportsNativeTransformLists()) { - var id = elem.id || 'temp'; - var t = listMap_[id]; - - if (!t || id === 'temp') { - listMap_[id] = new SVGTransformList(elem); - - listMap_[id]._init(); - - t = listMap_[id]; - } - - return t; - } - - if (elem.transform) { - return elem.transform.baseVal; - } - - if (elem.gradientTransform) { - return elem.gradientTransform.baseVal; - } - - if (elem.patternTransform) { - return elem.patternTransform.baseVal; - } - - return null; -}; - -/** - * Tools for working with units. - * @module units - * @license MIT - * - * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller - */ -var wAttrs = ['x', 'x1', 'cx', 'rx', 'width']; -var hAttrs = ['y', 'y1', 'cy', 'ry', 'height']; -var unitAttrs = ['r', 'radius'].concat(wAttrs, hAttrs); // unused - -/* -const unitNumMap = { - '%': 2, - em: 3, - ex: 4, - px: 5, - cm: 6, - mm: 7, - in: 8, - pt: 9, - pc: 10 -}; -*/ -// Container of elements. - -var elementContainer_; // Stores mapping of unit type to user coordinates. - -var typeMap_ = {}; -/** - * @interface module:units.ElementContainer - */ - -/** - * @function module:units.ElementContainer#getBaseUnit - * @returns {string} The base unit type of the container ('em') - */ - -/** - * @function module:units.ElementContainer#getElement - * @returns {?Element} An element in the container given an id - */ - -/** - * @function module:units.ElementContainer#getHeight - * @returns {Float} The container's height - */ - -/** - * @function module:units.ElementContainer#getWidth - * @returns {Float} The container's width - */ - -/** - * @function module:units.ElementContainer#getRoundDigits - * @returns {Integer} The number of digits number should be rounded to - */ - -/* eslint-disable jsdoc/valid-types */ - -/** - * @typedef {PlainObject} module:units.TypeMap - * @property {Float} em - * @property {Float} ex - * @property {Float} in - * @property {Float} cm - * @property {Float} mm - * @property {Float} pt - * @property {Float} pc - * @property {Integer} px - * @property {0} % - */ - -/* eslint-enable jsdoc/valid-types */ - -/** - * Initializes this module. - * - * @function module:units.init - * @param {module:units.ElementContainer} elementContainer - An object implementing the ElementContainer interface. - * @returns {void} - */ - -var init = function init(elementContainer) { - elementContainer_ = elementContainer; // Get correct em/ex values by creating a temporary SVG. - - var svg = document.createElementNS(NS.SVG, 'svg'); - document.body.append(svg); - var rect = document.createElementNS(NS.SVG, 'rect'); - rect.setAttribute('width', '1em'); - rect.setAttribute('height', '1ex'); - rect.setAttribute('x', '1in'); - svg.append(rect); - var bb = rect.getBBox(); - svg.remove(); - var inch = bb.x; - typeMap_ = { - em: bb.width, - ex: bb.height, - "in": inch, - cm: inch / 2.54, - mm: inch / 25.4, - pt: inch / 72, - pc: inch / 6, - px: 1, - '%': 0 - }; -}; -/** -* Group: Unit conversion functions. -*/ - -/** - * @function module:units.getTypeMap - * @returns {module:units.TypeMap} The unit object with values for each unit -*/ - -var getTypeMap = function getTypeMap() { - return typeMap_; -}; -/** -* @typedef {GenericArray} module:units.CompareNumbers -* @property {Integer} length 2 -* @property {Float} 0 -* @property {Float} 1 -*/ - -/** -* Rounds a given value to a float with number of digits defined in -* `round_digits` of `saveOptions` -* -* @function module:units.shortFloat -* @param {string|Float|module:units.CompareNumbers} val - The value (or Array of two numbers) to be rounded -* @returns {Float|string} If a string/number was given, returns a Float. If an array, return a string -* with comma-separated floats -*/ - -var shortFloat = function shortFloat(val) { - var digits = elementContainer_.getRoundDigits(); - - if (!isNaN(val)) { - return Number(Number(val).toFixed(digits)); - } - - if (Array.isArray(val)) { - return shortFloat(val[0]) + ',' + shortFloat(val[1]); - } - - return Number.parseFloat(val).toFixed(digits) - 0; -}; -/** -* Converts the number to given unit or baseUnit. -* @function module:units.convertUnit -* @param {string|Float} val -* @param {"em"|"ex"|"in"|"cm"|"mm"|"pt"|"pc"|"px"|"%"} [unit] -* @returns {Float} -*/ - -var convertUnit = function convertUnit(val, unit) { - unit = unit || elementContainer_.getBaseUnit(); // baseVal.convertToSpecifiedUnits(unitNumMap[unit]); - // const val = baseVal.valueInSpecifiedUnits; - // baseVal.convertToSpecifiedUnits(1); - - return shortFloat(val / typeMap_[unit]); -}; -/** -* Sets an element's attribute based on the unit in its current value. -* -* @function module:units.setUnitAttr -* @param {Element} elem - DOM element to be changed -* @param {string} attr - Name of the attribute associated with the value -* @param {string} val - Attribute value to convert -* @returns {void} -*/ - -var setUnitAttr = function setUnitAttr(elem, attr, val) { - // if (!isNaN(val)) { - // New value is a number, so check currently used unit - // const oldVal = elem.getAttribute(attr); - // Enable this for alternate mode - // if (oldVal !== null && (isNaN(oldVal) || elementContainer_.getBaseUnit() !== 'px')) { - // // Old value was a number, so get unit, then convert - // let unit; - // if (oldVal.substr(-1) === '%') { - // const res = getResolution(); - // unit = '%'; - // val *= 100; - // if (wAttrs.includes(attr)) { - // val = val / res.w; - // } else if (hAttrs.includes(attr)) { - // val = val / res.h; - // } else { - // return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2); - // } - // } else { - // if (elementContainer_.getBaseUnit() !== 'px') { - // unit = elementContainer_.getBaseUnit(); - // } else { - // unit = oldVal.substr(-2); - // } - // val = val / typeMap_[unit]; - // } - // - // val += unit; - // } - // } - elem.setAttribute(attr, val); -}; -/** -* Converts given values to numbers. Attributes must be supplied in -* case a percentage is given. -* -* @function module:units.convertToNum -* @param {string} attr - Name of the attribute associated with the value -* @param {string} val - Attribute value to convert -* @returns {Float} The converted number -*/ - -var convertToNum = function convertToNum(attr, val) { - // Return a number if that's what it already is - if (!isNaN(val)) { - return val - 0; - } - - if (val.substr(-1) === '%') { - // Deal with percentage, depends on attribute - var _num = val.substr(0, val.length - 1) / 100; - - var width = elementContainer_.getWidth(); - var height = elementContainer_.getHeight(); - - if (wAttrs.includes(attr)) { - return _num * width; - } - - if (hAttrs.includes(attr)) { - return _num * height; - } - - return _num * Math.sqrt(width * width + height * height) / Math.sqrt(2); - } - - var unit = val.substr(-2); - var num = val.substr(0, val.length - 2); // Note that this multiplication turns the string into a number - - return num * typeMap_[unit]; -}; -/** -* Check if an attribute's value is in a valid format. -* @function module:units.isValidUnit -* @param {string} attr - The name of the attribute associated with the value -* @param {string} val - The attribute value to check -* @param {Element} selectedElement -* @returns {boolean} Whether the unit is valid -*/ - -var isValidUnit = function isValidUnit(attr, val, selectedElement) { - if (unitAttrs.includes(attr)) { - // True if it's just a number - if (!isNaN(val)) { - return true; - } // Not a number, check if it has a valid unit - - - val = val.toLowerCase(); - return Object.keys(typeMap_).some(function (unit) { - var re = new RegExp('^-?[\\d\\.]+' + unit + '$'); - return re.test(val); - }); - } - - if (attr === 'id') { - // if we're trying to change the id, make sure it's not already present in the doc - // and the id value is valid. - var result = false; // because getElem() can throw an exception in the case of an invalid id - // (according to https://www.w3.org/TR/xml-id/ IDs must be a NCName) - // we wrap it in an exception and only return true if the ID was valid and - // not already present - - try { - var elem = elementContainer_.getElement(val); - result = !elem || elem === selectedElement; - } catch (e) {} - - return result; - } - - return true; -}; - -/** - * Mathematical utilities. - * @module math - * @license MIT - * - * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller - */ - -var NEAR_ZERO = 1e-14; // Throw away SVGSVGElement used for creating matrices/transforms. - -var svg$1 = document.createElementNS(NS.SVG, 'svg'); -/** - * A (hopefully) quicker function to transform a point by a matrix - * (this function avoids any DOM calls and just does the math). - * @function module:math.transformPoint - * @param {Float} x - Float representing the x coordinate - * @param {Float} y - Float representing the y coordinate - * @param {SVGMatrix} m - Matrix object to transform the point with - * @returns {module:math.XYObject} An x, y object representing the transformed point -*/ - -var transformPoint = function transformPoint(x, y, m) { - return { - x: m.a * x + m.c * y + m.e, - y: m.b * x + m.d * y + m.f - }; -}; -/** - * Helper function to check if the matrix performs no actual transform - * (i.e. exists for identity purposes). - * @function module:math.isIdentity - * @param {SVGMatrix} m - The matrix object to check - * @returns {boolean} Indicates whether or not the matrix is 1,0,0,1,0,0 -*/ - -var isIdentity = function isIdentity(m) { - return m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && m.e === 0 && m.f === 0; -}; -/** - * This function tries to return a `SVGMatrix` that is the multiplication `m1 * m2`. - * We also round to zero when it's near zero. - * @function module:math.matrixMultiply - * @param {...SVGMatrix} args - Matrix objects to multiply - * @returns {SVGMatrix} The matrix object resulting from the calculation -*/ - -var matrixMultiply = function matrixMultiply() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var m = args.reduceRight(function (prev, m1) { - return m1.multiply(prev); - }); - - if (Math.abs(m.a) < NEAR_ZERO) { - m.a = 0; - } - - if (Math.abs(m.b) < NEAR_ZERO) { - m.b = 0; - } - - if (Math.abs(m.c) < NEAR_ZERO) { - m.c = 0; - } - - if (Math.abs(m.d) < NEAR_ZERO) { - m.d = 0; - } - - if (Math.abs(m.e) < NEAR_ZERO) { - m.e = 0; - } - - if (Math.abs(m.f) < NEAR_ZERO) { - m.f = 0; - } - - return m; -}; -var hasMatrixTransform = function hasMatrixTransform(tlist) { - if (!tlist) { - return false; - } - - var num = tlist.numberOfItems; - - while (num--) { - var xform = tlist.getItem(num); - - if (xform.type === 1 && !isIdentity(xform.matrix)) { - return true; - } - } - - return false; -}; -/** -* @typedef {PlainObject} module:math.TransformedBox An object with the following values -* @property {module:math.XYObject} tl - The top left coordinate -* @property {module:math.XYObject} tr - The top right coordinate -* @property {module:math.XYObject} bl - The bottom left coordinate -* @property {module:math.XYObject} br - The bottom right coordinate -* @property {PlainObject} aabox - Object with the following values: -* @property {Float} aabox.x - Float with the axis-aligned x coordinate -* @property {Float} aabox.y - Float with the axis-aligned y coordinate -* @property {Float} aabox.width - Float with the axis-aligned width coordinate -* @property {Float} aabox.height - Float with the axis-aligned height coordinate -*/ - -/** - * Transforms a rectangle based on the given matrix. - * @function module:math.transformBox - * @param {Float} l - Float with the box's left coordinate - * @param {Float} t - Float with the box's top coordinate - * @param {Float} w - Float with the box width - * @param {Float} h - Float with the box height - * @param {SVGMatrix} m - Matrix object to transform the box by - * @returns {module:math.TransformedBox} -*/ - -var transformBox = function transformBox(l, t, w, h, m) { - var tl = transformPoint(l, t, m), - tr = transformPoint(l + w, t, m), - bl = transformPoint(l, t + h, m), - br = transformPoint(l + w, t + h, m), - minx = Math.min(tl.x, tr.x, bl.x, br.x), - maxx = Math.max(tl.x, tr.x, bl.x, br.x), - miny = Math.min(tl.y, tr.y, bl.y, br.y), - maxy = Math.max(tl.y, tr.y, bl.y, br.y); - return { - tl: tl, - tr: tr, - bl: bl, - br: br, - aabox: { - x: minx, - y: miny, - width: maxx - minx, - height: maxy - miny - } - }; -}; -/** - * This returns a single matrix Transform for a given Transform List - * (this is the equivalent of `SVGTransformList.consolidate()` but unlike - * that method, this one does not modify the actual `SVGTransformList`). - * This function is very liberal with its `min`, `max` arguments. - * @function module:math.transformListToTransform - * @param {SVGTransformList} tlist - The transformlist object - * @param {Integer} [min=0] - Optional integer indicating start transform position - * @param {Integer} [max] - Optional integer indicating end transform position; - * defaults to one less than the tlist's `numberOfItems` - * @returns {SVGTransform} A single matrix transform object -*/ - -var transformListToTransform = function transformListToTransform(tlist, min, max) { - if (!tlist) { - // Or should tlist = null have been prevented before this? - return svg$1.createSVGTransformFromMatrix(svg$1.createSVGMatrix()); - } - - min = min || 0; - max = max || tlist.numberOfItems - 1; - min = Number.parseInt(min); - max = Number.parseInt(max); - - if (min > max) { - var temp = max; - max = min; - min = temp; - } - - var m = svg$1.createSVGMatrix(); - - for (var i = min; i <= max; ++i) { - // if our indices are out of range, just use a harmless identity matrix - var mtom = i >= 0 && i < tlist.numberOfItems ? tlist.getItem(i).matrix : svg$1.createSVGMatrix(); - m = matrixMultiply(m, mtom); - } - - return svg$1.createSVGTransformFromMatrix(m); -}; -/** - * Get the matrix object for a given element. - * @function module:math.getMatrix - * @param {Element} elem - The DOM element to check - * @returns {SVGMatrix} The matrix object associated with the element's transformlist -*/ - -var getMatrix = function getMatrix(elem) { - var tlist = getTransformList(elem); - return transformListToTransform(tlist).matrix; -}; -/** - * Returns a 45 degree angle coordinate associated with the two given - * coordinates. - * @function module:math.snapToAngle - * @param {Integer} x1 - First coordinate's x value - * @param {Integer} y1 - First coordinate's y value - * @param {Integer} x2 - Second coordinate's x value - * @param {Integer} y2 - Second coordinate's y value - * @returns {module:math.AngleCoord45} -*/ - -var snapToAngle = function snapToAngle(x1, y1, x2, y2) { - var snap = Math.PI / 4; // 45 degrees - - var dx = x2 - x1; - var dy = y2 - y1; - var angle = Math.atan2(dy, dx); - var dist = Math.sqrt(dx * dx + dy * dy); - var snapangle = Math.round(angle / snap) * snap; - return { - x: x1 + dist * Math.cos(snapangle), - y: y1 + dist * Math.sin(snapangle), - a: snapangle - }; -}; -/** - * Check if two rectangles (BBoxes objects) intersect each other. - * @function module:math.rectsIntersect - * @param {SVGRect} r1 - The first BBox-like object - * @param {SVGRect} r2 - The second BBox-like object - * @returns {boolean} True if rectangles intersect - */ - -var rectsIntersect = function rectsIntersect(r1, r2) { - return r2.x < r1.x + r1.width && r2.x + r2.width > r1.x && r2.y < r1.y + r1.height && r2.y + r2.height > r1.y; -}; - -var $$1 = jQueryPluginSVG(jQuery); // String used to encode base64. - -var KEYSTR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; // Much faster than running getBBox() every time - -var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use,clipPath'; -var visElemsArr = visElems.split(','); // const hidElems = 'defs,desc,feGaussianBlur,filter,linearGradient,marker,mask,metadata,pattern,radialGradient,stop,switch,symbol,title,textPath'; - -var editorContext_ = null; -var domdoc_ = null; -var domcontainer_ = null; -var svgroot_ = null; -/** -* Object with the following keys/values. -* @typedef {PlainObject} module:utilities.SVGElementJSON -* @property {string} element - Tag name of the SVG element to create -* @property {PlainObject} attr - Has key-value attributes to assign to the new element. An `id` should be set so that {@link module:utilities.EditorContext#addSVGElementFromJson} can later re-identify the element for modification or replacement. -* @property {boolean} [curStyles=false] - Indicates whether current style attributes should be applied first -* @property {module:utilities.SVGElementJSON[]} [children] - Data objects to be added recursively as children -* @property {string} [namespace="http://www.w3.org/2000/svg"] - Indicate a (non-SVG) namespace -*/ - -/** - * An object that creates SVG elements for the canvas. - * - * @interface module:utilities.EditorContext - * @property {module:path.pathActions} pathActions - */ - -/** - * @function module:utilities.EditorContext#getSVGContent - * @returns {SVGSVGElement} - */ - -/** - * Create a new SVG element based on the given object keys/values and add it - * to the current layer. - * The element will be run through `cleanupElement` before being returned. - * @function module:utilities.EditorContext#addSVGElementFromJson - * @param {module:utilities.SVGElementJSON} data - * @returns {Element} The new element -*/ - -/** - * @function module:utilities.EditorContext#getSelectedElements - * @returns {Element[]} the array with selected DOM elements -*/ - -/** - * @function module:utilities.EditorContext#getDOMDocument - * @returns {HTMLDocument} -*/ - -/** - * @function module:utilities.EditorContext#getDOMContainer - * @returns {HTMLElement} -*/ - -/** - * @function module:utilities.EditorContext#getSVGRoot - * @returns {SVGSVGElement} -*/ - -/** - * @function module:utilities.EditorContext#getBaseUnit - * @returns {string} -*/ - -/** - * @function module:utilities.EditorContext#getSnappingStep - * @returns {Float|string} -*/ - -/** -* @function module:utilities.init -* @param {module:utilities.EditorContext} editorContext -* @returns {void} -*/ - -var init$1 = function init(editorContext) { - editorContext_ = editorContext; - domdoc_ = editorContext.getDOMDocument(); - domcontainer_ = editorContext.getDOMContainer(); - svgroot_ = editorContext.getSVGRoot(); -}; -/** - * Used to prevent the [Billion laughs attack]{@link https://en.wikipedia.org/wiki/Billion_laughs_attack}. - * @function module:utilities.dropXMLInternalSubset - * @param {string} str String to be processed - * @returns {string} The string with entity declarations in the internal subset removed - * @todo This might be needed in other places `parseFromString` is used even without LGTM flagging - */ - -var dropXMLInternalSubset = function dropXMLInternalSubset(str) { - return str.replace(/()/, '$1$2'); // return str.replace(/(?\?\]>)/, '$$'); -}; -/** -* Converts characters in a string to XML-friendly entities. -* @function module:utilities.toXml -* @example `&` becomes `&` -* @param {string} str - The string to be converted -* @returns {string} The converted string -*/ - -var toXml = function toXml(str) { - // ' is ok in XML, but not HTML - // > does not normally need escaping, though it can if within a CDATA expression (and preceded by "]]") - return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); // Note: `'` is XML only -}; -// public domain. It would be nice if you left this header intact. -// Base64 code from Tyler Akins -- http://rumkin.com -// schiller: Removed string concatenation in favour of Array.join() optimization, -// also precalculate the size of the array needed. - -/** -* Converts a string to base64. -* @function module:utilities.encode64 -* @param {string} input -* @returns {string} Base64 output -*/ - -function encode64(input) { - // base64 strings are 4/3 larger than the original string - input = encodeUTF8(input); // convert non-ASCII characters - // input = convertToXMLReferences(input); - - if (window.btoa) { - return window.btoa(input); // Use native if available - } - - var output = new Array(Math.floor((input.length + 2) / 3) * 4); - var i = 0, - p = 0; - - do { - var chr1 = input.charCodeAt(i++); - var chr2 = input.charCodeAt(i++); - var chr3 = input.charCodeAt(i++); - /* eslint-disable no-bitwise */ - - var enc1 = chr1 >> 2; - var enc2 = (chr1 & 3) << 4 | chr2 >> 4; - var enc3 = (chr2 & 15) << 2 | chr3 >> 6; - var enc4 = chr3 & 63; - /* eslint-enable no-bitwise */ - - if (Number.isNaN(chr2)) { - enc3 = 64; - enc4 = 64; - } else if (Number.isNaN(chr3)) { - enc4 = 64; - } - - output[p++] = KEYSTR.charAt(enc1); - output[p++] = KEYSTR.charAt(enc2); - output[p++] = KEYSTR.charAt(enc3); - output[p++] = KEYSTR.charAt(enc4); - } while (i < input.length); - - return output.join(''); -} -/** -* Converts a string from base64. -* @function module:utilities.decode64 -* @param {string} input Base64-encoded input -* @returns {string} Decoded output -*/ - -function decode64(input) { - if (window.atob) { - return decodeUTF8(window.atob(input)); - } // remove all characters that are not A-Z, a-z, 0-9, +, /, or = - - - input = input.replace(/[^A-Za-z\d+/=]/g, ''); - var output = ''; - var i = 0; - - do { - var enc1 = KEYSTR.indexOf(input.charAt(i++)); - var enc2 = KEYSTR.indexOf(input.charAt(i++)); - var enc3 = KEYSTR.indexOf(input.charAt(i++)); - var enc4 = KEYSTR.indexOf(input.charAt(i++)); - /* eslint-disable no-bitwise */ - - var chr1 = enc1 << 2 | enc2 >> 4; - var chr2 = (enc2 & 15) << 4 | enc3 >> 2; - var chr3 = (enc3 & 3) << 6 | enc4; - /* eslint-enable no-bitwise */ - - output += String.fromCharCode(chr1); - - if (enc3 !== 64) { - output += String.fromCharCode(chr2); - } - - if (enc4 !== 64) { - output += String.fromCharCode(chr3); - } - } while (i < input.length); - - return decodeUTF8(output); -} -/** -* @function module:utilities.decodeUTF8 -* @param {string} argString -* @returns {string} -*/ - -function decodeUTF8(argString) { - return decodeURIComponent(escape(argString)); -} // codedread:does not seem to work with webkit-based browsers on OSX // Brettz9: please test again as function upgraded - -/** -* @function module:utilities.encodeUTF8 -* @param {string} argString -* @returns {string} -*/ - -var encodeUTF8 = function encodeUTF8(argString) { - return unescape(encodeURIComponent(argString)); -}; -/** - * Convert dataURL to object URL. - * @function module:utilities.dataURLToObjectURL - * @param {string} dataurl - * @returns {string} object URL or empty string - */ - -var dataURLToObjectURL = function dataURLToObjectURL(dataurl) { - if (typeof Uint8Array === 'undefined' || typeof Blob === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) { - return ''; - } - - var arr = dataurl.split(','), - mime = arr[0].match(/:(.*?);/)[1], - bstr = atob(arr[1]); - /* - const [prefix, suffix] = dataurl.split(','), - {groups: {mime}} = prefix.match(/:(?.*?);/), - bstr = atob(suffix); - */ - - var n = bstr.length; - var u8arr = new Uint8Array(n); - - while (n--) { - u8arr[n] = bstr.charCodeAt(n); - } - - var blob = new Blob([u8arr], { - type: mime - }); - return URL.createObjectURL(blob); -}; -/** - * Get object URL for a blob object. - * @function module:utilities.createObjectURL - * @param {Blob} blob A Blob object or File object - * @returns {string} object URL or empty string - */ - -var createObjectURL = function createObjectURL(blob) { - if (!blob || typeof URL === 'undefined' || !URL.createObjectURL) { - return ''; - } - - return URL.createObjectURL(blob); -}; -/** - * @property {string} blankPageObjectURL - */ - -var blankPageObjectURL = function () { - if (typeof Blob === 'undefined') { - return ''; - } - - var blob = new Blob(['SVG-edit '], { - type: 'text/html' - }); - return createObjectURL(blob); -}(); -/** -* Cross-browser compatible method of converting a string to an XML tree. -* Found this function [here]{@link http://groups.google.com/group/jquery-dev/browse_thread/thread/c6d11387c580a77f}. -* @function module:utilities.text2xml -* @param {string} sXML -* @throws {Error} -* @returns {XMLDocument} -*/ - -var text2xml = function text2xml(sXML) { - if (sXML.includes('` -* - `` -* - `` -* @function module:utilities.getUrlFromAttr -* @param {string} attrVal The attribute value as a string -* @returns {string} String with just the URL, like "someFile.svg#foo" -*/ - -var getUrlFromAttr = function getUrlFromAttr(attrVal) { - if (attrVal) { - // url('#somegrad') - if (attrVal.startsWith('url("')) { - return attrVal.substring(5, attrVal.indexOf('"', 6)); - } // url('#somegrad') - - - if (attrVal.startsWith("url('")) { - return attrVal.substring(5, attrVal.indexOf("'", 6)); - } - - if (attrVal.startsWith('url(')) { - return attrVal.substring(4, attrVal.indexOf(')')); - } - } - - return null; -}; -/** -* @function module:utilities.getHref -* @param {Element} elem -* @returns {string} The given element's `xlink:href` value -*/ - -var getHref = function getHref(elem) { - // eslint-disable-line import/no-mutable-exports - return elem.getAttributeNS(NS.XLINK, 'href'); -}; -/** -* Sets the given element's `xlink:href` value. -* @function module:utilities.setHref -* @param {Element} elem -* @param {string} val -* @returns {void} -*/ - -var setHref = function setHref(elem, val) { - // eslint-disable-line import/no-mutable-exports - elem.setAttributeNS(NS.XLINK, 'xlink:href', val); -}; -/** -* @function module:utilities.findDefs -* @returns {SVGDefsElement} The document's `` element, creating it first if necessary -*/ - -var findDefs = function findDefs() { - var svgElement = editorContext_.getSVGContent(); - var defs = svgElement.getElementsByTagNameNS(NS.SVG, 'defs'); - - if (defs.length > 0) { - defs = defs[0]; - } else { - defs = svgElement.ownerDocument.createElementNS(NS.SVG, 'defs'); - - if (svgElement.firstChild) { - // first child is a comment, so call nextSibling - svgElement.insertBefore(defs, svgElement.firstChild.nextSibling); // svgElement.firstChild.nextSibling.before(defs); // Not safe - } else { - svgElement.append(defs); - } - } - - return defs; -}; // TODO(codedread): Consider moving the next to functions to bbox.js - -/** -* Get correct BBox for a path in Webkit. -* Converted from code found [here]{@link http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html}. -* @function module:utilities.getPathBBox -* @param {SVGPathElement} path - The path DOM element to get the BBox for -* @returns {module:utilities.BBoxObject} A BBox-like object -*/ - -var getPathBBox = function getPathBBox(path) { - var seglist = path.pathSegList; - var tot = seglist.numberOfItems; - var bounds = [[], []]; - var start = seglist.getItem(0); - var P0 = [start.x, start.y]; - - var getCalc = function getCalc(j, P1, P2, P3) { - return function (t) { - return 1 - Math.pow(t, 3) * P0[j] + 3 * 1 - Math.pow(t, 2) * t * P1[j] + 3 * (1 - t) * Math.pow(t, 2) * P2[j] + Math.pow(t, 3) * P3[j]; - }; - }; - - for (var i = 0; i < tot; i++) { - var seg = seglist.getItem(i); - - if (seg.x === undefined) { - continue; - } // Add actual points to limits - - - bounds[0].push(P0[0]); - bounds[1].push(P0[1]); - - if (seg.x1) { - var P1 = [seg.x1, seg.y1], - P2 = [seg.x2, seg.y2], - P3 = [seg.x, seg.y]; - - for (var j = 0; j < 2; j++) { - var calc = getCalc(j, P1, P2, P3); - var b = 6 * P0[j] - 12 * P1[j] + 6 * P2[j]; - var a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j]; - var c = 3 * P1[j] - 3 * P0[j]; - - if (a === 0) { - if (b === 0) { - continue; - } - - var t = -c / b; - - if (t > 0 && t < 1) { - bounds[j].push(calc(t)); - } - - continue; - } - - var b2ac = Math.pow(b, 2) - 4 * c * a; - - if (b2ac < 0) { - continue; - } - - var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); - - if (t1 > 0 && t1 < 1) { - bounds[j].push(calc(t1)); - } - - var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); - - if (t2 > 0 && t2 < 1) { - bounds[j].push(calc(t2)); - } - } - - P0 = P3; - } else { - bounds[0].push(seg.x); - bounds[1].push(seg.y); - } - } - - var x = Math.min.apply(null, bounds[0]); - var w = Math.max.apply(null, bounds[0]) - x; - var y = Math.min.apply(null, bounds[1]); - var h = Math.max.apply(null, bounds[1]) - y; - return { - x: x, - y: y, - width: w, - height: h - }; -}; -/** -* Get the given/selected element's bounding box object, checking for -* horizontal/vertical lines (see issue 717) -* Note that performance is currently terrible, so some way to improve would -* be great. -* @param {Element} selected - Container or `` DOM element -* @returns {DOMRect} Bounding box object -*/ - -function groupBBFix(selected) { - if (supportsHVLineContainerBBox()) { - try { - return selected.getBBox(); - } catch (e) {} - } - - var ref = $$1.data(selected, 'ref'); - var matched = null; - var ret, copy; - - if (ref) { - copy = $$1(ref).children().clone().attr('visibility', 'hidden'); - $$1(svgroot_).append(copy); - matched = copy.filter('line, path'); - } else { - matched = $$1(selected).find('line, path'); - } - - var issue = false; - - if (matched.length) { - matched.each(function () { - var bb = this.getBBox(); - - if (!bb.width || !bb.height) { - issue = true; - } - }); - - if (issue) { - var elems = ref ? copy : $$1(selected).children(); - ret = getStrokedBBox(elems); - } else { - ret = selected.getBBox(); - } - } else { - ret = selected.getBBox(); - } - - if (ref) { - copy.remove(); - } - - return ret; -} -/** -* Get the given/selected element's bounding box object, convert it to be more -* usable when necessary. -* @function module:utilities.getBBox -* @param {Element} elem - Optional DOM element to get the BBox for -* @returns {module:utilities.BBoxObject} Bounding box object -*/ - - -var getBBox = function getBBox(elem) { - var selected = elem || editorContext_.geSelectedElements()[0]; - - if (elem.nodeType !== 1) { - return null; - } - - var elname = selected.nodeName; - var ret = null; - - switch (elname) { - case 'text': - if (selected.textContent === '') { - selected.textContent = 'a'; // Some character needed for the selector to use. - - ret = selected.getBBox(); - selected.textContent = ''; - } else if (selected.getBBox) { - ret = selected.getBBox(); - } - - break; - - case 'path': - if (!supportsPathBBox()) { - ret = getPathBBox(selected); - } else if (selected.getBBox) { - ret = selected.getBBox(); - } - - break; - - case 'g': - case 'a': - ret = groupBBFix(selected); - break; - - default: - if (elname === 'use') { - ret = groupBBFix(selected); // , true); - } - - if (elname === 'use' || elname === 'foreignObject' && isWebkit()) { - if (!ret) { - ret = selected.getBBox(); - } // This is resolved in later versions of webkit, perhaps we should - // have a featured detection for correct 'use' behavior? - // —————————— - - - if (!isWebkit()) { - var _ret = ret, - x = _ret.x, - y = _ret.y, - width = _ret.width, - height = _ret.height; - var bb = { - width: width, - height: height, - x: x + Number.parseFloat(selected.getAttribute('x') || 0), - y: y + Number.parseFloat(selected.getAttribute('y') || 0) - }; - ret = bb; - } - } else if (visElemsArr.includes(elname)) { - if (selected) { - try { - ret = selected.getBBox(); - } catch (err) { - // tspan (and textPath apparently) have no `getBBox` in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=937268 - // Re: Chrome returning bbox for containing text element, see: https://bugs.chromium.org/p/chromium/issues/detail?id=349835 - var extent = selected.getExtentOfChar(0); // pos+dimensions of the first glyph - - var _width = selected.getComputedTextLength(); // width of the tspan - - - ret = { - x: extent.x, - y: extent.y, - width: _width, - height: extent.height - }; - } - } else { - // Check if element is child of a foreignObject - var fo = $$1(selected).closest('foreignObject'); - - if (fo.length) { - if (fo[0].getBBox) { - ret = fo[0].getBBox(); - } - } - } - } - - } - - if (ret) { - ret = bboxToObj(ret); - } // get the bounding box from the DOM (which is in that element's coordinate system) - - - return ret; -}; -/** -* @typedef {GenericArray} module:utilities.PathSegmentArray -* @property {Integer} length 2 -* @property {"M"|"L"|"C"|"Z"} 0 -* @property {Float[]} 1 -*/ - -/** -* Create a path 'd' attribute from path segments. -* Each segment is an array of the form: `[singleChar, [x,y, x,y, ...]]` -* @function module:utilities.getPathDFromSegments -* @param {module:utilities.PathSegmentArray[]} pathSegments - An array of path segments to be converted -* @returns {string} The converted path d attribute. -*/ - -var getPathDFromSegments = function getPathDFromSegments(pathSegments) { - var d = ''; - $$1.each(pathSegments, function (j, _ref2) { - var _ref3 = _slicedToArray(_ref2, 2), - singleChar = _ref3[0], - pts = _ref3[1]; - - d += singleChar; - - for (var i = 0; i < pts.length; i += 2) { - d += pts[i] + ',' + pts[i + 1] + ' '; - } - }); - return d; -}; -/** -* Make a path 'd' attribute from a simple SVG element shape. -* @function module:utilities.getPathDFromElement -* @param {Element} elem - The element to be converted -* @returns {string} The path d attribute or `undefined` if the element type is unknown. -*/ - -var getPathDFromElement = function getPathDFromElement(elem) { - // Possibly the cubed root of 6, but 1.81 works best - var num = 1.81; - var d, a, rx, ry; - - switch (elem.tagName) { - case 'ellipse': - case 'circle': - { - a = $$1(elem).attr(['rx', 'ry', 'cx', 'cy']); - var _a = a, - cx = _a.cx, - cy = _a.cy; - var _a2 = a; - rx = _a2.rx; - ry = _a2.ry; - - if (elem.tagName === 'circle') { - ry = $$1(elem).attr('r'); - rx = ry; - } - - d = getPathDFromSegments([['M', [cx - rx, cy]], ['C', [cx - rx, cy - ry / num, cx - rx / num, cy - ry, cx, cy - ry]], ['C', [cx + rx / num, cy - ry, cx + rx, cy - ry / num, cx + rx, cy]], ['C', [cx + rx, cy + ry / num, cx + rx / num, cy + ry, cx, cy + ry]], ['C', [cx - rx / num, cy + ry, cx - rx, cy + ry / num, cx - rx, cy]], ['Z', []]]); - break; - } - - case 'path': - d = elem.getAttribute('d'); - break; - - case 'line': - a = $$1(elem).attr(['x1', 'y1', 'x2', 'y2']); - d = 'M' + a.x1 + ',' + a.y1 + 'L' + a.x2 + ',' + a.y2; - break; - - case 'polyline': - d = 'M' + elem.getAttribute('points'); - break; - - case 'polygon': - d = 'M' + elem.getAttribute('points') + ' Z'; - break; - - case 'rect': - { - var r = $$1(elem).attr(['rx', 'ry']); - rx = r.rx; - ry = r.ry; - var b = elem.getBBox(); - var x = b.x, - y = b.y, - w = b.width, - h = b.height; - num = 4 - num; // Why? Because! - - if (!rx && !ry) { - // Regular rect - d = getPathDFromSegments([['M', [x, y]], ['L', [x + w, y]], ['L', [x + w, y + h]], ['L', [x, y + h]], ['L', [x, y]], ['Z', []]]); - } else { - d = getPathDFromSegments([['M', [x, y + ry]], ['C', [x, y + ry / num, x + rx / num, y, x + rx, y]], ['L', [x + w - rx, y]], ['C', [x + w - rx / num, y, x + w, y + ry / num, x + w, y + ry]], ['L', [x + w, y + h - ry]], ['C', [x + w, y + h - ry / num, x + w - rx / num, y + h, x + w - rx, y + h]], ['L', [x + rx, y + h]], ['C', [x + rx / num, y + h, x, y + h - ry / num, x, y + h - ry]], ['L', [x, y + ry]], ['Z', []]]); - } - - break; - } - } - - return d; -}; -/** -* Get a set of attributes from an element that is useful for convertToPath. -* @function module:utilities.getExtraAttributesForConvertToPath -* @param {Element} elem - The element to be probed -* @returns {PlainObject<"marker-start"|"marker-end"|"marker-mid"|"filter"|"clip-path", string>} An object with attributes. -*/ - -var getExtraAttributesForConvertToPath = function getExtraAttributesForConvertToPath(elem) { - var attrs = {}; // TODO: make this list global so that we can properly maintain it - // TODO: what about @transform, @clip-rule, @fill-rule, etc? - - $$1.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function () { - var a = elem.getAttribute(this); - - if (a) { - attrs[this] = a; - } - }); - return attrs; -}; -/** -* Get the BBox of an element-as-path. -* @function module:utilities.getBBoxOfElementAsPath -* @param {Element} elem - The DOM element to be probed -* @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson -* @param {module:path.pathActions} pathActions - If a transform exists, `pathActions.resetOrientation()` is used. See: canvas.pathActions. -* @returns {DOMRect|false} The resulting path's bounding box object. -*/ - -var getBBoxOfElementAsPath = function getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions) { - var path = addSVGElementFromJson({ - element: 'path', - attr: getExtraAttributesForConvertToPath(elem) - }); - var eltrans = elem.getAttribute('transform'); - - if (eltrans) { - path.setAttribute('transform', eltrans); - } - - var parentNode = elem.parentNode; - - if (elem.nextSibling) { - elem.before(path); - } else { - parentNode.append(path); - } - - var d = getPathDFromElement(elem); - - if (d) { - path.setAttribute('d', d); - } else { - path.remove(); - } // Get the correct BBox of the new path, then discard it - - - pathActions.resetOrientation(path); - var bb = false; - - try { - bb = path.getBBox(); - } catch (e) {// Firefox fails - } - - path.remove(); - return bb; -}; -/** -* Convert selected element to a path. -* @function module:utilities.convertToPath -* @param {Element} elem - The DOM element to be converted -* @param {module:utilities.SVGElementJSON} attrs - Apply attributes to new path. see canvas.convertToPath -* @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson -* @param {module:path.pathActions} pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions. -* @param {module:draw.DrawCanvasInit#clearSelection|module:path.EditorContext#clearSelection} clearSelection - see [canvas.clearSelection]{@link module:svgcanvas.SvgCanvas#clearSelection} -* @param {module:path.EditorContext#addToSelection} addToSelection - see [canvas.addToSelection]{@link module:svgcanvas.SvgCanvas#addToSelection} -* @param {module:history} hstry - see history module -* @param {module:path.EditorContext#addCommandToHistory|module:draw.DrawCanvasInit#addCommandToHistory} addCommandToHistory - see [canvas.addCommandToHistory]{@link module:svgcanvas~addCommandToHistory} -* @returns {SVGPathElement|null} The converted path element or null if the DOM element was not recognized. -*/ - -var convertToPath = function convertToPath(elem, attrs, addSVGElementFromJson, pathActions, clearSelection, addToSelection, hstry, addCommandToHistory) { - var batchCmd = new hstry.BatchCommand('Convert element to Path'); // Any attribute on the element not covered by the passed-in attributes - - attrs = $$1.extend({}, attrs, getExtraAttributesForConvertToPath(elem)); - var path = addSVGElementFromJson({ - element: 'path', - attr: attrs - }); - var eltrans = elem.getAttribute('transform'); - - if (eltrans) { - path.setAttribute('transform', eltrans); - } - - var id = elem.id; - var parentNode = elem.parentNode; - - if (elem.nextSibling) { - elem.before(path); - } else { - parentNode.append(path); - } - - var d = getPathDFromElement(elem); - - if (d) { - path.setAttribute('d', d); // Replace the current element with the converted one - // Reorient if it has a matrix - - if (eltrans) { - var tlist = getTransformList(path); - - if (hasMatrixTransform(tlist)) { - pathActions.resetOrientation(path); - } - } - - var nextSibling = elem.nextSibling; - batchCmd.addSubCommand(new hstry.RemoveElementCommand(elem, nextSibling, parent)); - batchCmd.addSubCommand(new hstry.InsertElementCommand(path)); - clearSelection(); - elem.remove(); - path.setAttribute('id', id); - path.removeAttribute('visibility'); - addToSelection([path], true); - addCommandToHistory(batchCmd); - return path; - } // the elem.tagName was not recognized, so no "d" attribute. Remove it, so we've haven't changed anything. - - - path.remove(); - return null; -}; -/** -* Can the bbox be optimized over the native getBBox? The optimized bbox is the same as the native getBBox when -* the rotation angle is a multiple of 90 degrees and there are no complex transforms. -* Getting an optimized bbox can be dramatically slower, so we want to make sure it's worth it. -* -* The best example for this is a circle rotate 45 degrees. The circle doesn't get wider or taller when rotated -* about it's center. -* -* The standard, unoptimized technique gets the native bbox of the circle, rotates the box 45 degrees, uses -* that width and height, and applies any transforms to get the final bbox. This means the calculated bbox -* is much wider than the original circle. If the angle had been 0, 90, 180, etc. both techniques render the -* same bbox. -* -* The optimization is not needed if the rotation is a multiple 90 degrees. The default technique is to call -* getBBox then apply the angle and any transforms. -* -* @param {Float} angle - The rotation angle in degrees -* @param {boolean} hasAMatrixTransform - True if there is a matrix transform -* @returns {boolean} True if the bbox can be optimized. -*/ - -function bBoxCanBeOptimizedOverNativeGetBBox(angle, hasAMatrixTransform) { - var angleModulo90 = angle % 90; - var closeTo90 = angleModulo90 < -89.99 || angleModulo90 > 89.99; - var closeTo0 = angleModulo90 > -0.001 && angleModulo90 < 0.001; - return hasAMatrixTransform || !(closeTo0 || closeTo90); -} -/** -* Get bounding box that includes any transforms. -* @function module:utilities.getBBoxWithTransform -* @param {Element} elem - The DOM element to be converted -* @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson -* @param {module:path.pathActions} pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions. -* @returns {module:utilities.BBoxObject|module:math.TransformedBox|DOMRect} A single bounding box object -*/ - - -var getBBoxWithTransform = function getBBoxWithTransform(elem, addSVGElementFromJson, pathActions) { - // TODO: Fix issue with rotated groups. Currently they work - // fine in FF, but not in other browsers (same problem mentioned - // in Issue 339 comment #2). - var bb = getBBox(elem); - - if (!bb) { - return null; - } - - var tlist = getTransformList(elem); - var angle = getRotationAngleFromTransformList(tlist); - var hasMatrixXForm = hasMatrixTransform(tlist); - - if (angle || hasMatrixXForm) { - var goodBb = false; - - if (bBoxCanBeOptimizedOverNativeGetBBox(angle, hasMatrixXForm)) { - // Get the BBox from the raw path for these elements - // TODO: why ellipse and not circle - var elemNames = ['ellipse', 'path', 'line', 'polyline', 'polygon']; - - if (elemNames.includes(elem.tagName)) { - goodBb = getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions); - bb = goodBb; - } else if (elem.tagName === 'rect') { - // Look for radius - var rx = elem.getAttribute('rx'); - var ry = elem.getAttribute('ry'); - - if (rx || ry) { - goodBb = getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions); - bb = goodBb; - } - } - } - - if (!goodBb) { - var _transformListToTrans = transformListToTransform(tlist), - matrix = _transformListToTrans.matrix; - - bb = transformBox(bb.x, bb.y, bb.width, bb.height, matrix).aabox; // Old technique that was exceedingly slow with large documents. - // - // Accurate way to get BBox of rotated element in Firefox: - // Put element in group and get its BBox - // - // Must use clone else FF freaks out - // const clone = elem.cloneNode(true); - // const g = document.createElementNS(NS.SVG, 'g'); - // const parent = elem.parentNode; - // parent.append(g); - // g.append(clone); - // const bb2 = bboxToObj(g.getBBox()); - // g.remove(); - } - } - - return bb; -}; -/** - * @param {Element} elem - * @returns {Float} - * @todo This is problematic with large stroke-width and, for example, a single - * horizontal line. The calculated BBox extends way beyond left and right sides. - */ - -function getStrokeOffsetForBBox(elem) { - var sw = elem.getAttribute('stroke-width'); - return !isNaN(sw) && elem.getAttribute('stroke') !== 'none' ? sw / 2 : 0; -} -/** - * @typedef {PlainObject} BBox - * @property {Integer} x The x value - * @property {Integer} y The y value - * @property {Float} width - * @property {Float} height - */ - -/** -* Get the bounding box for one or more stroked and/or transformed elements. -* @function module:utilities.getStrokedBBox -* @param {Element[]} elems - Array with DOM elements to check -* @param {module:utilities.EditorContext#addSVGElementFromJson} addSVGElementFromJson - Function to add the path element to the current layer. See canvas.addSVGElementFromJson -* @param {module:path.pathActions} pathActions - If a transform exists, pathActions.resetOrientation() is used. See: canvas.pathActions. -* @returns {module:utilities.BBoxObject|module:math.TransformedBox|DOMRect} A single bounding box object -*/ - - -var getStrokedBBox = function getStrokedBBox(elems, addSVGElementFromJson, pathActions) { - if (!elems || !elems.length) { - return false; - } - - var fullBb; - $$1.each(elems, function () { - if (fullBb) { - return; - } - - if (!this.parentNode) { - return; - } - - fullBb = getBBoxWithTransform(this, addSVGElementFromJson, pathActions); - }); // This shouldn't ever happen... - - if (fullBb === undefined) { - return null; - } // fullBb doesn't include the stoke, so this does no good! - // if (elems.length == 1) return fullBb; - - - var maxX = fullBb.x + fullBb.width; - var maxY = fullBb.y + fullBb.height; - var minX = fullBb.x; - var minY = fullBb.y; // If only one elem, don't call the potentially slow getBBoxWithTransform method again. - - if (elems.length === 1) { - var offset = getStrokeOffsetForBBox(elems[0]); - minX -= offset; - minY -= offset; - maxX += offset; - maxY += offset; - } else { - $$1.each(elems, function (i, elem) { - var curBb = getBBoxWithTransform(elem, addSVGElementFromJson, pathActions); - - if (curBb) { - var _offset = getStrokeOffsetForBBox(elem); - - minX = Math.min(minX, curBb.x - _offset); - minY = Math.min(minY, curBb.y - _offset); // TODO: The old code had this test for max, but not min. I suspect this test should be for both min and max - - if (elem.nodeType === 1) { - maxX = Math.max(maxX, curBb.x + curBb.width + _offset); - maxY = Math.max(maxY, curBb.y + curBb.height + _offset); - } - } - }); - } - - fullBb.x = minX; - fullBb.y = minY; - fullBb.width = maxX - minX; - fullBb.height = maxY - minY; - return fullBb; -}; -/** -* Get all elements that have a BBox (excludes ``, ``, etc). -* Note that 0-opacity, off-screen etc elements are still considered "visible" -* for this function. -* @function module:utilities.getVisibleElements -* @param {Element} parentElement - The parent DOM element to search within -* @returns {Element[]} All "visible" elements. -*/ - -var getVisibleElements = function getVisibleElements(parentElement) { - if (!parentElement) { - parentElement = $$1(editorContext_.getSVGContent()).children(); // Prevent layers from being included - } - - var contentElems = []; - $$1(parentElement).children().each(function (i, elem) { - if (elem.getBBox) { - contentElems.push(elem); - } - }); - return contentElems.reverse(); -}; -/** -* Get the bounding box for one or more stroked and/or transformed elements. -* @function module:utilities.getStrokedBBoxDefaultVisible -* @param {Element[]} elems - Array with DOM elements to check -* @returns {module:utilities.BBoxObject} A single bounding box object -*/ - -var getStrokedBBoxDefaultVisible = function getStrokedBBoxDefaultVisible(elems) { - if (!elems) { - elems = getVisibleElements(); - } - - return getStrokedBBox(elems, editorContext_.addSVGElementFromJson, editorContext_.pathActions); -}; -/** -* Get the rotation angle of the given transform list. -* @function module:utilities.getRotationAngleFromTransformList -* @param {SVGTransformList} tlist - List of transforms -* @param {boolean} toRad - When true returns the value in radians rather than degrees -* @returns {Float} The angle in degrees or radians -*/ - -var getRotationAngleFromTransformList = function getRotationAngleFromTransformList(tlist, toRad) { - if (!tlist) { - return 0; - } // <svg> elements have no tlist - - - var N = tlist.numberOfItems; - - for (var i = 0; i < N; ++i) { - var xform = tlist.getItem(i); - - if (xform.type === 4) { - return toRad ? xform.angle * Math.PI / 180.0 : xform.angle; - } - } - - return 0.0; -}; -/** -* Get the rotation angle of the given/selected DOM element. -* @function module:utilities.getRotationAngle -* @param {Element} [elem] - DOM element to get the angle for. Default to first of selected elements. -* @param {boolean} [toRad=false] - When true returns the value in radians rather than degrees -* @returns {Float} The angle in degrees or radians -*/ - -var getRotationAngle = function getRotationAngle(elem, toRad) { - // eslint-disable-line import/no-mutable-exports - var selected = elem || editorContext_.getSelectedElements()[0]; // find the rotation transform (if any) and set it - - var tlist = getTransformList(selected); - return getRotationAngleFromTransformList(tlist, toRad); -}; -/** -* Get the reference element associated with the given attribute value. -* @function module:utilities.getRefElem -* @param {string} attrVal - The attribute value as a string -* @returns {Element} Reference element -*/ - -var getRefElem = function getRefElem(attrVal) { - return getElem(getUrlFromAttr(attrVal).substr(1)); -}; -/** -* Get a DOM element by ID within the SVG root element. -* @function module:utilities.getElem -* @param {string} id - String with the element's new ID -* @returns {?Element} -*/ - -var getElem = supportsSelectors() ? function (id) { - // querySelector lookup - return svgroot_.querySelector('#' + id); -} : supportsXpath() ? function (id) { - // xpath lookup - return domdoc_.evaluate('svg:svg[@id="svgroot"]//svg:*[@id="' + id + '"]', domcontainer_, function () { - return NS.SVG; - }, 9, null).singleNodeValue; -} : function (id) { - // jQuery lookup: twice as slow as xpath in FF - return $$1(svgroot_).find("[id=".concat(id, "]"))[0]; -}; -/** -* Assigns multiple attributes to an element. -* @function module:utilities.assignAttributes -* @param {Element} elem - DOM element to apply new attribute values to -* @param {PlainObject<string, string>} attrs - Object with attribute keys/values -* @param {Integer} [suspendLength] - Milliseconds to suspend redraw -* @param {boolean} [unitCheck=false] - Boolean to indicate the need to use units.setUnitAttr -* @returns {void} -*/ - -var assignAttributes = function assignAttributes(elem, attrs, suspendLength, unitCheck) { - for (var _i = 0, _Object$entries = Object.entries(attrs); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), - key = _Object$entries$_i[0], - value = _Object$entries$_i[1]; - - var ns = key.substr(0, 4) === 'xml:' ? NS.XML : key.substr(0, 6) === 'xlink:' ? NS.XLINK : null; - - if (isNullish(value)) { - if (ns) { - elem.removeAttributeNS(ns, key); - } else { - elem.removeAttribute(key); - } - - continue; - } - - if (ns) { - elem.setAttributeNS(ns, key, value); - } else if (!unitCheck) { - elem.setAttribute(key, value); - } else { - setUnitAttr(elem, key, value); - } - } -}; -/** -* Remove unneeded (default) attributes, making resulting SVG smaller. -* @function module:utilities.cleanupElement -* @param {Element} element - DOM element to clean up -* @returns {void} -*/ - -var cleanupElement = function cleanupElement(element) { - var defaults = { - 'fill-opacity': 1, - 'stop-opacity': 1, - opacity: 1, - stroke: 'none', - 'stroke-dasharray': 'none', - 'stroke-linejoin': 'miter', - 'stroke-linecap': 'butt', - 'stroke-opacity': 1, - 'stroke-width': 1, - rx: 0, - ry: 0 - }; - - if (element.nodeName === 'ellipse') { - // Ellipse elements require rx and ry attributes - delete defaults.rx; - delete defaults.ry; - } - - Object.entries(defaults).forEach(function (_ref4) { - var _ref5 = _slicedToArray(_ref4, 2), - attr = _ref5[0], - val = _ref5[1]; - - if (element.getAttribute(attr) === String(val)) { - element.removeAttribute(attr); - } - }); -}; -/** -* Round value to for snapping. -* @function module:utilities.snapToGrid -* @param {Float} value -* @returns {Integer} -*/ - -var snapToGrid = function snapToGrid(value) { - var unit = editorContext_.getBaseUnit(); - var stepSize = editorContext_.getSnappingStep(); - - if (unit !== 'px') { - stepSize *= getTypeMap()[unit]; - } - - value = Math.round(value / stepSize) * stepSize; - return value; -}; -/** -* Escapes special characters in a regular expression. -* @function module:utilities.regexEscape -* @param {string} str -* @returns {string} -*/ - -var regexEscape = function regexEscape(str) { - // Originally from: http://phpjs.org/functions - return String(str).replace(/[.\\+*?[^\]$(){}=!<>|:-]/g, '\\$&'); -}; -/** - * Prevents default browser click behaviour on the given element. - * @function module:utilities.preventClickDefault - * @param {Element} img - The DOM element to prevent the click on - * @returns {void} - */ - -var preventClickDefault = function preventClickDefault(img) { - $$1(img).click(function (e) { - e.preventDefault(); - }); -}; -/** - * @callback module:utilities.GetNextID - * @returns {string} The ID - */ - -/** - * Whether a value is `null` or `undefined`. - * @param {any} val - * @returns {boolean} - */ - -var isNullish = function isNullish(val) { - return val === null || val === undefined; -}; -var $q = function $q(sel) { - return document.querySelector(sel); -}; - -/* globals jQuery */ - -/** - * Adds context menu functionality. - * @module contextmenu - * @license Apache-2.0 - * @author Adam Bender - */ -// Dependencies: -// 1) jQuery (for dom injection of context menus) -var $$2 = jQuery; -var contextMenuExtensions = {}; -/** -* @function module:contextmenu.hasCustomHandler -* @param {string} handlerKey -* @returns {boolean} -*/ - -var hasCustomHandler = function hasCustomHandler(handlerKey) { - return Boolean(contextMenuExtensions[handlerKey]); -}; -/** -* @function module:contextmenu.getCustomHandler -* @param {string} handlerKey -* @returns {module:contextmenu.MenuItemAction} -*/ - -var getCustomHandler = function getCustomHandler(handlerKey) { - return contextMenuExtensions[handlerKey].action; -}; -/** -* @param {module:contextmenu.MenuItem} menuItem -* @returns {void} -*/ - -var injectExtendedContextMenuItemIntoDom = function injectExtendedContextMenuItemIntoDom(menuItem) { - if (!Object.keys(contextMenuExtensions).length) { - // all menuItems appear at the bottom of the menu in their own container. - // if this is the first extension menu we need to add the separator. - $$2('#cmenu_canvas').append("<li class='separator'>"); - } - - var shortcut = menuItem.shortcut || ''; - $$2('#cmenu_canvas').append("<li class='disabled'><a href='#" + menuItem.id + "'>" + menuItem.label + "<span class='shortcut'>" + shortcut + '</span></a></li>'); -}; -/** -* @function module:contextmenu.injectExtendedContextMenuItemsIntoDom -* @returns {void} -*/ - - -var injectExtendedContextMenuItemsIntoDom = function injectExtendedContextMenuItemsIntoDom() { - Object.values(contextMenuExtensions).forEach(function (menuItem) { - injectExtendedContextMenuItemIntoDom(menuItem); - }); -}; - -/* eslint-disable jsdoc/require-file-overview */ - -/** - * Adapted from {@link https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js}. - * @module importModule - * @license MIT - */ - -/** - * Converts a possible relative URL into an absolute one. - * @param {string} url - * @returns {string} - */ -function toAbsoluteURL(url) { - var a = document.createElement('a'); - a.setAttribute('href', url); // <a href="hoge.html"> - - return a.cloneNode(false).href; // -> "http://example.com/hoge.html" -} -/** - * Add any of the whitelisted attributes to the script tag. - * @param {HTMLScriptElement} script - * @param {PlainObject<string, string>} atts - * @returns {void} - */ - - -function addScriptAtts(script, atts) { - ['id', 'class', 'type'].forEach(function (prop) { - if (prop in atts) { - script[prop] = atts[prop]; - } - }); -} // Additions by Brett - -/** -* @typedef {PlainObject} module:importModule.ImportConfig -* @property {string} global The variable name to set on `window` (when not using the modular version) -* @property {boolean} [returnDefault=false] -*/ - -/** -* @function module:importModule.importSetGlobalDefault -* @param {string|GenericArray<any>} url -* @param {module:importModule.ImportConfig} config -* @returns {Promise<any>} The value to which it resolves depends on the export of the targeted module. -*/ - - -function importSetGlobalDefault(url, config) { - return importSetGlobal(url, _extends({}, config, { - returnDefault: true - })); -} -/** -* @function module:importModule.importSetGlobal -* @param {string|string[]} url -* @param {module:importModule.ImportConfig} config -* @returns {Promise<ArbitraryModule>} The promise resolves to either an `ArbitraryModule` or -* any other value depends on the export of the targeted module. -*/ - -function importSetGlobal(_x, _x2) { - return _importSetGlobal.apply(this, arguments); -} -/** - * - * @author Brett Zamir (other items are from `dynamic-import-polyfill`) - * @param {string|string[]} url - * @param {PlainObject} [atts={}] - * @returns {Promise<void|Error>} Resolves to `undefined` or rejects with an `Error` upon a - * script loading error - */ - -function _importSetGlobal() { - _importSetGlobal = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url, _ref) { - var glob, returnDefault, modularVersion; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - glob = _ref.global, returnDefault = _ref.returnDefault; - // Todo: Replace calls to this function with `import()` when supported - modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false; - - if (!modularVersion) { - _context.next = 4; - break; - } - - return _context.abrupt("return", importModule(url, undefined, { - returnDefault: returnDefault - })); - - case 4: - _context.next = 6; - return importScript(url); - - case 6: - return _context.abrupt("return", window[glob]); - - case 7: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - return _importSetGlobal.apply(this, arguments); -} - -function importScript(url) { - var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - if (Array.isArray(url)) { - return Promise.all(url.map(function (u) { - return importScript(u, atts); - })); - } - - return new Promise(function (resolve, reject) { - // eslint-disable-line promise/avoid-new - var script = document.createElement('script'); - /** - * - * @returns {void} - */ - - function scriptOnError() { - reject(new Error("Failed to import: ".concat(url))); - destructor(); - } - /** - * - * @returns {void} - */ - - - function scriptOnLoad() { - resolve(); - destructor(); - } - - var destructor = function destructor() { - script.removeEventListener('error', scriptOnError); - script.removeEventListener('load', scriptOnLoad); - script.remove(); - script.src = ''; - }; - - script.defer = 'defer'; - addScriptAtts(script, atts); - script.addEventListener('error', scriptOnError); - script.addEventListener('load', scriptOnLoad); - script.src = url; - document.head.append(script); - }); -} -/** -* -* @param {string|string[]} url -* @param {PlainObject} [atts={}] -* @param {PlainObject} opts -* @param {boolean} [opts.returnDefault=false} = {}] -* @returns {Promise<any>} Resolves to value of loading module or rejects with -* `Error` upon a script loading error. -*/ - -function importModule(url) { - var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - _ref2$returnDefault = _ref2.returnDefault, - returnDefault = _ref2$returnDefault === void 0 ? false : _ref2$returnDefault; - - if (Array.isArray(url)) { - return Promise.all(url.map(function (u) { - return importModule(u, atts); - })); - } - - return new Promise(function (resolve, reject) { - // eslint-disable-line promise/avoid-new - var vector = '$importModule$' + Math.random().toString(32).slice(2); - var script = document.createElement('script'); - /** - * - * @returns {void} - */ - - function scriptOnError() { - reject(new Error("Failed to import: ".concat(url))); - destructor(); - } - /** - * - * @returns {void} - */ - - - function scriptOnLoad() { - resolve(window[vector]); - destructor(); - } - - var destructor = function destructor() { - delete window[vector]; - script.removeEventListener('error', scriptOnError); - script.removeEventListener('load', scriptOnLoad); - script.remove(); - URL.revokeObjectURL(script.src); - script.src = ''; - }; - - addScriptAtts(script, atts); - script.defer = 'defer'; - script.type = 'module'; - script.addEventListener('error', scriptOnError); - script.addEventListener('load', scriptOnLoad); - var absURL = toAbsoluteURL(url); - var loader = "import * as m from '".concat(absURL.replace(/'/g, "\\'"), "'; window.").concat(vector, " = ").concat(returnDefault ? 'm.default || ' : '', "m;"); // export Module - - var blob = new Blob([loader], { - type: 'text/javascript' - }); - script.src = URL.createObjectURL(blob); - document.head.append(script); - }); -} - -/** - * Created by alexey2baranov on 28.01.17. - */ - -/* - An extraction of the deparam method from Ben Alman's jQuery BBQ - http://benalman.com/projects/jquery-bbq-plugin/ - */ -var coerce_types = { - 'true': !0, - 'false': !1, - 'null': null -}; - -function deparam(params, coerce) { - // console.log(params) - var obj = {}; // Iterate over all name=value pairs. - - params.replace(/\+/g, ' ').split('&').forEach(function (v) { - var param = v.split('='); - var key = decodeURIComponent(param[0]), - // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it - // into its component parts. - keys = key.split(']['), - keys_last = keys.length - 1; // If the first keys part contains [ and the last ends with ], then [] - // are correctly balanced. - - if (/\[/.test(keys[0]) && /\]$/.test(keys[keys_last])) { - // Remove the trailing ] from the last keys part. - keys[keys_last] = keys[keys_last].replace(/\]$/, ''); // Split first keys part into two parts on the [ and add them back onto - // the beginning of the keys array. - - keys = keys.shift().split('[').concat(keys); - keys_last = keys.length - 1; - } else { - // Basic 'foo' style key. - keys_last = 0; - } // Are we dealing with a name=value pair, or just a name? - - - if (param.length >= 2) { - var val = decodeURIComponent(param.slice(1).join('=')); // Coerce values. - - if (coerce) { - val = val && !isNaN(val) ? +val // number - : val === 'undefined' ? undefined // undefined - : coerce_types[val] !== undefined ? coerce_types[val] // true, false, null - : val; // string - } - - if (keys_last) { - var cur = obj; // Complex key, build deep object structure based on a few rules: - // * The 'cur' pointer starts at the object top-level. - // * [] = array push (n is set to array length), [n] = array if n is - // numeric, otherwise object. - // * If at the last keys part, set the value. - // * For each keys part, if the current level is undefined create an - // object or array based on the type of the next keys part. - // * Move the 'cur' pointer to the next level. - // * Rinse & repeat. - - for (var i = 0; i <= keys_last; i++) { - key = keys[i] === '' ? cur.length : keys[i]; - cur = cur[key] = i < keys_last ? cur[key] || (keys[i + 1] && isNaN(keys[i + 1]) ? {} : []) : val; - } - } else { - // Simple key, even simpler rules, since only scalars and shallow - // arrays are allowed. - if (Array.isArray(obj[key])) { - // val is already an array, so push on the next value. - obj[key].push(val); - } else if (obj[key] !== undefined) { - // val isn't an array, but since a second value has been specified, - // convert val into an array. - obj[key] = [obj[key], val]; - } else { - // val is a scalar. - obj[key] = val; - } - } - } else if (key) { - // No value was defined, so set something meaningful. - obj[key] = coerce ? undefined : ''; - } - }); - return obj; -} - -/** - * @module jQueryPluginDBox - */ - -/** -* @param {external:jQuery} $ -* @param {PlainObject} [strings] -* @param {PlainObject} [strings.ok] -* @param {PlainObject} [strings.cancel] -* @returns {external:jQuery} -*/ -function jQueryPluginDBox($) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$ok = _ref.ok, - okString = _ref$ok === void 0 ? 'Ok' : _ref$ok, - _ref$cancel = _ref.cancel, - cancelString = _ref$cancel === void 0 ? 'Cancel' : _ref$cancel; - - // This sets up alternative dialog boxes. They mostly work the same way as - // their UI counterparts, expect instead of returning the result, a callback - // needs to be included that returns the result as its first parameter. - // In the future we may want to add additional types of dialog boxes, since - // they should be easy to handle this way. - $('#dialog_container').draggable({ - cancel: '#dialog_content, #dialog_buttons *', - containment: 'window' - }).css('position', 'absolute'); - var box = $('#dialog_box'), - btnHolder = $('#dialog_buttons'), - dialogContent = $('#dialog_content'); - /** - * @typedef {PlainObject} module:jQueryPluginDBox.PromiseResultObject - * @property {string|true} response - * @property {boolean} checked - */ - - /** - * Resolves to `false` (if cancelled), for prompts and selects - * without checkboxes, it resolves to the value of the form control. For other - * types without checkboxes, it resolves to `true`. For checkboxes, it resolves - * to an object with the `response` key containing the same value as the previous - * mentioned (string or `true`) and a `checked` (boolean) property. - * @typedef {Promise<boolean|string|module:jQueryPluginDBox.PromiseResultObject>} module:jQueryPluginDBox.ResultPromise - */ - - /** - * @typedef {PlainObject} module:jQueryPluginDBox.SelectOption - * @property {string} text - * @property {string} value - */ - - /** - * @typedef {PlainObject} module:jQueryPluginDBox.CheckboxInfo - * @property {string} label Label for the checkbox - * @property {string} value Value of the checkbox - * @property {string} tooltip Tooltip on the checkbox label - * @property {boolean} checked Whether the checkbox is checked by default - */ - - /** - * Triggered upon a change of value for the select pull-down. - * @callback module:jQueryPluginDBox.SelectChangeListener - * @returns {void} - */ - - /** - * Creates a dialog of the specified type with a given message - * and any defaults and type-specific metadata. Returns a `Promise` - * which resolves differently depending on whether the dialog - * was cancelled or okayed (with the response and any checked state). - * @param {"alert"|"prompt"|"select"|"process"} type - * @param {string} msg - * @param {string} [defaultVal] - * @param {module:jQueryPluginDBox.SelectOption[]} [opts] - * @param {module:jQueryPluginDBox.SelectChangeListener} [changeListener] - * @param {module:jQueryPluginDBox.CheckboxInfo} [checkbox] - * @returns {jQueryPluginDBox.ResultPromise} - */ - - function dbox(type, msg, defaultVal, opts, changeListener, checkbox) { - dialogContent.html('<p>' + msg.replace(/\n/g, '</p><p>') + '</p>').toggleClass('prompt', type === 'prompt'); - btnHolder.empty(); - var ok = $('<input type="button" data-ok="" value="' + okString + '">').appendTo(btnHolder); - return new Promise(function (resolve, reject) { - // eslint-disable-line promise/avoid-new - if (type !== 'alert') { - $('<input type="button" value="' + cancelString + '">').appendTo(btnHolder).click(function () { - box.hide(); - resolve(false); - }); - } - - var ctrl, chkbx; - - if (type === 'prompt') { - ctrl = $('<input type="text">').prependTo(btnHolder); - ctrl.val(defaultVal || ''); - ctrl.bind('keydown', 'return', function () { - ok.click(); - }); - } else if (type === 'select') { - var div = $('<div style="text-align:center;">'); - ctrl = $("<select aria-label=\"".concat(msg, "\">")).appendTo(div); - - if (checkbox) { - var label = $('<label>').text(checkbox.label); - chkbx = $('<input type="checkbox">').appendTo(label); - chkbx.val(checkbox.value); - - if (checkbox.tooltip) { - label.attr('title', checkbox.tooltip); - } - - chkbx.prop('checked', Boolean(checkbox.checked)); - div.append($('<div>').append(label)); - } - - $.each(opts || [], function (opt, val) { - if (_typeof(val) === 'object') { - ctrl.append($('<option>').val(val.value).html(val.text)); - } else { - ctrl.append($('<option>').html(val)); - } - }); - dialogContent.append(div); - - if (defaultVal) { - ctrl.val(defaultVal); - } - - if (changeListener) { - ctrl.bind('change', 'return', changeListener); - } - - ctrl.bind('keydown', 'return', function () { - ok.click(); - }); - } else if (type === 'process') { - ok.hide(); - } - - box.show(); - ok.click(function () { - box.hide(); - var response = type === 'prompt' || type === 'select' ? ctrl.val() : true; - - if (chkbx) { - resolve({ - response: response, - checked: chkbx.prop('checked') - }); - return; - } - - resolve(response); - }).focus(); - - if (type === 'prompt' || type === 'select') { - ctrl.focus(); - } - }); - } - /** - * @param {string} msg Message to alert - * @returns {jQueryPluginDBox.ResultPromise} - */ - - - $.alert = function (msg) { - return dbox('alert', msg); - }; - /** - * @param {string} msg Message for which to ask confirmation - * @returns {jQueryPluginDBox.ResultPromise} - */ - - - $.confirm = function (msg) { - return dbox('confirm', msg); - }; - /** - * @param {string} msg Message to indicate upon cancelable indicator - * @returns {jQueryPluginDBox.ResultPromise} - */ - - - $.process_cancel = function (msg) { - return dbox('process', msg); - }; - /** - * @param {string} msg Message to accompany the prompt - * @param {string} [defaultText=''] The default text to show for the prompt - * @returns {jQueryPluginDBox.ResultPromise} - */ - - - $.prompt = function (msg) { - var defaultText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; - return dbox('prompt', msg, defaultText); - }; - - $.select = function (msg, opts, changeListener, txt, checkbox) { - return dbox('select', msg, txt, opts, changeListener, checkbox); - }; - - return $; -} - -/** -* Group: Undo/Redo history management. -*/ - -var HistoryEventTypes = { - BEFORE_APPLY: 'before_apply', - AFTER_APPLY: 'after_apply', - BEFORE_UNAPPLY: 'before_unapply', - AFTER_UNAPPLY: 'after_unapply' -}; -/** -* Base class for commands. -*/ - -var Command = /*#__PURE__*/function () { - function Command() { - _classCallCheck(this, Command); - } - - _createClass(Command, [{ - key: "getText", - - /** - * @returns {string} - */ - value: function getText() { - return this.text; - } - /** - * @param {module:history.HistoryEventHandler} handler - * @param {callback} applyFunction - * @returns {void} - */ - - }, { - key: "apply", - value: function apply(handler, applyFunction) { - handler && handler.handleHistoryEvent(HistoryEventTypes.BEFORE_APPLY, this); - applyFunction(handler); - handler && handler.handleHistoryEvent(HistoryEventTypes.AFTER_APPLY, this); - } - /** - * @param {module:history.HistoryEventHandler} handler - * @param {callback} unapplyFunction - * @returns {void} - */ - - }, { - key: "unapply", - value: function unapply(handler, unapplyFunction) { - handler && handler.handleHistoryEvent(HistoryEventTypes.BEFORE_UNAPPLY, this); - unapplyFunction(); - handler && handler.handleHistoryEvent(HistoryEventTypes.AFTER_UNAPPLY, this); - } - /** - * @returns {Element[]} Array with element associated with this command - * This function needs to be surcharged if multiple elements are returned. - */ - - }, { - key: "elements", - value: function elements() { - return [this.elem]; - } - /** - * @returns {string} String with element associated with this command - */ - - }, { - key: "type", - value: function type() { - return this.constructor.name; - } - }]); - - return Command; -}(); // Todo: Figure out why the interface members aren't showing -// up (with or without modules applied), despite our apparently following -// http://usejsdoc.org/tags-interface.html#virtual-comments - -/** - * An interface that all command objects must implement. - * @interface module:history.HistoryCommand -*/ - -/** - * Applies. - * - * @function module:history.HistoryCommand#apply - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void|true} - */ - -/** - * - * Unapplies. - * @function module:history.HistoryCommand#unapply - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void|true} - */ - -/** - * Returns the elements. - * @function module:history.HistoryCommand#elements - * @returns {Element[]} - */ - -/** - * Gets the text. - * @function module:history.HistoryCommand#getText - * @returns {string} - */ - -/** - * Gives the type. - * @function module:history.HistoryCommand.type - * @returns {string} - */ - -/** - * @event module:history~Command#event:history - * @type {module:history.HistoryCommand} - */ - -/** - * An interface for objects that will handle history events. - * @interface module:history.HistoryEventHandler - */ - -/** - * - * @function module:history.HistoryEventHandler#handleHistoryEvent - * @param {string} eventType One of the HistoryEvent types - * @param {module:history~Command#event:history} command - * @listens module:history~Command#event:history - * @returns {void} - * - */ - -/** - * History command for an element that had its DOM position changed. - * @implements {module:history.HistoryCommand} -*/ - -var MoveElementCommand = /*#__PURE__*/function (_Command) { - _inherits(MoveElementCommand, _Command); - - var _super = _createSuper(MoveElementCommand); - - /** - * @param {Element} elem - The DOM element that was moved - * @param {Element} oldNextSibling - The element's next sibling before it was moved - * @param {Element} oldParent - The element's parent before it was moved - * @param {string} [text] - An optional string visible to user related to this change - */ - function MoveElementCommand(elem, oldNextSibling, oldParent, text) { - var _this; - - _classCallCheck(this, MoveElementCommand); - - _this = _super.call(this); - _this.elem = elem; - _this.text = text ? 'Move ' + elem.tagName + ' to ' + text : 'Move ' + elem.tagName; - _this.oldNextSibling = oldNextSibling; - _this.oldParent = oldParent; - _this.newNextSibling = elem.nextSibling; - _this.newParent = elem.parentNode; - return _this; - } - /** - * Re-positions the element. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - - _createClass(MoveElementCommand, [{ - key: "apply", - value: function apply(handler) { - var _this2 = this; - - _get(_getPrototypeOf(MoveElementCommand.prototype), "apply", this).call(this, handler, function () { - _this2.elem = _this2.newParent.insertBefore(_this2.elem, _this2.newNextSibling); - }); - } - /** - * Positions the element back to its original location. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - }, { - key: "unapply", - value: function unapply(handler) { - var _this3 = this; - - _get(_getPrototypeOf(MoveElementCommand.prototype), "unapply", this).call(this, handler, function () { - _this3.elem = _this3.oldParent.insertBefore(_this3.elem, _this3.oldNextSibling); - }); - } - }]); - - return MoveElementCommand; -}(Command); -/** -* History command for an element that was added to the DOM. -* @implements {module:history.HistoryCommand} -*/ - -var InsertElementCommand = /*#__PURE__*/function (_Command2) { - _inherits(InsertElementCommand, _Command2); - - var _super2 = _createSuper(InsertElementCommand); - - /** - * @param {Element} elem - The newly added DOM element - * @param {string} text - An optional string visible to user related to this change - */ - function InsertElementCommand(elem, text) { - var _this4; - - _classCallCheck(this, InsertElementCommand); - - _this4 = _super2.call(this); - _this4.elem = elem; - _this4.text = text || 'Create ' + elem.tagName; - _this4.parent = elem.parentNode; - _this4.nextSibling = _this4.elem.nextSibling; - return _this4; - } - /** - * Re-inserts the new element. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - - _createClass(InsertElementCommand, [{ - key: "apply", - value: function apply(handler) { - var _this5 = this; - - _get(_getPrototypeOf(InsertElementCommand.prototype), "apply", this).call(this, handler, function () { - _this5.elem = _this5.parent.insertBefore(_this5.elem, _this5.nextSibling); - }); - } - /** - * Removes the element. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - }, { - key: "unapply", - value: function unapply(handler) { - var _this6 = this; - - _get(_getPrototypeOf(InsertElementCommand.prototype), "unapply", this).call(this, handler, function () { - _this6.parent = _this6.elem.parentNode; - - _this6.elem.remove(); - }); - } - }]); - - return InsertElementCommand; -}(Command); -/** -* History command for an element removed from the DOM. -* @implements {module:history.HistoryCommand} -*/ - -var RemoveElementCommand = /*#__PURE__*/function (_Command3) { - _inherits(RemoveElementCommand, _Command3); - - var _super3 = _createSuper(RemoveElementCommand); - - /** - * @param {Element} elem - The removed DOM element - * @param {Node} oldNextSibling - The DOM element's nextSibling when it was in the DOM - * @param {Element} oldParent - The DOM element's parent - * @param {string} [text] - An optional string visible to user related to this change - */ - function RemoveElementCommand(elem, oldNextSibling, oldParent, text) { - var _this7; - - _classCallCheck(this, RemoveElementCommand); - - _this7 = _super3.call(this); - _this7.elem = elem; - _this7.text = text || 'Delete ' + elem.tagName; - _this7.nextSibling = oldNextSibling; - _this7.parent = oldParent; // special hack for webkit: remove this element's entry in the svgTransformLists map - - removeElementFromListMap(elem); - return _this7; - } - /** - * Re-removes the new element. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - - _createClass(RemoveElementCommand, [{ - key: "apply", - value: function apply(handler) { - var _this8 = this; - - _get(_getPrototypeOf(RemoveElementCommand.prototype), "apply", this).call(this, handler, function () { - removeElementFromListMap(_this8.elem); - _this8.parent = _this8.elem.parentNode; - - _this8.elem.remove(); - }); - } - /** - * Re-adds the new element. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - }, { - key: "unapply", - value: function unapply(handler) { - var _this9 = this; - - _get(_getPrototypeOf(RemoveElementCommand.prototype), "unapply", this).call(this, handler, function () { - removeElementFromListMap(_this9.elem); - - if (isNullish(_this9.nextSibling)) { - if (window.console) { - console.error('Reference element was lost'); - } - } - - _this9.parent.insertBefore(_this9.elem, _this9.nextSibling); // Don't use `before` or `prepend` as `this.nextSibling` may be `null` - - }); - } - }]); - - return RemoveElementCommand; -}(Command); -/** -* @typedef {"#text"|"#href"|string} module:history.CommandAttributeName -*/ - -/** -* @typedef {PlainObject<module:history.CommandAttributeName, string>} module:history.CommandAttributes -*/ - -/** -* History command to make a change to an element. -* Usually an attribute change, but can also be textcontent. -* @implements {module:history.HistoryCommand} -*/ - -var ChangeElementCommand = /*#__PURE__*/function (_Command4) { - _inherits(ChangeElementCommand, _Command4); - - var _super4 = _createSuper(ChangeElementCommand); - - /** - * @param {Element} elem - The DOM element that was changed - * @param {module:history.CommandAttributes} attrs - Attributes to be changed with the values they had *before* the change - * @param {string} text - An optional string visible to user related to this change - */ - function ChangeElementCommand(elem, attrs, text) { - var _this10; - - _classCallCheck(this, ChangeElementCommand); - - _this10 = _super4.call(this); - _this10.elem = elem; - _this10.text = text ? 'Change ' + elem.tagName + ' ' + text : 'Change ' + elem.tagName; - _this10.newValues = {}; - _this10.oldValues = attrs; - - for (var attr in attrs) { - if (attr === '#text') { - _this10.newValues[attr] = elem.textContent; - } else if (attr === '#href') { - _this10.newValues[attr] = getHref(elem); - } else { - _this10.newValues[attr] = elem.getAttribute(attr); - } - } - - return _this10; - } - /** - * Performs the stored change action. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - - _createClass(ChangeElementCommand, [{ - key: "apply", - value: function apply(handler) { - var _this11 = this; - - _get(_getPrototypeOf(ChangeElementCommand.prototype), "apply", this).call(this, handler, function () { - var bChangedTransform = false; - Object.entries(_this11.newValues).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - attr = _ref2[0], - value = _ref2[1]; - - if (value) { - if (attr === '#text') { - _this11.elem.textContent = value; - } else if (attr === '#href') { - setHref(_this11.elem, value); - } else { - _this11.elem.setAttribute(attr, value); - } - } else if (attr === '#text') { - _this11.elem.textContent = ''; - } else { - _this11.elem.setAttribute(attr, ''); - - _this11.elem.removeAttribute(attr); - } - - if (attr === 'transform') { - bChangedTransform = true; - } - }); // relocate rotational transform, if necessary - - if (!bChangedTransform) { - var angle = getRotationAngle(_this11.elem); - - if (angle) { - var bbox = _this11.elem.getBBox(); - - var cx = bbox.x + bbox.width / 2; - var cy = bbox.y + bbox.height / 2; - var rotate = ['rotate(', angle, ' ', cx, ',', cy, ')'].join(''); - - if (rotate !== _this11.elem.getAttribute('transform')) { - _this11.elem.setAttribute('transform', rotate); - } - } - } - }); - } - /** - * Reverses the stored change action. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - }, { - key: "unapply", - value: function unapply(handler) { - var _this12 = this; - - _get(_getPrototypeOf(ChangeElementCommand.prototype), "unapply", this).call(this, handler, function () { - var bChangedTransform = false; - Object.entries(_this12.oldValues).forEach(function (_ref3) { - var _ref4 = _slicedToArray(_ref3, 2), - attr = _ref4[0], - value = _ref4[1]; - - if (value) { - if (attr === '#text') { - _this12.elem.textContent = value; - } else if (attr === '#href') { - setHref(_this12.elem, value); - } else { - _this12.elem.setAttribute(attr, value); - } - } else if (attr === '#text') { - _this12.elem.textContent = ''; - } else { - _this12.elem.removeAttribute(attr); - } - - if (attr === 'transform') { - bChangedTransform = true; - } - }); // relocate rotational transform, if necessary - - if (!bChangedTransform) { - var angle = getRotationAngle(_this12.elem); - - if (angle) { - var bbox = _this12.elem.getBBox(); - - var cx = bbox.x + bbox.width / 2, - cy = bbox.y + bbox.height / 2; - var rotate = ['rotate(', angle, ' ', cx, ',', cy, ')'].join(''); - - if (rotate !== _this12.elem.getAttribute('transform')) { - _this12.elem.setAttribute('transform', rotate); - } - } - } // Remove transformlist to prevent confusion that causes bugs like 575. - - - removeElementFromListMap(_this12.elem); - }); - } - }]); - - return ChangeElementCommand; -}(Command); // TODO: create a 'typing' command object that tracks changes in text -// if a new Typing command is created and the top command on the stack is also a Typing -// and they both affect the same element, then collapse the two commands into one - -/** -* History command that can contain/execute multiple other commands. -* @implements {module:history.HistoryCommand} -*/ - -var BatchCommand = /*#__PURE__*/function (_Command5) { - _inherits(BatchCommand, _Command5); - - var _super5 = _createSuper(BatchCommand); - - /** - * @param {string} [text] - An optional string visible to user related to this change - */ - function BatchCommand(text) { - var _this13; - - _classCallCheck(this, BatchCommand); - - _this13 = _super5.call(this); - _this13.text = text || 'Batch Command'; - _this13.stack = []; - return _this13; - } - /** - * Runs "apply" on all subcommands. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - - _createClass(BatchCommand, [{ - key: "apply", - value: function apply(handler) { - var _this14 = this; - - _get(_getPrototypeOf(BatchCommand.prototype), "apply", this).call(this, handler, function () { - _this14.stack.forEach(function (stackItem) { - console.assert(stackItem, 'stack item should not be null'); - stackItem && stackItem.apply(handler); - }); - }); - } - /** - * Runs "unapply" on all subcommands. - * @param {module:history.HistoryEventHandler} handler - * @fires module:history~Command#event:history - * @returns {void} - */ - - }, { - key: "unapply", - value: function unapply(handler) { - var _this15 = this; - - _get(_getPrototypeOf(BatchCommand.prototype), "unapply", this).call(this, handler, function () { - _this15.stack.reverse().forEach(function (stackItem) { - console.assert(stackItem, 'stack item should not be null'); - stackItem && stackItem.unapply(handler); - }); - }); - } - /** - * Iterate through all our subcommands. - * @returns {Element[]} All the elements we are changing - */ - - }, { - key: "elements", - value: function elements() { - var elems = []; - var cmd = this.stack.length; - - while (cmd--) { - if (!this.stack[cmd]) continue; - var thisElems = this.stack[cmd].elements(); - var elem = thisElems.length; - - while (elem--) { - if (!elems.includes(thisElems[elem])) { - elems.push(thisElems[elem]); - } - } - } - - return elems; - } - /** - * Adds a given command to the history stack. - * @param {Command} cmd - The undo command object to add - * @returns {void} - */ - - }, { - key: "addSubCommand", - value: function addSubCommand(cmd) { - console.assert(cmd !== null, 'cmd should not be null'); - this.stack.push(cmd); - } - /** - * @returns {boolean} Indicates whether or not the batch command is empty - */ - - }, { - key: "isEmpty", - value: function isEmpty() { - return !this.stack.length; - } - }]); - - return BatchCommand; -}(Command); -/** -* -*/ - -var UndoManager = /*#__PURE__*/function () { - /** - * @param {module:history.HistoryEventHandler} historyEventHandler - */ - function UndoManager(historyEventHandler) { - _classCallCheck(this, UndoManager); - - this.handler_ = historyEventHandler || null; - this.undoStackPointer = 0; - this.undoStack = []; // this is the stack that stores the original values, the elements and - // the attribute name for begin/finish - - this.undoChangeStackPointer = -1; - this.undoableChangeStack = []; - } - /** - * Resets the undo stack, effectively clearing the undo/redo history. - * @returns {void} - */ - - - _createClass(UndoManager, [{ - key: "resetUndoStack", - value: function resetUndoStack() { - this.undoStack = []; - this.undoStackPointer = 0; - } - /** - * @returns {Integer} Current size of the undo history stack - */ - - }, { - key: "getUndoStackSize", - value: function getUndoStackSize() { - return this.undoStackPointer; - } - /** - * @returns {Integer} Current size of the redo history stack - */ - - }, { - key: "getRedoStackSize", - value: function getRedoStackSize() { - return this.undoStack.length - this.undoStackPointer; - } - /** - * @returns {string} String associated with the next undo command - */ - - }, { - key: "getNextUndoCommandText", - value: function getNextUndoCommandText() { - return this.undoStackPointer > 0 ? this.undoStack[this.undoStackPointer - 1].getText() : ''; - } - /** - * @returns {string} String associated with the next redo command - */ - - }, { - key: "getNextRedoCommandText", - value: function getNextRedoCommandText() { - return this.undoStackPointer < this.undoStack.length ? this.undoStack[this.undoStackPointer].getText() : ''; - } - /** - * Performs an undo step. - * @returns {void} - */ - - }, { - key: "undo", - value: function undo() { - if (this.undoStackPointer > 0) { - var cmd = this.undoStack[--this.undoStackPointer]; - cmd.unapply(this.handler_); - } - } - /** - * Performs a redo step. - * @returns {void} - */ - - }, { - key: "redo", - value: function redo() { - if (this.undoStackPointer < this.undoStack.length && this.undoStack.length > 0) { - var cmd = this.undoStack[this.undoStackPointer++]; - cmd.apply(this.handler_); - } - } - /** - * Adds a command object to the undo history stack. - * @param {Command} cmd - The command object to add - * @returns {void} - */ - - }, { - key: "addCommandToHistory", - value: function addCommandToHistory(cmd) { - // TODO: we MUST compress consecutive text changes to the same element - // (right now each keystroke is saved as a separate command that includes the - // entire text contents of the text element) - // TODO: consider limiting the history that we store here (need to do some slicing) - // if our stack pointer is not at the end, then we have to remove - // all commands after the pointer and insert the new command - if (this.undoStackPointer < this.undoStack.length && this.undoStack.length > 0) { - this.undoStack = this.undoStack.splice(0, this.undoStackPointer); - } - - this.undoStack.push(cmd); - this.undoStackPointer = this.undoStack.length; - } - /** - * This function tells the canvas to remember the old values of the - * `attrName` attribute for each element sent in. The elements and values - * are stored on a stack, so the next call to `finishUndoableChange()` will - * pop the elements and old values off the stack, gets the current values - * from the DOM and uses all of these to construct the undo-able command. - * @param {string} attrName - The name of the attribute being changed - * @param {Element[]} elems - Array of DOM elements being changed - * @returns {void} - */ - - }, { - key: "beginUndoableChange", - value: function beginUndoableChange(attrName, elems) { - var p = ++this.undoChangeStackPointer; - var i = elems.length; - var oldValues = new Array(i), - elements = new Array(i); - - while (i--) { - var elem = elems[i]; - - if (isNullish(elem)) { - continue; - } - - elements[i] = elem; - oldValues[i] = elem.getAttribute(attrName); - } - - this.undoableChangeStack[p] = { - attrName: attrName, - oldValues: oldValues, - elements: elements - }; - } - /** - * This function returns a `BatchCommand` object which summarizes the - * change since `beginUndoableChange` was called. The command can then - * be added to the command history. - * @returns {BatchCommand} Batch command object with resulting changes - */ - - }, { - key: "finishUndoableChange", - value: function finishUndoableChange() { - var p = this.undoChangeStackPointer--; - var changeset = this.undoableChangeStack[p]; - var attrName = changeset.attrName; - var batchCmd = new BatchCommand('Change ' + attrName); - var i = changeset.elements.length; - - while (i--) { - var elem = changeset.elements[i]; - - if (isNullish(elem)) { - continue; - } - - var changes = {}; - changes[attrName] = changeset.oldValues[i]; - - if (changes[attrName] !== elem.getAttribute(attrName)) { - batchCmd.addSubCommand(new ChangeElementCommand(elem, changes, attrName)); - } - } - - this.undoableChangeStack[p] = null; - return batchCmd; - } - }]); - - return UndoManager; -}(); - -var hstry = /*#__PURE__*/Object.freeze({ - __proto__: null, - HistoryEventTypes: HistoryEventTypes, - Command: Command, - MoveElementCommand: MoveElementCommand, - InsertElementCommand: InsertElementCommand, - RemoveElementCommand: RemoveElementCommand, - ChangeElementCommand: ChangeElementCommand, - BatchCommand: BatchCommand, - UndoManager: UndoManager -}); - -var $$3 = jQuery; -var segData = { - 2: ['x', 'y'], - // PATHSEG_MOVETO_ABS - 4: ['x', 'y'], - // PATHSEG_LINETO_ABS - 6: ['x', 'y', 'x1', 'y1', 'x2', 'y2'], - // PATHSEG_CURVETO_CUBIC_ABS - 8: ['x', 'y', 'x1', 'y1'], - // PATHSEG_CURVETO_QUADRATIC_ABS - 10: ['x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'], - // PATHSEG_ARC_ABS - 12: ['x'], - // PATHSEG_LINETO_HORIZONTAL_ABS - 14: ['y'], - // PATHSEG_LINETO_VERTICAL_ABS - 16: ['x', 'y', 'x2', 'y2'], - // PATHSEG_CURVETO_CUBIC_SMOOTH_ABS - 18: ['x', 'y'] // PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS - -}; -/** - * @tutorial LocaleDocs - * @typedef {module:locale.LocaleStrings|PlainObject} module:path.uiStrings - * @property {PlainObject<string, string>} ui -*/ - -var uiStrings = {}; -/** -* @function module:path.setUiStrings -* @param {module:path.uiStrings} strs -* @returns {void} -*/ - -var setUiStrings = function setUiStrings(strs) { - Object.assign(uiStrings, strs.ui); -}; -var pathFuncs = []; -var linkControlPts = true; // Stores references to paths via IDs. -// TODO: Make this cross-document happy. - -var pathData = {}; -/** -* @function module:path.setLinkControlPoints -* @param {boolean} lcp -* @returns {void} -*/ - -var setLinkControlPoints = function setLinkControlPoints(lcp) { - linkControlPts = lcp; -}; -/** - * @name module:path.path - * @type {null|module:path.Path} - * @memberof module:path -*/ - -var path = null; // eslint-disable-line import/no-mutable-exports - -var editorContext_$1 = null; -/** -* @external MouseEvent -*/ - -/** -* Object with the following keys/values. -* @typedef {PlainObject} module:path.SVGElementJSON -* @property {string} element - Tag name of the SVG element to create -* @property {PlainObject<string, string>} attr - Has key-value attributes to assign to the new element. An `id` should be set so that {@link module:utilities.EditorContext#addSVGElementFromJson} can later re-identify the element for modification or replacement. -* @property {boolean} [curStyles=false] - Indicates whether current style attributes should be applied first -* @property {module:path.SVGElementJSON[]} [children] - Data objects to be added recursively as children -* @property {string} [namespace="http://www.w3.org/2000/svg"] - Indicate a (non-SVG) namespace -*/ - -/** - * @interface module:path.EditorContext - * @property {module:select.SelectorManager} selectorManager - * @property {module:svgcanvas.SvgCanvas} canvas - */ - -/** - * @function module:path.EditorContext#call - * @param {"selected"|"changed"} ev - String with the event name - * @param {module:svgcanvas.SvgCanvas#event:selected|module:svgcanvas.SvgCanvas#event:changed} arg - Argument to pass through to the callback function. If the event is "changed", an array of `Element`s is passed; if "selected", a single-item array of `Element` is passed. - * @returns {void} - */ - -/** - * @function module:path.EditorContext#resetD - * @param {SVGPathElement} p - * @returns {void} -*/ - -/** - * Note: This doesn't round to an integer necessarily. - * @function module:path.EditorContext#round - * @param {Float} val - * @returns {Float} Rounded value to nearest value based on `currentZoom` - */ - -/** - * @function module:path.EditorContext#clearSelection - * @param {boolean} [noCall] - When `true`, does not call the "selected" handler - * @returns {void} -*/ - -/** - * @function module:path.EditorContext#addToSelection - * @param {Element[]} elemsToAdd - An array of DOM elements to add to the selection - * @param {boolean} showGrips - Indicates whether the resize grips should be shown - * @returns {void} -*/ - -/** - * @function module:path.EditorContext#addCommandToHistory - * @param {Command} cmd - * @returns {void} - */ - -/** - * @function module:path.EditorContext#remapElement - * @param {Element} selected - DOM element to be changed - * @param {PlainObject<string, string>} changes - Object with changes to be remapped - * @param {SVGMatrix} m - Matrix object to use for remapping coordinates - * @returns {void} - */ - -/** - * @function module:path.EditorContext#addSVGElementFromJson - * @param {module:path.SVGElementJSON} data - * @returns {Element} The new element -*/ - -/** - * @function module:path.EditorContext#getGridSnapping - * @returns {boolean} - */ - -/** - * @function module:path.EditorContext#getOpacity - * @returns {Float} - */ - -/** - * @function module:path.EditorContext#getSelectedElements - * @returns {Element[]} the array with selected DOM elements -*/ - -/** - * @function module:path.EditorContext#getContainer - * @returns {Element} - */ - -/** - * @function module:path.EditorContext#setStarted - * @param {boolean} s - * @returns {void} - */ - -/** - * @function module:path.EditorContext#getRubberBox - * @returns {SVGRectElement} -*/ - -/** - * @function module:path.EditorContext#setRubberBox - * @param {SVGRectElement} rb - * @returns {SVGRectElement} Same as parameter passed in - */ - -/** - * @function module:path.EditorContext#addPtsToSelection - * @param {PlainObject} cfg - * @param {boolean} cfg.closedSubpath - * @param {SVGCircleElement[]} cfg.grips - * @returns {void} - */ - -/** - * @function module:path.EditorContext#endChanges - * @param {PlainObject} cfg - * @param {string} cfg.cmd - * @param {Element} cfg.elem - * @returns {void} -*/ - -/** - * @function module:path.EditorContext#getCurrentZoom - * @returns {Float} The current zoom level - */ - -/** - * Returns the last created DOM element ID string. - * @function module:path.EditorContext#getId - * @returns {string} - */ - -/** - * Creates and returns a unique ID string for a DOM element. - * @function module:path.EditorContext#getNextId - * @returns {string} -*/ - -/** - * Gets the desired element from a mouse event. - * @function module:path.EditorContext#getMouseTarget - * @param {external:MouseEvent} evt - Event object from the mouse event - * @returns {Element} DOM element we want - */ - -/** - * @function module:path.EditorContext#getCurrentMode - * @returns {string} - */ - -/** - * @function module:path.EditorContext#setCurrentMode - * @param {string} cm The mode - * @returns {string} The same mode as passed in -*/ - -/** - * @function module:path.EditorContext#getDrawnPath - * @returns {SVGPathElement|null} - */ - -/** - * @function module:path.EditorContext#setDrawnPath - * @param {SVGPathElement|null} dp - * @returns {SVGPathElement|null} The same value as passed in - */ - -/** - * @function module:path.EditorContext#getSVGRoot - * @returns {SVGSVGElement} -*/ - -/** -* @function module:path.init -* @param {module:path.EditorContext} editorContext -* @returns {void} -*/ - -var init$2 = function init(editorContext) { - editorContext_$1 = editorContext; - pathFuncs = [0, 'ClosePath']; - var pathFuncsStrs = ['Moveto', 'Lineto', 'CurvetoCubic', 'CurvetoQuadratic', 'Arc', 'LinetoHorizontal', 'LinetoVertical', 'CurvetoCubicSmooth', 'CurvetoQuadraticSmooth']; - $$3.each(pathFuncsStrs, function (i, s) { - pathFuncs.push(s + 'Abs'); - pathFuncs.push(s + 'Rel'); - }); -}; -/** -* @function module:path.insertItemBefore -* @param {Element} elem -* @param {Segment} newseg -* @param {Integer} index -* @returns {void} -*/ - -var insertItemBefore = function insertItemBefore(elem, newseg, index) { - // Support insertItemBefore on paths for FF2 - var list = elem.pathSegList; - - if (supportsPathInsertItemBefore()) { - list.insertItemBefore(newseg, index); - return; - } - - var len = list.numberOfItems; - var arr = []; - - for (var i = 0; i < len; i++) { - var curSeg = list.getItem(i); - arr.push(curSeg); - } - - list.clear(); - - for (var _i = 0; _i < len; _i++) { - if (_i === index) { - // index + 1 - list.appendItem(newseg); - } - - list.appendItem(arr[_i]); - } -}; -/** -* @function module:path.ptObjToArr -* @todo See if this should just live in `replacePathSeg` -* @param {string} type -* @param {SVGPathSegMovetoAbs|SVGPathSegLinetoAbs|SVGPathSegCurvetoCubicAbs|SVGPathSegCurvetoQuadraticAbs|SVGPathSegArcAbs|SVGPathSegLinetoHorizontalAbs|SVGPathSegLinetoVerticalAbs|SVGPathSegCurvetoCubicSmoothAbs|SVGPathSegCurvetoQuadraticSmoothAbs} segItem -* @returns {ArgumentsArray} -*/ - -var ptObjToArr = function ptObjToArr(type, segItem) { - var props = segData[type]; - return props.map(function (prop) { - return segItem[prop]; - }); -}; -/** -* @function module:path.getGripPt -* @param {Segment} seg -* @param {module:math.XYObject} altPt -* @returns {module:math.XYObject} -*/ - -var getGripPt = function getGripPt(seg, altPt) { - var pth = seg.path; - var out = { - x: altPt ? altPt.x : seg.item.x, - y: altPt ? altPt.y : seg.item.y - }; - - if (pth.matrix) { - var pt = transformPoint(out.x, out.y, pth.matrix); - out = pt; - } - - var currentZoom = editorContext_$1.getCurrentZoom(); - out.x *= currentZoom; - out.y *= currentZoom; - return out; -}; -/** -* @function module:path.getPointFromGrip -* @param {module:math.XYObject} pt -* @param {module:path.Path} pth -* @returns {module:math.XYObject} -*/ - -var getPointFromGrip = function getPointFromGrip(pt, pth) { - var out = { - x: pt.x, - y: pt.y - }; - - if (pth.matrix) { - pt = transformPoint(out.x, out.y, pth.imatrix); - out.x = pt.x; - out.y = pt.y; - } - - var currentZoom = editorContext_$1.getCurrentZoom(); - out.x /= currentZoom; - out.y /= currentZoom; - return out; -}; -/** -* Requires prior call to `setUiStrings` if `xlink:title` -* to be set on the grip. -* @function module:path.addPointGrip -* @param {Integer} index -* @param {Integer} x -* @param {Integer} y -* @returns {SVGCircleElement} -*/ - -var addPointGrip = function addPointGrip(index, x, y) { - // create the container of all the point grips - var pointGripContainer = getGripContainer(); - var pointGrip = getElem('pathpointgrip_' + index); // create it - - if (!pointGrip) { - pointGrip = document.createElementNS(NS.SVG, 'circle'); - var atts = { - id: 'pathpointgrip_' + index, - display: 'none', - r: 4, - fill: '#0FF', - stroke: '#00F', - 'stroke-width': 2, - cursor: 'move', - style: 'pointer-events:all' - }; - - if ('pathNodeTooltip' in uiStrings) { - // May be empty if running path.js without svg-editor - atts['xlink:title'] = uiStrings.pathNodeTooltip; - } - - assignAttributes(pointGrip, atts); - pointGrip = pointGripContainer.appendChild(pointGrip); - var grip = $$3('#pathpointgrip_' + index); - grip.dblclick(function () { - if (path) { - path.setSegType(); - } - }); - } - - if (x && y) { - // set up the point grip element and display it - assignAttributes(pointGrip, { - cx: x, - cy: y, - display: 'inline' - }); - } - - return pointGrip; -}; -/** -* @function module:path.getGripContainer -* @returns {Element} -*/ - -var getGripContainer = function getGripContainer() { - var c = getElem('pathpointgrip_container'); - - if (!c) { - var parentElement = getElem('selectorParentGroup'); - c = parentElement.appendChild(document.createElementNS(NS.SVG, 'g')); - c.id = 'pathpointgrip_container'; - } - - return c; -}; -/** -* Requires prior call to `setUiStrings` if `xlink:title` -* to be set on the grip. -* @function module:path.addCtrlGrip -* @param {string} id -* @returns {SVGCircleElement} -*/ - -var addCtrlGrip = function addCtrlGrip(id) { - var pointGrip = getElem('ctrlpointgrip_' + id); - - if (pointGrip) { - return pointGrip; - } - - pointGrip = document.createElementNS(NS.SVG, 'circle'); - var atts = { - id: 'ctrlpointgrip_' + id, - display: 'none', - r: 4, - fill: '#0FF', - stroke: '#55F', - 'stroke-width': 1, - cursor: 'move', - style: 'pointer-events:all' - }; - - if ('pathCtrlPtTooltip' in uiStrings) { - // May be empty if running path.js without svg-editor - atts['xlink:title'] = uiStrings.pathCtrlPtTooltip; - } - - assignAttributes(pointGrip, atts); - getGripContainer().append(pointGrip); - return pointGrip; -}; -/** -* @function module:path.getCtrlLine -* @param {string} id -* @returns {SVGLineElement} -*/ - -var getCtrlLine = function getCtrlLine(id) { - var ctrlLine = getElem('ctrlLine_' + id); - - if (ctrlLine) { - return ctrlLine; - } - - ctrlLine = document.createElementNS(NS.SVG, 'line'); - assignAttributes(ctrlLine, { - id: 'ctrlLine_' + id, - stroke: '#555', - 'stroke-width': 1, - style: 'pointer-events:none' - }); - getGripContainer().append(ctrlLine); - return ctrlLine; -}; -/** -* @function module:path.getPointGrip -* @param {Segment} seg -* @param {boolean} update -* @returns {SVGCircleElement} -*/ - -var getPointGrip = function getPointGrip(seg, update) { - var index = seg.index; - var pointGrip = addPointGrip(index); - - if (update) { - var pt = getGripPt(seg); - assignAttributes(pointGrip, { - cx: pt.x, - cy: pt.y, - display: 'inline' - }); - } - - return pointGrip; -}; -/** -* @function module:path.getControlPoints -* @param {Segment} seg -* @returns {PlainObject<string, SVGLineElement|SVGCircleElement>} -*/ - -var getControlPoints = function getControlPoints(seg) { - var item = seg.item, - index = seg.index; - - if (!('x1' in item) || !('x2' in item)) { - return null; - } - - var cpt = {}; - /* const pointGripContainer = */ - - getGripContainer(); // Note that this is intentionally not seg.prev.item - - var prev = path.segs[index - 1].item; - var segItems = [prev, item]; - - for (var i = 1; i < 3; i++) { - var id = index + 'c' + i; - var ctrlLine = cpt['c' + i + '_line'] = getCtrlLine(id); - var pt = getGripPt(seg, { - x: item['x' + i], - y: item['y' + i] - }); - var gpt = getGripPt(seg, { - x: segItems[i - 1].x, - y: segItems[i - 1].y - }); - assignAttributes(ctrlLine, { - x1: pt.x, - y1: pt.y, - x2: gpt.x, - y2: gpt.y, - display: 'inline' - }); - cpt['c' + i + '_line'] = ctrlLine; // create it - - var pointGrip = cpt['c' + i] = addCtrlGrip(id); - assignAttributes(pointGrip, { - cx: pt.x, - cy: pt.y, - display: 'inline' - }); - cpt['c' + i] = pointGrip; - } - - return cpt; -}; -/** -* This replaces the segment at the given index. Type is given as number. -* @function module:path.replacePathSeg -* @param {Integer} type Possible values set during {@link module:path.init} -* @param {Integer} index -* @param {ArgumentsArray} pts -* @param {SVGPathElement} elem -* @returns {void} -*/ - -var replacePathSeg = function replacePathSeg(type, index, pts, elem) { - var pth = elem || path.elem; - var func = 'createSVGPathSeg' + pathFuncs[type]; - var seg = pth[func].apply(pth, _toConsumableArray(pts)); - - if (supportsPathReplaceItem()) { - pth.pathSegList.replaceItem(seg, index); - } else { - var segList = pth.pathSegList; - var len = segList.numberOfItems; - var arr = []; - - for (var i = 0; i < len; i++) { - var curSeg = segList.getItem(i); - arr.push(curSeg); - } - - segList.clear(); - - for (var _i2 = 0; _i2 < len; _i2++) { - if (_i2 === index) { - segList.appendItem(seg); - } else { - segList.appendItem(arr[_i2]); - } - } - } -}; -/** -* @function module:path.getSegSelector -* @param {Segment} seg -* @param {boolean} update -* @returns {SVGPathElement} -*/ - -var getSegSelector = function getSegSelector(seg, update) { - var index = seg.index; - var segLine = getElem('segline_' + index); - - if (!segLine) { - var pointGripContainer = getGripContainer(); // create segline - - segLine = document.createElementNS(NS.SVG, 'path'); - assignAttributes(segLine, { - id: 'segline_' + index, - display: 'none', - fill: 'none', - stroke: '#0FF', - 'stroke-width': 2, - style: 'pointer-events:none', - d: 'M0,0 0,0' - }); - pointGripContainer.append(segLine); - } - - if (update) { - var prev = seg.prev; - - if (!prev) { - segLine.setAttribute('display', 'none'); - return segLine; - } - - var pt = getGripPt(prev); // Set start point - - replacePathSeg(2, 0, [pt.x, pt.y], segLine); - var pts = ptObjToArr(seg.type, seg.item); // , true); - - for (var i = 0; i < pts.length; i += 2) { - var point = getGripPt(seg, { - x: pts[i], - y: pts[i + 1] - }); - pts[i] = point.x; - pts[i + 1] = point.y; - } - - replacePathSeg(seg.type, 1, pts, segLine); - } - - return segLine; -}; -/** - * @typedef {PlainObject} Point - * @property {Integer} x The x value - * @property {Integer} y The y value - */ - -/** -* Takes three points and creates a smoother line based on them. -* @function module:path.smoothControlPoints -* @param {Point} ct1 - Object with x and y values (first control point) -* @param {Point} ct2 - Object with x and y values (second control point) -* @param {Point} pt - Object with x and y values (third point) -* @returns {Point[]} Array of two "smoothed" point objects -*/ - -var smoothControlPoints = function smoothControlPoints(ct1, ct2, pt) { - // each point must not be the origin - var x1 = ct1.x - pt.x, - y1 = ct1.y - pt.y, - x2 = ct2.x - pt.x, - y2 = ct2.y - pt.y; - - if ((x1 !== 0 || y1 !== 0) && (x2 !== 0 || y2 !== 0)) { - var r1 = Math.sqrt(x1 * x1 + y1 * y1), - r2 = Math.sqrt(x2 * x2 + y2 * y2), - nct1 = editorContext_$1.getSVGRoot().createSVGPoint(), - nct2 = editorContext_$1.getSVGRoot().createSVGPoint(); - var anglea = Math.atan2(y1, x1), - angleb = Math.atan2(y2, x2); - - if (anglea < 0) { - anglea += 2 * Math.PI; - } - - if (angleb < 0) { - angleb += 2 * Math.PI; - } - - var angleBetween = Math.abs(anglea - angleb), - angleDiff = Math.abs(Math.PI - angleBetween) / 2; - var newAnglea, newAngleb; - - if (anglea - angleb > 0) { - newAnglea = angleBetween < Math.PI ? anglea + angleDiff : anglea - angleDiff; - newAngleb = angleBetween < Math.PI ? angleb - angleDiff : angleb + angleDiff; - } else { - newAnglea = angleBetween < Math.PI ? anglea - angleDiff : anglea + angleDiff; - newAngleb = angleBetween < Math.PI ? angleb + angleDiff : angleb - angleDiff; - } // rotate the points - - - nct1.x = r1 * Math.cos(newAnglea) + pt.x; - nct1.y = r1 * Math.sin(newAnglea) + pt.y; - nct2.x = r2 * Math.cos(newAngleb) + pt.x; - nct2.y = r2 * Math.sin(newAngleb) + pt.y; - return [nct1, nct2]; - } - - return undefined; -}; -/** -* -*/ - -var Segment = /*#__PURE__*/function () { - /** - * @param {Integer} index - * @param {SVGPathSeg} item - * @todo Is `item` be more constrained here? - */ - function Segment(index, item) { - _classCallCheck(this, Segment); - - this.selected = false; - this.index = index; - this.item = item; - this.type = item.pathSegType; - this.ctrlpts = []; - this.ptgrip = null; - this.segsel = null; - } - /** - * @param {boolean} y - * @returns {void} - */ - - - _createClass(Segment, [{ - key: "showCtrlPts", - value: function showCtrlPts(y) { - for (var i in this.ctrlpts) { - if ({}.hasOwnProperty.call(this.ctrlpts, i)) { - this.ctrlpts[i].setAttribute('display', y ? 'inline' : 'none'); - } - } - } - /** - * @param {boolean} y - * @returns {void} - */ - - }, { - key: "selectCtrls", - value: function selectCtrls(y) { - $$3('#ctrlpointgrip_' + this.index + 'c1, #ctrlpointgrip_' + this.index + 'c2').attr('fill', y ? '#0FF' : '#EEE'); - } - /** - * @param {boolean} y - * @returns {void} - */ - - }, { - key: "show", - value: function show(y) { - if (this.ptgrip) { - this.ptgrip.setAttribute('display', y ? 'inline' : 'none'); - this.segsel.setAttribute('display', y ? 'inline' : 'none'); // Show/hide all control points if available - - this.showCtrlPts(y); - } - } - /** - * @param {boolean} y - * @returns {void} - */ - - }, { - key: "select", - value: function select(y) { - if (this.ptgrip) { - this.ptgrip.setAttribute('stroke', y ? '#0FF' : '#00F'); - this.segsel.setAttribute('display', y ? 'inline' : 'none'); - - if (this.ctrlpts) { - this.selectCtrls(y); - } - - this.selected = y; - } - } - /** - * @returns {void} - */ - - }, { - key: "addGrip", - value: function addGrip() { - this.ptgrip = getPointGrip(this, true); - this.ctrlpts = getControlPoints(this); // , true); - - this.segsel = getSegSelector(this, true); - } - /** - * @param {boolean} full - * @returns {void} - */ - - }, { - key: "update", - value: function update(full) { - if (this.ptgrip) { - var pt = getGripPt(this); - assignAttributes(this.ptgrip, { - cx: pt.x, - cy: pt.y - }); - getSegSelector(this, true); - - if (this.ctrlpts) { - if (full) { - this.item = path.elem.pathSegList.getItem(this.index); - this.type = this.item.pathSegType; - } - - getControlPoints(this); - } // this.segsel.setAttribute('display', y ? 'inline' : 'none'); - - } - } - /** - * @param {Integer} dx - * @param {Integer} dy - * @returns {void} - */ - - }, { - key: "move", - value: function move(dx, dy) { - var item = this.item; - var curPts = this.ctrlpts ? [item.x += dx, item.y += dy, item.x1, item.y1, item.x2 += dx, item.y2 += dy] : [item.x += dx, item.y += dy]; - replacePathSeg(this.type, this.index, // type 10 means ARC - this.type === 10 ? ptObjToArr(this.type, item) : curPts); - - if (this.next && this.next.ctrlpts) { - var next = this.next.item; - var nextPts = [next.x, next.y, next.x1 += dx, next.y1 += dy, next.x2, next.y2]; - replacePathSeg(this.next.type, this.next.index, nextPts); - } - - if (this.mate) { - // The last point of a closed subpath has a 'mate', - // which is the 'M' segment of the subpath - var itm = this.mate.item; - var pts = [itm.x += dx, itm.y += dy]; - replacePathSeg(this.mate.type, this.mate.index, pts); // Has no grip, so does not need 'updating'? - } - - this.update(true); - - if (this.next) { - this.next.update(true); - } - } - /** - * @param {Integer} num - * @returns {void} - */ - - }, { - key: "setLinked", - value: function setLinked(num) { - var seg, anum, pt; - - if (num === 2) { - anum = 1; - seg = this.next; - - if (!seg) { - return; - } - - pt = this.item; - } else { - anum = 2; - seg = this.prev; - - if (!seg) { - return; - } - - pt = seg.item; - } - - var _seg = seg, - item = _seg.item; - item['x' + anum] = pt.x + (pt.x - this.item['x' + num]); - item['y' + anum] = pt.y + (pt.y - this.item['y' + num]); - var pts = [item.x, item.y, item.x1, item.y1, item.x2, item.y2]; - replacePathSeg(seg.type, seg.index, pts); - seg.update(true); - } - /** - * @param {Integer} num - * @param {Integer} dx - * @param {Integer} dy - * @returns {void} - */ - - }, { - key: "moveCtrl", - value: function moveCtrl(num, dx, dy) { - var item = this.item; - item['x' + num] += dx; - item['y' + num] += dy; - var pts = [item.x, item.y, item.x1, item.y1, item.x2, item.y2]; - replacePathSeg(this.type, this.index, pts); - this.update(true); - } - /** - * @param {Integer} newType Possible values set during {@link module:path.init} - * @param {ArgumentsArray} pts - * @returns {void} - */ - - }, { - key: "setType", - value: function setType(newType, pts) { - replacePathSeg(newType, this.index, pts); - this.type = newType; - this.item = path.elem.pathSegList.getItem(this.index); - this.showCtrlPts(newType === 6); - this.ctrlpts = getControlPoints(this); - this.update(true); - } - }]); - - return Segment; -}(); -/** -* -*/ - -var Path = /*#__PURE__*/function () { - /** - * @param {SVGPathElement} elem - * @throws {Error} If constructed without a path element - */ - function Path(elem) { - _classCallCheck(this, Path); - - if (!elem || elem.tagName !== 'path') { - throw new Error('svgedit.path.Path constructed without a <path> element'); - } - - this.elem = elem; - this.segs = []; - this.selected_pts = []; - path = this; - this.init(); - } - /** - * Reset path data. - * @returns {module:path.Path} - */ - - - _createClass(Path, [{ - key: "init", - value: function init() { - // Hide all grips, etc - // fixed, needed to work on all found elements, not just first - $$3(getGripContainer()).find('*').each(function () { - $$3(this).attr('display', 'none'); - }); - var segList = this.elem.pathSegList; - var len = segList.numberOfItems; - this.segs = []; - this.selected_pts = []; - this.first_seg = null; // Set up segs array - - for (var i = 0; i < len; i++) { - var item = segList.getItem(i); - var segment = new Segment(i, item); - segment.path = this; - this.segs.push(segment); - } - - var segs = this.segs; - var startI = null; - - for (var _i3 = 0; _i3 < len; _i3++) { - var seg = segs[_i3]; - var nextSeg = _i3 + 1 >= len ? null : segs[_i3 + 1]; - var prevSeg = _i3 - 1 < 0 ? null : segs[_i3 - 1]; - - if (seg.type === 2) { - if (prevSeg && prevSeg.type !== 1) { - // New sub-path, last one is open, - // so add a grip to last sub-path's first point - var startSeg = segs[startI]; - startSeg.next = segs[startI + 1]; - startSeg.next.prev = startSeg; - startSeg.addGrip(); - } // Remember that this is a starter seg - - - startI = _i3; - } else if (nextSeg && nextSeg.type === 1) { - // This is the last real segment of a closed sub-path - // Next is first seg after "M" - seg.next = segs[startI + 1]; // First seg after "M"'s prev is this - - seg.next.prev = seg; - seg.mate = segs[startI]; - seg.addGrip(); - - if (isNullish(this.first_seg)) { - this.first_seg = seg; - } - } else if (!nextSeg) { - if (seg.type !== 1) { - // Last seg, doesn't close so add a grip - // to last sub-path's first point - var _startSeg = segs[startI]; - _startSeg.next = segs[startI + 1]; - _startSeg.next.prev = _startSeg; - - _startSeg.addGrip(); - - seg.addGrip(); - - if (!this.first_seg) { - // Open path, so set first as real first and add grip - this.first_seg = segs[startI]; - } - } - } else if (seg.type !== 1) { - // Regular segment, so add grip and its "next" - seg.addGrip(); // Don't set its "next" if it's an "M" - - if (nextSeg && nextSeg.type !== 2) { - seg.next = nextSeg; - seg.next.prev = seg; - } - } - } - - return this; - } - /** - * @callback module:path.PathEachSegCallback - * @this module:path.Segment - * @param {Integer} i The index of the seg being iterated - * @returns {boolean|void} Will stop execution of `eachSeg` if returns `false` - */ - - /** - * @param {module:path.PathEachSegCallback} fn - * @returns {void} - */ - - }, { - key: "eachSeg", - value: function eachSeg(fn) { - var len = this.segs.length; - - for (var i = 0; i < len; i++) { - var ret = fn.call(this.segs[i], i); - - if (ret === false) { - break; - } - } - } - /** - * @param {Integer} index - * @returns {void} - */ - - }, { - key: "addSeg", - value: function addSeg(index) { - // Adds a new segment - var seg = this.segs[index]; - - if (!seg.prev) { - return; - } - - var prev = seg.prev; - var newseg, newX, newY; - - switch (seg.item.pathSegType) { - case 4: - { - newX = (seg.item.x + prev.item.x) / 2; - newY = (seg.item.y + prev.item.y) / 2; - newseg = this.elem.createSVGPathSegLinetoAbs(newX, newY); - break; - } - - case 6: - { - // make it a curved segment to preserve the shape (WRS) - // https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm#Geometric_interpretation - var p0x = (prev.item.x + seg.item.x1) / 2; - var p1x = (seg.item.x1 + seg.item.x2) / 2; - var p2x = (seg.item.x2 + seg.item.x) / 2; - var p01x = (p0x + p1x) / 2; - var p12x = (p1x + p2x) / 2; - newX = (p01x + p12x) / 2; - var p0y = (prev.item.y + seg.item.y1) / 2; - var p1y = (seg.item.y1 + seg.item.y2) / 2; - var p2y = (seg.item.y2 + seg.item.y) / 2; - var p01y = (p0y + p1y) / 2; - var p12y = (p1y + p2y) / 2; - newY = (p01y + p12y) / 2; - newseg = this.elem.createSVGPathSegCurvetoCubicAbs(newX, newY, p0x, p0y, p01x, p01y); - var pts = [seg.item.x, seg.item.y, p12x, p12y, p2x, p2y]; - replacePathSeg(seg.type, index, pts); - break; - } - } - - insertItemBefore(this.elem, newseg, index); - } - /** - * @param {Integer} index - * @returns {void} - */ - - }, { - key: "deleteSeg", - value: function deleteSeg(index) { - var seg = this.segs[index]; - var list = this.elem.pathSegList; - seg.show(false); - var next = seg.next; - - if (seg.mate) { - // Make the next point be the "M" point - var pt = [next.item.x, next.item.y]; - replacePathSeg(2, next.index, pt); // Reposition last node - - replacePathSeg(4, seg.index, pt); - list.removeItem(seg.mate.index); - } else if (!seg.prev) { - // First node of open path, make next point the M - // const {item} = seg; - var _pt = [next.item.x, next.item.y]; - replacePathSeg(2, seg.next.index, _pt); - list.removeItem(index); - } else { - list.removeItem(index); - } - } - /** - * @param {Integer} index - * @returns {void} - */ - - }, { - key: "removePtFromSelection", - value: function removePtFromSelection(index) { - var pos = this.selected_pts.indexOf(index); - - if (pos === -1) { - return; - } - - this.segs[index].select(false); - this.selected_pts.splice(pos, 1); - } - /** - * @returns {void} - */ - - }, { - key: "clearSelection", - value: function clearSelection() { - this.eachSeg(function () { - // 'this' is the segment here - this.select(false); - }); - this.selected_pts = []; - } - /** - * @returns {void} - */ - - }, { - key: "storeD", - value: function storeD() { - this.last_d = this.elem.getAttribute('d'); - } - /** - * @param {Integer} y - * @returns {Path} - */ - - }, { - key: "show", - value: function show(y) { - // Shows this path's segment grips - this.eachSeg(function () { - // 'this' is the segment here - this.show(y); - }); - - if (y) { - this.selectPt(this.first_seg.index); - } - - return this; - } - /** - * Move selected points. - * @param {Integer} dx - * @param {Integer} dy - * @returns {void} - */ - - }, { - key: "movePts", - value: function movePts(dx, dy) { - var i = this.selected_pts.length; - - while (i--) { - var seg = this.segs[this.selected_pts[i]]; - seg.move(dx, dy); - } - } - /** - * @param {Integer} dx - * @param {Integer} dy - * @returns {void} - */ - - }, { - key: "moveCtrl", - value: function moveCtrl(dx, dy) { - var seg = this.segs[this.selected_pts[0]]; - seg.moveCtrl(this.dragctrl, dx, dy); - - if (linkControlPts) { - seg.setLinked(this.dragctrl); - } - } - /** - * @param {?Integer} newType See {@link https://www.w3.org/TR/SVG/single-page.html#paths-InterfaceSVGPathSeg} - * @returns {void} - */ - - }, { - key: "setSegType", - value: function setSegType(newType) { - this.storeD(); - var i = this.selected_pts.length; - var text; - - while (i--) { - var selPt = this.selected_pts[i]; // Selected seg - - var cur = this.segs[selPt]; - var prev = cur.prev; - - if (!prev) { - continue; - } - - if (!newType) { - // double-click, so just toggle - text = 'Toggle Path Segment Type'; // Toggle segment to curve/straight line - - var oldType = cur.type; - newType = oldType === 6 ? 4 : 6; - } - - newType = Number(newType); - var curX = cur.item.x; - var curY = cur.item.y; - var prevX = prev.item.x; - var prevY = prev.item.y; - var points = void 0; - - switch (newType) { - case 6: - { - if (cur.olditem) { - var old = cur.olditem; - points = [curX, curY, old.x1, old.y1, old.x2, old.y2]; - } else { - var diffX = curX - prevX; - var diffY = curY - prevY; // get control points from straight line segment - - /* - const ct1x = (prevX + (diffY/2)); - const ct1y = (prevY - (diffX/2)); - const ct2x = (curX + (diffY/2)); - const ct2y = (curY - (diffX/2)); - */ - // create control points on the line to preserve the shape (WRS) - - var ct1x = prevX + diffX / 3; - var ct1y = prevY + diffY / 3; - var ct2x = curX - diffX / 3; - var ct2y = curY - diffY / 3; - points = [curX, curY, ct1x, ct1y, ct2x, ct2y]; - } - - break; - } - - case 4: - { - points = [curX, curY]; // Store original prevve segment nums - - cur.olditem = cur.item; - break; - } - } - - cur.setType(newType, points); - } - - path.endChanges(text); - } - /** - * @param {Integer} pt - * @param {Integer} ctrlNum - * @returns {void} - */ - - }, { - key: "selectPt", - value: function selectPt(pt, ctrlNum) { - this.clearSelection(); - - if (isNullish(pt)) { - this.eachSeg(function (i) { - // 'this' is the segment here. - if (this.prev) { - pt = i; - } - }); - } - - this.addPtsToSelection(pt); - - if (ctrlNum) { - this.dragctrl = ctrlNum; - - if (linkControlPts) { - this.segs[pt].setLinked(ctrlNum); - } - } - } - /** - * Update position of all points. - * @returns {Path} - */ - - }, { - key: "update", - value: function update() { - var elem = this.elem; - - if (getRotationAngle(elem)) { - this.matrix = getMatrix(elem); - this.imatrix = this.matrix.inverse(); - } else { - this.matrix = null; - this.imatrix = null; - } - - this.eachSeg(function (i) { - this.item = elem.pathSegList.getItem(i); - this.update(); - }); - return this; - } - /** - * @param {string} text - * @returns {void} - */ - - }, { - key: "endChanges", - value: function endChanges(text) { - if (isWebkit()) { - editorContext_$1.resetD(this.elem); - } - - var cmd = new ChangeElementCommand(this.elem, { - d: this.last_d - }, text); - editorContext_$1.endChanges({ - cmd: cmd, - elem: this.elem - }); - } - /** - * @param {Integer|Integer[]} indexes - * @returns {void} - */ - - }, { - key: "addPtsToSelection", - value: function addPtsToSelection(indexes) { - var _this = this; - - if (!Array.isArray(indexes)) { - indexes = [indexes]; - } - - indexes.forEach(function (index) { - var seg = _this.segs[index]; - - if (seg.ptgrip) { - if (!_this.selected_pts.includes(index) && index >= 0) { - _this.selected_pts.push(index); - } - } - }); - this.selected_pts.sort(); - var i = this.selected_pts.length; - var grips = []; - grips.length = i; // Loop through points to be selected and highlight each - - while (i--) { - var pt = this.selected_pts[i]; - var seg = this.segs[pt]; - seg.select(true); - grips[i] = seg.ptgrip; - } - - var closedSubpath = Path.subpathIsClosed(this.selected_pts[0]); - editorContext_$1.addPtsToSelection({ - grips: grips, - closedSubpath: closedSubpath - }); - } // STATIC - - /** - * @param {Integer} index - * @returns {boolean} - */ - - }], [{ - key: "subpathIsClosed", - value: function subpathIsClosed(index) { - var clsd = false; // Check if subpath is already open - - path.eachSeg(function (i) { - if (i <= index) { - return true; - } - - if (this.type === 2) { - // Found M first, so open - return false; - } - - if (this.type === 1) { - // Found Z first, so closed - clsd = true; - return false; - } - - return true; - }); - return clsd; - } - }]); - - return Path; -}(); -/** -* @function module:path.getPath_ -* @param {SVGPathElement} elem -* @returns {module:path.Path} -*/ - -var getPath_ = function getPath_(elem) { - var p = pathData[elem.id]; - - if (!p) { - p = pathData[elem.id] = new Path(elem); - } - - return p; -}; -/** -* @function module:path.removePath_ -* @param {string} id -* @returns {void} -*/ - -var removePath_ = function removePath_(id) { - if (id in pathData) { - delete pathData[id]; - } -}; -var newcx, newcy, oldcx, oldcy, angle; - -var getRotVals = function getRotVals(x, y) { - var dx = x - oldcx; - var dy = y - oldcy; // rotate the point around the old center - - var r = Math.sqrt(dx * dx + dy * dy); - var theta = Math.atan2(dy, dx) + angle; - dx = r * Math.cos(theta) + oldcx; - dy = r * Math.sin(theta) + oldcy; // dx,dy should now hold the actual coordinates of each - // point after being rotated - // now we want to rotate them around the new center in the reverse direction - - dx -= newcx; - dy -= newcy; - r = Math.sqrt(dx * dx + dy * dy); - theta = Math.atan2(dy, dx) - angle; - return { - x: r * Math.cos(theta) + newcx, - y: r * Math.sin(theta) + newcy - }; -}; // If the path was rotated, we must now pay the piper: -// Every path point must be rotated into the rotated coordinate system of -// its old center, then determine the new center, then rotate it back -// This is because we want the path to remember its rotation - -/** -* @function module:path.recalcRotatedPath -* @todo This is still using ye olde transform methods, can probably -* be optimized or even taken care of by `recalculateDimensions` -* @returns {void} -*/ - - -var recalcRotatedPath = function recalcRotatedPath() { - var currentPath = path.elem; - angle = getRotationAngle(currentPath, true); - - if (!angle) { - return; - } // selectedBBoxes[0] = path.oldbbox; - - - var oldbox = path.oldbbox; // selectedBBoxes[0], - - oldcx = oldbox.x + oldbox.width / 2; - oldcy = oldbox.y + oldbox.height / 2; - var box = getBBox(currentPath); - newcx = box.x + box.width / 2; - newcy = box.y + box.height / 2; // un-rotate the new center to the proper position - - var dx = newcx - oldcx, - dy = newcy - oldcy, - r = Math.sqrt(dx * dx + dy * dy), - theta = Math.atan2(dy, dx) + angle; - newcx = r * Math.cos(theta) + oldcx; - newcy = r * Math.sin(theta) + oldcy; - var list = currentPath.pathSegList; - var i = list.numberOfItems; - - while (i) { - i -= 1; - var seg = list.getItem(i), - type = seg.pathSegType; - - if (type === 1) { - continue; - } - - var rvals = getRotVals(seg.x, seg.y), - points = [rvals.x, rvals.y]; - - if (!isNullish(seg.x1) && !isNullish(seg.x2)) { - var cVals1 = getRotVals(seg.x1, seg.y1); - var cVals2 = getRotVals(seg.x2, seg.y2); - points.splice(points.length, 0, cVals1.x, cVals1.y, cVals2.x, cVals2.y); - } - - replacePathSeg(type, i, points); - } // loop for each point - - /* box = */ - - - getBBox(currentPath); // selectedBBoxes[0].x = box.x; selectedBBoxes[0].y = box.y; - // selectedBBoxes[0].width = box.width; selectedBBoxes[0].height = box.height; - // now we must set the new transform to be rotated around the new center - - var Rnc = editorContext_$1.getSVGRoot().createSVGTransform(), - tlist = getTransformList(currentPath); - Rnc.setRotate(angle * 180.0 / Math.PI, newcx, newcy); - tlist.replaceItem(Rnc, 0); -}; // ==================================== -// Public API starts here - -/** -* @function module:path.clearData -* @returns {void} -*/ - -var clearData = function clearData() { - pathData = {}; -}; // Making public for mocking - -/** -* @function module:path.reorientGrads -* @param {Element} elem -* @param {SVGMatrix} m -* @returns {void} -*/ - -var reorientGrads = function reorientGrads(elem, m) { - var bb = getBBox(elem); - - for (var i = 0; i < 2; i++) { - var type = i === 0 ? 'fill' : 'stroke'; - var attrVal = elem.getAttribute(type); - - if (attrVal && attrVal.startsWith('url(')) { - var grad = getRefElem(attrVal); - - if (grad.tagName === 'linearGradient') { - var x1 = grad.getAttribute('x1') || 0; - var y1 = grad.getAttribute('y1') || 0; - var x2 = grad.getAttribute('x2') || 1; - var y2 = grad.getAttribute('y2') || 0; // Convert to USOU points - - x1 = bb.width * x1 + bb.x; - y1 = bb.height * y1 + bb.y; - x2 = bb.width * x2 + bb.x; - y2 = bb.height * y2 + bb.y; // Transform those points - - var pt1 = transformPoint(x1, y1, m); - var pt2 = transformPoint(x2, y2, m); // Convert back to BB points - - var gCoords = { - x1: (pt1.x - bb.x) / bb.width, - y1: (pt1.y - bb.y) / bb.height, - x2: (pt2.x - bb.x) / bb.width, - y2: (pt2.y - bb.y) / bb.height - }; - var newgrad = grad.cloneNode(true); - $$3(newgrad).attr(gCoords); - newgrad.id = editorContext_$1.getNextId(); - findDefs().append(newgrad); - elem.setAttribute(type, 'url(#' + newgrad.id + ')'); - } - } - } -}; -/** -* This is how we map paths to our preferred relative segment types. -* @name module:path.pathMap -* @type {GenericArray} -*/ - -var pathMap = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a', 'H', 'h', 'V', 'v', 'S', 's', 'T', 't']; -/** - * Convert a path to one with only absolute or relative values. - * @todo move to pathActions.js - * @function module:path.convertPath - * @param {SVGPathElement} pth - the path to convert - * @param {boolean} toRel - true of convert to relative - * @returns {string} - */ - -var convertPath = function convertPath(pth, toRel) { - var pathSegList = pth.pathSegList; - var len = pathSegList.numberOfItems; - var curx = 0, - cury = 0; - var d = ''; - var lastM = null; - - for (var i = 0; i < len; ++i) { - var seg = pathSegList.getItem(i); // if these properties are not in the segment, set them to zero - - var x = seg.x || 0, - y = seg.y || 0, - x1 = seg.x1 || 0, - y1 = seg.y1 || 0, - x2 = seg.x2 || 0, - y2 = seg.y2 || 0; - var type = seg.pathSegType; - var letter = pathMap[type][toRel ? 'toLowerCase' : 'toUpperCase'](); - - switch (type) { - case 1: - // z,Z closepath (Z/z) - d += 'z'; - - if (lastM && !toRel) { - curx = lastM[0]; - cury = lastM[1]; - } - - break; - - case 12: - // absolute horizontal line (H) - x -= curx; - // Fallthrough - - case 13: - // relative horizontal line (h) - if (toRel) { - y = 0; - curx += x; - letter = 'l'; - } else { - y = cury; - x += curx; - curx = x; - letter = 'L'; - } // Convert to "line" for easier editing - - - d += pathDSegment(letter, [[x, y]]); - break; - - case 14: - // absolute vertical line (V) - y -= cury; - // Fallthrough - - case 15: - // relative vertical line (v) - if (toRel) { - x = 0; - cury += y; - letter = 'l'; - } else { - x = curx; - y += cury; - cury = y; - letter = 'L'; - } // Convert to "line" for easier editing - - - d += pathDSegment(letter, [[x, y]]); - break; - - case 2: // absolute move (M) - - case 4: // absolute line (L) - - case 18: - // absolute smooth quad (T) - x -= curx; - y -= cury; - // Fallthrough - - case 5: // relative line (l) - - case 3: // relative move (m) - - case 19: - // relative smooth quad (t) - if (toRel) { - curx += x; - cury += y; - } else { - x += curx; - y += cury; - curx = x; - cury = y; - } - - if (type === 2 || type === 3) { - lastM = [curx, cury]; - } - - d += pathDSegment(letter, [[x, y]]); - break; - - case 6: - // absolute cubic (C) - x -= curx; - x1 -= curx; - x2 -= curx; - y -= cury; - y1 -= cury; - y2 -= cury; - // Fallthrough - - case 7: - // relative cubic (c) - if (toRel) { - curx += x; - cury += y; - } else { - x += curx; - x1 += curx; - x2 += curx; - y += cury; - y1 += cury; - y2 += cury; - curx = x; - cury = y; - } - - d += pathDSegment(letter, [[x1, y1], [x2, y2], [x, y]]); - break; - - case 8: - // absolute quad (Q) - x -= curx; - x1 -= curx; - y -= cury; - y1 -= cury; - // Fallthrough - - case 9: - // relative quad (q) - if (toRel) { - curx += x; - cury += y; - } else { - x += curx; - x1 += curx; - y += cury; - y1 += cury; - curx = x; - cury = y; - } - - d += pathDSegment(letter, [[x1, y1], [x, y]]); - break; - // eslint-disable-next-line sonarjs/no-duplicated-branches - - case 10: - // absolute elliptical arc (A) - x -= curx; - y -= cury; - // Fallthrough - - case 11: - // relative elliptical arc (a) - if (toRel) { - curx += x; - cury += y; - } else { - x += curx; - y += cury; - curx = x; - cury = y; - } - - d += pathDSegment(letter, [[seg.r1, seg.r2]], [seg.angle, seg.largeArcFlag ? 1 : 0, seg.sweepFlag ? 1 : 0], [x, y]); - break; - - case 16: - // absolute smooth cubic (S) - x -= curx; - x2 -= curx; - y -= cury; - y2 -= cury; - // Fallthrough - - case 17: - // relative smooth cubic (s) - if (toRel) { - curx += x; - cury += y; - } else { - x += curx; - x2 += curx; - y += cury; - y2 += cury; - curx = x; - cury = y; - } - - d += pathDSegment(letter, [[x2, y2], [x, y]]); - break; - } // switch on path segment type - - } // for each segment - - - return d; -}; -/** - * TODO: refactor callers in `convertPath` to use `getPathDFromSegments` instead of this function. - * Legacy code refactored from `svgcanvas.pathActions.convertPath`. - * @param {string} letter - path segment command (letter in potentially either case from {@link module:path.pathMap}; see [SVGPathSeg#pathSegTypeAsLetter]{@link https://www.w3.org/TR/SVG/single-page.html#paths-__svg__SVGPathSeg__pathSegTypeAsLetter}) - * @param {GenericArray<GenericArray<Integer>>} points - x,y points - * @param {GenericArray<GenericArray<Integer>>} [morePoints] - x,y points - * @param {Integer[]} [lastPoint] - x,y point - * @returns {string} - */ - -function pathDSegment(letter, points, morePoints, lastPoint) { - $$3.each(points, function (i, pnt) { - points[i] = shortFloat(pnt); - }); - var segment = letter + points.join(' '); - - if (morePoints) { - segment += ' ' + morePoints.join(' '); - } - - if (lastPoint) { - segment += ' ' + shortFloat(lastPoint); - } - - return segment; -} -/* eslint-disable jsdoc/require-property */ - -/** -* Group: Path edit functions. -* Functions relating to editing path elements. -* @namespace {PlainObject} pathActions -* @memberof module:path -*/ - - -var pathActions = function () { - /* eslint-enable jsdoc/require-property */ - var subpath = false; - var newPoint, firstCtrl; - var currentPath = null; - var hasMoved = false; // No `editorContext_` yet but should be ok as is `null` by default - // editorContext_.setDrawnPath(null); - - /** - * This function converts a polyline (created by the fh_path tool) into - * a path element and coverts every three line segments into a single bezier - * curve in an attempt to smooth out the free-hand. - * @function smoothPolylineIntoPath - * @param {Element} element - * @returns {Element} - */ - - var smoothPolylineIntoPath = function smoothPolylineIntoPath(element) { - var i; - var _element = element, - points = _element.points; - var N = points.numberOfItems; - - if (N >= 4) { - // loop through every 3 points and convert to a cubic bezier curve segment - // - // NOTE: this is cheating, it means that every 3 points has the potential to - // be a corner instead of treating each point in an equal manner. In general, - // this technique does not look that good. - // - // I am open to better ideas! - // - // Reading: - // - http://www.efg2.com/Lab/Graphics/Jean-YvesQueinecBezierCurves.htm - // - https://www.codeproject.com/KB/graphics/BezierSpline.aspx?msg=2956963 - // - https://www.ian-ko.com/ET_GeoWizards/UserGuide/smooth.htm - // - https://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-der.html - var curpos = points.getItem(0), - prevCtlPt = null; - var d = []; - d.push(['M', curpos.x, ',', curpos.y, ' C'].join('')); - - for (i = 1; i <= N - 4; i += 3) { - var ct1 = points.getItem(i); - var ct2 = points.getItem(i + 1); - var end = points.getItem(i + 2); // if the previous segment had a control point, we want to smooth out - // the control points on both sides - - if (prevCtlPt) { - var newpts = smoothControlPoints(prevCtlPt, ct1, curpos); - - if (newpts && newpts.length === 2) { - var prevArr = d[d.length - 1].split(','); - prevArr[2] = newpts[0].x; - prevArr[3] = newpts[0].y; - d[d.length - 1] = prevArr.join(','); - ct1 = newpts[1]; - } - } - - d.push([ct1.x, ct1.y, ct2.x, ct2.y, end.x, end.y].join(',')); - curpos = end; - prevCtlPt = ct2; - } // handle remaining line segments - - - d.push('L'); - - while (i < N) { - var pt = points.getItem(i); - d.push([pt.x, pt.y].join(',')); - i++; - } - - d = d.join(' '); // create new path element - - element = editorContext_$1.addSVGElementFromJson({ - element: 'path', - curStyles: true, - attr: { - id: editorContext_$1.getId(), - d: d, - fill: 'none' - } - }); // No need to call "changed", as this is already done under mouseUp - } - - return element; - }; - - return ( - /** @lends module:path.pathActions */ - { - /** - * @param {MouseEvent} evt - * @param {Element} mouseTarget - * @param {Float} startX - * @param {Float} startY - * @returns {boolean|void} - */ - mouseDown: function mouseDown(evt, mouseTarget, startX, startY) { - var id; - - if (editorContext_$1.getCurrentMode() === 'path') { - var mouseX = startX; // Was this meant to work with the other `mouseX`? (was defined globally so adding `let` to at least avoid a global) - - var mouseY = startY; // Was this meant to work with the other `mouseY`? (was defined globally so adding `let` to at least avoid a global) - - var currentZoom = editorContext_$1.getCurrentZoom(); - var x = mouseX / currentZoom, - y = mouseY / currentZoom, - stretchy = getElem('path_stretch_line'); - newPoint = [x, y]; - - if (editorContext_$1.getGridSnapping()) { - x = snapToGrid(x); - y = snapToGrid(y); - mouseX = snapToGrid(mouseX); - mouseY = snapToGrid(mouseY); - } - - if (!stretchy) { - stretchy = document.createElementNS(NS.SVG, 'path'); - assignAttributes(stretchy, { - id: 'path_stretch_line', - stroke: '#22C', - 'stroke-width': '0.5', - fill: 'none' - }); - stretchy = getElem('selectorParentGroup').appendChild(stretchy); - } - - stretchy.setAttribute('display', 'inline'); - var keep = null; - var index; // if pts array is empty, create path element with M at current point - - var drawnPath = editorContext_$1.getDrawnPath(); - - if (!drawnPath) { - var dAttr = 'M' + x + ',' + y + ' '; // Was this meant to work with the other `dAttr`? (was defined globally so adding `var` to at least avoid a global) - - /* drawnPath = */ - - editorContext_$1.setDrawnPath(editorContext_$1.addSVGElementFromJson({ - element: 'path', - curStyles: true, - attr: { - d: dAttr, - id: editorContext_$1.getNextId(), - opacity: editorContext_$1.getOpacity() / 2 - } - })); // set stretchy line to first point - - stretchy.setAttribute('d', ['M', mouseX, mouseY, mouseX, mouseY].join(' ')); - index = subpath ? path.segs.length : 0; - addPointGrip(index, mouseX, mouseY); - } else { - // determine if we clicked on an existing point - var seglist = drawnPath.pathSegList; - var i = seglist.numberOfItems; - var FUZZ = 6 / currentZoom; - var clickOnPoint = false; - - while (i) { - i--; - var item = seglist.getItem(i); - var px = item.x, - py = item.y; // found a matching point - - if (x >= px - FUZZ && x <= px + FUZZ && y >= py - FUZZ && y <= py + FUZZ) { - clickOnPoint = true; - break; - } - } // get path element that we are in the process of creating - - - id = editorContext_$1.getId(); // Remove previous path object if previously created - - removePath_(id); - var newpath = getElem(id); - var newseg; - var sSeg; - var len = seglist.numberOfItems; // if we clicked on an existing point, then we are done this path, commit it - // (i, i+1) are the x,y that were clicked on - - if (clickOnPoint) { - // if clicked on any other point but the first OR - // the first point was clicked on and there are less than 3 points - // then leave the path open - // otherwise, close the path - if (i <= 1 && len >= 2) { - // Create end segment - var absX = seglist.getItem(0).x; - var absY = seglist.getItem(0).y; - sSeg = stretchy.pathSegList.getItem(1); - - if (sSeg.pathSegType === 4) { - newseg = drawnPath.createSVGPathSegLinetoAbs(absX, absY); - } else { - newseg = drawnPath.createSVGPathSegCurvetoCubicAbs(absX, absY, sSeg.x1 / currentZoom, sSeg.y1 / currentZoom, absX, absY); - } - - var endseg = drawnPath.createSVGPathSegClosePath(); - seglist.appendItem(newseg); - seglist.appendItem(endseg); - } else if (len < 3) { - keep = false; - return keep; - } - - $$3(stretchy).remove(); // This will signal to commit the path - // const element = newpath; // Other event handlers define own `element`, so this was probably not meant to interact with them or one which shares state (as there were none); I therefore adding a missing `var` to avoid a global - - /* drawnPath = */ - - editorContext_$1.setDrawnPath(null); - editorContext_$1.setStarted(false); - - if (subpath) { - if (path.matrix) { - editorContext_$1.remapElement(newpath, {}, path.matrix.inverse()); - } - - var newD = newpath.getAttribute('d'); - var origD = $$3(path.elem).attr('d'); - $$3(path.elem).attr('d', origD + newD); - $$3(newpath).remove(); - - if (path.matrix) { - recalcRotatedPath(); - } - - init$2(); - pathActions.toEditMode(path.elem); - path.selectPt(); - return false; - } // else, create a new point, update path element - - } else { - // Checks if current target or parents are #svgcontent - if (!$$3.contains(editorContext_$1.getContainer(), editorContext_$1.getMouseTarget(evt))) { - // Clicked outside canvas, so don't make point - // console.log('Clicked outside canvas'); - return false; - } - - var num = drawnPath.pathSegList.numberOfItems; - var last = drawnPath.pathSegList.getItem(num - 1); - var lastx = last.x, - lasty = last.y; - - if (evt.shiftKey) { - var xya = snapToAngle(lastx, lasty, x, y); - x = xya.x; - y = xya.y; - } // Use the segment defined by stretchy - - - sSeg = stretchy.pathSegList.getItem(1); - - if (sSeg.pathSegType === 4) { - newseg = drawnPath.createSVGPathSegLinetoAbs(editorContext_$1.round(x), editorContext_$1.round(y)); - } else { - newseg = drawnPath.createSVGPathSegCurvetoCubicAbs(editorContext_$1.round(x), editorContext_$1.round(y), sSeg.x1 / currentZoom, sSeg.y1 / currentZoom, sSeg.x2 / currentZoom, sSeg.y2 / currentZoom); - } - - drawnPath.pathSegList.appendItem(newseg); - x *= currentZoom; - y *= currentZoom; // set stretchy line to latest point - - stretchy.setAttribute('d', ['M', x, y, x, y].join(' ')); - index = num; - - if (subpath) { - index += path.segs.length; - } - - addPointGrip(index, x, y); - } // keep = true; - - } - - return undefined; - } // TODO: Make sure currentPath isn't null at this point - - - if (!path) { - return undefined; - } - - path.storeD(); - id = evt.target.id; - var curPt; - - if (id.substr(0, 14) === 'pathpointgrip_') { - // Select this point - curPt = path.cur_pt = Number.parseInt(id.substr(14)); - path.dragging = [startX, startY]; - var seg = path.segs[curPt]; // only clear selection if shift is not pressed (otherwise, add - // node to selection) - - if (!evt.shiftKey) { - if (path.selected_pts.length <= 1 || !seg.selected) { - path.clearSelection(); - } - - path.addPtsToSelection(curPt); - } else if (seg.selected) { - path.removePtFromSelection(curPt); - } else { - path.addPtsToSelection(curPt); - } - } else if (id.startsWith('ctrlpointgrip_')) { - path.dragging = [startX, startY]; - var parts = id.split('_')[1].split('c'); - curPt = Number(parts[0]); - var ctrlNum = Number(parts[1]); - path.selectPt(curPt, ctrlNum); - } // Start selection box - - - if (!path.dragging) { - var rubberBox = editorContext_$1.getRubberBox(); - - if (isNullish(rubberBox)) { - rubberBox = editorContext_$1.setRubberBox(editorContext_$1.selectorManager.getRubberBandBox()); - } - - var currentZoom = editorContext_$1.getCurrentZoom(); - assignAttributes(rubberBox, { - x: startX * currentZoom, - y: startY * currentZoom, - width: 0, - height: 0, - display: 'inline' - }); - } - - return undefined; - }, - - /** - * @param {Float} mouseX - * @param {Float} mouseY - * @returns {void} - */ - mouseMove: function mouseMove(mouseX, mouseY) { - var currentZoom = editorContext_$1.getCurrentZoom(); - hasMoved = true; - var drawnPath = editorContext_$1.getDrawnPath(); - - if (editorContext_$1.getCurrentMode() === 'path') { - if (!drawnPath) { - return; - } - - var seglist = drawnPath.pathSegList; - var index = seglist.numberOfItems - 1; - - if (newPoint) { - // First point - // if (!index) { return; } - // Set control points - var pointGrip1 = addCtrlGrip('1c1'); - var pointGrip2 = addCtrlGrip('0c2'); // dragging pointGrip1 - - pointGrip1.setAttribute('cx', mouseX); - pointGrip1.setAttribute('cy', mouseY); - pointGrip1.setAttribute('display', 'inline'); - var ptX = newPoint[0]; - var ptY = newPoint[1]; // set curve - // const seg = seglist.getItem(index); - - var curX = mouseX / currentZoom; - var curY = mouseY / currentZoom; - var altX = ptX + (ptX - curX); - var altY = ptY + (ptY - curY); - pointGrip2.setAttribute('cx', altX * currentZoom); - pointGrip2.setAttribute('cy', altY * currentZoom); - pointGrip2.setAttribute('display', 'inline'); - var ctrlLine = getCtrlLine(1); - assignAttributes(ctrlLine, { - x1: mouseX, - y1: mouseY, - x2: altX * currentZoom, - y2: altY * currentZoom, - display: 'inline' - }); - - if (index === 0) { - firstCtrl = [mouseX, mouseY]; - } else { - var last = seglist.getItem(index - 1); - var lastX = last.x; - var lastY = last.y; - - if (last.pathSegType === 6) { - lastX += lastX - last.x2; - lastY += lastY - last.y2; - } else if (firstCtrl) { - lastX = firstCtrl[0] / currentZoom; - lastY = firstCtrl[1] / currentZoom; - } - - replacePathSeg(6, index, [ptX, ptY, lastX, lastY, altX, altY], drawnPath); - } - } else { - var stretchy = getElem('path_stretch_line'); - - if (stretchy) { - var prev = seglist.getItem(index); - - if (prev.pathSegType === 6) { - var prevX = prev.x + (prev.x - prev.x2); - var prevY = prev.y + (prev.y - prev.y2); - replacePathSeg(6, 1, [mouseX, mouseY, prevX * currentZoom, prevY * currentZoom, mouseX, mouseY], stretchy); - } else if (firstCtrl) { - replacePathSeg(6, 1, [mouseX, mouseY, firstCtrl[0], firstCtrl[1], mouseX, mouseY], stretchy); - } else { - replacePathSeg(4, 1, [mouseX, mouseY], stretchy); - } - } - } - - return; - } // if we are dragging a point, let's move it - - - if (path.dragging) { - var pt = getPointFromGrip({ - x: path.dragging[0], - y: path.dragging[1] - }, path); - var mpt = getPointFromGrip({ - x: mouseX, - y: mouseY - }, path); - var diffX = mpt.x - pt.x; - var diffY = mpt.y - pt.y; - path.dragging = [mouseX, mouseY]; - - if (path.dragctrl) { - path.moveCtrl(diffX, diffY); - } else { - path.movePts(diffX, diffY); - } - } else { - path.selected_pts = []; - path.eachSeg(function (i) { - var seg = this; - - if (!seg.next && !seg.prev) { - return; - } // const {item} = seg; - - - var rubberBox = editorContext_$1.getRubberBox(); - var rbb = rubberBox.getBBox(); - var pt = getGripPt(seg); - var ptBb = { - x: pt.x, - y: pt.y, - width: 0, - height: 0 - }; - var sel = rectsIntersect(rbb, ptBb); - this.select(sel); // Note that addPtsToSelection is not being run - - if (sel) { - path.selected_pts.push(seg.index); - } - }); - } - }, - - /** - * @typedef module:path.keepElement - * @type {PlainObject} - * @property {boolean} keep - * @property {Element} element - */ - - /** - * @param {Event} evt - * @param {Element} element - * @param {Float} mouseX - * @param {Float} mouseY - * @returns {module:path.keepElement|void} - */ - mouseUp: function mouseUp(evt, element, mouseX, mouseY) { - var drawnPath = editorContext_$1.getDrawnPath(); // Create mode - - if (editorContext_$1.getCurrentMode() === 'path') { - newPoint = null; - - if (!drawnPath) { - element = getElem(editorContext_$1.getId()); - editorContext_$1.setStarted(false); - firstCtrl = null; - } - - return { - keep: true, - element: element - }; - } // Edit mode - - - var rubberBox = editorContext_$1.getRubberBox(); - - if (path.dragging) { - var lastPt = path.cur_pt; - path.dragging = false; - path.dragctrl = false; - path.update(); - - if (hasMoved) { - path.endChanges('Move path point(s)'); - } - - if (!evt.shiftKey && !hasMoved) { - path.selectPt(lastPt); - } - } else if (rubberBox && rubberBox.getAttribute('display') !== 'none') { - // Done with multi-node-select - rubberBox.setAttribute('display', 'none'); - - if (rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) { - pathActions.toSelectMode(evt.target); - } // else, move back to select mode - - } else { - pathActions.toSelectMode(evt.target); - } - - hasMoved = false; - return undefined; - }, - - /** - * @param {Element} element - * @returns {void} - */ - toEditMode: function toEditMode(element) { - path = getPath_(element); - editorContext_$1.setCurrentMode('pathedit'); - editorContext_$1.clearSelection(); - path.show(true).update(); - path.oldbbox = getBBox(path.elem); - subpath = false; - }, - - /** - * @param {Element} elem - * @fires module:svgcanvas.SvgCanvas#event:selected - * @returns {void} - */ - toSelectMode: function toSelectMode(elem) { - var selPath = elem === path.elem; - editorContext_$1.setCurrentMode('select'); - path.show(false); - currentPath = false; - editorContext_$1.clearSelection(); - - if (path.matrix) { - // Rotated, so may need to re-calculate the center - recalcRotatedPath(); - } - - if (selPath) { - editorContext_$1.call('selected', [elem]); - editorContext_$1.addToSelection([elem], true); - } - }, - - /** - * @param {boolean} on - * @returns {void} - */ - addSubPath: function addSubPath(on) { - if (on) { - // Internally we go into "path" mode, but in the UI it will - // still appear as if in "pathedit" mode. - editorContext_$1.setCurrentMode('path'); - subpath = true; - } else { - pathActions.clear(true); - pathActions.toEditMode(path.elem); - } - }, - - /** - * @param {Element} target - * @returns {void} - */ - select: function select(target) { - if (currentPath === target) { - pathActions.toEditMode(target); - editorContext_$1.setCurrentMode('pathedit'); // going into pathedit mode - } else { - currentPath = target; - } - }, - - /** - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - reorient: function reorient() { - var elem = editorContext_$1.getSelectedElements()[0]; - - if (!elem) { - return; - } - - var angl = getRotationAngle(elem); - - if (angl === 0) { - return; - } - - var batchCmd = new BatchCommand('Reorient path'); - var changes = { - d: elem.getAttribute('d'), - transform: elem.getAttribute('transform') - }; - batchCmd.addSubCommand(new ChangeElementCommand(elem, changes)); - editorContext_$1.clearSelection(); - this.resetOrientation(elem); - editorContext_$1.addCommandToHistory(batchCmd); // Set matrix to null - - getPath_(elem).show(false).matrix = null; - this.clear(); - editorContext_$1.addToSelection([elem], true); - editorContext_$1.call('changed', editorContext_$1.getSelectedElements()); - }, - - /** - * @param {boolean} remove Not in use - * @returns {void} - */ - clear: function clear(remove) { - var drawnPath = editorContext_$1.getDrawnPath(); - currentPath = null; - - if (drawnPath) { - var elem = getElem(editorContext_$1.getId()); - $$3(getElem('path_stretch_line')).remove(); - $$3(elem).remove(); - $$3(getElem('pathpointgrip_container')).find('*').attr('display', 'none'); - firstCtrl = null; - editorContext_$1.setDrawnPath(null); - editorContext_$1.setStarted(false); - } else if (editorContext_$1.getCurrentMode() === 'pathedit') { - this.toSelectMode(); - } - - if (path) { - path.init().show(false); - } - }, - - /** - * @param {?(Element|SVGPathElement)} pth - * @returns {false|void} - */ - resetOrientation: function resetOrientation(pth) { - if (isNullish(pth) || pth.nodeName !== 'path') { - return false; - } - - var tlist = getTransformList(pth); - var m = transformListToTransform(tlist).matrix; - tlist.clear(); - pth.removeAttribute('transform'); - var segList = pth.pathSegList; // Opera/win/non-EN throws an error here. - // TODO: Find out why! - // Presumed fixed in Opera 10.5, so commented out for now - // try { - - var len = segList.numberOfItems; // } catch(err) { - // const fixed_d = pathActions.convertPath(pth); - // pth.setAttribute('d', fixed_d); - // segList = pth.pathSegList; - // const len = segList.numberOfItems; - // } - // let lastX, lastY; - - var _loop = function _loop(i) { - var seg = segList.getItem(i); - var type = seg.pathSegType; - - if (type === 1) { - return "continue"; - } - - var pts = []; - $$3.each(['', 1, 2], function (j, n) { - var x = seg['x' + n], - y = seg['y' + n]; - - if (x !== undefined && y !== undefined) { - var pt = transformPoint(x, y, m); - pts.splice(pts.length, 0, pt.x, pt.y); - } - }); - replacePathSeg(type, i, pts, pth); - }; - - for (var i = 0; i < len; ++i) { - var _ret = _loop(i); - - if (_ret === "continue") continue; - } - - reorientGrads(pth, m); - return undefined; - }, - - /** - * @returns {void} - */ - zoomChange: function zoomChange() { - if (editorContext_$1.getCurrentMode() === 'pathedit') { - path.update(); - } - }, - - /** - * @typedef {PlainObject} module:path.NodePoint - * @property {Float} x - * @property {Float} y - * @property {Integer} type - */ - - /** - * @returns {module:path.NodePoint} - */ - getNodePoint: function getNodePoint() { - var selPt = path.selected_pts.length ? path.selected_pts[0] : 1; - var seg = path.segs[selPt]; - return { - x: seg.item.x, - y: seg.item.y, - type: seg.type - }; - }, - - /** - * @param {boolean} linkPoints - * @returns {void} - */ - linkControlPoints: function linkControlPoints(linkPoints) { - setLinkControlPoints(linkPoints); - }, - - /** - * @returns {void} - */ - clonePathNode: function clonePathNode() { - path.storeD(); - var selPts = path.selected_pts; // const {segs} = path; - - var i = selPts.length; - var nums = []; - - while (i--) { - var pt = selPts[i]; - path.addSeg(pt); - nums.push(pt + i); - nums.push(pt + i + 1); - } - - path.init().addPtsToSelection(nums); - path.endChanges('Clone path node(s)'); - }, - - /** - * @returns {void} - */ - opencloseSubPath: function opencloseSubPath() { - var selPts = path.selected_pts; // Only allow one selected node for now - - if (selPts.length !== 1) { - return; - } - - var _path = path, - elem = _path.elem; - var list = elem.pathSegList; // const len = list.numberOfItems; - - var index = selPts[0]; - var openPt = null; - var startItem = null; // Check if subpath is already open - - path.eachSeg(function (i) { - if (this.type === 2 && i <= index) { - startItem = this.item; - } - - if (i <= index) { - return true; - } - - if (this.type === 2) { - // Found M first, so open - openPt = i; - return false; - } - - if (this.type === 1) { - // Found Z first, so closed - openPt = false; - return false; - } - - return true; - }); - - if (isNullish(openPt)) { - // Single path, so close last seg - openPt = path.segs.length - 1; - } - - if (openPt !== false) { - // Close this path - // Create a line going to the previous "M" - var newseg = elem.createSVGPathSegLinetoAbs(startItem.x, startItem.y); - var closer = elem.createSVGPathSegClosePath(); - - if (openPt === path.segs.length - 1) { - list.appendItem(newseg); - list.appendItem(closer); - } else { - insertItemBefore(elem, closer, openPt); - insertItemBefore(elem, newseg, openPt); - } - - path.init().selectPt(openPt + 1); - return; - } // M 1,1 L 2,2 L 3,3 L 1,1 z // open at 2,2 - // M 2,2 L 3,3 L 1,1 - // M 1,1 L 2,2 L 1,1 z M 4,4 L 5,5 L6,6 L 5,5 z - // M 1,1 L 2,2 L 1,1 z [M 4,4] L 5,5 L(M)6,6 L 5,5 z - - - var seg = path.segs[index]; - - if (seg.mate) { - list.removeItem(index); // Removes last "L" - - list.removeItem(index); // Removes the "Z" - - path.init().selectPt(index - 1); - return; - } - - var lastM, zSeg; // Find this sub-path's closing point and remove - - for (var i = 0; i < list.numberOfItems; i++) { - var item = list.getItem(i); - - if (item.pathSegType === 2) { - // Find the preceding M - lastM = i; - } else if (i === index) { - // Remove it - list.removeItem(lastM); // index--; - } else if (item.pathSegType === 1 && index < i) { - // Remove the closing seg of this subpath - zSeg = i - 1; - list.removeItem(i); - break; - } - } - - var num = index - lastM - 1; - - while (num--) { - insertItemBefore(elem, list.getItem(lastM), zSeg); - } - - var pt = list.getItem(lastM); // Make this point the new "M" - - replacePathSeg(2, lastM, [pt.x, pt.y]); // i = index; // i is local here, so has no effect; what was the intent for this? - - path.init().selectPt(0); - }, - - /** - * @returns {void} - */ - deletePathNode: function deletePathNode() { - if (!pathActions.canDeleteNodes) { - return; - } - - path.storeD(); - var selPts = path.selected_pts; - var i = selPts.length; - - while (i--) { - var pt = selPts[i]; - path.deleteSeg(pt); - } // Cleanup - - - var cleanup = function cleanup() { - var segList = path.elem.pathSegList; - var len = segList.numberOfItems; - - var remItems = function remItems(pos, count) { - while (count--) { - segList.removeItem(pos); - } - }; - - if (len <= 1) { - return true; - } - - while (len--) { - var item = segList.getItem(len); - - if (item.pathSegType === 1) { - var prev = segList.getItem(len - 1); - var nprev = segList.getItem(len - 2); - - if (prev.pathSegType === 2) { - remItems(len - 1, 2); - cleanup(); - break; - } else if (nprev.pathSegType === 2) { - remItems(len - 2, 3); - cleanup(); - break; - } - } else if (item.pathSegType === 2) { - if (len > 0) { - var prevType = segList.getItem(len - 1).pathSegType; // Path has M M - - if (prevType === 2) { - remItems(len - 1, 1); - cleanup(); - break; // Entire path ends with Z M - } else if (prevType === 1 && segList.numberOfItems - 1 === len) { - remItems(len, 1); - cleanup(); - break; - } - } - } - } - - return false; - }; - - cleanup(); // Completely delete a path with 1 or 0 segments - - if (path.elem.pathSegList.numberOfItems <= 1) { - pathActions.toSelectMode(path.elem); - editorContext_$1.canvas.deleteSelectedElements(); - return; - } - - path.init(); - path.clearSelection(); // TODO: Find right way to select point now - // path.selectPt(selPt); - - if (window.opera) { - // Opera repaints incorrectly - var cp = $$3(path.elem); - cp.attr('d', cp.attr('d')); - } - - path.endChanges('Delete path node(s)'); - }, - - /* eslint-disable jsdoc/require-returns */ - // Can't seem to use `@borrows` here, so using `@see` - - /** - * Smooth polyline into path. - * @function module:path.pathActions.smoothPolylineIntoPath - * @see module:path~smoothPolylineIntoPath - */ - smoothPolylineIntoPath: smoothPolylineIntoPath, - - /* eslint-enable jsdoc/require-returns */ - - /** - * @param {?Integer} v See {@link https://www.w3.org/TR/SVG/single-page.html#paths-InterfaceSVGPathSeg} - * @returns {void} - */ - setSegType: function setSegType(v) { - path.setSegType(v); - }, - - /** - * @param {string} attr - * @param {Float} newValue - * @returns {void} - */ - moveNode: function moveNode(attr, newValue) { - var selPts = path.selected_pts; - - if (!selPts.length) { - return; - } - - path.storeD(); // Get first selected point - - var seg = path.segs[selPts[0]]; - var diff = { - x: 0, - y: 0 - }; - diff[attr] = newValue - seg.item[attr]; - seg.move(diff.x, diff.y); - path.endChanges('Move path point'); - }, - - /** - * @param {Element} elem - * @returns {void} - */ - fixEnd: function fixEnd(elem) { - // Adds an extra segment if the last seg before a Z doesn't end - // at its M point - // M0,0 L0,100 L100,100 z - var segList = elem.pathSegList; - var len = segList.numberOfItems; - var lastM; - - for (var i = 0; i < len; ++i) { - var item = segList.getItem(i); - - if (item.pathSegType === 2) { - lastM = item; - } - - if (item.pathSegType === 1) { - var prev = segList.getItem(i - 1); - - if (prev.x !== lastM.x || prev.y !== lastM.y) { - // Add an L segment here - var newseg = elem.createSVGPathSegLinetoAbs(lastM.x, lastM.y); - insertItemBefore(elem, newseg, i); // Can this be done better? - - pathActions.fixEnd(elem); - break; - } - } - } - - if (isWebkit()) { - editorContext_$1.resetD(elem); - } - }, - - /* eslint-disable jsdoc/require-returns */ - // Can't seem to use `@borrows` here, so using `@see` - - /** - * Convert a path to one with only absolute or relative values. - * @function module:path.pathActions.convertPath - * @see module:path.convertPath - */ - convertPath: convertPath - /* eslint-enable jsdoc/require-returns */ - - } - ); -}(); // end pathActions - -var $$4 = jQuery; -/** - * This class encapsulates the concept of a layer in the drawing. It can be constructed with - * an existing group element or, with three parameters, will create a new layer group element. - * - * @example - * const l1 = new Layer('name', group); // Use the existing group for this layer. - * const l2 = new Layer('name', group, svgElem); // Create a new group and add it to the DOM after group. - * const l3 = new Layer('name', null, svgElem); // Create a new group and add it to the DOM as the last layer. - * @memberof module:layer - */ - -var Layer = /*#__PURE__*/function () { - /** - * @param {string} name - Layer name - * @param {SVGGElement|null} group - An existing SVG group element or null. - * If group and no svgElem, use group for this layer. - * If group and svgElem, create a new group element and insert it in the DOM after group. - * If no group and svgElem, create a new group element and insert it in the DOM as the last layer. - * @param {SVGGElement} [svgElem] - The SVG DOM element. If defined, use this to add - * a new layer to the document. - */ - function Layer(name, group, svgElem) { - _classCallCheck(this, Layer); - - this.name_ = name; - this.group_ = svgElem ? null : group; - - if (svgElem) { - // Create a group element with title and add it to the DOM. - var svgdoc = svgElem.ownerDocument; - this.group_ = svgdoc.createElementNS(NS.SVG, 'g'); - var layerTitle = svgdoc.createElementNS(NS.SVG, 'title'); - layerTitle.textContent = name; - this.group_.append(layerTitle); - - if (group) { - $$4(group).after(this.group_); - } else { - svgElem.append(this.group_); - } - } - - addLayerClass(this.group_); - walkTree(this.group_, function (e) { - e.setAttribute('style', 'pointer-events:inherit'); - }); - this.group_.setAttribute('style', svgElem ? 'pointer-events:all' : 'pointer-events:none'); - } - /** - * Get the layer's name. - * @returns {string} The layer name - */ - - - _createClass(Layer, [{ - key: "getName", - value: function getName() { - return this.name_; - } - /** - * Get the group element for this layer. - * @returns {SVGGElement} The layer SVG group - */ - - }, { - key: "getGroup", - value: function getGroup() { - return this.group_; - } - /** - * Active this layer so it takes pointer events. - * @returns {void} - */ - - }, { - key: "activate", - value: function activate() { - this.group_.setAttribute('style', 'pointer-events:all'); - } - /** - * Deactive this layer so it does NOT take pointer events. - * @returns {void} - */ - - }, { - key: "deactivate", - value: function deactivate() { - this.group_.setAttribute('style', 'pointer-events:none'); - } - /** - * Set this layer visible or hidden based on 'visible' parameter. - * @param {boolean} visible - If true, make visible; otherwise, hide it. - * @returns {void} - */ - - }, { - key: "setVisible", - value: function setVisible(visible) { - var expected = visible === undefined || visible ? 'inline' : 'none'; - var oldDisplay = this.group_.getAttribute('display'); - - if (oldDisplay !== expected) { - this.group_.setAttribute('display', expected); - } - } - /** - * Is this layer visible? - * @returns {boolean} True if visible. - */ - - }, { - key: "isVisible", - value: function isVisible() { - return this.group_.getAttribute('display') !== 'none'; - } - /** - * Get layer opacity. - * @returns {Float} Opacity value. - */ - - }, { - key: "getOpacity", - value: function getOpacity() { - var opacity = this.group_.getAttribute('opacity'); - - if (isNullish(opacity)) { - return 1; - } - - return Number.parseFloat(opacity); - } - /** - * Sets the opacity of this layer. If opacity is not a value between 0.0 and 1.0, - * nothing happens. - * @param {Float} opacity - A float value in the range 0.0-1.0 - * @returns {void} - */ - - }, { - key: "setOpacity", - value: function setOpacity(opacity) { - if (typeof opacity === 'number' && opacity >= 0.0 && opacity <= 1.0) { - this.group_.setAttribute('opacity', opacity); - } - } - /** - * Append children to this layer. - * @param {SVGGElement} children - The children to append to this layer. - * @returns {void} - */ - - }, { - key: "appendChildren", - value: function appendChildren(children) { - var _iterator = _createForOfIteratorHelper(children), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var child = _step.value; - this.group_.append(child); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - /** - * @returns {SVGTitleElement|null} - */ - - }, { - key: "getTitleElement", - value: function getTitleElement() { - var len = this.group_.childNodes.length; - - for (var i = 0; i < len; ++i) { - var child = this.group_.childNodes.item(i); - - if (child && child.tagName === 'title') { - return child; - } - } - - return null; - } - /** - * Set the name of this layer. - * @param {string} name - The new name. - * @param {module:history.HistoryRecordingService} hrService - History recording service - * @returns {string|null} The new name if changed; otherwise, null. - */ - - }, { - key: "setName", - value: function setName(name, hrService) { - var previousName = this.name_; - name = toXml(name); // now change the underlying title element contents - - var title = this.getTitleElement(); - - if (title) { - $$4(title).empty(); - title.textContent = name; - this.name_ = name; - - if (hrService) { - hrService.changeElement(title, { - '#text': previousName - }); - } - - return this.name_; - } - - return null; - } - /** - * Remove this layer's group from the DOM. No more functions on group can be called after this. - * @returns {SVGGElement} The layer SVG group that was just removed. - */ - - }, { - key: "removeGroup", - value: function removeGroup() { - var group = this.group_; - this.group_.remove(); - this.group_ = undefined; - return group; - } - }]); - - return Layer; -}(); -/** - * @property {string} CLASS_NAME - class attribute assigned to all layer groups. - */ - - -Layer.CLASS_NAME = 'layer'; -/** - * @property {RegExp} CLASS_REGEX - Used to test presence of class Layer.CLASS_NAME - */ - -Layer.CLASS_REGEX = new RegExp('(\\s|^)' + Layer.CLASS_NAME + '(\\s|$)'); -/** - * Add class `Layer.CLASS_NAME` to the element (usually `class='layer'`). - * - * @param {SVGGElement} elem - The SVG element to update - * @returns {void} - */ - -function addLayerClass(elem) { - var classes = elem.getAttribute('class'); - - if (isNullish(classes) || !classes.length) { - elem.setAttribute('class', Layer.CLASS_NAME); - } else if (!Layer.CLASS_REGEX.test(classes)) { - elem.setAttribute('class', classes + ' ' + Layer.CLASS_NAME); - } -} - -/** - * History recording service. - * - * A self-contained service interface for recording history. Once injected, no other dependencies - * or globals are required (example: UndoManager, command types, etc.). Easy to mock for unit tests. - * Built on top of history classes in history.js. - * - * There is a simple start/end interface for batch commands. - * - * HistoryRecordingService.NO_HISTORY is a singleton that can be passed in to functions - * that record history. This helps when the caller requires that no history be recorded. - * - * The following will record history: insert, batch, insert. - * @example - * hrService = new HistoryRecordingService(this.undoMgr); - * hrService.insertElement(elem, text); // add simple command to history. - * hrService.startBatchCommand('create two elements'); - * hrService.changeElement(elem, attrs, text); // add to batchCommand - * hrService.changeElement(elem, attrs2, text); // add to batchCommand - * hrService.endBatchCommand(); // add batch command with two change commands to history. - * hrService.insertElement(elem, text); // add simple command to history. - * - * @example - * // Note that all functions return this, so commands can be chained, like so: - * hrService - * .startBatchCommand('create two elements') - * .insertElement(elem, text) - * .changeElement(elem, attrs, text) - * .endBatchCommand(); - * - * @memberof module:history - */ - -var HistoryRecordingService = /*#__PURE__*/function () { - /** - * @param {history.UndoManager|null} undoManager - The undo manager. - * A value of `null` is valid for cases where no history recording is required. - * See singleton: {@link module:history.HistoryRecordingService.HistoryRecordingService.NO_HISTORY} - */ - function HistoryRecordingService(undoManager) { - _classCallCheck(this, HistoryRecordingService); - - this.undoManager_ = undoManager; - this.currentBatchCommand_ = null; - this.batchCommandStack_ = []; - } - /** - * Start a batch command so multiple commands can recorded as a single history command. - * Requires a corresponding call to endBatchCommand. Start and end commands can be nested. - * - * @param {string} text - Optional string describing the batch command. - * @returns {module:history.HistoryRecordingService} - */ - - - _createClass(HistoryRecordingService, [{ - key: "startBatchCommand", - value: function startBatchCommand(text) { - if (!this.undoManager_) { - return this; - } - - this.currentBatchCommand_ = new BatchCommand(text); - this.batchCommandStack_.push(this.currentBatchCommand_); - return this; - } - /** - * End a batch command and add it to the history or a parent batch command. - * @returns {module:history.HistoryRecordingService} - */ - - }, { - key: "endBatchCommand", - value: function endBatchCommand() { - if (!this.undoManager_) { - return this; - } - - if (this.currentBatchCommand_) { - var batchCommand = this.currentBatchCommand_; - this.batchCommandStack_.pop(); - var len = this.batchCommandStack_.length; - this.currentBatchCommand_ = len ? this.batchCommandStack_[len - 1] : null; - this.addCommand_(batchCommand); - } - - return this; - } - /** - * Add a `MoveElementCommand` to the history or current batch command. - * @param {Element} elem - The DOM element that was moved - * @param {Element} oldNextSibling - The element's next sibling before it was moved - * @param {Element} oldParent - The element's parent before it was moved - * @param {string} [text] - An optional string visible to user related to this change - * @returns {module:history.HistoryRecordingService} - */ - - }, { - key: "moveElement", - value: function moveElement(elem, oldNextSibling, oldParent, text) { - if (!this.undoManager_) { - return this; - } - - this.addCommand_(new MoveElementCommand(elem, oldNextSibling, oldParent, text)); - return this; - } - /** - * Add an `InsertElementCommand` to the history or current batch command. - * @param {Element} elem - The DOM element that was added - * @param {string} [text] - An optional string visible to user related to this change - * @returns {module:history.HistoryRecordingService} - */ - - }, { - key: "insertElement", - value: function insertElement(elem, text) { - if (!this.undoManager_) { - return this; - } - - this.addCommand_(new InsertElementCommand(elem, text)); - return this; - } - /** - * Add a `RemoveElementCommand` to the history or current batch command. - * @param {Element} elem - The DOM element that was removed - * @param {Element} oldNextSibling - The element's next sibling before it was removed - * @param {Element} oldParent - The element's parent before it was removed - * @param {string} [text] - An optional string visible to user related to this change - * @returns {module:history.HistoryRecordingService} - */ - - }, { - key: "removeElement", - value: function removeElement(elem, oldNextSibling, oldParent, text) { - if (!this.undoManager_) { - return this; - } - - this.addCommand_(new RemoveElementCommand(elem, oldNextSibling, oldParent, text)); - return this; - } - /** - * Add a `ChangeElementCommand` to the history or current batch command. - * @param {Element} elem - The DOM element that was changed - * @param {module:history.CommandAttributes} attrs - An object with the attributes to be changed and the values they had *before* the change - * @param {string} [text] - An optional string visible to user related to this change - * @returns {module:history.HistoryRecordingService} - */ - - }, { - key: "changeElement", - value: function changeElement(elem, attrs, text) { - if (!this.undoManager_) { - return this; - } - - this.addCommand_(new ChangeElementCommand(elem, attrs, text)); - return this; - } - /** - * Private function to add a command to the history or current batch command. - * @private - * @param {Command} cmd - * @returns {module:history.HistoryRecordingService|void} - */ - - }, { - key: "addCommand_", - value: function addCommand_(cmd) { - if (!this.undoManager_) { - return this; - } - - if (this.currentBatchCommand_) { - this.currentBatchCommand_.addSubCommand(cmd); - } else { - this.undoManager_.addCommandToHistory(cmd); - } - - return undefined; - } - }]); - - return HistoryRecordingService; -}(); -/** - * @memberof module:history.HistoryRecordingService - * @property {module:history.HistoryRecordingService} NO_HISTORY - Singleton that can be passed to functions that record history, but the caller requires that no history be recorded. - */ - - -HistoryRecordingService.NO_HISTORY = new HistoryRecordingService(); - -/* globals jQuery */ - -var $$5 = jQueryPluginSVG(jQuery); -/** - * Create a clone of an element, updating its ID and its children's IDs when needed. - * @function module:utilities.copyElem - * @param {Element} el - DOM element to clone - * @param {module:utilities.GetNextID} getNextId - The getter of the next unique ID. - * @returns {Element} The cloned element - */ - -var copyElem = function copyElem(el, getNextId) { - // manually create a copy of the element - var newEl = document.createElementNS(el.namespaceURI, el.nodeName); - $$5.each(el.attributes, function (i, attr) { - if (attr.localName !== '-moz-math-font-style') { - newEl.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value); - } - }); // set the copied element's new id - - newEl.removeAttribute('id'); - newEl.id = getNextId(); // Opera's "d" value needs to be reset for Opera/Win/non-EN - // Also needed for webkit (else does not keep curved segments on clone) - - if (isWebkit() && el.nodeName === 'path') { - var fixedD = convertPath(el); - newEl.setAttribute('d', fixedD); - } // now create copies of all children - - - $$5.each(el.childNodes, function (i, child) { - switch (child.nodeType) { - case 1: - // element node - newEl.append(copyElem(child, getNextId)); - break; - - case 3: - // text node - newEl.textContent = child.nodeValue; - break; - } - }); - - if ($$5(el).data('gsvg')) { - $$5(newEl).data('gsvg', newEl.firstChild); - } else if ($$5(el).data('symbol')) { - var ref = $$5(el).data('symbol'); - $$5(newEl).data('ref', ref).data('symbol', ref); - } else if (newEl.tagName === 'image') { - preventClickDefault(newEl); - } - - return newEl; -}; - -var $$6 = jQuery; -var visElems$1 = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'.split(','); -var RandomizeModes = { - LET_DOCUMENT_DECIDE: 0, - ALWAYS_RANDOMIZE: 1, - NEVER_RANDOMIZE: 2 -}; -var randIds = RandomizeModes.LET_DOCUMENT_DECIDE; // Array with current disabled elements (for in-group editing) - -var disabledElems = []; -/** - * Get a HistoryRecordingService. - * @param {module:history.HistoryRecordingService} [hrService] - if exists, return it instead of creating a new service. - * @returns {module:history.HistoryRecordingService} - */ - -function historyRecordingService(hrService) { - return hrService || new HistoryRecordingService(canvas_.undoMgr); -} -/** - * Find the layer name in a group element. - * @param {Element} group The group element to search in. - * @returns {string} The layer name or empty string. - */ - - -function findLayerNameInGroup(group) { - return $$6('title', group).text() || (isOpera() && group.querySelectorAll // Hack for Opera 10.60 - ? $$6(group.querySelectorAll('title')).text() : ''); -} -/** - * Given a set of names, return a new unique name. - * @param {string[]} existingLayerNames - Existing layer names. - * @returns {string} - The new name. - */ - - -function getNewLayerName(existingLayerNames) { - var i = 1; // TODO(codedread): What about internationalization of "Layer"? - - while (existingLayerNames.includes('Layer ' + i)) { - i++; - } - - return 'Layer ' + i; -} -/** - * This class encapsulates the concept of a SVG-edit drawing. - */ - - -var Drawing = /*#__PURE__*/function () { - /** - * @param {SVGSVGElement} svgElem - The SVG DOM Element that this JS object - * encapsulates. If the svgElem has a se:nonce attribute on it, then - * IDs will use the nonce as they are generated. - * @param {string} [optIdPrefix=svg_] - The ID prefix to use. - * @throws {Error} If not initialized with an SVG element - */ - function Drawing(svgElem, optIdPrefix) { - _classCallCheck(this, Drawing); - - if (!svgElem || !svgElem.tagName || !svgElem.namespaceURI || svgElem.tagName !== 'svg' || svgElem.namespaceURI !== NS.SVG) { - throw new Error('Error: svgedit.draw.Drawing instance initialized without a <svg> element'); - } - /** - * The SVG DOM Element that represents this drawing. - * @type {SVGSVGElement} - */ - - - this.svgElem_ = svgElem; - /** - * The latest object number used in this drawing. - * @type {Integer} - */ - - this.obj_num = 0; - /** - * The prefix to prepend to each element id in the drawing. - * @type {string} - */ - - this.idPrefix = optIdPrefix || 'svg_'; - /** - * An array of released element ids to immediately reuse. - * @type {Integer[]} - */ - - this.releasedNums = []; - /** - * The z-ordered array of Layer objects. Each layer has a name - * and group element. - * The first layer is the one at the bottom of the rendering. - * @type {Layer[]} - */ - - this.all_layers = []; - /** - * Map of all_layers by name. - * - * Note: Layers are ordered, but referenced externally by name; so, we need both container - * types depending on which function is called (i.e. all_layers and layer_map). - * - * @type {PlainObject<string, Layer>} - */ - - this.layer_map = {}; - /** - * The current layer being used. - * @type {Layer} - */ - - this.current_layer = null; - /** - * The nonce to use to uniquely identify elements across drawings. - * @type {!string} - */ - - this.nonce_ = ''; - var n = this.svgElem_.getAttributeNS(NS.SE, 'nonce'); // If already set in the DOM, use the nonce throughout the document - // else, if randomizeIds(true) has been called, create and set the nonce. - - if (n && randIds !== RandomizeModes.NEVER_RANDOMIZE) { - this.nonce_ = n; - } else if (randIds === RandomizeModes.ALWAYS_RANDOMIZE) { - this.setNonce(Math.floor(Math.random() * 100001)); - } - } - /** - * @param {string} id Element ID to retrieve - * @returns {Element} SVG element within the root SVGSVGElement - */ - - - _createClass(Drawing, [{ - key: "getElem_", - value: function getElem_(id) { - if (this.svgElem_.querySelector) { - // querySelector lookup - return this.svgElem_.querySelector('#' + id); - } // jQuery lookup: twice as slow as xpath in FF - - - return $$6(this.svgElem_).find('[id=' + id + ']')[0]; - } - /** - * @returns {SVGSVGElement} - */ - - }, { - key: "getSvgElem", - value: function getSvgElem() { - return this.svgElem_; - } - /** - * @returns {!(string|Integer)} The previously set nonce - */ - - }, { - key: "getNonce", - value: function getNonce() { - return this.nonce_; - } - /** - * @param {!(string|Integer)} n The nonce to set - * @returns {void} - */ - - }, { - key: "setNonce", - value: function setNonce(n) { - this.svgElem_.setAttributeNS(NS.XMLNS, 'xmlns:se', NS.SE); - this.svgElem_.setAttributeNS(NS.SE, 'se:nonce', n); - this.nonce_ = n; - } - /** - * Clears any previously set nonce. - * @returns {void} - */ - - }, { - key: "clearNonce", - value: function clearNonce() { - // We deliberately leave any se:nonce attributes alone, - // we just don't use it to randomize ids. - this.nonce_ = ''; - } - /** - * Returns the latest object id as a string. - * @returns {string} The latest object Id. - */ - - }, { - key: "getId", - value: function getId() { - return this.nonce_ ? this.idPrefix + this.nonce_ + '_' + this.obj_num : this.idPrefix + this.obj_num; - } - /** - * Returns the next object Id as a string. - * @returns {string} The next object Id to use. - */ - - }, { - key: "getNextId", - value: function getNextId() { - var oldObjNum = this.obj_num; - var restoreOldObjNum = false; // If there are any released numbers in the release stack, - // use the last one instead of the next obj_num. - // We need to temporarily use obj_num as that is what getId() depends on. - - if (this.releasedNums.length > 0) { - this.obj_num = this.releasedNums.pop(); - restoreOldObjNum = true; - } else { - // If we are not using a released id, then increment the obj_num. - this.obj_num++; - } // Ensure the ID does not exist. - - - var id = this.getId(); - - while (this.getElem_(id)) { - if (restoreOldObjNum) { - this.obj_num = oldObjNum; - restoreOldObjNum = false; - } - - this.obj_num++; - id = this.getId(); - } // Restore the old object number if required. - - - if (restoreOldObjNum) { - this.obj_num = oldObjNum; - } - - return id; - } - /** - * Releases the object Id, letting it be used as the next id in getNextId(). - * This method DOES NOT remove any elements from the DOM, it is expected - * that client code will do this. - * @param {string} id - The id to release. - * @returns {boolean} True if the id was valid to be released, false otherwise. - */ - - }, { - key: "releaseId", - value: function releaseId(id) { - // confirm if this is a valid id for this Document, else return false - var front = this.idPrefix + (this.nonce_ ? this.nonce_ + '_' : ''); - - if (typeof id !== 'string' || !id.startsWith(front)) { - return false; - } // extract the obj_num of this id - - - var num = Number.parseInt(id.substr(front.length)); // if we didn't get a positive number or we already released this number - // then return false. - - if (typeof num !== 'number' || num <= 0 || this.releasedNums.includes(num)) { - return false; - } // push the released number into the released queue - - - this.releasedNums.push(num); - return true; - } - /** - * Returns the number of layers in the current drawing. - * @returns {Integer} The number of layers in the current drawing. - */ - - }, { - key: "getNumLayers", - value: function getNumLayers() { - return this.all_layers.length; - } - /** - * Check if layer with given name already exists. - * @param {string} name - The layer name to check - * @returns {boolean} - */ - - }, { - key: "hasLayer", - value: function hasLayer(name) { - return this.layer_map[name] !== undefined; - } - /** - * Returns the name of the ith layer. If the index is out of range, an empty string is returned. - * @param {Integer} i - The zero-based index of the layer you are querying. - * @returns {string} The name of the ith layer (or the empty string if none found) - */ - - }, { - key: "getLayerName", - value: function getLayerName(i) { - return i >= 0 && i < this.getNumLayers() ? this.all_layers[i].getName() : ''; - } - /** - * @returns {SVGGElement|null} The SVGGElement representing the current layer. - */ - - }, { - key: "getCurrentLayer", - value: function getCurrentLayer() { - return this.current_layer ? this.current_layer.getGroup() : null; - } - /** - * Get a layer by name. - * @param {string} name - * @returns {SVGGElement} The SVGGElement representing the named layer or null. - */ - - }, { - key: "getLayerByName", - value: function getLayerByName(name) { - var layer = this.layer_map[name]; - return layer ? layer.getGroup() : null; - } - /** - * Returns the name of the currently selected layer. If an error occurs, an empty string - * is returned. - * @returns {string} The name of the currently active layer (or the empty string if none found). - */ - - }, { - key: "getCurrentLayerName", - value: function getCurrentLayerName() { - return this.current_layer ? this.current_layer.getName() : ''; - } - /** - * Set the current layer's name. - * @param {string} name - The new name. - * @param {module:history.HistoryRecordingService} hrService - History recording service - * @returns {string|null} The new name if changed; otherwise, null. - */ - - }, { - key: "setCurrentLayerName", - value: function setCurrentLayerName(name, hrService) { - var finalName = null; - - if (this.current_layer) { - var oldName = this.current_layer.getName(); - finalName = this.current_layer.setName(name, hrService); - - if (finalName) { - delete this.layer_map[oldName]; - this.layer_map[finalName] = this.current_layer; - } - } - - return finalName; - } - /** - * Set the current layer's position. - * @param {Integer} newpos - The zero-based index of the new position of the layer. Range should be 0 to layers-1 - * @returns {{title: SVGGElement, previousName: string}|null} If the name was changed, returns {title:SVGGElement, previousName:string}; otherwise null. - */ - - }, { - key: "setCurrentLayerPosition", - value: function setCurrentLayerPosition(newpos) { - var layerCount = this.getNumLayers(); - - if (!this.current_layer || newpos < 0 || newpos >= layerCount) { - return null; - } - - var oldpos; - - for (oldpos = 0; oldpos < layerCount; ++oldpos) { - if (this.all_layers[oldpos] === this.current_layer) { - break; - } - } // some unknown error condition (current_layer not in all_layers) - - - if (oldpos === layerCount) { - return null; - } - - if (oldpos !== newpos) { - // if our new position is below us, we need to insert before the node after newpos - var currentGroup = this.current_layer.getGroup(); - var oldNextSibling = currentGroup.nextSibling; - var refGroup = null; - - if (newpos > oldpos) { - if (newpos < layerCount - 1) { - refGroup = this.all_layers[newpos + 1].getGroup(); - } // if our new position is above us, we need to insert before the node at newpos - - } else { - refGroup = this.all_layers[newpos].getGroup(); - } - - this.svgElem_.insertBefore(currentGroup, refGroup); // Ok to replace with `refGroup.before(currentGroup);`? - - this.identifyLayers(); - this.setCurrentLayer(this.getLayerName(newpos)); - return { - currentGroup: currentGroup, - oldNextSibling: oldNextSibling - }; - } - - return null; - } - /** - * @param {module:history.HistoryRecordingService} hrService - * @returns {void} - */ - - }, { - key: "mergeLayer", - value: function mergeLayer(hrService) { - var currentGroup = this.current_layer.getGroup(); - var prevGroup = $$6(currentGroup).prev()[0]; - - if (!prevGroup) { - return; - } - - hrService.startBatchCommand('Merge Layer'); - var layerNextSibling = currentGroup.nextSibling; - hrService.removeElement(currentGroup, layerNextSibling, this.svgElem_); - - while (currentGroup.firstChild) { - var child = currentGroup.firstChild; - - if (child.localName === 'title') { - hrService.removeElement(child, child.nextSibling, currentGroup); - child.remove(); - continue; - } - - var oldNextSibling = child.nextSibling; - prevGroup.append(child); - hrService.moveElement(child, oldNextSibling, currentGroup); - } // Remove current layer's group - - - this.current_layer.removeGroup(); // Remove the current layer and set the previous layer as the new current layer - - var index = this.all_layers.indexOf(this.current_layer); - - if (index > 0) { - var _name = this.current_layer.getName(); - - this.current_layer = this.all_layers[index - 1]; - this.all_layers.splice(index, 1); - delete this.layer_map[_name]; - } - - hrService.endBatchCommand(); - } - /** - * @param {module:history.HistoryRecordingService} hrService - * @returns {void} - */ - - }, { - key: "mergeAllLayers", - value: function mergeAllLayers(hrService) { - // Set the current layer to the last layer. - this.current_layer = this.all_layers[this.all_layers.length - 1]; - hrService.startBatchCommand('Merge all Layers'); - - while (this.all_layers.length > 1) { - this.mergeLayer(hrService); - } - - hrService.endBatchCommand(); - } - /** - * Sets the current layer. If the name is not a valid layer name, then this - * function returns `false`. Otherwise it returns `true`. This is not an - * undo-able action. - * @param {string} name - The name of the layer you want to switch to. - * @returns {boolean} `true` if the current layer was switched, otherwise `false` - */ - - }, { - key: "setCurrentLayer", - value: function setCurrentLayer(name) { - var layer = this.layer_map[name]; - - if (layer) { - if (this.current_layer) { - this.current_layer.deactivate(); - } - - this.current_layer = layer; - this.current_layer.activate(); - return true; - } - - return false; - } - /** - * Deletes the current layer from the drawing and then clears the selection. - * This function then calls the 'changed' handler. This is an undoable action. - * @todo Does this actually call the 'changed' handler? - * @returns {SVGGElement} The SVGGElement of the layer removed or null. - */ - - }, { - key: "deleteCurrentLayer", - value: function deleteCurrentLayer() { - if (this.current_layer && this.getNumLayers() > 1) { - var oldLayerGroup = this.current_layer.removeGroup(); - this.identifyLayers(); - return oldLayerGroup; - } - - return null; - } - /** - * Updates layer system and sets the current layer to the - * top-most layer (last `<g>` child of this drawing). - * @returns {void} - */ - - }, { - key: "identifyLayers", - value: function identifyLayers() { - this.all_layers = []; - this.layer_map = {}; - var numchildren = this.svgElem_.childNodes.length; // loop through all children of SVG element - - var orphans = [], - layernames = []; - var layer = null; - var childgroups = false; - - for (var i = 0; i < numchildren; ++i) { - var child = this.svgElem_.childNodes.item(i); // for each g, find its layer name - - if (child && child.nodeType === 1) { - if (child.tagName === 'g') { - childgroups = true; - - var _name2 = findLayerNameInGroup(child); - - if (_name2) { - layernames.push(_name2); - layer = new Layer(_name2, child); - this.all_layers.push(layer); - this.layer_map[_name2] = layer; - } else { - // if group did not have a name, it is an orphan - orphans.push(child); - } - } else if (visElems$1.includes(child.nodeName)) { - // Child is "visible" (i.e. not a <title> or <defs> element), so it is an orphan - orphans.push(child); - } - } - } // If orphans or no layers found, create a new layer and add all the orphans to it - - - if (orphans.length > 0 || !childgroups) { - layer = new Layer(getNewLayerName(layernames), null, this.svgElem_); - layer.appendChildren(orphans); - this.all_layers.push(layer); - this.layer_map[name] = layer; - } else { - layer.activate(); - } - - this.current_layer = layer; - } - /** - * Creates a new top-level layer in the drawing with the given name and - * makes it the current layer. - * @param {string} name - The given name. If the layer name exists, a new name will be generated. - * @param {module:history.HistoryRecordingService} hrService - History recording service - * @returns {SVGGElement} The SVGGElement of the new layer, which is - * also the current layer of this drawing. - */ - - }, { - key: "createLayer", - value: function createLayer(name, hrService) { - if (this.current_layer) { - this.current_layer.deactivate(); - } // Check for duplicate name. - - - if (name === undefined || name === null || name === '' || this.layer_map[name]) { - name = getNewLayerName(Object.keys(this.layer_map)); - } // Crate new layer and add to DOM as last layer - - - var layer = new Layer(name, null, this.svgElem_); // Like to assume hrService exists, but this is backwards compatible with old version of createLayer. - - if (hrService) { - hrService.startBatchCommand('Create Layer'); - hrService.insertElement(layer.getGroup()); - hrService.endBatchCommand(); - } - - this.all_layers.push(layer); - this.layer_map[name] = layer; - this.current_layer = layer; - return layer.getGroup(); - } - /** - * Creates a copy of the current layer with the given name and makes it the current layer. - * @param {string} name - The given name. If the layer name exists, a new name will be generated. - * @param {module:history.HistoryRecordingService} hrService - History recording service - * @returns {SVGGElement} The SVGGElement of the new layer, which is - * also the current layer of this drawing. - */ - - }, { - key: "cloneLayer", - value: function cloneLayer(name, hrService) { - var _this = this; - - if (!this.current_layer) { - return null; - } - - this.current_layer.deactivate(); // Check for duplicate name. - - if (name === undefined || name === null || name === '' || this.layer_map[name]) { - name = getNewLayerName(Object.keys(this.layer_map)); - } // Create new group and add to DOM just after current_layer - - - var currentGroup = this.current_layer.getGroup(); - var layer = new Layer(name, currentGroup, this.svgElem_); - var group = layer.getGroup(); // Clone children - - var children = _toConsumableArray(currentGroup.childNodes); - - children.forEach(function (child) { - if (child.localName === 'title') { - return; - } - - group.append(_this.copyElem(child)); - }); - - if (hrService) { - hrService.startBatchCommand('Duplicate Layer'); - hrService.insertElement(group); - hrService.endBatchCommand(); - } // Update layer containers and current_layer. - - - var index = this.all_layers.indexOf(this.current_layer); - - if (index >= 0) { - this.all_layers.splice(index + 1, 0, layer); - } else { - this.all_layers.push(layer); - } - - this.layer_map[name] = layer; - this.current_layer = layer; - return group; - } - /** - * Returns whether the layer is visible. If the layer name is not valid, - * then this function returns `false`. - * @param {string} layerName - The name of the layer which you want to query. - * @returns {boolean} The visibility state of the layer, or `false` if the layer name was invalid. - */ - - }, { - key: "getLayerVisibility", - value: function getLayerVisibility(layerName) { - var layer = this.layer_map[layerName]; - return layer ? layer.isVisible() : false; - } - /** - * Sets the visibility of the layer. If the layer name is not valid, this - * function returns `null`, otherwise it returns the `SVGElement` representing - * the layer. This is an undo-able action. - * @param {string} layerName - The name of the layer to change the visibility - * @param {boolean} bVisible - Whether the layer should be visible - * @returns {?SVGGElement} The SVGGElement representing the layer if the - * `layerName` was valid, otherwise `null`. - */ - - }, { - key: "setLayerVisibility", - value: function setLayerVisibility(layerName, bVisible) { - if (typeof bVisible !== 'boolean') { - return null; - } - - var layer = this.layer_map[layerName]; - - if (!layer) { - return null; - } - - layer.setVisible(bVisible); - return layer.getGroup(); - } - /** - * Returns the opacity of the given layer. If the input name is not a layer, `null` is returned. - * @param {string} layerName - name of the layer on which to get the opacity - * @returns {?Float} The opacity value of the given layer. This will be a value between 0.0 and 1.0, or `null` - * if `layerName` is not a valid layer - */ - - }, { - key: "getLayerOpacity", - value: function getLayerOpacity(layerName) { - var layer = this.layer_map[layerName]; - - if (!layer) { - return null; - } - - return layer.getOpacity(); - } - /** - * Sets the opacity of the given layer. If the input name is not a layer, - * nothing happens. If opacity is not a value between 0.0 and 1.0, then - * nothing happens. - * NOTE: this function exists solely to apply a highlighting/de-emphasis - * effect to a layer. When it is possible for a user to affect the opacity - * of a layer, we will need to allow this function to produce an undo-able - * action. - * @param {string} layerName - Name of the layer on which to set the opacity - * @param {Float} opacity - A float value in the range 0.0-1.0 - * @returns {void} - */ - - }, { - key: "setLayerOpacity", - value: function setLayerOpacity(layerName, opacity) { - if (typeof opacity !== 'number' || opacity < 0.0 || opacity > 1.0) { - return; - } - - var layer = this.layer_map[layerName]; - - if (layer) { - layer.setOpacity(opacity); - } - } - /** - * Create a clone of an element, updating its ID and its children's IDs when needed. - * @param {Element} el - DOM element to clone - * @returns {Element} - */ - - }, { - key: "copyElem", - value: function copyElem$1(el) { - var that = this; - - var getNextIdClosure = function getNextIdClosure() { - return that.getNextId(); - }; - - return copyElem(el, getNextIdClosure); - } - }]); - - return Drawing; -}(); -/** - * Called to ensure that drawings will or will not have randomized ids. - * The currentDrawing will have its nonce set if it doesn't already. - * @function module:draw.randomizeIds - * @param {boolean} enableRandomization - flag indicating if documents should have randomized ids - * @param {draw.Drawing} currentDrawing - * @returns {void} - */ - -var randomizeIds = function randomizeIds(enableRandomization, currentDrawing) { - randIds = enableRandomization === false ? RandomizeModes.NEVER_RANDOMIZE : RandomizeModes.ALWAYS_RANDOMIZE; - - if (randIds === RandomizeModes.ALWAYS_RANDOMIZE && !currentDrawing.getNonce()) { - currentDrawing.setNonce(Math.floor(Math.random() * 100001)); - } else if (randIds === RandomizeModes.NEVER_RANDOMIZE && currentDrawing.getNonce()) { - currentDrawing.clearNonce(); - } -}; // Layer API Functions - -/** -* Group: Layers. -*/ - -/** - * @see {@link https://api.jquery.com/jQuery.data/} - * @name external:jQuery.data - */ - -/** - * @interface module:draw.DrawCanvasInit - * @property {module:path.pathActions} pathActions - * @property {external:jQuery.data} elData - * @property {module:history.UndoManager} undoMgr - */ - -/** - * @function module:draw.DrawCanvasInit#getCurrentGroup - * @returns {Element} - */ - -/** - * @function module:draw.DrawCanvasInit#setCurrentGroup - * @param {Element} cg - * @returns {void} -*/ - -/** - * @function module:draw.DrawCanvasInit#getSelectedElements - * @returns {Element[]} the array with selected DOM elements -*/ - -/** - * @function module:draw.DrawCanvasInit#getSVGContent - * @returns {SVGSVGElement} - */ - -/** - * @function module:draw.DrawCanvasInit#getCurrentDrawing - * @returns {module:draw.Drawing} - */ - -/** - * @function module:draw.DrawCanvasInit#clearSelection - * @param {boolean} [noCall] - When `true`, does not call the "selected" handler - * @returns {void} -*/ - -/** - * Run the callback function associated with the given event. - * @function module:draw.DrawCanvasInit#call - * @param {"changed"|"contextset"} ev - String with the event name - * @param {module:svgcanvas.SvgCanvas#event:changed|module:svgcanvas.SvgCanvas#event:contextset} arg - Argument to pass through to the callback - * function. If the event is "changed", a (single-item) array of `Element`s is - * passed. If the event is "contextset", the arg is `null` or `Element`. - * @returns {void} - */ - -/** - * @function module:draw.DrawCanvasInit#addCommandToHistory - * @param {Command} cmd - * @returns {void} -*/ - -/** - * @function module:draw.DrawCanvasInit#changeSVGContent - * @returns {void} - */ - -var canvas_; -/** -* @function module:draw.init -* @param {module:draw.DrawCanvasInit} canvas -* @returns {void} -*/ - -var init$3 = function init(canvas) { - canvas_ = canvas; -}; -/** -* Updates layer system. -* @function module:draw.identifyLayers -* @returns {void} -*/ - -var identifyLayers = function identifyLayers() { - leaveContext(); - canvas_.getCurrentDrawing().identifyLayers(); -}; -/** -* Creates a new top-level layer in the drawing with the given name, sets the current layer -* to it, and then clears the selection. This function then calls the 'changed' handler. -* This is an undoable action. -* @function module:draw.createLayer -* @param {string} name - The given name -* @param {module:history.HistoryRecordingService} hrService -* @fires module:svgcanvas.SvgCanvas#event:changed -* @returns {void} -*/ - -var createLayer = function createLayer(name, hrService) { - var newLayer = canvas_.getCurrentDrawing().createLayer(name, historyRecordingService(hrService)); - canvas_.clearSelection(); - canvas_.call('changed', [newLayer]); -}; -/** - * Creates a new top-level layer in the drawing with the given name, copies all the current layer's contents - * to it, and then clears the selection. This function then calls the 'changed' handler. - * This is an undoable action. - * @function module:draw.cloneLayer - * @param {string} name - The given name. If the layer name exists, a new name will be generated. - * @param {module:history.HistoryRecordingService} hrService - History recording service - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - -var cloneLayer = function cloneLayer(name, hrService) { - // Clone the current layer and make the cloned layer the new current layer - var newLayer = canvas_.getCurrentDrawing().cloneLayer(name, historyRecordingService(hrService)); - canvas_.clearSelection(); - leaveContext(); - canvas_.call('changed', [newLayer]); -}; -/** -* Deletes the current layer from the drawing and then clears the selection. This function -* then calls the 'changed' handler. This is an undoable action. -* @function module:draw.deleteCurrentLayer -* @fires module:svgcanvas.SvgCanvas#event:changed -* @returns {boolean} `true` if an old layer group was found to delete -*/ - -var deleteCurrentLayer = function deleteCurrentLayer() { - var currentLayer = canvas_.getCurrentDrawing().getCurrentLayer(); - var _currentLayer = currentLayer, - nextSibling = _currentLayer.nextSibling; - var parent = currentLayer.parentNode; - currentLayer = canvas_.getCurrentDrawing().deleteCurrentLayer(); - - if (currentLayer) { - var batchCmd = new BatchCommand('Delete Layer'); // store in our Undo History - - batchCmd.addSubCommand(new RemoveElementCommand(currentLayer, nextSibling, parent)); - canvas_.addCommandToHistory(batchCmd); - canvas_.clearSelection(); - canvas_.call('changed', [parent]); - return true; - } - - return false; -}; -/** -* Sets the current layer. If the name is not a valid layer name, then this function returns -* false. Otherwise it returns true. This is not an undo-able action. -* @function module:draw.setCurrentLayer -* @param {string} name - The name of the layer you want to switch to. -* @returns {boolean} true if the current layer was switched, otherwise false -*/ - -var setCurrentLayer = function setCurrentLayer(name) { - var result = canvas_.getCurrentDrawing().setCurrentLayer(toXml(name)); - - if (result) { - canvas_.clearSelection(); - } - - return result; -}; -/** -* Renames the current layer. If the layer name is not valid (i.e. unique), then this function -* does nothing and returns `false`, otherwise it returns `true`. This is an undo-able action. -* @function module:draw.renameCurrentLayer -* @param {string} newName - the new name you want to give the current layer. This name must -* be unique among all layer names. -* @fires module:svgcanvas.SvgCanvas#event:changed -* @returns {boolean} Whether the rename succeeded -*/ - -var renameCurrentLayer = function renameCurrentLayer(newName) { - var drawing = canvas_.getCurrentDrawing(); - var layer = drawing.getCurrentLayer(); - - if (layer) { - var result = drawing.setCurrentLayerName(newName, historyRecordingService()); - - if (result) { - canvas_.call('changed', [layer]); - return true; - } - } - - return false; -}; -/** -* Changes the position of the current layer to the new value. If the new index is not valid, -* this function does nothing and returns false, otherwise it returns true. This is an -* undo-able action. -* @function module:draw.setCurrentLayerPosition -* @param {Integer} newPos - The zero-based index of the new position of the layer. This should be between -* 0 and (number of layers - 1) -* @returns {boolean} `true` if the current layer position was changed, `false` otherwise. -*/ - -var setCurrentLayerPosition = function setCurrentLayerPosition(newPos) { - var drawing = canvas_.getCurrentDrawing(); - var result = drawing.setCurrentLayerPosition(newPos); - - if (result) { - canvas_.addCommandToHistory(new MoveElementCommand(result.currentGroup, result.oldNextSibling, canvas_.getSVGContent())); - return true; - } - - return false; -}; -/** -* Sets the visibility of the layer. If the layer name is not valid, this function return -* `false`, otherwise it returns `true`. This is an undo-able action. -* @function module:draw.setLayerVisibility -* @param {string} layerName - The name of the layer to change the visibility -* @param {boolean} bVisible - Whether the layer should be visible -* @returns {boolean} true if the layer's visibility was set, false otherwise -*/ - -var setLayerVisibility = function setLayerVisibility(layerName, bVisible) { - var drawing = canvas_.getCurrentDrawing(); - var prevVisibility = drawing.getLayerVisibility(layerName); - var layer = drawing.setLayerVisibility(layerName, bVisible); - - if (layer) { - var oldDisplay = prevVisibility ? 'inline' : 'none'; - canvas_.addCommandToHistory(new ChangeElementCommand(layer, { - display: oldDisplay - }, 'Layer Visibility')); - } else { - return false; - } - - if (layer === drawing.getCurrentLayer()) { - canvas_.clearSelection(); - canvas_.pathActions.clear(); - } // call('changed', [selected]); - - - return true; -}; -/** -* Moves the selected elements to layerName. If the name is not a valid layer name, then `false` -* is returned. Otherwise it returns `true`. This is an undo-able action. -* @function module:draw.moveSelectedToLayer -* @param {string} layerName - The name of the layer you want to which you want to move the selected elements -* @returns {boolean} Whether the selected elements were moved to the layer. -*/ - -var moveSelectedToLayer = function moveSelectedToLayer(layerName) { - // find the layer - var drawing = canvas_.getCurrentDrawing(); - var layer = drawing.getLayerByName(layerName); - - if (!layer) { - return false; - } - - var batchCmd = new BatchCommand('Move Elements to Layer'); // loop for each selected element and move it - - var selElems = canvas_.getSelectedElements(); - var i = selElems.length; - - while (i--) { - var elem = selElems[i]; - - if (!elem) { - continue; - } - - var oldNextSibling = elem.nextSibling; // TODO: this is pretty brittle! - - var oldLayer = elem.parentNode; - layer.append(elem); - batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldLayer)); - } - - canvas_.addCommandToHistory(batchCmd); - return true; -}; -/** -* @function module:draw.mergeLayer -* @param {module:history.HistoryRecordingService} hrService -* @returns {void} -*/ - -var mergeLayer = function mergeLayer(hrService) { - canvas_.getCurrentDrawing().mergeLayer(historyRecordingService(hrService)); - canvas_.clearSelection(); - leaveContext(); - canvas_.changeSVGContent(); -}; -/** -* @function module:draw.mergeAllLayers -* @param {module:history.HistoryRecordingService} hrService -* @returns {void} -*/ - -var mergeAllLayers = function mergeAllLayers(hrService) { - canvas_.getCurrentDrawing().mergeAllLayers(historyRecordingService(hrService)); - canvas_.clearSelection(); - leaveContext(); - canvas_.changeSVGContent(); -}; -/** -* Return from a group context to the regular kind, make any previously -* disabled elements enabled again. -* @function module:draw.leaveContext -* @fires module:svgcanvas.SvgCanvas#event:contextset -* @returns {void} -*/ - -var leaveContext = function leaveContext() { - var len = disabledElems.length; - - if (len) { - for (var i = 0; i < len; i++) { - var elem = disabledElems[i]; - var orig = canvas_.elData(elem, 'orig_opac'); - - if (orig !== 1) { - elem.setAttribute('opacity', orig); - } else { - elem.removeAttribute('opacity'); - } - - elem.setAttribute('style', 'pointer-events: inherit'); - } - - disabledElems = []; - canvas_.clearSelection(true); - canvas_.call('contextset', null); - } - - canvas_.setCurrentGroup(null); -}; -/** -* Set the current context (for in-group editing). -* @function module:draw.setContext -* @param {Element} elem -* @fires module:svgcanvas.SvgCanvas#event:contextset -* @returns {void} -*/ - -var setContext = function setContext(elem) { - leaveContext(); - - if (typeof elem === 'string') { - elem = getElem(elem); - } // Edit inside this group - - - canvas_.setCurrentGroup(elem); // Disable other elements - - $$6(elem).parentsUntil('#svgcontent').andSelf().siblings().each(function () { - var opac = this.getAttribute('opacity') || 1; // Store the original's opacity - - canvas_.elData(this, 'orig_opac', opac); - this.setAttribute('opacity', opac * 0.33); - this.setAttribute('style', 'pointer-events: none'); - disabledElems.push(this); - }); - canvas_.clearSelection(); - canvas_.call('contextset', canvas_.getCurrentGroup()); -}; - -var REVERSE_NS = getReverseNS(); // Todo: Split out into core attributes, presentation attributes, etc. so consistent - -/** - * This defines which elements and attributes that we support (or at least - * don't remove). - * @type {PlainObject} - */ - -/* eslint-disable max-len */ - -var svgWhiteList_ = { - // SVG Elements - a: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'xlink:href', 'xlink:title'], - circle: ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'r', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], - clipPath: ['class', 'clipPathUnits', 'id'], - defs: [], - style: ['type'], - desc: [], - ellipse: ['class', 'clip-path', 'clip-rule', 'cx', 'cy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], - feGaussianBlur: ['class', 'color-interpolation-filters', 'id', 'requiredFeatures', 'stdDeviation'], - feMorphology: ['class', 'in', 'operator', 'radius'], - filter: ['class', 'color-interpolation-filters', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'requiredFeatures', 'width', 'x', 'xlink:href', 'y'], - foreignObject: ['class', 'font-size', 'height', 'id', 'opacity', 'requiredFeatures', 'style', 'transform', 'width', 'x', 'y'], - g: ['class', 'clip-path', 'clip-rule', 'id', 'display', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-anchor'], - image: ['class', 'clip-path', 'clip-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:href', 'xlink:title', 'y'], - line: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'y1', 'y2'], - linearGradient: ['class', 'id', 'gradientTransform', 'gradientUnits', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'x1', 'x2', 'xlink:href', 'y1', 'y2'], - marker: ['id', 'class', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'systemLanguage', 'viewBox'], - mask: ['class', 'height', 'id', 'maskContentUnits', 'maskUnits', 'width', 'x', 'y'], - metadata: ['class', 'id'], - path: ['class', 'clip-path', 'clip-rule', 'd', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], - pattern: ['class', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:href', 'y'], - polygon: ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'class', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], - polyline: ['class', 'clip-path', 'clip-rule', 'id', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'opacity', 'points', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform'], - radialGradient: ['class', 'cx', 'cy', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'requiredFeatures', 'spreadMethod', 'systemLanguage', 'xlink:href'], - rect: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'opacity', 'requiredFeatures', 'rx', 'ry', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'width', 'x', 'y'], - stop: ['class', 'id', 'offset', 'requiredFeatures', 'stop-color', 'stop-opacity', 'style', 'systemLanguage'], - svg: ['class', 'clip-path', 'clip-rule', 'filter', 'id', 'height', 'mask', 'preserveAspectRatio', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xmlns', 'xmlns:se', 'xmlns:xlink', 'y'], - "switch": ['class', 'id', 'requiredFeatures', 'systemLanguage'], - symbol: ['class', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'opacity', 'preserveAspectRatio', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'transform', 'viewBox'], - text: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'transform', 'x', 'xml:space', 'y'], - textPath: ['class', 'id', 'method', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'transform', 'xlink:href'], - title: [], - tspan: ['class', 'clip-path', 'clip-rule', 'dx', 'dy', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-style', 'font-weight', 'id', 'mask', 'opacity', 'requiredFeatures', 'rotate', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemLanguage', 'text-anchor', 'textLength', 'transform', 'x', 'xml:space', 'y'], - use: ['class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'height', 'id', 'mask', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'transform', 'width', 'x', 'xlink:href', 'y'], - // MathML Elements - annotation: ['encoding'], - 'annotation-xml': ['encoding'], - maction: ['actiontype', 'other', 'selection'], - math: ['class', 'id', 'display', 'xmlns'], - menclose: ['notation'], - merror: [], - mfrac: ['linethickness'], - mi: ['mathvariant'], - mmultiscripts: [], - mn: [], - mo: ['fence', 'lspace', 'maxsize', 'minsize', 'rspace', 'stretchy'], - mover: [], - mpadded: ['lspace', 'width', 'height', 'depth', 'voffset'], - mphantom: [], - mprescripts: [], - mroot: [], - mrow: ['xlink:href', 'xlink:type', 'xmlns:xlink'], - mspace: ['depth', 'height', 'width'], - msqrt: [], - mstyle: ['displaystyle', 'mathbackground', 'mathcolor', 'mathvariant', 'scriptlevel'], - msub: [], - msubsup: [], - msup: [], - mtable: ['align', 'columnalign', 'columnlines', 'columnspacing', 'displaystyle', 'equalcolumns', 'equalrows', 'frame', 'rowalign', 'rowlines', 'rowspacing', 'width'], - mtd: ['columnalign', 'columnspan', 'rowalign', 'rowspan'], - mtext: [], - mtr: ['columnalign', 'rowalign'], - munder: [], - munderover: [], - none: [], - semantics: [] -}; -/* eslint-enable max-len */ -// Produce a Namespace-aware version of svgWhitelist - -var svgWhiteListNS_ = {}; -Object.entries(svgWhiteList_).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - elt = _ref2[0], - atts = _ref2[1]; - - var attNS = {}; - Object.entries(atts).forEach(function (_ref3) { - var _ref4 = _slicedToArray(_ref3, 2), - i = _ref4[0], - att = _ref4[1]; - - if (att.includes(':')) { - var v = att.split(':'); - attNS[v[1]] = NS[v[0].toUpperCase()]; - } else { - attNS[att] = att === 'xmlns' ? NS.XMLNS : null; - } - }); - svgWhiteListNS_[elt] = attNS; -}); -/** -* Sanitizes the input node and its children. -* It only keeps what is allowed from our whitelist defined above. -* @function module:sanitize.sanitizeSvg -* @param {Text|Element} node - The DOM element to be checked (we'll also check its children) or text node to be cleaned up -* @returns {void} -*/ - -var sanitizeSvg = function sanitizeSvg(node) { - // Cleanup text nodes - if (node.nodeType === 3) { - // 3 === TEXT_NODE - // Trim whitespace - node.nodeValue = node.nodeValue.replace(/^\s+|\s+$/g, ''); // Remove if empty - - if (!node.nodeValue.length) { - node.remove(); - } - } // We only care about element nodes. - // Automatically return for all non-element nodes, such as comments, etc. - - - if (node.nodeType !== 1) { - // 1 == ELEMENT_NODE - return; - } - - var doc = node.ownerDocument; - var parent = node.parentNode; // can parent ever be null here? I think the root node's parent is the document... - - if (!doc || !parent) { - return; - } - - var allowedAttrs = svgWhiteList_[node.nodeName]; - var allowedAttrsNS = svgWhiteListNS_[node.nodeName]; // if this element is supported, sanitize it - - if (typeof allowedAttrs !== 'undefined') { - var seAttrs = []; - var i = node.attributes.length; - - while (i--) { - // if the attribute is not in our whitelist, then remove it - // could use jQuery's inArray(), but I don't know if that's any better - var attr = node.attributes.item(i); - var attrName = attr.nodeName; - var attrLocalName = attr.localName; - var attrNsURI = attr.namespaceURI; // Check that an attribute with the correct localName in the correct namespace is on - // our whitelist or is a namespace declaration for one of our allowed namespaces - - if (!({}.hasOwnProperty.call(allowedAttrsNS, attrLocalName) && attrNsURI === allowedAttrsNS[attrLocalName] && attrNsURI !== NS.XMLNS) && !(attrNsURI === NS.XMLNS && REVERSE_NS[attr.value])) { - // TODO(codedread): Programmatically add the se: attributes to the NS-aware whitelist. - // Bypassing the whitelist to allow se: prefixes. - // Is there a more appropriate way to do this? - if (attrName.startsWith('se:') || attrName.startsWith('data-')) { - seAttrs.push([attrName, attr.value]); - } - - node.removeAttributeNS(attrNsURI, attrLocalName); - } // Add spaces before negative signs where necessary - - - if (isGecko()) { - switch (attrName) { - case 'transform': - case 'gradientTransform': - case 'patternTransform': - { - var val = attr.value.replace(/(\d)-/g, '$1 -'); // const val = attr.value.replace(/(?<digit>\d)-/g, '$<digit> -'); - - node.setAttribute(attrName, val); - break; - } - } - } // For the style attribute, rewrite it in terms of XML presentational attributes - - - if (attrName === 'style') { - var props = attr.value.split(';'); - var p = props.length; - - while (p--) { - var _props$p$split = props[p].split(':'), - _props$p$split2 = _slicedToArray(_props$p$split, 2), - name = _props$p$split2[0], - _val = _props$p$split2[1]; - - var styleAttrName = (name || '').trim(); - - var styleAttrVal = (_val || '').trim(); // Now check that this attribute is supported - - - if (allowedAttrs.includes(styleAttrName)) { - node.setAttribute(styleAttrName, styleAttrVal); - } - } - - node.removeAttribute('style'); - } - } - - Object.values(seAttrs).forEach(function (_ref5) { - var _ref6 = _slicedToArray(_ref5, 2), - att = _ref6[0], - val = _ref6[1]; - - node.setAttributeNS(NS.SE, att, val); - }); // for some elements that have a xlink:href, ensure the URI refers to a local element - // (but not for links) - - var href = getHref(node); - - if (href && ['filter', 'linearGradient', 'pattern', 'radialGradient', 'textPath', 'use'].includes(node.nodeName)) { - // TODO: we simply check if the first character is a #, is this bullet-proof? - if (href[0] !== '#') { - // remove the attribute (but keep the element) - setHref(node, ''); - node.removeAttributeNS(NS.XLINK, 'href'); - } - } // Safari crashes on a <use> without a xlink:href, so we just remove the node here - - - if (node.nodeName === 'use' && !getHref(node)) { - node.remove(); - return; - } // if the element has attributes pointing to a non-local reference, - // need to remove the attribute - - - Object.values(['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke'], function (attr) { - var val = node.getAttribute(attr); - - if (val) { - val = getUrlFromAttr(val); // simply check for first character being a '#' - - if (val && val[0] !== '#') { - node.setAttribute(attr, ''); - node.removeAttribute(attr); - } - } - }); // recurse to children - - i = node.childNodes.length; - - while (i--) { - sanitizeSvg(node.childNodes.item(i)); - } // else (element not supported), remove it - - } else { - // remove all children from this node and insert them before this node - // TODO: in the case of animation elements this will hardly ever be correct - var children = []; - - while (node.hasChildNodes()) { - children.push(parent.insertBefore(node.firstChild, node)); - } // remove this node from the document altogether - - - node.remove(); // call sanitizeSvg on each of those children - - var _i = children.length; - - while (_i--) { - sanitizeSvg(children[_i]); - } - } -}; - -var $$7 = jQuery; // this is how we map paths to our preferred relative segment types - -var pathMap$1 = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a', 'H', 'h', 'V', 'v', 'S', 's', 'T', 't']; -/** - * @interface module:coords.EditorContext - */ - -/** - * @function module:coords.EditorContext#getGridSnapping - * @returns {boolean} - */ - -/** - * @function module:coords.EditorContext#getDrawing - * @returns {module:draw.Drawing} -*/ - -/** - * @function module:coords.EditorContext#getSVGRoot - * @returns {SVGSVGElement} -*/ - -var editorContext_$2 = null; -/** -* @function module:coords.init -* @param {module:svgcanvas.SvgCanvas#event:pointsAdded} editorContext -* @returns {void} -*/ - -var init$4 = function init(editorContext) { - editorContext_$2 = editorContext; -}; -/** - * Applies coordinate changes to an element based on the given matrix. - * @name module:coords.remapElement - * @type {module:path.EditorContext#remapElement} -*/ - -var remapElement = function remapElement(selected, changes, m) { - var remap = function remap(x, y) { - return transformPoint(x, y, m); - }, - scalew = function scalew(w) { - return m.a * w; - }, - scaleh = function scaleh(h) { - return m.d * h; - }, - doSnapping = editorContext_$2.getGridSnapping() && selected.parentNode.parentNode.localName === 'svg', - finishUp = function finishUp() { - if (doSnapping) { - Object.entries(changes).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - o = _ref2[0], - value = _ref2[1]; - - changes[o] = snapToGrid(value); - }); - } - - assignAttributes(selected, changes, 1000, true); - }, - box = getBBox(selected); - - for (var i = 0; i < 2; i++) { - var type = i === 0 ? 'fill' : 'stroke'; - var attrVal = selected.getAttribute(type); - - if (attrVal && attrVal.startsWith('url(')) { - if (m.a < 0 || m.d < 0) { - var grad = getRefElem(attrVal); - var newgrad = grad.cloneNode(true); - - if (m.a < 0) { - // flip x - var x1 = newgrad.getAttribute('x1'); - var x2 = newgrad.getAttribute('x2'); - newgrad.setAttribute('x1', -(x1 - 1)); - newgrad.setAttribute('x2', -(x2 - 1)); - } - - if (m.d < 0) { - // flip y - var y1 = newgrad.getAttribute('y1'); - var y2 = newgrad.getAttribute('y2'); - newgrad.setAttribute('y1', -(y1 - 1)); - newgrad.setAttribute('y2', -(y2 - 1)); - } - - newgrad.id = editorContext_$2.getDrawing().getNextId(); - findDefs().append(newgrad); - selected.setAttribute(type, 'url(#' + newgrad.id + ')'); - } // Not really working :( - // if (selected.tagName === 'path') { - // reorientGrads(selected, m); - // } - - } - } - - var elName = selected.tagName; - - if (elName === 'g' || elName === 'text' || elName === 'tspan' || elName === 'use') { - // if it was a translate, then just update x,y - if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && (m.e !== 0 || m.f !== 0)) { - // [T][M] = [M][T'] - // therefore [T'] = [M_inv][T][M] - var existing = transformListToTransform(selected).matrix, - tNew = matrixMultiply(existing.inverse(), m, existing); - changes.x = Number.parseFloat(changes.x) + tNew.e; - changes.y = Number.parseFloat(changes.y) + tNew.f; - } else { - // we just absorb all matrices into the element and don't do any remapping - var chlist = getTransformList(selected); - var mt = editorContext_$2.getSVGRoot().createSVGTransform(); - mt.setMatrix(matrixMultiply(transformListToTransform(chlist).matrix, m)); - chlist.clear(); - chlist.appendItem(mt); - } - } // now we have a set of changes and an applied reduced transform list - // we apply the changes directly to the DOM - - - switch (elName) { - case 'foreignObject': - case 'rect': - case 'image': - { - // Allow images to be inverted (give them matrix when flipped) - if (elName === 'image' && (m.a < 0 || m.d < 0)) { - // Convert to matrix - var _chlist = getTransformList(selected); - - var _mt = editorContext_$2.getSVGRoot().createSVGTransform(); - - _mt.setMatrix(matrixMultiply(transformListToTransform(_chlist).matrix, m)); - - _chlist.clear(); - - _chlist.appendItem(_mt); - } else { - var pt1 = remap(changes.x, changes.y); - changes.width = scalew(changes.width); - changes.height = scaleh(changes.height); - changes.x = pt1.x + Math.min(0, changes.width); - changes.y = pt1.y + Math.min(0, changes.height); - changes.width = Math.abs(changes.width); - changes.height = Math.abs(changes.height); - } - - finishUp(); - break; - } - - case 'ellipse': - { - var c = remap(changes.cx, changes.cy); - changes.cx = c.x; - changes.cy = c.y; - changes.rx = scalew(changes.rx); - changes.ry = scaleh(changes.ry); - changes.rx = Math.abs(changes.rx); - changes.ry = Math.abs(changes.ry); - finishUp(); - break; - } - - case 'circle': - { - var _c = remap(changes.cx, changes.cy); - - changes.cx = _c.x; - changes.cy = _c.y; // take the minimum of the new selected box's dimensions for the new circle radius - - var tbox = transformBox(box.x, box.y, box.width, box.height, m); - var w = tbox.tr.x - tbox.tl.x, - h = tbox.bl.y - tbox.tl.y; - changes.r = Math.min(w / 2, h / 2); - - if (changes.r) { - changes.r = Math.abs(changes.r); - } - - finishUp(); - break; - } - - case 'line': - { - var _pt = remap(changes.x1, changes.y1); - - var pt2 = remap(changes.x2, changes.y2); - changes.x1 = _pt.x; - changes.y1 = _pt.y; - changes.x2 = pt2.x; - changes.y2 = pt2.y; - } - // Fallthrough - - case 'text': - case 'tspan': - case 'use': - { - finishUp(); - break; - } - - case 'g': - { - var gsvg = $$7(selected).data('gsvg'); - - if (gsvg) { - assignAttributes(gsvg, changes, 1000, true); - } - - break; - } - - case 'polyline': - case 'polygon': - { - var len = changes.points.length; - - for (var _i = 0; _i < len; ++_i) { - var pt = changes.points[_i]; - - var _remap = remap(pt.x, pt.y), - x = _remap.x, - y = _remap.y; - - changes.points[_i].x = x; - changes.points[_i].y = y; - } // const len = changes.points.length; - - - var pstr = ''; - - for (var _i2 = 0; _i2 < len; ++_i2) { - var _pt2 = changes.points[_i2]; - pstr += _pt2.x + ',' + _pt2.y + ' '; - } - - selected.setAttribute('points', pstr); - break; - } - - case 'path': - { - var segList = selected.pathSegList; - var _len = segList.numberOfItems; - changes.d = []; - - for (var _i3 = 0; _i3 < _len; ++_i3) { - var seg = segList.getItem(_i3); - changes.d[_i3] = { - type: seg.pathSegType, - x: seg.x, - y: seg.y, - x1: seg.x1, - y1: seg.y1, - x2: seg.x2, - y2: seg.y2, - r1: seg.r1, - r2: seg.r2, - angle: seg.angle, - largeArcFlag: seg.largeArcFlag, - sweepFlag: seg.sweepFlag - }; - } - - _len = changes.d.length; - var firstseg = changes.d[0], - currentpt = remap(firstseg.x, firstseg.y); - changes.d[0].x = currentpt.x; - changes.d[0].y = currentpt.y; - - for (var _i4 = 1; _i4 < _len; ++_i4) { - var _seg = changes.d[_i4]; - var _type = _seg.type; // if absolute or first segment, we want to remap x, y, x1, y1, x2, y2 - // if relative, we want to scalew, scaleh - - if (_type % 2 === 0) { - // absolute - var thisx = _seg.x !== undefined ? _seg.x : currentpt.x, - // for V commands - thisy = _seg.y !== undefined ? _seg.y : currentpt.y; // for H commands - - var _pt3 = remap(thisx, thisy); - - var _pt4 = remap(_seg.x1, _seg.y1); - - var _pt5 = remap(_seg.x2, _seg.y2); - - _seg.x = _pt3.x; - _seg.y = _pt3.y; - _seg.x1 = _pt4.x; - _seg.y1 = _pt4.y; - _seg.x2 = _pt5.x; - _seg.y2 = _pt5.y; - _seg.r1 = scalew(_seg.r1); - _seg.r2 = scaleh(_seg.r2); - } else { - // relative - _seg.x = scalew(_seg.x); - _seg.y = scaleh(_seg.y); - _seg.x1 = scalew(_seg.x1); - _seg.y1 = scaleh(_seg.y1); - _seg.x2 = scalew(_seg.x2); - _seg.y2 = scaleh(_seg.y2); - _seg.r1 = scalew(_seg.r1); - _seg.r2 = scaleh(_seg.r2); - } - } // for each segment - - - var dstr = ''; - _len = changes.d.length; - - for (var _i5 = 0; _i5 < _len; ++_i5) { - var _seg2 = changes.d[_i5]; - var _type2 = _seg2.type; - dstr += pathMap$1[_type2]; - - switch (_type2) { - case 13: // relative horizontal line (h) - - case 12: - // absolute horizontal line (H) - dstr += _seg2.x + ' '; - break; - - case 15: // relative vertical line (v) - - case 14: - // absolute vertical line (V) - dstr += _seg2.y + ' '; - break; - - case 3: // relative move (m) - - case 5: // relative line (l) - - case 19: // relative smooth quad (t) - - case 2: // absolute move (M) - - case 4: // absolute line (L) - - case 18: - // absolute smooth quad (T) - dstr += _seg2.x + ',' + _seg2.y + ' '; - break; - - case 7: // relative cubic (c) - - case 6: - // absolute cubic (C) - dstr += _seg2.x1 + ',' + _seg2.y1 + ' ' + _seg2.x2 + ',' + _seg2.y2 + ' ' + _seg2.x + ',' + _seg2.y + ' '; - break; - - case 9: // relative quad (q) - - case 8: - // absolute quad (Q) - dstr += _seg2.x1 + ',' + _seg2.y1 + ' ' + _seg2.x + ',' + _seg2.y + ' '; - break; - - case 11: // relative elliptical arc (a) - - case 10: - // absolute elliptical arc (A) - dstr += _seg2.r1 + ',' + _seg2.r2 + ' ' + _seg2.angle + ' ' + Number(_seg2.largeArcFlag) + ' ' + Number(_seg2.sweepFlag) + ' ' + _seg2.x + ',' + _seg2.y + ' '; - break; - - case 17: // relative smooth cubic (s) - - case 16: - // absolute smooth cubic (S) - dstr += _seg2.x2 + ',' + _seg2.y2 + ' ' + _seg2.x + ',' + _seg2.y + ' '; - break; - } - } - - selected.setAttribute('d', dstr); - break; - } - } -}; - -/* globals jQuery */ -var $$8 = jQueryPluginSVG(jQuery); -var context_; -/** -* @interface module:recalculate.EditorContext -*/ - -/** - * @function module:recalculate.EditorContext#getSVGRoot - * @returns {SVGSVGElement} The root DOM element - */ - -/** - * @function module:recalculate.EditorContext#getStartTransform - * @returns {string} -*/ - -/** - * @function module:recalculate.EditorContext#setStartTransform - * @param {string} transform - * @returns {void} - */ - -/** -* @function module:recalculate.init -* @param {module:recalculate.EditorContext} editorContext -* @returns {void} -*/ - -var init$5 = function init(editorContext) { - context_ = editorContext; -}; -/** -* Updates a `<clipPath>`s values based on the given translation of an element. -* @function module:recalculate.updateClipPath -* @param {string} attr - The clip-path attribute value with the clipPath's ID -* @param {Float} tx - The translation's x value -* @param {Float} ty - The translation's y value -* @returns {void} -*/ - -var updateClipPath = function updateClipPath(attr, tx, ty) { - var path = getRefElem(attr).firstChild; - var cpXform = getTransformList(path); - var newxlate = context_.getSVGRoot().createSVGTransform(); - newxlate.setTranslate(tx, ty); - cpXform.appendItem(newxlate); // Update clipPath's dimensions - - recalculateDimensions(path); -}; -/** -* Decides the course of action based on the element's transform list. -* @function module:recalculate.recalculateDimensions -* @param {Element} selected - The DOM element to recalculate -* @returns {Command} Undo command object with the resulting change -*/ - -var recalculateDimensions = function recalculateDimensions(selected) { - if (isNullish(selected)) { - return null; - } // Firefox Issue - 1081 - - - if (selected.nodeName === 'svg' && navigator.userAgent.includes('Firefox/20')) { - return null; - } - - var svgroot = context_.getSVGRoot(); - var tlist = getTransformList(selected); // remove any unnecessary transforms - - if (tlist && tlist.numberOfItems > 0) { - var k = tlist.numberOfItems; - var noi = k; - - while (k--) { - var xform = tlist.getItem(k); - - if (xform.type === 0) { - tlist.removeItem(k); // remove identity matrices - } else if (xform.type === 1) { - if (isIdentity(xform.matrix)) { - if (noi === 1) { - // Overcome Chrome bug (though only when noi is 1) with - // `removeItem` preventing `removeAttribute` from - // subsequently working - // See https://bugs.chromium.org/p/chromium/issues/detail?id=843901 - selected.removeAttribute('transform'); - return null; - } - - tlist.removeItem(k); - } // remove zero-degree rotations - - } else if (xform.type === 4) { - if (xform.angle === 0) { - tlist.removeItem(k); - } - } - } // End here if all it has is a rotation - - - if (tlist.numberOfItems === 1 && getRotationAngle(selected)) { - return null; - } - } // if this element had no transforms, we are done - - - if (!tlist || tlist.numberOfItems === 0) { - // Chrome apparently had a bug that requires clearing the attribute first. - selected.setAttribute('transform', ''); // However, this still next line currently doesn't work at all in Chrome - - selected.removeAttribute('transform'); // selected.transform.baseVal.clear(); // Didn't help for Chrome bug - - return null; - } // TODO: Make this work for more than 2 - - - if (tlist) { - var mxs = []; - var _k = tlist.numberOfItems; - - while (_k--) { - var _xform = tlist.getItem(_k); - - if (_xform.type === 1) { - mxs.push([_xform.matrix, _k]); - } else if (mxs.length) { - mxs = []; - } - } - - if (mxs.length === 2) { - var mNew = svgroot.createSVGTransformFromMatrix(matrixMultiply(mxs[1][0], mxs[0][0])); - tlist.removeItem(mxs[0][1]); - tlist.removeItem(mxs[1][1]); - tlist.insertItemBefore(mNew, mxs[1][1]); - } // combine matrix + translate - - - _k = tlist.numberOfItems; - - if (_k >= 2 && tlist.getItem(_k - 2).type === 1 && tlist.getItem(_k - 1).type === 2) { - var mt = svgroot.createSVGTransform(); - var m = matrixMultiply(tlist.getItem(_k - 2).matrix, tlist.getItem(_k - 1).matrix); - mt.setMatrix(m); - tlist.removeItem(_k - 2); - tlist.removeItem(_k - 2); - tlist.appendItem(mt); - } - } // If it still has a single [M] or [R][M], return null too (prevents BatchCommand from being returned). - - - switch (selected.tagName) { - // Ignore these elements, as they can absorb the [M] - case 'line': - case 'polyline': - case 'polygon': - case 'path': - break; - - default: - if (tlist.numberOfItems === 1 && tlist.getItem(0).type === 1 || tlist.numberOfItems === 2 && tlist.getItem(0).type === 1 && tlist.getItem(0).type === 4) { - return null; - } - - } // Grouped SVG element - - - var gsvg = $$8(selected).data('gsvg'); // we know we have some transforms, so set up return variable - - var batchCmd = new BatchCommand('Transform'); // store initial values that will be affected by reducing the transform list - - var changes = {}; - var initial = null; - var attrs = []; - - switch (selected.tagName) { - case 'line': - attrs = ['x1', 'y1', 'x2', 'y2']; - break; - - case 'circle': - attrs = ['cx', 'cy', 'r']; - break; - - case 'ellipse': - attrs = ['cx', 'cy', 'rx', 'ry']; - break; - - case 'foreignObject': - case 'rect': - case 'image': - attrs = ['width', 'height', 'x', 'y']; - break; - - case 'use': - case 'text': - case 'tspan': - attrs = ['x', 'y']; - break; - - case 'polygon': - case 'polyline': - { - initial = {}; - initial.points = selected.getAttribute('points'); - var list = selected.points; - var len = list.numberOfItems; - changes.points = new Array(len); - - for (var i = 0; i < len; ++i) { - var pt = list.getItem(i); - changes.points[i] = { - x: pt.x, - y: pt.y - }; - } - - break; - } - - case 'path': - initial = {}; - initial.d = selected.getAttribute('d'); - changes.d = selected.getAttribute('d'); - break; - } // switch on element type to get initial values - - - if (attrs.length) { - changes = $$8(selected).attr(attrs); - $$8.each(changes, function (attr, val) { - changes[attr] = convertToNum(attr, val); - }); - } else if (gsvg) { - // GSVG exception - changes = { - x: $$8(gsvg).attr('x') || 0, - y: $$8(gsvg).attr('y') || 0 - }; - } // if we haven't created an initial array in polygon/polyline/path, then - // make a copy of initial values and include the transform - - - if (isNullish(initial)) { - initial = $$8.extend(true, {}, changes); - $$8.each(initial, function (attr, val) { - initial[attr] = convertToNum(attr, val); - }); - } // save the start transform value too - - - initial.transform = context_.getStartTransform() || ''; - var oldcenter, newcenter; // if it's a regular group, we have special processing to flatten transforms - - if (selected.tagName === 'g' && !gsvg || selected.tagName === 'a') { - var box = getBBox(selected); - oldcenter = { - x: box.x + box.width / 2, - y: box.y + box.height / 2 - }; - newcenter = transformPoint(box.x + box.width / 2, box.y + box.height / 2, transformListToTransform(tlist).matrix); // let m = svgroot.createSVGMatrix(); - // temporarily strip off the rotate and save the old center - - var gangle = getRotationAngle(selected); - - if (gangle) { - var a = gangle * Math.PI / 180; - var s; - - if (Math.abs(a) > 1.0e-10) { - s = Math.sin(a) / (1 - Math.cos(a)); - } else { - // TODO: This blows up if the angle is exactly 0! - s = 2 / a; - } - - for (var _i = 0; _i < tlist.numberOfItems; ++_i) { - var _xform2 = tlist.getItem(_i); - - if (_xform2.type === 4) { - // extract old center through mystical arts - var rm = _xform2.matrix; - oldcenter.y = (s * rm.e + rm.f) / 2; - oldcenter.x = (rm.e - s * rm.f) / 2; - tlist.removeItem(_i); - break; - } - } - } - - var N = tlist.numberOfItems; - var tx = 0, - ty = 0, - operation = 0; - var firstM; - - if (N) { - firstM = tlist.getItem(0).matrix; - } - - var oldStartTransform; // first, if it was a scale then the second-last transform will be it - - if (N >= 3 && tlist.getItem(N - 2).type === 3 && tlist.getItem(N - 3).type === 2 && tlist.getItem(N - 1).type === 2) { - operation = 3; // scale - // if the children are unrotated, pass the scale down directly - // otherwise pass the equivalent matrix() down directly - - var tm = tlist.getItem(N - 3).matrix, - sm = tlist.getItem(N - 2).matrix, - tmn = tlist.getItem(N - 1).matrix; - var children = selected.childNodes; - var c = children.length; - - while (c--) { - var child = children.item(c); - tx = 0; - ty = 0; - - if (child.nodeType === 1) { - var childTlist = getTransformList(child); // some children might not have a transform (<metadata>, <defs>, etc) - - if (!childTlist) { - continue; - } - - var _m = transformListToTransform(childTlist).matrix; // Convert a matrix to a scale if applicable - // if (hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) { - // if (m.b==0 && m.c==0 && m.e==0 && m.f==0) { - // childTlist.removeItem(0); - // const translateOrigin = svgroot.createSVGTransform(), - // scale = svgroot.createSVGTransform(), - // translateBack = svgroot.createSVGTransform(); - // translateOrigin.setTranslate(0, 0); - // scale.setScale(m.a, m.d); - // translateBack.setTranslate(0, 0); - // childTlist.appendItem(translateBack); - // childTlist.appendItem(scale); - // childTlist.appendItem(translateOrigin); - // } - // } - - var angle = getRotationAngle(child); - oldStartTransform = context_.getStartTransform(); // const childxforms = []; - - context_.setStartTransform(child.getAttribute('transform')); - - if (angle || hasMatrixTransform(childTlist)) { - var e2t = svgroot.createSVGTransform(); - e2t.setMatrix(matrixMultiply(tm, sm, tmn, _m)); - childTlist.clear(); - childTlist.appendItem(e2t); // childxforms.push(e2t); - // if not rotated or skewed, push the [T][S][-T] down to the child - } else { - // update the transform list with translate,scale,translate - // slide the [T][S][-T] from the front to the back - // [T][S][-T][M] = [M][T2][S2][-T2] - // (only bringing [-T] to the right of [M]) - // [T][S][-T][M] = [T][S][M][-T2] - // [-T2] = [M_inv][-T][M] - var t2n = matrixMultiply(_m.inverse(), tmn, _m); // [T2] is always negative translation of [-T2] - - var t2 = svgroot.createSVGMatrix(); - t2.e = -t2n.e; - t2.f = -t2n.f; // [T][S][-T][M] = [M][T2][S2][-T2] - // [S2] = [T2_inv][M_inv][T][S][-T][M][-T2_inv] - - var s2 = matrixMultiply(t2.inverse(), _m.inverse(), tm, sm, tmn, _m, t2n.inverse()); - var translateOrigin = svgroot.createSVGTransform(), - scale = svgroot.createSVGTransform(), - translateBack = svgroot.createSVGTransform(); - translateOrigin.setTranslate(t2n.e, t2n.f); - scale.setScale(s2.a, s2.d); - translateBack.setTranslate(t2.e, t2.f); - childTlist.appendItem(translateBack); - childTlist.appendItem(scale); - childTlist.appendItem(translateOrigin); // childxforms.push(translateBack); - // childxforms.push(scale); - // childxforms.push(translateOrigin); - // logMatrix(translateBack.matrix); - // logMatrix(scale.matrix); - } // not rotated - - - batchCmd.addSubCommand(recalculateDimensions(child)); // TODO: If any <use> have this group as a parent and are - // referencing this child, then we need to impose a reverse - // scale on it so that when it won't get double-translated - // const uses = selected.getElementsByTagNameNS(NS.SVG, 'use'); - // const href = '#' + child.id; - // let u = uses.length; - // while (u--) { - // const useElem = uses.item(u); - // if (href == getHref(useElem)) { - // const usexlate = svgroot.createSVGTransform(); - // usexlate.setTranslate(-tx,-ty); - // getTransformList(useElem).insertItemBefore(usexlate,0); - // batchCmd.addSubCommand( recalculateDimensions(useElem) ); - // } - // } - - context_.setStartTransform(oldStartTransform); - } // element - - } // for each child - // Remove these transforms from group - - - tlist.removeItem(N - 1); - tlist.removeItem(N - 2); - tlist.removeItem(N - 3); - } else if (N >= 3 && tlist.getItem(N - 1).type === 1) { - operation = 3; // scale - - var _m2 = transformListToTransform(tlist).matrix; - - var _e2t = svgroot.createSVGTransform(); - - _e2t.setMatrix(_m2); - - tlist.clear(); - tlist.appendItem(_e2t); // next, check if the first transform was a translate - // if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ] - // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] - } else if ((N === 1 || N > 1 && tlist.getItem(1).type !== 3) && tlist.getItem(0).type === 2) { - operation = 2; // translate - - var T_M = transformListToTransform(tlist).matrix; - tlist.removeItem(0); - var mInv = transformListToTransform(tlist).matrix.inverse(); - var M2 = matrixMultiply(mInv, T_M); - tx = M2.e; - ty = M2.f; - - if (tx !== 0 || ty !== 0) { - // we pass the translates down to the individual children - var _children = selected.childNodes; - var _c = _children.length; - var clipPathsDone = []; - - while (_c--) { - var _child = _children.item(_c); - - if (_child.nodeType === 1) { - // Check if child has clip-path - if (_child.getAttribute('clip-path')) { - // tx, ty - var attr = _child.getAttribute('clip-path'); - - if (!clipPathsDone.includes(attr)) { - updateClipPath(attr, tx, ty); - clipPathsDone.push(attr); - } - } - - oldStartTransform = context_.getStartTransform(); - context_.setStartTransform(_child.getAttribute('transform')); - - var _childTlist = getTransformList(_child); // some children might not have a transform (<metadata>, <defs>, etc) - - - if (_childTlist) { - var newxlate = svgroot.createSVGTransform(); - newxlate.setTranslate(tx, ty); - - if (_childTlist.numberOfItems) { - _childTlist.insertItemBefore(newxlate, 0); - } else { - _childTlist.appendItem(newxlate); - } - - batchCmd.addSubCommand(recalculateDimensions(_child)); // If any <use> have this group as a parent and are - // referencing this child, then impose a reverse translate on it - // so that when it won't get double-translated - - var uses = selected.getElementsByTagNameNS(NS.SVG, 'use'); - var href = '#' + _child.id; - var u = uses.length; - - while (u--) { - var useElem = uses.item(u); - - if (href === getHref(useElem)) { - var usexlate = svgroot.createSVGTransform(); - usexlate.setTranslate(-tx, -ty); - getTransformList(useElem).insertItemBefore(usexlate, 0); - batchCmd.addSubCommand(recalculateDimensions(useElem)); - } - } - - context_.setStartTransform(oldStartTransform); - } - } - } - - context_.setStartTransform(oldStartTransform); - } // else, a matrix imposition from a parent group - // keep pushing it down to the children - - } else if (N === 1 && tlist.getItem(0).type === 1 && !gangle) { - operation = 1; - var _m3 = tlist.getItem(0).matrix, - _children2 = selected.childNodes; - var _c2 = _children2.length; - - while (_c2--) { - var _child2 = _children2.item(_c2); - - if (_child2.nodeType === 1) { - oldStartTransform = context_.getStartTransform(); - context_.setStartTransform(_child2.getAttribute('transform')); - - var _childTlist2 = getTransformList(_child2); - - if (!_childTlist2) { - continue; - } - - var em = matrixMultiply(_m3, transformListToTransform(_childTlist2).matrix); - var e2m = svgroot.createSVGTransform(); - e2m.setMatrix(em); - - _childTlist2.clear(); - - _childTlist2.appendItem(e2m, 0); - - batchCmd.addSubCommand(recalculateDimensions(_child2)); - context_.setStartTransform(oldStartTransform); // Convert stroke - // TODO: Find out if this should actually happen somewhere else - - var sw = _child2.getAttribute('stroke-width'); - - if (_child2.getAttribute('stroke') !== 'none' && !isNaN(sw)) { - var avg = (Math.abs(em.a) + Math.abs(em.d)) / 2; - - _child2.setAttribute('stroke-width', sw * avg); - } - } - } - - tlist.clear(); // else it was just a rotate - } else { - if (gangle) { - var newRot = svgroot.createSVGTransform(); - newRot.setRotate(gangle, newcenter.x, newcenter.y); - - if (tlist.numberOfItems) { - tlist.insertItemBefore(newRot, 0); - } else { - tlist.appendItem(newRot); - } - } - - if (tlist.numberOfItems === 0) { - selected.removeAttribute('transform'); - } - - return null; - } // if it was a translate, put back the rotate at the new center - - - if (operation === 2) { - if (gangle) { - newcenter = { - x: oldcenter.x + firstM.e, - y: oldcenter.y + firstM.f - }; - - var _newRot = svgroot.createSVGTransform(); - - _newRot.setRotate(gangle, newcenter.x, newcenter.y); - - if (tlist.numberOfItems) { - tlist.insertItemBefore(_newRot, 0); - } else { - tlist.appendItem(_newRot); - } - } // if it was a resize - - } else if (operation === 3) { - var _m4 = transformListToTransform(tlist).matrix; - var roldt = svgroot.createSVGTransform(); - roldt.setRotate(gangle, oldcenter.x, oldcenter.y); - var rold = roldt.matrix; - var rnew = svgroot.createSVGTransform(); - rnew.setRotate(gangle, newcenter.x, newcenter.y); - - var rnewInv = rnew.matrix.inverse(), - _mInv = _m4.inverse(), - extrat = matrixMultiply(_mInv, rnewInv, rold, _m4); - - tx = extrat.e; - ty = extrat.f; - - if (tx !== 0 || ty !== 0) { - // now push this transform down to the children - // we pass the translates down to the individual children - var _children3 = selected.childNodes; - var _c3 = _children3.length; - - while (_c3--) { - var _child3 = _children3.item(_c3); - - if (_child3.nodeType === 1) { - oldStartTransform = context_.getStartTransform(); - context_.setStartTransform(_child3.getAttribute('transform')); - - var _childTlist3 = getTransformList(_child3); - - var _newxlate = svgroot.createSVGTransform(); - - _newxlate.setTranslate(tx, ty); - - if (_childTlist3.numberOfItems) { - _childTlist3.insertItemBefore(_newxlate, 0); - } else { - _childTlist3.appendItem(_newxlate); - } - - batchCmd.addSubCommand(recalculateDimensions(_child3)); - context_.setStartTransform(oldStartTransform); - } - } - } - - if (gangle) { - if (tlist.numberOfItems) { - tlist.insertItemBefore(rnew, 0); - } else { - tlist.appendItem(rnew); - } - } - } // else, it's a non-group - - } else { - // TODO: box might be null for some elements (<metadata> etc), need to handle this - var _box = getBBox(selected); // Paths (and possbly other shapes) will have no BBox while still in <defs>, - // but we still may need to recalculate them (see issue 595). - // TODO: Figure out how to get BBox from these elements in case they - // have a rotation transform - - - if (!_box && selected.tagName !== 'path') return null; - - var _m5; // = svgroot.createSVGMatrix(); - // temporarily strip off the rotate and save the old center - - - var _angle = getRotationAngle(selected); - - if (_angle) { - oldcenter = { - x: _box.x + _box.width / 2, - y: _box.y + _box.height / 2 - }; - newcenter = transformPoint(_box.x + _box.width / 2, _box.y + _box.height / 2, transformListToTransform(tlist).matrix); - - var _a = _angle * Math.PI / 180; - - var _s = Math.abs(_a) > 1.0e-10 ? Math.sin(_a) / (1 - Math.cos(_a)) // TODO: This blows up if the angle is exactly 0! - : 2 / _a; - - for (var _i2 = 0; _i2 < tlist.numberOfItems; ++_i2) { - var _xform3 = tlist.getItem(_i2); - - if (_xform3.type === 4) { - // extract old center through mystical arts - var _rm = _xform3.matrix; - oldcenter.y = (_s * _rm.e + _rm.f) / 2; - oldcenter.x = (_rm.e - _s * _rm.f) / 2; - tlist.removeItem(_i2); - break; - } - } - } // 2 = translate, 3 = scale, 4 = rotate, 1 = matrix imposition - - - var _operation = 0; - var _N = tlist.numberOfItems; // Check if it has a gradient with userSpaceOnUse, in which case - // adjust it by recalculating the matrix transform. - // TODO: Make this work in Webkit using transformlist.SVGTransformList - - if (!isWebkit()) { - var fill = selected.getAttribute('fill'); - - if (fill && fill.startsWith('url(')) { - var paint = getRefElem(fill); - var type = 'pattern'; - if (paint.tagName !== type) type = 'gradient'; - var attrVal = paint.getAttribute(type + 'Units'); - - if (attrVal === 'userSpaceOnUse') { - // Update the userSpaceOnUse element - _m5 = transformListToTransform(tlist).matrix; - var gtlist = getTransformList(paint); - var gmatrix = transformListToTransform(gtlist).matrix; - _m5 = matrixMultiply(_m5, gmatrix); - var mStr = 'matrix(' + [_m5.a, _m5.b, _m5.c, _m5.d, _m5.e, _m5.f].join(',') + ')'; - paint.setAttribute(type + 'Transform', mStr); - } - } - } // first, if it was a scale of a non-skewed element, then the second-last - // transform will be the [S] - // if we had [M][T][S][T] we want to extract the matrix equivalent of - // [T][S][T] and push it down to the element - - - if (_N >= 3 && tlist.getItem(_N - 2).type === 3 && tlist.getItem(_N - 3).type === 2 && tlist.getItem(_N - 1).type === 2) { - // Removed this so a <use> with a given [T][S][T] would convert to a matrix. - // Is that bad? - // && selected.nodeName != 'use' - _operation = 3; // scale - - _m5 = transformListToTransform(tlist, _N - 3, _N - 1).matrix; - tlist.removeItem(_N - 1); - tlist.removeItem(_N - 2); - tlist.removeItem(_N - 3); // if we had [T][S][-T][M], then this was a skewed element being resized - // Thus, we simply combine it all into one matrix - } else if (_N === 4 && tlist.getItem(_N - 1).type === 1) { - _operation = 3; // scale - - _m5 = transformListToTransform(tlist).matrix; - - var _e2t2 = svgroot.createSVGTransform(); - - _e2t2.setMatrix(_m5); - - tlist.clear(); - tlist.appendItem(_e2t2); // reset the matrix so that the element is not re-mapped - - _m5 = svgroot.createSVGMatrix(); // if we had [R][T][S][-T][M], then this was a rotated matrix-element - // if we had [T1][M] we want to transform this into [M][T2] - // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2] - // down to the element - } else if ((_N === 1 || _N > 1 && tlist.getItem(1).type !== 3) && tlist.getItem(0).type === 2) { - _operation = 2; // translate - - var oldxlate = tlist.getItem(0).matrix, - meq = transformListToTransform(tlist, 1).matrix, - meqInv = meq.inverse(); - _m5 = matrixMultiply(meqInv, oldxlate, meq); - tlist.removeItem(0); // else if this child now has a matrix imposition (from a parent group) - // we might be able to simplify - } else if (_N === 1 && tlist.getItem(0).type === 1 && !_angle) { - // Remap all point-based elements - _m5 = transformListToTransform(tlist).matrix; - - switch (selected.tagName) { - case 'line': - changes = $$8(selected).attr(['x1', 'y1', 'x2', 'y2']); - // Fallthrough - - case 'polyline': - case 'polygon': - changes.points = selected.getAttribute('points'); - - if (changes.points) { - var _list = selected.points; - var _len = _list.numberOfItems; - changes.points = new Array(_len); - - for (var _i3 = 0; _i3 < _len; ++_i3) { - var _pt = _list.getItem(_i3); - - changes.points[_i3] = { - x: _pt.x, - y: _pt.y - }; - } - } - - // Fallthrough - - case 'path': - changes.d = selected.getAttribute('d'); - _operation = 1; - tlist.clear(); - break; - } // if it was a rotation, put the rotate back and return without a command - // (this function has zero work to do for a rotate()) - - } else { - // operation = 4; // rotation - if (_angle) { - var _newRot2 = svgroot.createSVGTransform(); - - _newRot2.setRotate(_angle, newcenter.x, newcenter.y); - - if (tlist.numberOfItems) { - tlist.insertItemBefore(_newRot2, 0); - } else { - tlist.appendItem(_newRot2); - } - } - - if (tlist.numberOfItems === 0) { - selected.removeAttribute('transform'); - } - - return null; - } // if it was a translate or resize, we need to remap the element and absorb the xform - - - if (_operation === 1 || _operation === 2 || _operation === 3) { - remapElement(selected, changes, _m5); - } // if we are remapping - // if it was a translate, put back the rotate at the new center - - - if (_operation === 2) { - if (_angle) { - if (!hasMatrixTransform(tlist)) { - newcenter = { - x: oldcenter.x + _m5.e, - y: oldcenter.y + _m5.f - }; - } - - var _newRot3 = svgroot.createSVGTransform(); - - _newRot3.setRotate(_angle, newcenter.x, newcenter.y); - - if (tlist.numberOfItems) { - tlist.insertItemBefore(_newRot3, 0); - } else { - tlist.appendItem(_newRot3); - } - } // We have special processing for tspans: Tspans are not transformable - // but they can have x,y coordinates (sigh). Thus, if this was a translate, - // on a text element, also translate any tspan children. - - - if (selected.tagName === 'text') { - var _children4 = selected.childNodes; - var _c4 = _children4.length; - - while (_c4--) { - var _child4 = _children4.item(_c4); - - if (_child4.tagName === 'tspan') { - var tspanChanges = { - x: $$8(_child4).attr('x') || 0, - y: $$8(_child4).attr('y') || 0 - }; - remapElement(_child4, tspanChanges, _m5); - } - } - } // [Rold][M][T][S][-T] became [Rold][M] - // we want it to be [Rnew][M][Tr] where Tr is the - // translation required to re-center it - // Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M] - - } else if (_operation === 3 && _angle) { - var _transformListToTrans = transformListToTransform(tlist), - matrix = _transformListToTrans.matrix; - - var _roldt = svgroot.createSVGTransform(); - - _roldt.setRotate(_angle, oldcenter.x, oldcenter.y); - - var _rold = _roldt.matrix; - - var _rnew = svgroot.createSVGTransform(); - - _rnew.setRotate(_angle, newcenter.x, newcenter.y); - - var _rnewInv = _rnew.matrix.inverse(); - - var _mInv2 = matrix.inverse(); - - var _extrat = matrixMultiply(_mInv2, _rnewInv, _rold, matrix); - - remapElement(selected, changes, _extrat); - - if (_angle) { - if (tlist.numberOfItems) { - tlist.insertItemBefore(_rnew, 0); - } else { - tlist.appendItem(_rnew); - } - } - } - } // a non-group - // if the transform list has been emptied, remove it - - - if (tlist.numberOfItems === 0) { - selected.removeAttribute('transform'); - } - - batchCmd.addSubCommand(new ChangeElementCommand(selected, initial)); - return batchCmd; -}; - -var $$9 = jQuery; -var svgFactory_; -var config_; -var selectorManager_; // A Singleton - -var gripRadius = isTouch() ? 10 : 4; -/** -* Private class for DOM element selection boxes. -*/ - -var Selector = /*#__PURE__*/function () { - /** - * @param {Integer} id - Internally identify the selector - * @param {Element} elem - DOM element associated with this selector - * @param {module:utilities.BBoxObject} [bbox] - Optional bbox to use for initialization (prevents duplicate `getBBox` call). - */ - function Selector(id, elem, bbox) { - _classCallCheck(this, Selector); - - // this is the selector's unique number - this.id = id; // this holds a reference to the element for which this selector is being used - - this.selectedElement = elem; // this is a flag used internally to track whether the selector is being used or not - - this.locked = true; // this holds a reference to the <g> element that holds all visual elements of the selector - - this.selectorGroup = svgFactory_.createSVGElement({ - element: 'g', - attr: { - id: 'selectorGroup' + this.id - } - }); // this holds a reference to the path rect - - this.selectorRect = this.selectorGroup.appendChild(svgFactory_.createSVGElement({ - element: 'path', - attr: { - id: 'selectedBox' + this.id, - fill: 'none', - stroke: '#22C', - 'stroke-width': '1', - 'stroke-dasharray': '5,5', - // need to specify this so that the rect is not selectable - style: 'pointer-events:none' - } - })); // this holds a reference to the grip coordinates for this selector - - this.gripCoords = { - nw: null, - n: null, - ne: null, - e: null, - se: null, - s: null, - sw: null, - w: null - }; - this.reset(this.selectedElement, bbox); - } - /** - * Used to reset the id and element that the selector is attached to. - * @param {Element} e - DOM element associated with this selector - * @param {module:utilities.BBoxObject} bbox - Optional bbox to use for reset (prevents duplicate getBBox call). - * @returns {void} - */ - - - _createClass(Selector, [{ - key: "reset", - value: function reset(e, bbox) { - this.locked = true; - this.selectedElement = e; - this.resize(bbox); - this.selectorGroup.setAttribute('display', 'inline'); - } - /** - * Show the resize grips of this selector. - * @param {boolean} show - Indicates whether grips should be shown or not - * @returns {void} - */ - - }, { - key: "showGrips", - value: function showGrips(show) { - var bShow = show ? 'inline' : 'none'; - selectorManager_.selectorGripsGroup.setAttribute('display', bShow); - var elem = this.selectedElement; - this.hasGrips = show; - - if (elem && show) { - this.selectorGroup.append(selectorManager_.selectorGripsGroup); - Selector.updateGripCursors(getRotationAngle(elem)); - } - } - /** - * Updates the selector to match the element's size. - * @param {module:utilities.BBoxObject} [bbox] - BBox to use for resize (prevents duplicate getBBox call). - * @returns {void} - */ - - }, { - key: "resize", - value: function resize(bbox) { - var selectedBox = this.selectorRect, - mgr = selectorManager_, - selectedGrips = mgr.selectorGrips, - selected = this.selectedElement, - sw = selected.getAttribute('stroke-width'), - currentZoom = svgFactory_.getCurrentZoom(); - var offset = 1 / currentZoom; - - if (selected.getAttribute('stroke') !== 'none' && !isNaN(sw)) { - offset += sw / 2; - } - - var tagName = selected.tagName; - - if (tagName === 'text') { - offset += 2 / currentZoom; - } // loop and transform our bounding box until we reach our first rotation - - - var tlist = getTransformList(selected); - var m = transformListToTransform(tlist).matrix; // This should probably be handled somewhere else, but for now - // it keeps the selection box correctly positioned when zoomed - - m.e *= currentZoom; - m.f *= currentZoom; - - if (!bbox) { - bbox = getBBox(selected); - } // TODO: getBBox (previous line) already knows to call getStrokedBBox when tagName === 'g'. Remove this? - // TODO: getBBox doesn't exclude 'gsvg' and calls getStrokedBBox for any 'g'. Should getBBox be updated? - - - if (tagName === 'g' && !$$9.data(selected, 'gsvg')) { - // The bbox for a group does not include stroke vals, so we - // get the bbox based on its children. - var strokedBbox = getStrokedBBox([selected.childNodes]); - - if (strokedBbox) { - bbox = strokedBbox; - } - } // apply the transforms - - - var l = bbox.x, - t = bbox.y, - w = bbox.width, - h = bbox.height; // bbox = {x: l, y: t, width: w, height: h}; // Not in use - // we need to handle temporary transforms too - // if skewed, get its transformed box, then find its axis-aligned bbox - // * - - offset *= currentZoom; - var nbox = transformBox(l * currentZoom, t * currentZoom, w * currentZoom, h * currentZoom, m), - aabox = nbox.aabox; - var nbax = aabox.x - offset, - nbay = aabox.y - offset, - nbaw = aabox.width + offset * 2, - nbah = aabox.height + offset * 2; // now if the shape is rotated, un-rotate it - - var cx = nbax + nbaw / 2, - cy = nbay + nbah / 2; - var angle = getRotationAngle(selected); - - if (angle) { - var rot = svgFactory_.svgRoot().createSVGTransform(); - rot.setRotate(-angle, cx, cy); - var rotm = rot.matrix; - nbox.tl = transformPoint(nbox.tl.x, nbox.tl.y, rotm); - nbox.tr = transformPoint(nbox.tr.x, nbox.tr.y, rotm); - nbox.bl = transformPoint(nbox.bl.x, nbox.bl.y, rotm); - nbox.br = transformPoint(nbox.br.x, nbox.br.y, rotm); // calculate the axis-aligned bbox - - var tl = nbox.tl; - var minx = tl.x, - miny = tl.y, - maxx = tl.x, - maxy = tl.y; - var min = Math.min, - max = Math.max; - minx = min(minx, min(nbox.tr.x, min(nbox.bl.x, nbox.br.x))) - offset; - miny = min(miny, min(nbox.tr.y, min(nbox.bl.y, nbox.br.y))) - offset; - maxx = max(maxx, max(nbox.tr.x, max(nbox.bl.x, nbox.br.x))) + offset; - maxy = max(maxy, max(nbox.tr.y, max(nbox.bl.y, nbox.br.y))) + offset; - nbax = minx; - nbay = miny; - nbaw = maxx - minx; - nbah = maxy - miny; - } - - var dstr = 'M' + nbax + ',' + nbay + ' L' + (nbax + nbaw) + ',' + nbay + ' ' + (nbax + nbaw) + ',' + (nbay + nbah) + ' ' + nbax + ',' + (nbay + nbah) + 'z'; - selectedBox.setAttribute('d', dstr); - var xform = angle ? 'rotate(' + [angle, cx, cy].join(',') + ')' : ''; - this.selectorGroup.setAttribute('transform', xform); // TODO(codedread): Is this needed? - // if (selected === selectedElements[0]) { - - this.gripCoords = { - nw: [nbax, nbay], - ne: [nbax + nbaw, nbay], - sw: [nbax, nbay + nbah], - se: [nbax + nbaw, nbay + nbah], - n: [nbax + nbaw / 2, nbay], - w: [nbax, nbay + nbah / 2], - e: [nbax + nbaw, nbay + nbah / 2], - s: [nbax + nbaw / 2, nbay + nbah] - }; - Object.entries(this.gripCoords).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - dir = _ref2[0], - coords = _ref2[1]; - - selectedGrips[dir].setAttribute('cx', coords[0]); - selectedGrips[dir].setAttribute('cy', coords[1]); - }); // we want to go 20 pixels in the negative transformed y direction, ignoring scale - - mgr.rotateGripConnector.setAttribute('x1', nbax + nbaw / 2); - mgr.rotateGripConnector.setAttribute('y1', nbay); - mgr.rotateGripConnector.setAttribute('x2', nbax + nbaw / 2); - mgr.rotateGripConnector.setAttribute('y2', nbay - gripRadius * 5); - mgr.rotateGrip.setAttribute('cx', nbax + nbaw / 2); - mgr.rotateGrip.setAttribute('cy', nbay - gripRadius * 5); // } - } // STATIC methods - - /** - * Updates cursors for corner grips on rotation so arrows point the right way. - * @param {Float} angle - Current rotation angle in degrees - * @returns {void} - */ - - }], [{ - key: "updateGripCursors", - value: function updateGripCursors(angle) { - var dirArr = Object.keys(selectorManager_.selectorGrips); - var steps = Math.round(angle / 45); - - if (steps < 0) { - steps += 8; - } - - while (steps > 0) { - dirArr.push(dirArr.shift()); - steps--; - } - - Object.values(selectorManager_.selectorGrips).forEach(function (gripElement, i) { - gripElement.setAttribute('style', 'cursor:' + dirArr[i] + '-resize'); - }); - } - }]); - - return Selector; -}(); -/** -* Manage all selector objects (selection boxes). -*/ - -var SelectorManager = /*#__PURE__*/function () { - /** - * Sets up properties and calls `initGroup`. - */ - function SelectorManager() { - _classCallCheck(this, SelectorManager); - - // this will hold the <g> element that contains all selector rects/grips - this.selectorParentGroup = null; // this is a special rect that is used for multi-select - - this.rubberBandBox = null; // this will hold objects of type Selector (see above) - - this.selectors = []; // this holds a map of SVG elements to their Selector object - - this.selectorMap = {}; // this holds a reference to the grip elements - - this.selectorGrips = { - nw: null, - n: null, - ne: null, - e: null, - se: null, - s: null, - sw: null, - w: null - }; - this.selectorGripsGroup = null; - this.rotateGripConnector = null; - this.rotateGrip = null; - this.initGroup(); - } - /** - * Resets the parent selector group element. - * @returns {void} - */ - - - _createClass(SelectorManager, [{ - key: "initGroup", - value: function initGroup() { - var _this = this; - - // remove old selector parent group if it existed - if (this.selectorParentGroup && this.selectorParentGroup.parentNode) { - this.selectorParentGroup.remove(); - } // create parent selector group and add it to svgroot - - - this.selectorParentGroup = svgFactory_.createSVGElement({ - element: 'g', - attr: { - id: 'selectorParentGroup' - } - }); - this.selectorGripsGroup = svgFactory_.createSVGElement({ - element: 'g', - attr: { - display: 'none' - } - }); - this.selectorParentGroup.append(this.selectorGripsGroup); - svgFactory_.svgRoot().append(this.selectorParentGroup); - this.selectorMap = {}; - this.selectors = []; - this.rubberBandBox = null; // add the corner grips - - Object.keys(this.selectorGrips).forEach(function (dir) { - var grip = svgFactory_.createSVGElement({ - element: 'circle', - attr: { - id: 'selectorGrip_resize_' + dir, - fill: '#22C', - r: gripRadius, - style: 'cursor:' + dir + '-resize', - // This expands the mouse-able area of the grips making them - // easier to grab with the mouse. - // This works in Opera and WebKit, but does not work in Firefox - // see https://bugzilla.mozilla.org/show_bug.cgi?id=500174 - 'stroke-width': 2, - 'pointer-events': 'all' - } - }); - $$9.data(grip, 'dir', dir); - $$9.data(grip, 'type', 'resize'); - _this.selectorGrips[dir] = _this.selectorGripsGroup.appendChild(grip); - }); // add rotator elems - - this.rotateGripConnector = this.selectorGripsGroup.appendChild(svgFactory_.createSVGElement({ - element: 'line', - attr: { - id: 'selectorGrip_rotateconnector', - stroke: '#22C', - 'stroke-width': '1' - } - })); - this.rotateGrip = this.selectorGripsGroup.appendChild(svgFactory_.createSVGElement({ - element: 'circle', - attr: { - id: 'selectorGrip_rotate', - fill: 'lime', - r: gripRadius, - stroke: '#22C', - 'stroke-width': 2, - style: 'cursor:url(' + config_.imgPath + 'rotate.png) 12 12, auto;' - } - })); - $$9.data(this.rotateGrip, 'type', 'rotate'); - - if ($$9('#canvasBackground').length) { - return; - } - - var _config_$dimensions = _slicedToArray(config_.dimensions, 2), - width = _config_$dimensions[0], - height = _config_$dimensions[1]; - - var canvasbg = svgFactory_.createSVGElement({ - element: 'svg', - attr: { - id: 'canvasBackground', - width: width, - height: height, - x: 0, - y: 0, - overflow: isWebkit() ? 'none' : 'visible', - // Chrome 7 has a problem with this when zooming out - style: 'pointer-events:none' - } - }); - var rect = svgFactory_.createSVGElement({ - element: 'rect', - attr: { - width: '100%', - height: '100%', - x: 0, - y: 0, - 'stroke-width': 1, - stroke: '#000', - fill: '#FFF', - style: 'pointer-events:none' - } - }); // Both Firefox and WebKit are too slow with this filter region (especially at higher - // zoom levels) and Opera has at least one bug - // if (!isOpera()) rect.setAttribute('filter', 'url(#canvashadow)'); - - canvasbg.append(rect); - svgFactory_.svgRoot().insertBefore(canvasbg, svgFactory_.svgContent()); // Ok to replace above with `svgFactory_.svgContent().before(canvasbg);`? - } - /** - * - * @param {Element} elem - DOM element to get the selector for - * @param {module:utilities.BBoxObject} [bbox] - Optional bbox to use for reset (prevents duplicate getBBox call). - * @returns {Selector} The selector based on the given element - */ - - }, { - key: "requestSelector", - value: function requestSelector(elem, bbox) { - if (isNullish(elem)) { - return null; - } - - var N = this.selectors.length; // If we've already acquired one for this element, return it. - - if (_typeof(this.selectorMap[elem.id]) === 'object') { - this.selectorMap[elem.id].locked = true; - return this.selectorMap[elem.id]; - } - - for (var i = 0; i < N; ++i) { - if (this.selectors[i] && !this.selectors[i].locked) { - this.selectors[i].locked = true; - this.selectors[i].reset(elem, bbox); - this.selectorMap[elem.id] = this.selectors[i]; - return this.selectors[i]; - } - } // if we reached here, no available selectors were found, we create one - - - this.selectors[N] = new Selector(N, elem, bbox); - this.selectorParentGroup.append(this.selectors[N].selectorGroup); - this.selectorMap[elem.id] = this.selectors[N]; - return this.selectors[N]; - } - /** - * Removes the selector of the given element (hides selection box). - * - * @param {Element} elem - DOM element to remove the selector for - * @returns {void} - */ - - }, { - key: "releaseSelector", - value: function releaseSelector(elem) { - if (isNullish(elem)) { - return; - } - - var N = this.selectors.length, - sel = this.selectorMap[elem.id]; - - if (!sel.locked) { - // TODO(codedread): Ensure this exists in this module. - console.log('WARNING! selector was released but was already unlocked'); // eslint-disable-line no-console - } - - for (var i = 0; i < N; ++i) { - if (this.selectors[i] && this.selectors[i] === sel) { - delete this.selectorMap[elem.id]; - sel.locked = false; - sel.selectedElement = null; - sel.showGrips(false); // remove from DOM and store reference in JS but only if it exists in the DOM - - try { - sel.selectorGroup.setAttribute('display', 'none'); - } catch (e) {} - - break; - } - } - } - /** - * @returns {SVGRectElement} The rubberBandBox DOM element. This is the rectangle drawn by - * the user for selecting/zooming - */ - - }, { - key: "getRubberBandBox", - value: function getRubberBandBox() { - if (!this.rubberBandBox) { - this.rubberBandBox = this.selectorParentGroup.appendChild(svgFactory_.createSVGElement({ - element: 'rect', - attr: { - id: 'selectorRubberBand', - fill: '#22C', - 'fill-opacity': 0.15, - stroke: '#22C', - 'stroke-width': 0.5, - display: 'none', - style: 'pointer-events:none' - } - })); - } - - return this.rubberBandBox; - } - }]); - - return SelectorManager; -}(); -/** - * An object that creates SVG elements for the canvas. - * - * @interface module:select.SVGFactory - */ - -/** - * @function module:select.SVGFactory#createSVGElement - * @param {module:utilities.EditorContext#addSVGElementFromJson} jsonMap - * @returns {SVGElement} - */ - -/** - * @function module:select.SVGFactory#svgRoot - * @returns {SVGSVGElement} - */ - -/** - * @function module:select.SVGFactory#svgContent - * @returns {SVGSVGElement} - */ - -/** - * @function module:select.SVGFactory#getCurrentZoom - * @returns {Float} The current zoom level - */ - -/** - * @typedef {GenericArray} module:select.Dimensions - * @property {Integer} length 2 - * @property {Float} 0 Width - * @property {Float} 1 Height - */ - -/** - * @typedef {PlainObject} module:select.Config - * @property {string} imgPath - * @property {module:select.Dimensions} dimensions - */ - -/** - * Initializes this module. - * @function module:select.init - * @param {module:select.Config} config - An object containing configurable parameters (imgPath) - * @param {module:select.SVGFactory} svgFactory - An object implementing the SVGFactory interface. - * @returns {void} - */ - -var init$6 = function init(config, svgFactory) { - config_ = config; - svgFactory_ = svgFactory; - selectorManager_ = new SelectorManager(); -}; -/** - * @function module:select.getSelectorManager - * @returns {module:select.SelectorManager} The SelectorManager instance. - */ - -var getSelectorManager = function getSelectorManager() { - return selectorManager_; -}; - -var $$a = jQueryPluginSVG(jQuery); -var MoveElementCommand$1 = MoveElementCommand, - InsertElementCommand$1 = InsertElementCommand, - RemoveElementCommand$1 = RemoveElementCommand, - ChangeElementCommand$1 = ChangeElementCommand, - BatchCommand$1 = BatchCommand, - UndoManager$1 = UndoManager, - HistoryEventTypes$1 = HistoryEventTypes; - -if (!window.console) { - window.console = {}; - - window.console.log = function (str) { - /* */ - }; - - window.console.dir = function (str) { - /* */ - }; -} - -if (window.opera) { - window.console.log = function (str) { - window.opera.postError(str); - }; - - window.console.dir = function (str) { - /* */ - }; -} // Reenable after fixing eslint-plugin-jsdoc to handle - -/** -* The main SvgCanvas class that manages all SVG-related functions. -* @memberof module:svgcanvas -* -* @borrows module:coords.remapElement as #remapElement -* @borrows module:recalculate.recalculateDimensions as #recalculateDimensions -* -* @borrows module:utilities.cleanupElement as #cleanupElement -* @borrows module:utilities.getStrokedBBoxDefaultVisible as #getStrokedBBox -* @borrows module:utilities.getVisibleElements as #getVisibleElements -* @borrows module:utilities.findDefs as #findDefs -* @borrows module:utilities.getUrlFromAttr as #getUrlFromAttr -* @borrows module:utilities.getHref as #getHref -* @borrows module:utilities.setHref as #setHref -* @borrows module:utilities.getRotationAngle as #getRotationAngle -* @borrows module:utilities.getBBox as #getBBox -* @borrows module:utilities.getElem as #getElem -* @borrows module:utilities.getRefElem as #getRefElem -* @borrows module:utilities.assignAttributes as #assignAttributes -* -* @borrows module:SVGTransformList.getTransformList as #getTransformList -* @borrows module:math.matrixMultiply as #matrixMultiply -* @borrows module:math.hasMatrixTransform as #hasMatrixTransform -* @borrows module:math.transformListToTransform as #transformListToTransform -* @borrows module:units.convertToNum as #convertToNum -* @borrows module:sanitize.sanitizeSvg as #sanitizeSvg -* @borrows module:path.pathActions.linkControlPoints as #linkControlPoints -*/ - - -var SvgCanvas = -/** -* @param {HTMLElement} container - The container HTML element that should hold the SVG root element -* @param {module:SVGEditor.curConfig} config - An object that contains configuration data -*/ -function SvgCanvas(container, config) { - _classCallCheck(this, SvgCanvas); - - // Alias Namespace constants - // Default configuration options - var curConfig = { - show_outside_canvas: true, - selectNew: true, - dimensions: [640, 480] - }; // Update config with new one if given - - if (config) { - $$a.extend(curConfig, config); - } // Array with width/height of canvas - - - var dimensions = curConfig.dimensions; - var canvas = this; // "document" element associated with the container (same as window.document using default svg-editor.js) - // NOTE: This is not actually a SVG document, but an HTML document. - - var svgdoc = container.ownerDocument; // This is a container for the document being edited, not the document itself. - - /** - * @name module:svgcanvas~svgroot - * @type {SVGSVGElement} - */ - - var svgroot = svgdoc.importNode(text2xml('<svg id="svgroot" xmlns="' + NS.SVG + '" xlinkns="' + NS.XLINK + '" ' + 'width="' + dimensions[0] + '" height="' + dimensions[1] + '" x="' + dimensions[0] + '" y="' + dimensions[1] + '" overflow="visible">' + '<defs>' + '<filter id="canvashadow" filterUnits="objectBoundingBox">' + '<feGaussianBlur in="SourceAlpha" stdDeviation="4" result="blur"/>' + '<feOffset in="blur" dx="5" dy="5" result="offsetBlur"/>' + '<feMerge>' + '<feMergeNode in="offsetBlur"/>' + '<feMergeNode in="SourceGraphic"/>' + '</feMerge>' + '</filter>' + '</defs>' + '</svg>').documentElement, true); - container.append(svgroot); - /** - * The actual element that represents the final output SVG element. - * @name module:svgcanvas~svgcontent - * @type {SVGSVGElement} - */ - - var svgcontent = svgdoc.createElementNS(NS.SVG, 'svg'); - /** - * This function resets the svgcontent element while keeping it in the DOM. - * @function module:svgcanvas.SvgCanvas#clearSvgContentElement - * @returns {void} - */ - - var clearSvgContentElement = canvas.clearSvgContentElement = function () { - $$a(svgcontent).empty(); // TODO: Clear out all other attributes first? - - $$a(svgcontent).attr({ - id: 'svgcontent', - width: dimensions[0], - height: dimensions[1], - x: dimensions[0], - y: dimensions[1], - overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden', - xmlns: NS.SVG, - 'xmlns:se': NS.SE, - 'xmlns:xlink': NS.XLINK - }).appendTo(svgroot); // TODO: make this string optional and set by the client - - var comment = svgdoc.createComment(' Created with SVG-edit - https://github.com/SVG-Edit/svgedit'); - svgcontent.append(comment); - }; - - clearSvgContentElement(); // Prefix string for element IDs - - var idprefix = 'svg_'; - /** - * Changes the ID prefix to the given value. - * @function module:svgcanvas.SvgCanvas#setIdPrefix - * @param {string} p - String with the new prefix - * @returns {void} - */ - - canvas.setIdPrefix = function (p) { - idprefix = p; - }; - /** - * Current `draw.Drawing` object. - * @type {module:draw.Drawing} - * @name module:svgcanvas.SvgCanvas#current_drawing_ - */ - - - canvas.current_drawing_ = new Drawing(svgcontent, idprefix); - /** - * Returns the current Drawing. - * @name module:svgcanvas.SvgCanvas#getCurrentDrawing - * @type {module:draw.DrawCanvasInit#getCurrentDrawing} - */ - - var getCurrentDrawing = canvas.getCurrentDrawing = function () { - return canvas.current_drawing_; - }; - /** - * Float displaying the current zoom level (1 = 100%, .5 = 50%, etc.). - * @type {Float} - */ - - - var currentZoom = 1; // pointer to current group (for in-group editing) - - var currentGroup = null; // Object containing data for the currently selected styles - - var allProperties = { - shape: { - fill: (curConfig.initFill.color === 'none' ? '' : '#') + curConfig.initFill.color, - fill_paint: null, - fill_opacity: curConfig.initFill.opacity, - stroke: '#' + curConfig.initStroke.color, - stroke_paint: null, - stroke_opacity: curConfig.initStroke.opacity, - stroke_width: curConfig.initStroke.width, - stroke_dasharray: 'none', - stroke_linejoin: 'miter', - stroke_linecap: 'butt', - opacity: curConfig.initOpacity - } - }; - allProperties.text = $$a.extend(true, {}, allProperties.shape); - $$a.extend(allProperties.text, { - fill: '#000000', - stroke_width: curConfig.text && curConfig.text.stroke_width, - font_size: curConfig.text && curConfig.text.font_size, - font_family: curConfig.text && curConfig.text.font_family - }); // Current shape style properties - - var curShape = allProperties.shape; // Array with all the currently selected elements - // default size of 1 until it needs to grow bigger - - var selectedElements = []; - /** - * @typedef {PlainObject} module:svgcanvas.SVGAsJSON - * @property {string} element - * @property {PlainObject<string, string>} attr - * @property {module:svgcanvas.SVGAsJSON[]} children - */ - - /** - * @function module:svgcanvas.SvgCanvas#getContentElem - * @param {Text|Element} data - * @returns {module:svgcanvas.SVGAsJSON} - */ - - var getJsonFromSvgElement = this.getJsonFromSvgElement = function (data) { - // Text node - if (data.nodeType === 3) return data.nodeValue; - var retval = { - element: data.tagName, - // namespace: nsMap[data.namespaceURI], - attr: {}, - children: [] - }; // Iterate attributes - - for (var i = 0, attr; attr = data.attributes[i]; i++) { - retval.attr[attr.name] = attr.value; - } // Iterate children - - - for (var _i = 0, node; node = data.childNodes[_i]; _i++) { - retval.children[_i] = getJsonFromSvgElement(node); - } - - return retval; - }; - /** - * This should really be an intersection implementing all rather than a union. - * @name module:svgcanvas.SvgCanvas#addSVGElementFromJson - * @type {module:utilities.EditorContext#addSVGElementFromJson|module:path.EditorContext#addSVGElementFromJson} - */ - - - var addSVGElementFromJson = this.addSVGElementFromJson = function (data) { - if (typeof data === 'string') return svgdoc.createTextNode(data); - var shape = getElem(data.attr.id); // if shape is a path but we need to create a rect/ellipse, then remove the path - - var currentLayer = getCurrentDrawing().getCurrentLayer(); - - if (shape && data.element !== shape.tagName) { - shape.remove(); - shape = null; - } - - if (!shape) { - var ns = data.namespace || NS.SVG; - shape = svgdoc.createElementNS(ns, data.element); - - if (currentLayer) { - (currentGroup || currentLayer).append(shape); - } - } - - if (data.curStyles) { - assignAttributes(shape, { - fill: curShape.fill, - stroke: curShape.stroke, - 'stroke-width': curShape.stroke_width, - 'stroke-dasharray': curShape.stroke_dasharray, - 'stroke-linejoin': curShape.stroke_linejoin, - 'stroke-linecap': curShape.stroke_linecap, - 'stroke-opacity': curShape.stroke_opacity, - 'fill-opacity': curShape.fill_opacity, - opacity: curShape.opacity / 2, - style: 'pointer-events:inherit' - }); - } - - assignAttributes(shape, data.attr); - cleanupElement(shape); // Children - - if (data.children) { - data.children.forEach(function (child) { - shape.append(addSVGElementFromJson(child)); - }); - } - - return shape; - }; - - canvas.getTransformList = getTransformList; - canvas.matrixMultiply = matrixMultiply; - canvas.hasMatrixTransform = hasMatrixTransform; - canvas.transformListToTransform = transformListToTransform; - /** - * @type {module:utilities.EditorContext#getBaseUnit} - */ - - var getBaseUnit = function getBaseUnit() { - return curConfig.baseUnit; - }; - /** - * Initialize from units.js. - * Send in an object implementing the ElementContainer interface (see units.js). - */ - - - init( - /** - * @implements {module:units.ElementContainer} - */ - { - getBaseUnit: getBaseUnit, - getElement: getElem, - getHeight: function getHeight() { - return svgcontent.getAttribute('height') / currentZoom; - }, - getWidth: function getWidth() { - return svgcontent.getAttribute('width') / currentZoom; - }, - getRoundDigits: function getRoundDigits() { - return saveOptions.round_digits; - } - }); - canvas.convertToNum = convertToNum; - /** - * This should really be an intersection implementing all rather than a union. - * @type {module:draw.DrawCanvasInit#getSVGContent|module:utilities.EditorContext#getSVGContent} - */ - - var getSVGContent = function getSVGContent() { - return svgcontent; - }; - /** - * Should really be an intersection with all needing to apply rather than a union. - * @name module:svgcanvas.SvgCanvas#getSelectedElements - * @type {module:utilities.EditorContext#getSelectedElements|module:draw.DrawCanvasInit#getSelectedElements|module:path.EditorContext#getSelectedElements} - */ - - - var getSelectedElements = this.getSelectedElems = function () { - return selectedElements; - }; - - var pathActions$1 = pathActions; - /** - * This should actually be an intersection as all interfaces should be met. - * @type {module:utilities.EditorContext#getSVGRoot|module:recalculate.EditorContext#getSVGRoot|module:coords.EditorContext#getSVGRoot|module:path.EditorContext#getSVGRoot} - */ - - var getSVGRoot = function getSVGRoot() { - return svgroot; - }; - - init$1( - /** - * @implements {module:utilities.EditorContext} - */ - { - pathActions: pathActions$1, - // Ok since not modifying - getSVGContent: getSVGContent, - addSVGElementFromJson: addSVGElementFromJson, - getSelectedElements: getSelectedElements, - getDOMDocument: function getDOMDocument() { - return svgdoc; - }, - getDOMContainer: function getDOMContainer() { - return container; - }, - getSVGRoot: getSVGRoot, - // TODO: replace this mostly with a way to get the current drawing. - getBaseUnit: getBaseUnit, - getSnappingStep: function getSnappingStep() { - return curConfig.snappingStep; - } - }); - canvas.findDefs = findDefs; - canvas.getUrlFromAttr = getUrlFromAttr; - canvas.getHref = getHref; - canvas.setHref = setHref; - /* const getBBox = */ - - canvas.getBBox = getBBox; - canvas.getRotationAngle = getRotationAngle; - canvas.getElem = getElem; - canvas.getRefElem = getRefElem; - canvas.assignAttributes = assignAttributes; - this.cleanupElement = cleanupElement; - /** - * This should actually be an intersection not a union as all should apply. - * @type {module:coords.EditorContext#getGridSnapping|module:path.EditorContext#getGridSnapping} - */ - - var getGridSnapping = function getGridSnapping() { - return curConfig.gridSnapping; - }; - - init$4( - /** - * @implements {module:coords.EditorContext} - */ - { - getDrawing: function getDrawing() { - return getCurrentDrawing(); - }, - getSVGRoot: getSVGRoot, - getGridSnapping: getGridSnapping - }); - this.remapElement = remapElement; - init$5( - /** - * @implements {module:recalculate.EditorContext} - */ - { - getSVGRoot: getSVGRoot, - getStartTransform: function getStartTransform() { - return startTransform; - }, - setStartTransform: function setStartTransform(transform) { - startTransform = transform; - } - }); - this.recalculateDimensions = recalculateDimensions; // import from sanitize.js - - var nsMap = getReverseNS(); - canvas.sanitizeSvg = sanitizeSvg; - /** - * @name undoMgr - * @memberof module:svgcanvas.SvgCanvas# - * @type {module:history.HistoryEventHandler} - */ - - var undoMgr = canvas.undoMgr = new UndoManager$1({ - /** - * @param {string} eventType One of the HistoryEvent types - * @param {module:history.HistoryCommand} cmd Fulfills the HistoryCommand interface - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - handleHistoryEvent: function handleHistoryEvent(eventType, cmd) { - var EventTypes = HistoryEventTypes$1; // TODO: handle setBlurOffsets. - - if (eventType === EventTypes.BEFORE_UNAPPLY || eventType === EventTypes.BEFORE_APPLY) { - canvas.clearSelection(); - } else if (eventType === EventTypes.AFTER_APPLY || eventType === EventTypes.AFTER_UNAPPLY) { - var elems = cmd.elements(); - canvas.pathActions.clear(); - call('changed', elems); - var cmdType = cmd.type(); - var isApply = eventType === EventTypes.AFTER_APPLY; - - if (cmdType === 'MoveElementCommand') { - var parent = isApply ? cmd.newParent : cmd.oldParent; - - if (parent === svgcontent) { - identifyLayers(); - } - } else if (cmdType === 'InsertElementCommand' || cmdType === 'RemoveElementCommand') { - if (cmd.parent === svgcontent) { - identifyLayers(); - } - - if (cmdType === 'InsertElementCommand') { - if (isApply) { - restoreRefElems(cmd.elem); - } - } else if (!isApply) { - restoreRefElems(cmd.elem); - } - - if (cmd.elem && cmd.elem.tagName === 'use') { - setUseData(cmd.elem); - } - } else if (cmdType === 'ChangeElementCommand') { - // if we are changing layer names, re-identify all layers - if (cmd.elem.tagName === 'title' && cmd.elem.parentNode.parentNode === svgcontent) { - identifyLayers(); - } - - var values = isApply ? cmd.newValues : cmd.oldValues; // If stdDeviation was changed, update the blur. - - if (values.stdDeviation) { - canvas.setBlurOffsets(cmd.elem.parentNode, values.stdDeviation); - } // This is resolved in later versions of webkit, perhaps we should - // have a featured detection for correct 'use' behavior? - // —————————— - // Remove & Re-add hack for Webkit (issue 775) - // if (cmd.elem.tagName === 'use' && isWebkit()) { - // const {elem} = cmd; - // if (!elem.getAttribute('x') && !elem.getAttribute('y')) { - // const parent = elem.parentNode; - // const sib = elem.nextSibling; - // elem.remove(); - // parent.insertBefore(elem, sib); - // // Ok to replace above with this? `sib.before(elem);` - // } - // } - - } - } - } - }); - /** - * This should really be an intersection applying to all types rather than a union. - * @name module:svgcanvas~addCommandToHistory - * @type {module:path.EditorContext#addCommandToHistory|module:draw.DrawCanvasInit#addCommandToHistory} - */ - - var addCommandToHistory = function addCommandToHistory(cmd) { - canvas.undoMgr.addCommandToHistory(cmd); - }; - /** - * This should really be an intersection applying to all types rather than a union. - * @name module:svgcanvas.SvgCanvas#getZoom - * @type {module:path.EditorContext#getCurrentZoom|module:select.SVGFactory#getCurrentZoom} - */ - - - var getCurrentZoom = this.getZoom = function () { - return currentZoom; - }; - /** - * This method rounds the incoming value to the nearest value based on the `currentZoom` - * @name module:svgcanvas.SvgCanvas#round - * @type {module:path.EditorContext#round} - */ - - - var round = this.round = function (val) { - return Number.parseInt(val * currentZoom) / currentZoom; - }; - - init$6(curConfig, - /** - * Export to select.js. - * @implements {module:select.SVGFactory} - */ - { - createSVGElement: function createSVGElement(jsonMap) { - return canvas.addSVGElementFromJson(jsonMap); - }, - svgRoot: function svgRoot() { - return svgroot; - }, - svgContent: function svgContent() { - return svgcontent; - }, - getCurrentZoom: getCurrentZoom - }); - /** - * This object manages selectors for us. - * @name module:svgcanvas.SvgCanvas#selectorManager - * @type {module:select.SelectorManager} - */ - - var selectorManager = this.selectorManager = getSelectorManager(); - /** - * @name module:svgcanvas.SvgCanvas#getNextId - * @type {module:path.EditorContext#getNextId} - */ - - var getNextId = canvas.getNextId = function () { - return getCurrentDrawing().getNextId(); - }; - /** - * @name module:svgcanvas.SvgCanvas#getId - * @type {module:path.EditorContext#getId} - */ - - - var getId = canvas.getId = function () { - return getCurrentDrawing().getId(); - }; - /** - * The "implements" should really be an intersection applying to all types rather than a union. - * @name module:svgcanvas.SvgCanvas#call - * @type {module:draw.DrawCanvasInit#call|module:path.EditorContext#call} - */ - - - var call = function call(ev, arg) { - if (events[ev]) { - return events[ev](window, arg); - } - - return undefined; - }; - /** - * Clears the selection. The 'selected' handler is then optionally called. - * This should really be an intersection applying to all types rather than a union. - * @name module:svgcanvas.SvgCanvas#clearSelection - * @type {module:draw.DrawCanvasInit#clearSelection|module:path.EditorContext#clearSelection} - * @fires module:svgcanvas.SvgCanvas#event:selected - */ - - - var clearSelection = this.clearSelection = function (noCall) { - selectedElements.forEach(function (elem) { - if (isNullish(elem)) { - return; - } - - selectorManager.releaseSelector(elem); - }); - selectedElements = []; - - if (!noCall) { - call('selected', selectedElements); - } - }; - /** - * Adds a list of elements to the selection. The 'selected' handler is then called. - * @name module:svgcanvas.SvgCanvas#addToSelection - * @type {module:path.EditorContext#addToSelection} - * @fires module:svgcanvas.SvgCanvas#event:selected - */ - - - var addToSelection = this.addToSelection = function (elemsToAdd, showGrips) { - if (!elemsToAdd.length) { - return; - } // find the first null in our selectedElements array - - - var j = 0; - - while (j < selectedElements.length) { - if (isNullish(selectedElements[j])) { - break; - } - - ++j; - } // now add each element consecutively - - - var i = elemsToAdd.length; - - while (i--) { - var elem = elemsToAdd[i]; - - if (!elem) { - continue; - } - - var bbox = getBBox(elem); - - if (!bbox) { - continue; - } - - if (elem.tagName === 'a' && elem.childNodes.length === 1) { - // Make "a" element's child be the selected element - elem = elem.firstChild; - } // if it's not already there, add it - - - if (!selectedElements.includes(elem)) { - selectedElements[j] = elem; // only the first selectedBBoxes element is ever used in the codebase these days - // if (j === 0) selectedBBoxes[0] = utilsGetBBox(elem); - - j++; - var sel = selectorManager.requestSelector(elem, bbox); - - if (selectedElements.length > 1) { - sel.showGrips(false); - } - } - } - - if (!selectedElements.length) { - return; - } - - call('selected', selectedElements); - - if (selectedElements.length === 1) { - selectorManager.requestSelector(selectedElements[0]).showGrips(showGrips); - } // make sure the elements are in the correct order - // See: https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition - - - selectedElements.sort(function (a, b) { - if (a && b && a.compareDocumentPosition) { - return 3 - (b.compareDocumentPosition(a) & 6); // eslint-disable-line no-bitwise - } - - if (isNullish(a)) { - return 1; - } - - return 0; - }); // Make sure first elements are not null - - while (isNullish(selectedElements[0])) { - selectedElements.shift(0); - } - }; - /** - * @type {module:path.EditorContext#getOpacity} - */ - - - var getOpacity = function getOpacity() { - return curShape.opacity; - }; - /** - * @name module:svgcanvas.SvgCanvas#getMouseTarget - * @type {module:path.EditorContext#getMouseTarget} - */ - - - var getMouseTarget = this.getMouseTarget = function (evt) { - if (isNullish(evt)) { - return null; - } - - var mouseTarget = evt.target; // if it was a <use>, Opera and WebKit return the SVGElementInstance - - if (mouseTarget.correspondingUseElement) { - mouseTarget = mouseTarget.correspondingUseElement; - } // for foreign content, go up until we find the foreignObject - // WebKit browsers set the mouse target to the svgcanvas div - - - if ([NS.MATH, NS.HTML].includes(mouseTarget.namespaceURI) && mouseTarget.id !== 'svgcanvas') { - while (mouseTarget.nodeName !== 'foreignObject') { - mouseTarget = mouseTarget.parentNode; - - if (!mouseTarget) { - return svgroot; - } - } - } // Get the desired mouseTarget with jQuery selector-fu - // If it's root-like, select the root - - - var currentLayer = getCurrentDrawing().getCurrentLayer(); - - if ([svgroot, container, svgcontent, currentLayer].includes(mouseTarget)) { - return svgroot; - } - - var $target = $$a(mouseTarget); // If it's a selection grip, return the grip parent - - if ($target.closest('#selectorParentGroup').length) { - // While we could instead have just returned mouseTarget, - // this makes it easier to indentify as being a selector grip - return selectorManager.selectorParentGroup; - } - - while (mouseTarget.parentNode !== (currentGroup || currentLayer)) { - mouseTarget = mouseTarget.parentNode; - } // - // // go up until we hit a child of a layer - // while (mouseTarget.parentNode.parentNode.tagName == 'g') { - // mouseTarget = mouseTarget.parentNode; - // } - // Webkit bubbles the mouse event all the way up to the div, so we - // set the mouseTarget to the svgroot like the other browsers - // if (mouseTarget.nodeName.toLowerCase() == 'div') { - // mouseTarget = svgroot; - // } - - - return mouseTarget; - }; - /** - * @namespace {module:path.pathActions} pathActions - * @memberof module:svgcanvas.SvgCanvas# - * @see module:path.pathActions - */ - - - canvas.pathActions = pathActions$1; - /** - * @type {module:path.EditorContext#resetD} - */ - - function resetD(p) { - p.setAttribute('d', pathActions$1.convertPath(p)); - } - - init$2( - /** - * @implements {module:path.EditorContext} - */ - { - selectorManager: selectorManager, - // Ok since not changing - canvas: canvas, - // Ok since not changing - call: call, - resetD: resetD, - round: round, - clearSelection: clearSelection, - addToSelection: addToSelection, - addCommandToHistory: addCommandToHistory, - remapElement: remapElement, - addSVGElementFromJson: addSVGElementFromJson, - getGridSnapping: getGridSnapping, - getOpacity: getOpacity, - getSelectedElements: getSelectedElements, - getContainer: function getContainer() { - return container; - }, - setStarted: function setStarted(s) { - started = s; - }, - getRubberBox: function getRubberBox() { - return rubberBox; - }, - setRubberBox: function setRubberBox(rb) { - rubberBox = rb; - return rubberBox; - }, - - /** - * @param {PlainObject} ptsInfo - * @param {boolean} ptsInfo.closedSubpath - * @param {SVGCircleElement[]} ptsInfo.grips - * @fires module:svgcanvas.SvgCanvas#event:pointsAdded - * @fires module:svgcanvas.SvgCanvas#event:selected - * @returns {void} - */ - addPtsToSelection: function addPtsToSelection(_ref) { - var closedSubpath = _ref.closedSubpath, - grips = _ref.grips; - // TODO: Correct this: - pathActions$1.canDeleteNodes = true; - pathActions$1.closed_subpath = closedSubpath; - call('pointsAdded', { - closedSubpath: closedSubpath, - grips: grips - }); - call('selected', grips); - }, - - /** - * @param {PlainObject} changes - * @param {ChangeElementCommand} changes.cmd - * @param {SVGPathElement} changes.elem - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - endChanges: function endChanges(_ref2) { - var cmd = _ref2.cmd, - elem = _ref2.elem; - addCommandToHistory(cmd); - call('changed', [elem]); - }, - getCurrentZoom: getCurrentZoom, - getId: getId, - getNextId: getNextId, - getMouseTarget: getMouseTarget, - getCurrentMode: function getCurrentMode() { - return currentMode; - }, - setCurrentMode: function setCurrentMode(cm) { - currentMode = cm; - return currentMode; - }, - getDrawnPath: function getDrawnPath() { - return drawnPath; - }, - setDrawnPath: function setDrawnPath(dp) { - drawnPath = dp; - return drawnPath; - }, - getSVGRoot: getSVGRoot - }); // Interface strings, usually for title elements - - var uiStrings = {}; - var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'; - var refAttrs = ['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke']; - var elData = $$a.data; // Animation element to change the opacity of any newly created element - - var opacAni = document.createElementNS(NS.SVG, 'animate'); - $$a(opacAni).attr({ - attributeName: 'opacity', - begin: 'indefinite', - dur: 1, - fill: 'freeze' - }).appendTo(svgroot); - - var restoreRefElems = function restoreRefElems(elem) { - // Look for missing reference elements, restore any found - var attrs = $$a(elem).attr(refAttrs); - Object.values(attrs).forEach(function (val) { - if (val && val.startsWith('url(')) { - var id = getUrlFromAttr(val).substr(1); - var ref = getElem(id); - - if (!ref) { - findDefs().append(removedElements[id]); - delete removedElements[id]; - } - } - }); - var childs = elem.getElementsByTagName('*'); - - if (childs.length) { - for (var i = 0, l = childs.length; i < l; i++) { - restoreRefElems(childs[i]); - } - } - }; // (function () { - // TODO For Issue 208: this is a start on a thumbnail - // const svgthumb = svgdoc.createElementNS(NS.SVG, 'use'); - // svgthumb.setAttribute('width', '100'); - // svgthumb.setAttribute('height', '100'); - // setHref(svgthumb, '#svgcontent'); - // svgroot.append(svgthumb); - // }()); - - /** - * @typedef {PlainObject} module:svgcanvas.SaveOptions - * @property {boolean} apply - * @property {"embed"} [image] - * @property {Integer} round_digits - */ - // Object to contain image data for raster images that were found encodable - - - var encodableImages = {}, - // Object with save options - - /** - * @type {module:svgcanvas.SaveOptions} - */ - saveOptions = { - round_digits: 5 - }, - // Object with IDs for imported files, to see if one was already added - importIds = {}, - // Current text style properties - curText = allProperties.text, - // Object to contain all included extensions - extensions = {}, - // Map of deleted reference elements - removedElements = {}; - var // String with image URL of last loadable image - lastGoodImgUrl = curConfig.imgPath + 'logo.png', - // Boolean indicating whether or not a draw action has been started - started = false, - // String with an element's initial transform attribute value - startTransform = null, - // String indicating the current editor mode - currentMode = 'select', - // String with the current direction in which an element is being resized - currentResizeMode = 'none', - // Current general properties - curProperties = curShape, - // Array with selected elements' Bounding box object - // selectedBBoxes = new Array(1), - // The DOM element that was just selected - justSelected = null, - // DOM element for selection rectangle drawn by the user - rubberBox = null, - // Array of current BBoxes, used in getIntersectionList(). - curBBoxes = [], - // Canvas point for the most recent right click - lastClickPoint = null; - - this.runExtension = function (name, action, vars) { - return this.runExtensions(action, vars, false, function (n) { - return n === name; - }); - }; - /** - * @typedef {module:svgcanvas.ExtensionMouseDownStatus|module:svgcanvas.ExtensionMouseUpStatus|module:svgcanvas.ExtensionIDsUpdatedStatus|module:locale.ExtensionLocaleData[]|void} module:svgcanvas.ExtensionStatus - * @tutorial ExtensionDocs - */ - - /** - * @callback module:svgcanvas.ExtensionVarBuilder - * @param {string} name The name of the extension - * @returns {module:svgcanvas.SvgCanvas#event:ext_addLangData} - */ - - /** - * @callback module:svgcanvas.ExtensionNameFilter - * @param {string} name - * @returns {boolean} - */ - - /** - * @todo Consider: Should this return an array by default, so extension results aren't overwritten? - * @todo Would be easier to document if passing in object with key of action and vars as value; could then define an interface which tied both together - * @function module:svgcanvas.SvgCanvas#runExtensions - * @param {"mouseDown"|"mouseMove"|"mouseUp"|"zoomChanged"|"IDsUpdated"|"canvasUpdated"|"toolButtonStateUpdate"|"selectedChanged"|"elementTransition"|"elementChanged"|"langReady"|"langChanged"|"addLangData"|"onNewDocument"|"workareaResized"} action - * @param {module:svgcanvas.SvgCanvas#event:ext_mouseDown|module:svgcanvas.SvgCanvas#event:ext_mouseMove|module:svgcanvas.SvgCanvas#event:ext_mouseUp|module:svgcanvas.SvgCanvas#event:ext_zoomChanged|module:svgcanvas.SvgCanvas#event:ext_IDsUpdated|module:svgcanvas.SvgCanvas#event:ext_canvasUpdated|module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate|module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementTransition|module:svgcanvas.SvgCanvas#event:ext_elementChanged|module:svgcanvas.SvgCanvas#event:ext_langReady|module:svgcanvas.SvgCanvas#event:ext_langChanged|module:svgcanvas.SvgCanvas#event:ext_addLangData|module:svgcanvas.SvgCanvas#event:ext_onNewDocument|module:svgcanvas.SvgCanvas#event:ext_workareaResized|module:svgcanvas.ExtensionVarBuilder} [vars] - * @param {boolean} [returnArray] - * @param {module:svgcanvas.ExtensionNameFilter} nameFilter - * @returns {GenericArray<module:svgcanvas.ExtensionStatus>|module:svgcanvas.ExtensionStatus|false} See {@tutorial ExtensionDocs} on the ExtensionStatus. - */ - - - var runExtensions = this.runExtensions = function (action, vars, returnArray, nameFilter) { - var result = returnArray ? [] : false; - $$a.each(extensions, function (name, ext) { - if (nameFilter && !nameFilter(name)) { - return; - } - - if (ext && action in ext) { - if (typeof vars === 'function') { - vars = vars(name); // ext, action - } - - if (returnArray) { - result.push(ext[action](vars)); - } else { - result = ext[action](vars); - } - } - }); - return result; - }; - /** - * @typedef {PlainObject} module:svgcanvas.ExtensionMouseDownStatus - * @property {boolean} started Indicates that creating/editing has started - */ - - /** - * @typedef {PlainObject} module:svgcanvas.ExtensionMouseUpStatus - * @property {boolean} keep Indicates if the current element should be kept - * @property {boolean} started Indicates if editing should still be considered as "started" - * @property {Element} element The element being affected - */ - - /** - * @typedef {PlainObject} module:svgcanvas.ExtensionIDsUpdatedStatus - * @property {string[]} remove Contains string IDs (used by `ext-connector.js`) - */ - - /** - * @interface module:svgcanvas.ExtensionInitResponse - * @property {module:SVGEditor.ContextTool[]|PlainObject<string, module:SVGEditor.ContextTool>} [context_tools] - * @property {module:SVGEditor.Button[]|PlainObject<Integer, module:SVGEditor.Button>} [buttons] - * @property {string} [svgicons] The location of a local SVG or SVGz file - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#mouseDown - * @param {module:svgcanvas.SvgCanvas#event:ext_mouseDown} arg - * @returns {void|module:svgcanvas.ExtensionMouseDownStatus} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#mouseMove - * @param {module:svgcanvas.SvgCanvas#event:ext_mouseMove} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#mouseUp - * @param {module:svgcanvas.SvgCanvas#event:ext_mouseUp} arg - * @returns {module:svgcanvas.ExtensionMouseUpStatus} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#zoomChanged - * @param {module:svgcanvas.SvgCanvas#event:ext_zoomChanged} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#IDsUpdated - * @param {module:svgcanvas.SvgCanvas#event:ext_IDsUpdated} arg - * @returns {module:svgcanvas.ExtensionIDsUpdatedStatus} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#canvasUpdated - * @param {module:svgcanvas.SvgCanvas#event:ext_canvasUpdated} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#toolButtonStateUpdate - * @param {module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#selectedChanged - * @param {module:svgcanvas.SvgCanvas#event:ext_selectedChanged} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#elementTransition - * @param {module:svgcanvas.SvgCanvas#event:ext_elementTransition} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#elementChanged - * @param {module:svgcanvas.SvgCanvas#event:ext_elementChanged} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#langReady - * @param {module:svgcanvas.SvgCanvas#event:ext_langReady} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#langChanged - * @param {module:svgcanvas.SvgCanvas#event:ext_langChanged} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#addLangData - * @param {module:svgcanvas.SvgCanvas#event:ext_addLangData} arg - * @returns {Promise<module:locale.ExtensionLocaleData>} Resolves to {@link module:locale.ExtensionLocaleData} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#onNewDocument - * @param {module:svgcanvas.SvgCanvas#event:ext_onNewDocument} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#workareaResized - * @param {module:svgcanvas.SvgCanvas#event:ext_workareaResized} arg - * @returns {void} - */ - - /** - * @function module:svgcanvas.ExtensionInitResponse#callback - * @this module:SVGEditor - * @param {module:svgcanvas.SvgCanvas#event:ext_callback} arg - * @returns {void} - */ - - /** - * @callback module:svgcanvas.ExtensionInitCallback - * @this module:SVGEditor - * @param {module:svgcanvas.ExtensionArgumentObject} arg - * @returns {Promise<module:svgcanvas.ExtensionInitResponse|void>} Resolves to [ExtensionInitResponse]{@link module:svgcanvas.ExtensionInitResponse} or `undefined` - */ - - /** - * @typedef {PlainObject} module:svgcanvas.ExtensionInitArgs - * @property {external:jQuery} $ - * @property {module:SVGEditor~ImportLocale} importLocale - */ - - /** - * Add an extension to the editor. - * @function module:svgcanvas.SvgCanvas#addExtension - * @param {string} name - String with the ID of the extension. Used internally; no need for i18n. - * @param {module:svgcanvas.ExtensionInitCallback} [extInitFunc] - Function supplied by the extension with its data - * @param {module:svgcanvas.ExtensionInitArgs} initArgs - * @fires module:svgcanvas.SvgCanvas#event:extension_added - * @throws {TypeError|Error} `TypeError` if `extInitFunc` is not a function, `Error` - * if extension of supplied name already exists - * @returns {Promise<void>} Resolves to `undefined` - */ - - - this.addExtension = /*#__PURE__*/function () { - var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(name, extInitFunc, _ref3) { - var jq, importLocale, argObj, extObj; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - jq = _ref3.$, importLocale = _ref3.importLocale; - - if (!(typeof extInitFunc !== 'function')) { - _context.next = 3; - break; - } - - throw new TypeError('Function argument expected for `svgcanvas.addExtension`'); - - case 3: - if (!(name in extensions)) { - _context.next = 5; - break; - } - - throw new Error('Cannot add extension "' + name + '", an extension by that name already exists.'); - - case 5: - // Provide private vars/funcs here. Is there a better way to do this? - - /** - * @typedef {module:svgcanvas.PrivateMethods} module:svgcanvas.ExtensionArgumentObject - * @property {SVGSVGElement} svgroot See {@link module:svgcanvas~svgroot} - * @property {SVGSVGElement} svgcontent See {@link module:svgcanvas~svgcontent} - * @property {!(string|Integer)} nonce See {@link module:draw.Drawing#getNonce} - * @property {module:select.SelectorManager} selectorManager - * @property {module:SVGEditor~ImportLocale} importLocale - */ - - /** - * @type {module:svgcanvas.ExtensionArgumentObject} - * @see {@link module:svgcanvas.PrivateMethods} source for the other methods/properties - */ - argObj = $$a.extend(canvas.getPrivateMethods(), { - $: jq, - importLocale: importLocale, - svgroot: svgroot, - svgcontent: svgcontent, - nonce: getCurrentDrawing().getNonce(), - selectorManager: selectorManager - }); - _context.next = 8; - return extInitFunc(argObj); - - case 8: - extObj = _context.sent; - - if (extObj) { - extObj.name = name; - } - - extensions[name] = extObj; - return _context.abrupt("return", call('extension_added', extObj)); - - case 12: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function (_x, _x2, _x3) { - return _ref4.apply(this, arguments); - }; - }(); - /** - * This method sends back an array or a NodeList full of elements that - * intersect the multi-select rubber-band-box on the currentLayer only. - * - * We brute-force `getIntersectionList` for browsers that do not support it (Firefox). - * - * Reference: - * Firefox does not implement `getIntersectionList()`, see {@link https://bugzilla.mozilla.org/show_bug.cgi?id=501421}. - * @function module:svgcanvas.SvgCanvas#getIntersectionList - * @param {SVGRect} rect - * @returns {Element[]|NodeList} Bbox elements - */ - - - var getIntersectionList = this.getIntersectionList = function (rect) { - if (isNullish(rubberBox)) { - return null; - } - - var parent = currentGroup || getCurrentDrawing().getCurrentLayer(); - var rubberBBox; - - if (!rect) { - rubberBBox = rubberBox.getBBox(); - var bb = svgcontent.createSVGRect(); - ['x', 'y', 'width', 'height', 'top', 'right', 'bottom', 'left'].forEach(function (o) { - bb[o] = rubberBBox[o] / currentZoom; - }); - rubberBBox = bb; - } else { - rubberBBox = svgcontent.createSVGRect(); - rubberBBox.x = rect.x; - rubberBBox.y = rect.y; - rubberBBox.width = rect.width; - rubberBBox.height = rect.height; - } - - var resultList = null; - - if (!isIE()) { - if (typeof svgroot.getIntersectionList === 'function') { - // Offset the bbox of the rubber box by the offset of the svgcontent element. - rubberBBox.x += Number.parseInt(svgcontent.getAttribute('x')); - rubberBBox.y += Number.parseInt(svgcontent.getAttribute('y')); - resultList = svgroot.getIntersectionList(rubberBBox, parent); - } - } - - if (isNullish(resultList) || typeof resultList.item !== 'function') { - resultList = []; - - if (!curBBoxes.length) { - // Cache all bboxes - curBBoxes = getVisibleElementsAndBBoxes(parent); - } - - var i = curBBoxes.length; - - while (i--) { - if (!rubberBBox.width) { - continue; - } - - if (rectsIntersect(rubberBBox, curBBoxes[i].bbox)) { - resultList.push(curBBoxes[i].elem); - } - } - } // addToSelection expects an array, but it's ok to pass a NodeList - // because using square-bracket notation is allowed: - // https://www.w3.org/TR/DOM-Level-2-Core/ecma-script-binding.html - - - return resultList; - }; - - this.getStrokedBBox = getStrokedBBoxDefaultVisible; - this.getVisibleElements = getVisibleElements; - /** - * @typedef {PlainObject} ElementAndBBox - * @property {Element} elem - The element - * @property {module:utilities.BBoxObject} bbox - The element's BBox as retrieved from `getStrokedBBoxDefaultVisible` - */ - - /** - * Get all elements that have a BBox (excludes `<defs>`, `<title>`, etc). - * Note that 0-opacity, off-screen etc elements are still considered "visible" - * for this function. - * @function module:svgcanvas.SvgCanvas#getVisibleElementsAndBBoxes - * @param {Element} parent - The parent DOM element to search within - * @returns {ElementAndBBox[]} An array with objects that include: - */ - - var getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function (parent) { - if (!parent) { - parent = $$a(svgcontent).children(); // Prevent layers from being included - } - - var contentElems = []; - $$a(parent).children().each(function (i, elem) { - if (elem.getBBox) { - contentElems.push({ - elem: elem, - bbox: getStrokedBBoxDefaultVisible([elem]) - }); - } - }); - return contentElems.reverse(); - }; - /** - * Wrap an SVG element into a group element, mark the group as 'gsvg'. - * @function module:svgcanvas.SvgCanvas#groupSvgElem - * @param {Element} elem - SVG element to wrap - * @returns {void} - */ - - - var groupSvgElem = this.groupSvgElem = function (elem) { - var g = document.createElementNS(NS.SVG, 'g'); - elem.replaceWith(g); - $$a(g).append(elem).data('gsvg', elem)[0].id = getNextId(); - }; // Set scope for these functions - // Object to contain editor event names and callback functions - - - var events = {}; - canvas.call = call; - /** - * Array of what was changed (elements, layers). - * @event module:svgcanvas.SvgCanvas#event:changed - * @type {Element[]} - */ - - /** - * Array of selected elements. - * @event module:svgcanvas.SvgCanvas#event:selected - * @type {Element[]} - */ - - /** - * Array of selected elements. - * @event module:svgcanvas.SvgCanvas#event:transition - * @type {Element[]} - */ - - /** - * The Element is always `SVGGElement`? - * If not `null`, will be the set current group element. - * @event module:svgcanvas.SvgCanvas#event:contextset - * @type {null|Element} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:pointsAdded - * @type {PlainObject} - * @property {boolean} closedSubpath - * @property {SVGCircleElement[]} grips Grips elements - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:zoomed - * @type {PlainObject} - * @property {Float} x - * @property {Float} y - * @property {Float} width - * @property {Float} height - * @property {0.5|2} factor - * @see module:SVGEditor.BBoxObjectWithFactor - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:updateCanvas - * @type {PlainObject} - * @property {false} center - * @property {module:math.XYObject} newCtr - */ - - /** - * @typedef {PlainObject} module:svgcanvas.ExtensionInitResponsePlusName - * @implements {module:svgcanvas.ExtensionInitResponse} - * @property {string} name The extension's resolved ID (whether explicit or based on file name) - */ - - /** - * Generalized extension object response of - * [`init()`]{@link module:svgcanvas.ExtensionInitCallback} - * along with the name of the extension. - * @event module:svgcanvas.SvgCanvas#event:extension_added - * @type {module:svgcanvas.ExtensionInitResponsePlusName|void} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:extensions_added - * @type {void} - */ - - /** - * @typedef {PlainObject} module:svgcanvas.Message - * @property {any} data The data - * @property {string} origin The origin - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:message - * @type {module:svgcanvas.Message} - */ - - /** - * SVG canvas converted to string. - * @event module:svgcanvas.SvgCanvas#event:saved - * @type {string} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:setnonce - * @type {!(string|Integer)} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:unsetnonce - * @type {void} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:zoomDone - * @type {void} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:cleared - * @type {void} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:exported - * @type {module:svgcanvas.ImageExportedResults} - */ - - /** - * @event module:svgcanvas.SvgCanvas#event:exportedPDF - * @type {module:svgcanvas.PDFExportedResults} - */ - - /** - * Creating a cover-all class until {@link https://github.com/jsdoc3/jsdoc/issues/1545} may be supported. - * `undefined` may be returned by {@link module:svgcanvas.SvgCanvas#event:extension_added} if the extension's `init` returns `undefined` It is also the type for the following events "zoomDone", "unsetnonce", "cleared", and "extensions_added". - * @event module:svgcanvas.SvgCanvas#event:GenericCanvasEvent - * @type {module:svgcanvas.SvgCanvas#event:selected|module:svgcanvas.SvgCanvas#event:changed|module:svgcanvas.SvgCanvas#event:contextset|module:svgcanvas.SvgCanvas#event:pointsAdded|module:svgcanvas.SvgCanvas#event:extension_added|module:svgcanvas.SvgCanvas#event:extensions_added|module:svgcanvas.SvgCanvas#event:message|module:svgcanvas.SvgCanvas#event:transition|module:svgcanvas.SvgCanvas#event:zoomed|module:svgcanvas.SvgCanvas#event:updateCanvas|module:svgcanvas.SvgCanvas#event:saved|module:svgcanvas.SvgCanvas#event:exported|module:svgcanvas.SvgCanvas#event:exportedPDF|module:svgcanvas.SvgCanvas#event:setnonce|module:svgcanvas.SvgCanvas#event:unsetnonce|void} - */ - - /** - * The promise return, if present, resolves to `undefined` - * (`extension_added`, `exported`, `saved`). - * @typedef {Promise<void>|void} module:svgcanvas.EventHandlerReturn - */ - - /** - * @callback module:svgcanvas.EventHandler - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:GenericCanvasEvent} arg - * @listens module:svgcanvas.SvgCanvas#event:GenericCanvasEvent - * @returns {module:svgcanvas.EventHandlerReturn} - */ - - /** - * Attaches a callback function to an event. - * @function module:svgcanvas.SvgCanvas#bind - * @param {"changed"|"contextset"|"selected"|"pointsAdded"|"extension_added"|"extensions_added"|"message"|"transition"|"zoomed"|"updateCanvas"|"zoomDone"|"saved"|"exported"|"exportedPDF"|"setnonce"|"unsetnonce"|"cleared"} ev - String indicating the name of the event - * @param {module:svgcanvas.EventHandler} f - The callback function to bind to the event - * @returns {module:svgcanvas.EventHandler} The previous event - */ - - canvas.bind = function (ev, f) { - var old = events[ev]; - events[ev] = f; - return old; - }; - /** - * Runs the SVG Document through the sanitizer and then updates its paths. - * @function module:svgcanvas.SvgCanvas#prepareSvg - * @param {XMLDocument} newDoc - The SVG DOM document - * @returns {void} - */ - - - this.prepareSvg = function (newDoc) { - this.sanitizeSvg(newDoc.documentElement); // convert paths into absolute commands - - var paths = _toConsumableArray(newDoc.getElementsByTagNameNS(NS.SVG, 'path')); - - paths.forEach(function (path) { - path.setAttribute('d', pathActions$1.convertPath(path)); - pathActions$1.fixEnd(path); - }); - }; - /** - * Hack for Firefox bugs where text element features aren't updated or get - * messed up. See issue 136 and issue 137. - * This function clones the element and re-selects it. - * @function module:svgcanvas~ffClone - * @todo Test for this bug on load and add it to "support" object instead of - * browser sniffing - * @param {Element} elem - The (text) DOM element to clone - * @returns {Element} Cloned element - */ - - - var ffClone = function ffClone(elem) { - if (!isGecko()) { - return elem; - } - - var clone = elem.cloneNode(true); - elem.before(clone); - elem.remove(); - selectorManager.releaseSelector(elem); - selectedElements[0] = clone; - selectorManager.requestSelector(clone).showGrips(true); - return clone; - }; // `this.each` is deprecated, if any extension used this it can be recreated by doing this: - // * @example $(canvas.getRootElem()).children().each(...) - // * @function module:svgcanvas.SvgCanvas#each - // this.each = function (cb) { - // $(svgroot).children().each(cb); - // }; - - /** - * Removes any old rotations if present, prepends a new rotation at the - * transformed center. - * @function module:svgcanvas.SvgCanvas#setRotationAngle - * @param {string|Float} val - The new rotation angle in degrees - * @param {boolean} preventUndo - Indicates whether the action should be undoable or not - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.setRotationAngle = function (val, preventUndo) { - // ensure val is the proper type - val = Number.parseFloat(val); - var elem = selectedElements[0]; - var oldTransform = elem.getAttribute('transform'); - var bbox = getBBox(elem); - var cx = bbox.x + bbox.width / 2, - cy = bbox.y + bbox.height / 2; - var tlist = getTransformList(elem); // only remove the real rotational transform if present (i.e. at index=0) - - if (tlist.numberOfItems > 0) { - var xform = tlist.getItem(0); - - if (xform.type === 4) { - tlist.removeItem(0); - } - } // find Rnc and insert it - - - if (val !== 0) { - var center = transformPoint(cx, cy, transformListToTransform(tlist).matrix); - var Rnc = svgroot.createSVGTransform(); - Rnc.setRotate(val, center.x, center.y); - - if (tlist.numberOfItems) { - tlist.insertItemBefore(Rnc, 0); - } else { - tlist.appendItem(Rnc); - } - } else if (tlist.numberOfItems === 0) { - elem.removeAttribute('transform'); - } - - if (!preventUndo) { - // we need to undo it, then redo it so it can be undo-able! :) - // TODO: figure out how to make changes to transform list undo-able cross-browser? - var newTransform = elem.getAttribute('transform'); - elem.setAttribute('transform', oldTransform); - changeSelectedAttribute('transform', newTransform, selectedElements); - call('changed', selectedElements); - } // const pointGripContainer = getElem('pathpointgrip_container'); - // if (elem.nodeName === 'path' && pointGripContainer) { - // pathActions.setPointContainerTransform(elem.getAttribute('transform')); - // } - - - var selector = selectorManager.requestSelector(selectedElements[0]); - selector.resize(); - Selector.updateGripCursors(val); - }; - /** - * Runs `recalculateDimensions` on the selected elements, - * adding the changes to a single batch command. - * @function module:svgcanvas.SvgCanvas#recalculateAllSelectedDimensions - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function () { - var text = currentResizeMode === 'none' ? 'position' : 'size'; - var batchCmd = new BatchCommand$1(text); - var i = selectedElements.length; - - while (i--) { - var elem = selectedElements[i]; // if (getRotationAngle(elem) && !hasMatrixTransform(getTransformList(elem))) { continue; } - - var cmd = recalculateDimensions(elem); - - if (cmd) { - batchCmd.addSubCommand(cmd); - } - } - - if (!batchCmd.isEmpty()) { - addCommandToHistory(batchCmd); - call('changed', selectedElements); - } - }; - /** - * Debug tool to easily see the current matrix in the browser's console. - * @function module:svgcanvas~logMatrix - * @param {SVGMatrix} m The matrix - * @returns {void} - */ - - - var logMatrix = function logMatrix(m) { - console.log([m.a, m.b, m.c, m.d, m.e, m.f]); // eslint-disable-line no-console - }; // Root Current Transformation Matrix in user units - - - var rootSctm = null; - /** - * Group: Selection. - */ - // TODO: do we need to worry about selectedBBoxes here? - - /** - * Selects only the given elements, shortcut for `clearSelection(); addToSelection()`. - * @function module:svgcanvas.SvgCanvas#selectOnly - * @param {Element[]} elems - an array of DOM elements to be selected - * @param {boolean} showGrips - Indicates whether the resize grips should be shown - * @returns {void} - */ - - var selectOnly = this.selectOnly = function (elems, showGrips) { - clearSelection(true); - addToSelection(elems, showGrips); - }; // TODO: could use slice here to make this faster? - // TODO: should the 'selected' handler - - /** - * Removes elements from the selection. - * @function module:svgcanvas.SvgCanvas#removeFromSelection - * @param {Element[]} elemsToRemove - An array of elements to remove from selection - * @returns {void} - */ - - /* const removeFromSelection = */ - - - this.removeFromSelection = function (elemsToRemove) { - if (isNullish(selectedElements[0])) { - return; - } - - if (!elemsToRemove.length) { - return; - } // find every element and remove it from our array copy - - - var newSelectedItems = [], - len = selectedElements.length; - - for (var i = 0; i < len; ++i) { - var elem = selectedElements[i]; - - if (elem) { - // keep the item - if (!elemsToRemove.includes(elem)) { - newSelectedItems.push(elem); - } else { - // remove the item and its selector - selectorManager.releaseSelector(elem); - } - } - } // the copy becomes the master now - - - selectedElements = newSelectedItems; - }; - /** - * Clears the selection, then adds all elements in the current layer to the selection. - * @function module:svgcanvas.SvgCanvas#selectAllInCurrentLayer - * @returns {void} - */ - - - this.selectAllInCurrentLayer = function () { - var currentLayer = getCurrentDrawing().getCurrentLayer(); - - if (currentLayer) { - currentMode = 'select'; - selectOnly($$a(currentGroup || currentLayer).children()); - } - }; - - var drawnPath = null; // Mouse events - - (function () { - var freehand = { - minx: null, - miny: null, - maxx: null, - maxy: null - }; - var THRESHOLD_DIST = 0.8, - STEP_COUNT = 10; - var dAttr = null, - startX = null, - startY = null, - rStartX = null, - rStartY = null, - initBbox = {}, - sumDistance = 0, - controllPoint2 = { - x: 0, - y: 0 - }, - controllPoint1 = { - x: 0, - y: 0 - }, - start = { - x: 0, - y: 0 - }, - end = { - x: 0, - y: 0 - }, - bSpline = { - x: 0, - y: 0 - }, - nextPos = { - x: 0, - y: 0 - }, - parameter, - nextParameter; - - var getBsplinePoint = function getBsplinePoint(t) { - var spline = { - x: 0, - y: 0 - }, - p0 = controllPoint2, - p1 = controllPoint1, - p2 = start, - p3 = end, - S = 1.0 / 6.0, - t2 = t * t, - t3 = t2 * t; - var m = [[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 0, 3, 0], [1, 4, 1, 0]]; - spline.x = S * ((p0.x * m[0][0] + p1.x * m[0][1] + p2.x * m[0][2] + p3.x * m[0][3]) * t3 + (p0.x * m[1][0] + p1.x * m[1][1] + p2.x * m[1][2] + p3.x * m[1][3]) * t2 + (p0.x * m[2][0] + p1.x * m[2][1] + p2.x * m[2][2] + p3.x * m[2][3]) * t + (p0.x * m[3][0] + p1.x * m[3][1] + p2.x * m[3][2] + p3.x * m[3][3])); - spline.y = S * ((p0.y * m[0][0] + p1.y * m[0][1] + p2.y * m[0][2] + p3.y * m[0][3]) * t3 + (p0.y * m[1][0] + p1.y * m[1][1] + p2.y * m[1][2] + p3.y * m[1][3]) * t2 + (p0.y * m[2][0] + p1.y * m[2][1] + p2.y * m[2][2] + p3.y * m[2][3]) * t + (p0.y * m[3][0] + p1.y * m[3][1] + p2.y * m[3][2] + p3.y * m[3][3])); - return { - x: spline.x, - y: spline.y - }; - }; - /** - * Follows these conditions: - * - When we are in a create mode, the element is added to the canvas but the - * action is not recorded until mousing up. - * - When we are in select mode, select the element, remember the position - * and do nothing else. - * @param {MouseEvent} evt - * @fires module:svgcanvas.SvgCanvas#event:ext_mouseDown - * @returns {void} - */ - - - var mouseDown = function mouseDown(evt) { - if (canvas.spaceKey || evt.button === 1) { - return; - } - - var rightClick = evt.button === 2; - - if (evt.altKey) { - // duplicate when dragging - canvas.cloneSelectedElements(0, 0); - } - - rootSctm = $$a('#svgcontent g')[0].getScreenCTM().inverse(); - var pt = transformPoint(evt.pageX, evt.pageY, rootSctm), - mouseX = pt.x * currentZoom, - mouseY = pt.y * currentZoom; - evt.preventDefault(); - - if (rightClick) { - currentMode = 'select'; - lastClickPoint = pt; - } // This would seem to be unnecessary... - // if (!['select', 'resize'].includes(currentMode)) { - // setGradient(); - // } - - - var x = mouseX / currentZoom, - y = mouseY / currentZoom; - var mouseTarget = getMouseTarget(evt); - - if (mouseTarget.tagName === 'a' && mouseTarget.childNodes.length === 1) { - mouseTarget = mouseTarget.firstChild; - } // realX/y ignores grid-snap value - - - var realX = x; - rStartX = startX = x; - var realY = y; - rStartY = startY = y; - - if (curConfig.gridSnapping) { - x = snapToGrid(x); - y = snapToGrid(y); - startX = snapToGrid(startX); - startY = snapToGrid(startY); - } // if it is a selector grip, then it must be a single element selected, - // set the mouseTarget to that and update the mode to rotate/resize - - - if (mouseTarget === selectorManager.selectorParentGroup && !isNullish(selectedElements[0])) { - var grip = evt.target; - var griptype = elData(grip, 'type'); // rotating - - if (griptype === 'rotate') { - currentMode = 'rotate'; // resizing - } else if (griptype === 'resize') { - currentMode = 'resize'; - currentResizeMode = elData(grip, 'dir'); - } - - mouseTarget = selectedElements[0]; - } - - startTransform = mouseTarget.getAttribute('transform'); - var tlist = getTransformList(mouseTarget); - - switch (currentMode) { - case 'select': - started = true; - currentResizeMode = 'none'; - - if (rightClick) { - started = false; - } - - if (mouseTarget !== svgroot) { - // if this element is not yet selected, clear selection and select it - if (!selectedElements.includes(mouseTarget)) { - // only clear selection if shift is not pressed (otherwise, add - // element to selection) - if (!evt.shiftKey) { - // No need to do the call here as it will be done on addToSelection - clearSelection(true); - } - - addToSelection([mouseTarget]); - justSelected = mouseTarget; - pathActions$1.clear(); - } // else if it's a path, go into pathedit mode in mouseup - - - if (!rightClick) { - // insert a dummy transform so if the element(s) are moved it will have - // a transform to use for its translate - var _iterator = _createForOfIteratorHelper(selectedElements), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var selectedElement = _step.value; - - if (isNullish(selectedElement)) { - continue; - } - - var slist = getTransformList(selectedElement); - - if (slist.numberOfItems) { - slist.insertItemBefore(svgroot.createSVGTransform(), 0); - } else { - slist.appendItem(svgroot.createSVGTransform()); - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - } else if (!rightClick) { - clearSelection(); - currentMode = 'multiselect'; - - if (isNullish(rubberBox)) { - rubberBox = selectorManager.getRubberBandBox(); - } - - rStartX *= currentZoom; - rStartY *= currentZoom; // console.log('p',[evt.pageX, evt.pageY]); - // console.log('c',[evt.clientX, evt.clientY]); - // console.log('o',[evt.offsetX, evt.offsetY]); - // console.log('s',[startX, startY]); - - assignAttributes(rubberBox, { - x: rStartX, - y: rStartY, - width: 0, - height: 0, - display: 'inline' - }); - } - - break; - - case 'zoom': - started = true; - - if (isNullish(rubberBox)) { - rubberBox = selectorManager.getRubberBandBox(); - } - - assignAttributes(rubberBox, { - x: realX * currentZoom, - y: realX * currentZoom, - width: 0, - height: 0, - display: 'inline' - }); - break; - - case 'resize': - { - started = true; - startX = x; - startY = y; // Getting the BBox from the selection box, since we know we - // want to orient around it - - initBbox = getBBox($$a('#selectedBox0')[0]); - var bb = {}; - $$a.each(initBbox, function (key, val) { - bb[key] = val / currentZoom; - }); - initBbox = bb; // append three dummy transforms to the tlist so that - // we can translate,scale,translate in mousemove - - var pos = getRotationAngle(mouseTarget) ? 1 : 0; - - if (hasMatrixTransform(tlist)) { - tlist.insertItemBefore(svgroot.createSVGTransform(), pos); - tlist.insertItemBefore(svgroot.createSVGTransform(), pos); - tlist.insertItemBefore(svgroot.createSVGTransform(), pos); - } else { - tlist.appendItem(svgroot.createSVGTransform()); - tlist.appendItem(svgroot.createSVGTransform()); - tlist.appendItem(svgroot.createSVGTransform()); - - if (supportsNonScalingStroke()) { - // Handle crash for newer Chrome and Safari 6 (Mobile and Desktop): - // https://code.google.com/p/svg-edit/issues/detail?id=904 - // Chromium issue: https://code.google.com/p/chromium/issues/detail?id=114625 - // TODO: Remove this workaround once vendor fixes the issue - var iswebkit = isWebkit(); - var delayedStroke; - - if (iswebkit) { - delayedStroke = function delayedStroke(ele) { - var stroke_ = ele.getAttribute('stroke'); - ele.removeAttribute('stroke'); // Re-apply stroke after delay. Anything higher than 1 seems to cause flicker - - if (stroke_ !== null) setTimeout(function () { - ele.setAttribute('stroke', stroke_); - }, 0); - }; - } - - mouseTarget.style.vectorEffect = 'non-scaling-stroke'; - - if (iswebkit) { - delayedStroke(mouseTarget); - } - - var all = mouseTarget.getElementsByTagName('*'), - len = all.length; - - for (var i = 0; i < len; i++) { - if (!all[i].style) { - // mathML - continue; - } - - all[i].style.vectorEffect = 'non-scaling-stroke'; - - if (iswebkit) { - delayedStroke(all[i]); - } - } - } - } - - break; - } - - case 'fhellipse': - case 'fhrect': - case 'fhpath': - start.x = realX; - start.y = realY; - controllPoint1 = { - x: 0, - y: 0 - }; - controllPoint2 = { - x: 0, - y: 0 - }; - started = true; - dAttr = realX + ',' + realY + ' '; // Commented out as doing nothing now: - // strokeW = parseFloat(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width; - - addSVGElementFromJson({ - element: 'polyline', - curStyles: true, - attr: { - points: dAttr, - id: getNextId(), - fill: 'none', - opacity: curShape.opacity / 2, - 'stroke-linecap': 'round', - style: 'pointer-events:none' - } - }); - freehand.minx = realX; - freehand.maxx = realX; - freehand.miny = realY; - freehand.maxy = realY; - break; - - case 'image': - { - started = true; - var newImage = addSVGElementFromJson({ - element: 'image', - attr: { - x: x, - y: y, - width: 0, - height: 0, - id: getNextId(), - opacity: curShape.opacity / 2, - style: 'pointer-events:inherit' - } - }); - setHref(newImage, lastGoodImgUrl); - preventClickDefault(newImage); - break; - } - - case 'square': // TODO: once we create the rect, we lose information that this was a square - // (for resizing purposes this could be important) - // Fallthrough - - case 'rect': - started = true; - startX = x; - startY = y; - addSVGElementFromJson({ - element: 'rect', - curStyles: true, - attr: { - x: x, - y: y, - width: 0, - height: 0, - id: getNextId(), - opacity: curShape.opacity / 2 - } - }); - break; - - case 'line': - { - started = true; - var strokeW = Number(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width; - addSVGElementFromJson({ - element: 'line', - curStyles: true, - attr: { - x1: x, - y1: y, - x2: x, - y2: y, - id: getNextId(), - stroke: curShape.stroke, - 'stroke-width': strokeW, - 'stroke-dasharray': curShape.stroke_dasharray, - 'stroke-linejoin': curShape.stroke_linejoin, - 'stroke-linecap': curShape.stroke_linecap, - 'stroke-opacity': curShape.stroke_opacity, - fill: 'none', - opacity: curShape.opacity / 2, - style: 'pointer-events:none' - } - }); - break; - } - - case 'circle': - started = true; - addSVGElementFromJson({ - element: 'circle', - curStyles: true, - attr: { - cx: x, - cy: y, - r: 0, - id: getNextId(), - opacity: curShape.opacity / 2 - } - }); - break; - - case 'ellipse': - started = true; - addSVGElementFromJson({ - element: 'ellipse', - curStyles: true, - attr: { - cx: x, - cy: y, - rx: 0, - ry: 0, - id: getNextId(), - opacity: curShape.opacity / 2 - } - }); - break; - - case 'text': - started = true; - /* const newText = */ - - addSVGElementFromJson({ - element: 'text', - curStyles: true, - attr: { - x: x, - y: y, - id: getNextId(), - fill: curText.fill, - 'stroke-width': curText.stroke_width, - 'font-size': curText.font_size, - 'font-family': curText.font_family, - 'text-anchor': 'middle', - 'xml:space': 'preserve', - opacity: curShape.opacity - } - }); // newText.textContent = 'text'; - - break; - - case 'path': // Fall through - - case 'pathedit': - startX *= currentZoom; - startY *= currentZoom; - pathActions$1.mouseDown(evt, mouseTarget, startX, startY); - started = true; - break; - - case 'textedit': - startX *= currentZoom; - startY *= currentZoom; - textActions.mouseDown(evt, mouseTarget, startX, startY); - started = true; - break; - - case 'rotate': - started = true; // we are starting an undoable change (a drag-rotation) - - canvas.undoMgr.beginUndoableChange('transform', selectedElements); - break; - } - /** - * The main (left) mouse button is held down on the canvas area. - * @event module:svgcanvas.SvgCanvas#event:ext_mouseDown - * @type {PlainObject} - * @property {MouseEvent} event The event object - * @property {Float} start_x x coordinate on canvas - * @property {Float} start_y y coordinate on canvas - * @property {Element[]} selectedElements An array of the selected Elements - */ - - - var extResult = runExtensions('mouseDown', - /** @type {module:svgcanvas.SvgCanvas#event:ext_mouseDown} */ - { - event: evt, - start_x: startX, - start_y: startY, - selectedElements: selectedElements - }, true); - $$a.each(extResult, function (i, r) { - if (r && r.started) { - started = true; - } - }); - }; // in this function we do not record any state changes yet (but we do update - // any elements that are still being created, moved or resized on the canvas) - - /** - * - * @param {MouseEvent} evt - * @fires module:svgcanvas.SvgCanvas#event:transition - * @fires module:svgcanvas.SvgCanvas#event:ext_mouseMove - * @returns {void} - */ - - - var mouseMove = function mouseMove(evt) { - if (!started) { - return; - } - - if (evt.button === 1 || canvas.spaceKey) { - return; - } - - var i, - xya, - c, - cx, - cy, - dx, - dy, - len, - angle, - box, - selected = selectedElements[0]; - var pt = transformPoint(evt.pageX, evt.pageY, rootSctm), - mouseX = pt.x * currentZoom, - mouseY = pt.y * currentZoom, - shape = getElem(getId()); - var realX = mouseX / currentZoom; - var x = realX; - var realY = mouseY / currentZoom; - var y = realY; - - if (curConfig.gridSnapping) { - x = snapToGrid(x); - y = snapToGrid(y); - } - - evt.preventDefault(); - var tlist; - - switch (currentMode) { - case 'select': - { - // we temporarily use a translate on the element(s) being dragged - // this transform is removed upon mousing up and the element is - // relocated to the new location - if (selectedElements[0] !== null) { - dx = x - startX; - dy = y - startY; - - if (curConfig.gridSnapping) { - dx = snapToGrid(dx); - dy = snapToGrid(dy); - } - /* - // Commenting out as currently has no effect - if (evt.shiftKey) { - xya = snapToAngle(startX, startY, x, y); - ({x, y} = xya); - } - */ - - - if (dx !== 0 || dy !== 0) { - len = selectedElements.length; - - for (i = 0; i < len; ++i) { - selected = selectedElements[i]; - - if (isNullish(selected)) { - break; - } // if (i === 0) { - // const box = utilsGetBBox(selected); - // selectedBBoxes[i].x = box.x + dx; - // selectedBBoxes[i].y = box.y + dy; - // } - // update the dummy transform in our transform list - // to be a translate - - - var xform = svgroot.createSVGTransform(); - tlist = getTransformList(selected); // Note that if Webkit and there's no ID for this - // element, the dummy transform may have gotten lost. - // This results in unexpected behaviour - - xform.setTranslate(dx, dy); - - if (tlist.numberOfItems) { - tlist.replaceItem(xform, 0); - } else { - tlist.appendItem(xform); - } // update our internal bbox that we're tracking while dragging - - - selectorManager.requestSelector(selected).resize(); - } - - call('transition', selectedElements); - } - } - - break; - } - - case 'multiselect': - { - realX *= currentZoom; - realY *= currentZoom; - assignAttributes(rubberBox, { - x: Math.min(rStartX, realX), - y: Math.min(rStartY, realY), - width: Math.abs(realX - rStartX), - height: Math.abs(realY - rStartY) - }); // for each selected: - // - if newList contains selected, do nothing - // - if newList doesn't contain selected, remove it from selected - // - for any newList that was not in selectedElements, add it to selected - - var elemsToRemove = selectedElements.slice(), - elemsToAdd = [], - newList = getIntersectionList(); // For every element in the intersection, add if not present in selectedElements. - - len = newList.length; - - for (i = 0; i < len; ++i) { - var intElem = newList[i]; // Found an element that was not selected before, so we should add it. - - if (!selectedElements.includes(intElem)) { - elemsToAdd.push(intElem); - } // Found an element that was already selected, so we shouldn't remove it. - - - var foundInd = elemsToRemove.indexOf(intElem); - - if (foundInd !== -1) { - elemsToRemove.splice(foundInd, 1); - } - } - - if (elemsToRemove.length > 0) { - canvas.removeFromSelection(elemsToRemove); - } - - if (elemsToAdd.length > 0) { - canvas.addToSelection(elemsToAdd); - } - - break; - } - - case 'resize': - { - // we track the resize bounding box and translate/scale the selected element - // while the mouse is down, when mouse goes up, we use this to recalculate - // the shape's coordinates - tlist = getTransformList(selected); - var hasMatrix = hasMatrixTransform(tlist); - box = hasMatrix ? initBbox : getBBox(selected); - var left = box.x, - top = box.y, - _box = box, - width = _box.width, - height = _box.height; - dx = x - startX; - dy = y - startY; - - if (curConfig.gridSnapping) { - dx = snapToGrid(dx); - dy = snapToGrid(dy); - height = snapToGrid(height); - width = snapToGrid(width); - } // if rotated, adjust the dx,dy values - - - angle = getRotationAngle(selected); - - if (angle) { - var r = Math.sqrt(dx * dx + dy * dy), - theta = Math.atan2(dy, dx) - angle * Math.PI / 180.0; - dx = r * Math.cos(theta); - dy = r * Math.sin(theta); - } // if not stretching in y direction, set dy to 0 - // if not stretching in x direction, set dx to 0 - - - if (!currentResizeMode.includes('n') && !currentResizeMode.includes('s')) { - dy = 0; - } - - if (!currentResizeMode.includes('e') && !currentResizeMode.includes('w')) { - dx = 0; - } - - var // ts = null, - tx = 0, - ty = 0, - sy = height ? (height + dy) / height : 1, - sx = width ? (width + dx) / width : 1; // if we are dragging on the north side, then adjust the scale factor and ty - - if (currentResizeMode.includes('n')) { - sy = height ? (height - dy) / height : 1; - ty = height; - } // if we dragging on the east side, then adjust the scale factor and tx - - - if (currentResizeMode.includes('w')) { - sx = width ? (width - dx) / width : 1; - tx = width; - } // update the transform list with translate,scale,translate - - - var translateOrigin = svgroot.createSVGTransform(), - scale = svgroot.createSVGTransform(), - translateBack = svgroot.createSVGTransform(); - - if (curConfig.gridSnapping) { - left = snapToGrid(left); - tx = snapToGrid(tx); - top = snapToGrid(top); - ty = snapToGrid(ty); - } - - translateOrigin.setTranslate(-(left + tx), -(top + ty)); - - if (evt.shiftKey) { - if (sx === 1) { - sx = sy; - } else { - sy = sx; - } - } - - scale.setScale(sx, sy); - translateBack.setTranslate(left + tx, top + ty); - - if (hasMatrix) { - var diff = angle ? 1 : 0; - tlist.replaceItem(translateOrigin, 2 + diff); - tlist.replaceItem(scale, 1 + diff); - tlist.replaceItem(translateBack, Number(diff)); - } else { - var N = tlist.numberOfItems; - tlist.replaceItem(translateBack, N - 3); - tlist.replaceItem(scale, N - 2); - tlist.replaceItem(translateOrigin, N - 1); - } - - selectorManager.requestSelector(selected).resize(); - call('transition', selectedElements); - break; - } - - case 'zoom': - { - realX *= currentZoom; - realY *= currentZoom; - assignAttributes(rubberBox, { - x: Math.min(rStartX * currentZoom, realX), - y: Math.min(rStartY * currentZoom, realY), - width: Math.abs(realX - rStartX * currentZoom), - height: Math.abs(realY - rStartY * currentZoom) - }); - break; - } - - case 'text': - { - assignAttributes(shape, { - x: x, - y: y - }); - break; - } - - case 'line': - { - if (curConfig.gridSnapping) { - x = snapToGrid(x); - y = snapToGrid(y); - } - - var x2 = x; - var y2 = y; - - if (evt.shiftKey) { - xya = snapToAngle(startX, startY, x2, y2); - x2 = xya.x; - y2 = xya.y; - } - - shape.setAttribute('x2', x2); - shape.setAttribute('y2', y2); - break; - } - - case 'foreignObject': // fall through - - case 'square': // fall through - - case 'rect': // fall through - - case 'image': - { - var square = currentMode === 'square' || evt.shiftKey; - var w = Math.abs(x - startX), - h = Math.abs(y - startY); - var newX, newY; - - if (square) { - w = h = Math.max(w, h); - newX = startX < x ? startX : startX - w; - newY = startY < y ? startY : startY - h; - } else { - newX = Math.min(startX, x); - newY = Math.min(startY, y); - } - - if (curConfig.gridSnapping) { - w = snapToGrid(w); - h = snapToGrid(h); - newX = snapToGrid(newX); - newY = snapToGrid(newY); - } - - assignAttributes(shape, { - width: w, - height: h, - x: newX, - y: newY - }); - break; - } - - case 'circle': - { - c = $$a(shape).attr(['cx', 'cy']); - var _c = c; - cx = _c.cx; - cy = _c.cy; - var rad = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)); - - if (curConfig.gridSnapping) { - rad = snapToGrid(rad); - } - - shape.setAttribute('r', rad); - break; - } - - case 'ellipse': - { - c = $$a(shape).attr(['cx', 'cy']); - var _c2 = c; - cx = _c2.cx; - cy = _c2.cy; - - if (curConfig.gridSnapping) { - x = snapToGrid(x); - cx = snapToGrid(cx); - y = snapToGrid(y); - cy = snapToGrid(cy); - } - - shape.setAttribute('rx', Math.abs(x - cx)); - var ry = Math.abs(evt.shiftKey ? x - cx : y - cy); - shape.setAttribute('ry', ry); - break; - } - - case 'fhellipse': - case 'fhrect': - { - freehand.minx = Math.min(realX, freehand.minx); - freehand.maxx = Math.max(realX, freehand.maxx); - freehand.miny = Math.min(realY, freehand.miny); - freehand.maxy = Math.max(realY, freehand.maxy); - } - // Fallthrough - - case 'fhpath': - { - // dAttr += + realX + ',' + realY + ' '; - // shape.setAttribute('points', dAttr); - end.x = realX; - end.y = realY; - - if (controllPoint2.x && controllPoint2.y) { - for (i = 0; i < STEP_COUNT - 1; i++) { - parameter = i / STEP_COUNT; - nextParameter = (i + 1) / STEP_COUNT; - bSpline = getBsplinePoint(nextParameter); - nextPos = bSpline; - bSpline = getBsplinePoint(parameter); - sumDistance += Math.sqrt((nextPos.x - bSpline.x) * (nextPos.x - bSpline.x) + (nextPos.y - bSpline.y) * (nextPos.y - bSpline.y)); - - if (sumDistance > THRESHOLD_DIST) { - sumDistance -= THRESHOLD_DIST; // Faster than completely re-writing the points attribute. - - var point = svgcontent.createSVGPoint(); - point.x = bSpline.x; - point.y = bSpline.y; - shape.points.appendItem(point); - } - } - } - - controllPoint2 = { - x: controllPoint1.x, - y: controllPoint1.y - }; - controllPoint1 = { - x: start.x, - y: start.y - }; - start = { - x: end.x, - y: end.y - }; - break; // update path stretch line coordinates - } - - case 'path': // fall through - - case 'pathedit': - { - x *= currentZoom; - y *= currentZoom; - - if (curConfig.gridSnapping) { - x = snapToGrid(x); - y = snapToGrid(y); - startX = snapToGrid(startX); - startY = snapToGrid(startY); - } - - if (evt.shiftKey) { - var path$1 = path; - var x1, y1; - - if (path$1) { - x1 = path$1.dragging ? path$1.dragging[0] : startX; - y1 = path$1.dragging ? path$1.dragging[1] : startY; - } else { - x1 = startX; - y1 = startY; - } - - xya = snapToAngle(x1, y1, x, y); - var _xya = xya; - x = _xya.x; - y = _xya.y; - } - - if (rubberBox && rubberBox.getAttribute('display') !== 'none') { - realX *= currentZoom; - realY *= currentZoom; - assignAttributes(rubberBox, { - x: Math.min(rStartX * currentZoom, realX), - y: Math.min(rStartY * currentZoom, realY), - width: Math.abs(realX - rStartX * currentZoom), - height: Math.abs(realY - rStartY * currentZoom) - }); - } - - pathActions$1.mouseMove(x, y); - break; - } - - case 'textedit': - { - x *= currentZoom; - y *= currentZoom; // if (rubberBox && rubberBox.getAttribute('display') !== 'none') { - // assignAttributes(rubberBox, { - // x: Math.min(startX, x), - // y: Math.min(startY, y), - // width: Math.abs(x - startX), - // height: Math.abs(y - startY) - // }, 100); - // } - - textActions.mouseMove(mouseX, mouseY); - break; - } - - case 'rotate': - { - box = getBBox(selected); - cx = box.x + box.width / 2; - cy = box.y + box.height / 2; - var m = getMatrix(selected), - center = transformPoint(cx, cy, m); - cx = center.x; - cy = center.y; - angle = (Math.atan2(cy - y, cx - x) * (180 / Math.PI) - 90) % 360; - - if (curConfig.gridSnapping) { - angle = snapToGrid(angle); - } - - if (evt.shiftKey) { - // restrict rotations to nice angles (WRS) - var snap = 45; - angle = Math.round(angle / snap) * snap; - } - - canvas.setRotationAngle(angle < -180 ? 360 + angle : angle, true); - call('transition', selectedElements); - break; - } - } - /** - * The mouse has moved on the canvas area. - * @event module:svgcanvas.SvgCanvas#event:ext_mouseMove - * @type {PlainObject} - * @property {MouseEvent} event The event object - * @property {Float} mouse_x x coordinate on canvas - * @property {Float} mouse_y y coordinate on canvas - * @property {Element} selected Refers to the first selected element - */ - - - runExtensions('mouseMove', - /** @type {module:svgcanvas.SvgCanvas#event:ext_mouseMove} */ - { - event: evt, - mouse_x: mouseX, - mouse_y: mouseY, - selected: selected - }); - }; // mouseMove() - // - in create mode, the element's opacity is set properly, we create an InsertElementCommand - // and store it on the Undo stack - // - in move/resize mode, the element's attributes which were affected by the move/resize are - // identified, a ChangeElementCommand is created and stored on the stack for those attrs - // this is done in when we recalculate the selected dimensions() - - /** - * - * @param {MouseEvent} evt - * @fires module:svgcanvas.SvgCanvas#event:zoomed - * @fires module:svgcanvas.SvgCanvas#event:changed - * @fires module:svgcanvas.SvgCanvas#event:ext_mouseUp - * @returns {void} - */ - - - var mouseUp = function mouseUp(evt) { - if (evt.button === 2) { - return; - } - - var tempJustSelected = justSelected; - justSelected = null; - - if (!started) { - return; - } - - var pt = transformPoint(evt.pageX, evt.pageY, rootSctm), - mouseX = pt.x * currentZoom, - mouseY = pt.y * currentZoom, - x = mouseX / currentZoom, - y = mouseY / currentZoom; - var element = getElem(getId()); - var keep = false; - var realX = x; - var realY = y; // TODO: Make true when in multi-unit mode - - started = false; - var attrs, t; - - switch (currentMode) { - // intentionally fall-through to select here - case 'resize': - case 'multiselect': - if (!isNullish(rubberBox)) { - rubberBox.setAttribute('display', 'none'); - curBBoxes = []; - } - - currentMode = 'select'; - // Fallthrough - - case 'select': - if (!isNullish(selectedElements[0])) { - // if we only have one selected element - if (isNullish(selectedElements[1])) { - // set our current stroke/fill properties to the element's - var selected = selectedElements[0]; - - switch (selected.tagName) { - case 'g': - case 'use': - case 'image': - case 'foreignObject': - break; - - default: - curProperties.fill = selected.getAttribute('fill'); - curProperties.fill_opacity = selected.getAttribute('fill-opacity'); - curProperties.stroke = selected.getAttribute('stroke'); - curProperties.stroke_opacity = selected.getAttribute('stroke-opacity'); - curProperties.stroke_width = selected.getAttribute('stroke-width'); - curProperties.stroke_dasharray = selected.getAttribute('stroke-dasharray'); - curProperties.stroke_linejoin = selected.getAttribute('stroke-linejoin'); - curProperties.stroke_linecap = selected.getAttribute('stroke-linecap'); - } - - if (selected.tagName === 'text') { - curText.font_size = selected.getAttribute('font-size'); - curText.font_family = selected.getAttribute('font-family'); - } - - selectorManager.requestSelector(selected).showGrips(true); // This shouldn't be necessary as it was done on mouseDown... - // call('selected', [selected]); - } // always recalculate dimensions to strip off stray identity transforms - - - recalculateAllSelectedDimensions(); // if it was being dragged/resized - - if (realX !== rStartX || realY !== rStartY) { - var len = selectedElements.length; - - for (var i = 0; i < len; ++i) { - if (isNullish(selectedElements[i])) { - break; - } - - if (!selectedElements[i].firstChild) { - // Not needed for groups (incorrectly resizes elems), possibly not needed at all? - selectorManager.requestSelector(selectedElements[i]).resize(); - } - } // no change in position/size, so maybe we should move to pathedit - - } else { - t = evt.target; - - if (selectedElements[0].nodeName === 'path' && isNullish(selectedElements[1])) { - pathActions$1.select(selectedElements[0]); // if it was a path - // else, if it was selected and this is a shift-click, remove it from selection - } else if (evt.shiftKey) { - if (tempJustSelected !== t) { - canvas.removeFromSelection([t]); - } - } - } // no change in mouse position - // Remove non-scaling stroke - - - if (supportsNonScalingStroke()) { - var elem = selectedElements[0]; - - if (elem) { - elem.removeAttribute('style'); - walkTree(elem, function (el) { - el.removeAttribute('style'); - }); - } - } - } - - return; - - case 'zoom': - { - if (!isNullish(rubberBox)) { - rubberBox.setAttribute('display', 'none'); - } - - var factor = evt.shiftKey ? 0.5 : 2; - call('zoomed', { - x: Math.min(rStartX, realX), - y: Math.min(rStartY, realY), - width: Math.abs(realX - rStartX), - height: Math.abs(realY - rStartY), - factor: factor - }); - return; - } - - case 'fhpath': - { - // Check that the path contains at least 2 points; a degenerate one-point path - // causes problems. - // Webkit ignores how we set the points attribute with commas and uses space - // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870 - sumDistance = 0; - controllPoint2 = { - x: 0, - y: 0 - }; - controllPoint1 = { - x: 0, - y: 0 - }; - start = { - x: 0, - y: 0 - }; - end = { - x: 0, - y: 0 - }; - var coords = element.getAttribute('points'); - var commaIndex = coords.indexOf(','); - - if (commaIndex >= 0) { - keep = coords.includes(',', commaIndex + 1); - } else { - keep = coords.includes(' ', coords.indexOf(' ') + 1); - } - - if (keep) { - element = pathActions$1.smoothPolylineIntoPath(element); - } - - break; - } - - case 'line': - attrs = $$a(element).attr(['x1', 'x2', 'y1', 'y2']); - keep = attrs.x1 !== attrs.x2 || attrs.y1 !== attrs.y2; - break; - - case 'foreignObject': - case 'square': - case 'rect': - case 'image': - attrs = $$a(element).attr(['width', 'height']); // Image should be kept regardless of size (use inherit dimensions later) - - keep = attrs.width || attrs.height || currentMode === 'image'; - break; - - case 'circle': - keep = element.getAttribute('r') !== '0'; - break; - - case 'ellipse': - attrs = $$a(element).attr(['rx', 'ry']); - keep = attrs.rx || attrs.ry; - break; - - case 'fhellipse': - if (freehand.maxx - freehand.minx > 0 && freehand.maxy - freehand.miny > 0) { - element = addSVGElementFromJson({ - element: 'ellipse', - curStyles: true, - attr: { - cx: (freehand.minx + freehand.maxx) / 2, - cy: (freehand.miny + freehand.maxy) / 2, - rx: (freehand.maxx - freehand.minx) / 2, - ry: (freehand.maxy - freehand.miny) / 2, - id: getId() - } - }); - call('changed', [element]); - keep = true; - } - - break; - - case 'fhrect': - if (freehand.maxx - freehand.minx > 0 && freehand.maxy - freehand.miny > 0) { - element = addSVGElementFromJson({ - element: 'rect', - curStyles: true, - attr: { - x: freehand.minx, - y: freehand.miny, - width: freehand.maxx - freehand.minx, - height: freehand.maxy - freehand.miny, - id: getId() - } - }); - call('changed', [element]); - keep = true; - } - - break; - - case 'text': - keep = true; - selectOnly([element]); - textActions.start(element); - break; - - case 'path': - { - // set element to null here so that it is not removed nor finalized - element = null; // continue to be set to true so that mouseMove happens - - started = true; - var res = pathActions$1.mouseUp(evt, element, mouseX, mouseY); - element = res.element; - keep = res.keep; - break; - } - - case 'pathedit': - keep = true; - element = null; - pathActions$1.mouseUp(evt); - break; - - case 'textedit': - keep = false; - element = null; - textActions.mouseUp(evt, mouseX, mouseY); - break; - - case 'rotate': - { - keep = true; - element = null; - currentMode = 'select'; - var batchCmd = canvas.undoMgr.finishUndoableChange(); - - if (!batchCmd.isEmpty()) { - addCommandToHistory(batchCmd); - } // perform recalculation to weed out any stray identity transforms that might get stuck - - - recalculateAllSelectedDimensions(); - call('changed', selectedElements); - break; - } - } - /** - * The main (left) mouse button is released (anywhere). - * @event module:svgcanvas.SvgCanvas#event:ext_mouseUp - * @type {PlainObject} - * @property {MouseEvent} event The event object - * @property {Float} mouse_x x coordinate on canvas - * @property {Float} mouse_y y coordinate on canvas - */ - - - var extResult = runExtensions('mouseUp', - /** @type {module:svgcanvas.SvgCanvas#event:ext_mouseUp} */ - { - event: evt, - mouse_x: mouseX, - mouse_y: mouseY - }, true); - $$a.each(extResult, function (i, r) { - if (r) { - keep = r.keep || keep; - element = r.element; - started = r.started || started; - } - }); - - if (!keep && !isNullish(element)) { - getCurrentDrawing().releaseId(getId()); - element.remove(); - element = null; - t = evt.target; // if this element is in a group, go up until we reach the top-level group - // just below the layer groups - // TODO: once we implement links, we also would have to check for <a> elements - - while (t && t.parentNode && t.parentNode.parentNode && t.parentNode.parentNode.tagName === 'g') { - t = t.parentNode; - } // if we are not in the middle of creating a path, and we've clicked on some shape, - // then go to Select mode. - // WebKit returns <div> when the canvas is clicked, Firefox/Opera return <svg> - - - if ((currentMode !== 'path' || !drawnPath) && t && t.parentNode && t.parentNode.id !== 'selectorParentGroup' && t.id !== 'svgcanvas' && t.id !== 'svgroot') { - // switch into "select" mode if we've clicked on an element - canvas.setMode('select'); - selectOnly([t], true); - } - } else if (!isNullish(element)) { - /** - * @name module:svgcanvas.SvgCanvas#addedNew - * @type {boolean} - */ - canvas.addedNew = true; - - var aniDur = 0.2; - var cAni; - - if (opacAni.beginElement && Number.parseFloat(element.getAttribute('opacity')) !== curShape.opacity) { - cAni = $$a(opacAni).clone().attr({ - to: curShape.opacity, - dur: aniDur - }).appendTo(element); - - try { - // Fails in FF4 on foreignObject - cAni[0].beginElement(); - } catch (e) {} - } else { - aniDur = 0; - } // Ideally this would be done on the endEvent of the animation, - // but that doesn't seem to be supported in Webkit - - - setTimeout(function () { - if (cAni) { - cAni.remove(); - } - - element.setAttribute('opacity', curShape.opacity); - element.setAttribute('style', 'pointer-events:inherit'); - cleanupElement(element); - - if (currentMode === 'path') { - pathActions$1.toEditMode(element); - } else if (curConfig.selectNew) { - selectOnly([element], true); - } // we create the insert command that is stored on the stack - // undo means to call cmd.unapply(), redo means to call cmd.apply() - - - addCommandToHistory(new InsertElementCommand$1(element)); - call('changed', [element]); - }, aniDur * 1000); - } - - startTransform = null; - }; - - var dblClick = function dblClick(evt) { - var evtTarget = evt.target; - var parent = evtTarget.parentNode; - var mouseTarget = getMouseTarget(evt); - var _mouseTarget = mouseTarget, - tagName = _mouseTarget.tagName; - - if (tagName === 'text' && currentMode !== 'textedit') { - var pt = transformPoint(evt.pageX, evt.pageY, rootSctm); - textActions.select(mouseTarget, pt.x, pt.y); - } // Do nothing if already in current group - - - if (parent === currentGroup) { - return; - } - - if ((tagName === 'g' || tagName === 'a') && getRotationAngle(mouseTarget)) { - // TODO: Allow method of in-group editing without having to do - // this (similar to editing rotated paths) - // Ungroup and regroup - pushGroupProperties(mouseTarget); - mouseTarget = selectedElements[0]; - clearSelection(true); - } // Reset context - - - if (currentGroup) { - leaveContext(); - } - - if (parent.tagName !== 'g' && parent.tagName !== 'a' || parent === getCurrentDrawing().getCurrentLayer() || mouseTarget === selectorManager.selectorParentGroup) { - // Escape from in-group edit - return; - } - - setContext(mouseTarget); - }; // prevent links from being followed in the canvas - - - var handleLinkInCanvas = function handleLinkInCanvas(e) { - e.preventDefault(); - return false; - }; // Added mouseup to the container here. - // TODO(codedread): Figure out why after the Closure compiler, the window mouseup is ignored. - - - $$a(container).mousedown(mouseDown).mousemove(mouseMove).click(handleLinkInCanvas).dblclick(dblClick).mouseup(mouseUp); // $(window).mouseup(mouseUp); - // TODO(rafaelcastrocouto): User preference for shift key and zoom factor - - $$a(container).bind('mousewheel DOMMouseScroll', - /** - * @param {Event} e - * @fires module:svgcanvas.SvgCanvas#event:updateCanvas - * @fires module:svgcanvas.SvgCanvas#event:zoomDone - * @returns {void} - */ - function (e) { - if (!e.shiftKey) { - return; - } - - e.preventDefault(); - var evt = e.originalEvent; - rootSctm = $$a('#svgcontent g')[0].getScreenCTM().inverse(); - var workarea = $$a('#workarea'); - var scrbar = 15; - var rulerwidth = curConfig.showRulers ? 16 : 0; // mouse relative to content area in content pixels - - var pt = transformPoint(evt.pageX, evt.pageY, rootSctm); // full work area width in screen pixels - - var editorFullW = workarea.width(); - var editorFullH = workarea.height(); // work area width minus scroll and ruler in screen pixels - - var editorW = editorFullW - scrbar - rulerwidth; - var editorH = editorFullH - scrbar - rulerwidth; // work area width in content pixels - - var workareaViewW = editorW * rootSctm.a; - var workareaViewH = editorH * rootSctm.d; // content offset from canvas in screen pixels - - var wOffset = workarea.offset(); - var wOffsetLeft = wOffset.left + rulerwidth; - var wOffsetTop = wOffset.top + rulerwidth; - var delta = evt.wheelDelta ? evt.wheelDelta : evt.detail ? -evt.detail : 0; - - if (!delta) { - return; - } - - var factor = Math.max(3 / 4, Math.min(4 / 3, delta)); - var wZoom, hZoom; - - if (factor > 1) { - wZoom = Math.ceil(editorW / workareaViewW * factor * 100) / 100; - hZoom = Math.ceil(editorH / workareaViewH * factor * 100) / 100; - } else { - wZoom = Math.floor(editorW / workareaViewW * factor * 100) / 100; - hZoom = Math.floor(editorH / workareaViewH * factor * 100) / 100; - } - - var zoomlevel = Math.min(wZoom, hZoom); - zoomlevel = Math.min(10, Math.max(0.01, zoomlevel)); - - if (zoomlevel === currentZoom) { - return; - } - - factor = zoomlevel / currentZoom; // top left of workarea in content pixels before zoom - - var topLeftOld = transformPoint(wOffsetLeft, wOffsetTop, rootSctm); // top left of workarea in content pixels after zoom - - var topLeftNew = { - x: pt.x - (pt.x - topLeftOld.x) / factor, - y: pt.y - (pt.y - topLeftOld.y) / factor - }; // top left of workarea in canvas pixels relative to content after zoom - - var topLeftNewCanvas = { - x: topLeftNew.x * zoomlevel, - y: topLeftNew.y * zoomlevel - }; // new center in canvas pixels - - var newCtr = { - x: topLeftNewCanvas.x - rulerwidth + editorFullW / 2, - y: topLeftNewCanvas.y - rulerwidth + editorFullH / 2 - }; - canvas.setZoom(zoomlevel); - $$a('#zoom').val((zoomlevel * 100).toFixed(1)); - call('updateCanvas', { - center: false, - newCtr: newCtr - }); - call('zoomDone'); - }); - })(); - /* eslint-disable jsdoc/require-property */ - - /** - * Group: Text edit functions - * Functions relating to editing text elements. - * @namespace {PlainObject} textActions - * @memberof module:svgcanvas.SvgCanvas# - */ - - - var textActions = canvas.textActions = function () { - /* eslint-enable jsdoc/require-property */ - var curtext; - var textinput; - var cursor; - var selblock; - var blinker; - var chardata = []; - var textbb; // , transbb; - - var matrix; - var lastX, lastY; - var allowDbl; - /** - * - * @param {Integer} index - * @returns {void} - */ - - function setCursor(index) { - var empty = textinput.value === ''; - $$a(textinput).focus(); - - if (!arguments.length) { - if (empty) { - index = 0; - } else { - if (textinput.selectionEnd !== textinput.selectionStart) { - return; - } - - index = textinput.selectionEnd; - } - } - - var charbb = chardata[index]; - - if (!empty) { - textinput.setSelectionRange(index, index); - } - - cursor = getElem('text_cursor'); - - if (!cursor) { - cursor = document.createElementNS(NS.SVG, 'line'); - assignAttributes(cursor, { - id: 'text_cursor', - stroke: '#333', - 'stroke-width': 1 - }); - cursor = getElem('selectorParentGroup').appendChild(cursor); - } - - if (!blinker) { - blinker = setInterval(function () { - var show = cursor.getAttribute('display') === 'none'; - cursor.setAttribute('display', show ? 'inline' : 'none'); - }, 600); - } - - var startPt = ptToScreen(charbb.x, textbb.y); - var endPt = ptToScreen(charbb.x, textbb.y + textbb.height); - assignAttributes(cursor, { - x1: startPt.x, - y1: startPt.y, - x2: endPt.x, - y2: endPt.y, - visibility: 'visible', - display: 'inline' - }); - - if (selblock) { - selblock.setAttribute('d', ''); - } - } - /** - * - * @param {Integer} start - * @param {Integer} end - * @param {boolean} skipInput - * @returns {void} - */ - - - function setSelection(start, end, skipInput) { - if (start === end) { - setCursor(end); - return; - } - - if (!skipInput) { - textinput.setSelectionRange(start, end); - } - - selblock = getElem('text_selectblock'); - - if (!selblock) { - selblock = document.createElementNS(NS.SVG, 'path'); - assignAttributes(selblock, { - id: 'text_selectblock', - fill: 'green', - opacity: 0.5, - style: 'pointer-events:none' - }); - getElem('selectorParentGroup').append(selblock); - } - - var startbb = chardata[start]; - var endbb = chardata[end]; - cursor.setAttribute('visibility', 'hidden'); - var tl = ptToScreen(startbb.x, textbb.y), - tr = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y), - bl = ptToScreen(startbb.x, textbb.y + textbb.height), - br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height); - var dstr = 'M' + tl.x + ',' + tl.y + ' L' + tr.x + ',' + tr.y + ' ' + br.x + ',' + br.y + ' ' + bl.x + ',' + bl.y + 'z'; - assignAttributes(selblock, { - d: dstr, - display: 'inline' - }); - } - /** - * - * @param {Float} mouseX - * @param {Float} mouseY - * @returns {Integer} - */ - - - function getIndexFromPoint(mouseX, mouseY) { - // Position cursor here - var pt = svgroot.createSVGPoint(); - pt.x = mouseX; - pt.y = mouseY; // No content, so return 0 - - if (chardata.length === 1) { - return 0; - } // Determine if cursor should be on left or right of character - - - var charpos = curtext.getCharNumAtPosition(pt); - - if (charpos < 0) { - // Out of text range, look at mouse coords - charpos = chardata.length - 2; - - if (mouseX <= chardata[0].x) { - charpos = 0; - } - } else if (charpos >= chardata.length - 2) { - charpos = chardata.length - 2; - } - - var charbb = chardata[charpos]; - var mid = charbb.x + charbb.width / 2; - - if (mouseX > mid) { - charpos++; - } - - return charpos; - } - /** - * - * @param {Float} mouseX - * @param {Float} mouseY - * @returns {void} - */ - - - function setCursorFromPoint(mouseX, mouseY) { - setCursor(getIndexFromPoint(mouseX, mouseY)); - } - /** - * - * @param {Float} x - * @param {Float} y - * @param {boolean} apply - * @returns {void} - */ - - - function setEndSelectionFromPoint(x, y, apply) { - var i1 = textinput.selectionStart; - var i2 = getIndexFromPoint(x, y); - var start = Math.min(i1, i2); - var end = Math.max(i1, i2); - setSelection(start, end, !apply); - } - /** - * - * @param {Float} xIn - * @param {Float} yIn - * @returns {module:math.XYObject} - */ - - - function screenToPt(xIn, yIn) { - var out = { - x: xIn, - y: yIn - }; - out.x /= currentZoom; - out.y /= currentZoom; - - if (matrix) { - var pt = transformPoint(out.x, out.y, matrix.inverse()); - out.x = pt.x; - out.y = pt.y; - } - - return out; - } - /** - * - * @param {Float} xIn - * @param {Float} yIn - * @returns {module:math.XYObject} - */ - - - function ptToScreen(xIn, yIn) { - var out = { - x: xIn, - y: yIn - }; - - if (matrix) { - var pt = transformPoint(out.x, out.y, matrix); - out.x = pt.x; - out.y = pt.y; - } - - out.x *= currentZoom; - out.y *= currentZoom; - return out; - } - /* - // Not currently in use - function hideCursor () { - if (cursor) { - cursor.setAttribute('visibility', 'hidden'); - } - } - */ - - /** - * - * @param {Event} evt - * @returns {void} - */ - - - function selectAll(evt) { - setSelection(0, curtext.textContent.length); - $$a(this).unbind(evt); - } - /** - * - * @param {Event} evt - * @returns {void} - */ - - - function selectWord(evt) { - if (!allowDbl || !curtext) { - return; - } - - var ept = transformPoint(evt.pageX, evt.pageY, rootSctm), - mouseX = ept.x * currentZoom, - mouseY = ept.y * currentZoom; - var pt = screenToPt(mouseX, mouseY); - var index = getIndexFromPoint(pt.x, pt.y); - var str = curtext.textContent; - var first = str.substr(0, index).replace(/[a-z\d]+$/i, '').length; - var m = str.substr(index).match(/^[a-z\d]+/i); - var last = (m ? m[0].length : 0) + index; - setSelection(first, last); // Set tripleclick - - $$a(evt.target).click(selectAll); - setTimeout(function () { - $$a(evt.target).unbind('click', selectAll); - }, 300); - } - - return ( - /** @lends module:svgcanvas.SvgCanvas#textActions */ - { - /** - * @param {Element} target - * @param {Float} x - * @param {Float} y - * @returns {void} - */ - select: function select(target, x, y) { - curtext = target; - textActions.toEditMode(x, y); - }, - - /** - * @param {Element} elem - * @returns {void} - */ - start: function start(elem) { - curtext = elem; - textActions.toEditMode(); - }, - - /** - * @param {external:MouseEvent} evt - * @param {Element} mouseTarget - * @param {Float} startX - * @param {Float} startY - * @returns {void} - */ - mouseDown: function mouseDown(evt, mouseTarget, startX, startY) { - var pt = screenToPt(startX, startY); - textinput.focus(); - setCursorFromPoint(pt.x, pt.y); - lastX = startX; - lastY = startY; // TODO: Find way to block native selection - }, - - /** - * @param {Float} mouseX - * @param {Float} mouseY - * @returns {void} - */ - mouseMove: function mouseMove(mouseX, mouseY) { - var pt = screenToPt(mouseX, mouseY); - setEndSelectionFromPoint(pt.x, pt.y); - }, - - /** - * @param {external:MouseEvent} evt - * @param {Float} mouseX - * @param {Float} mouseY - * @returns {void} - */ - mouseUp: function mouseUp(evt, mouseX, mouseY) { - var pt = screenToPt(mouseX, mouseY); - setEndSelectionFromPoint(pt.x, pt.y, true); // TODO: Find a way to make this work: Use transformed BBox instead of evt.target - // if (lastX === mouseX && lastY === mouseY - // && !rectsIntersect(transbb, {x: pt.x, y: pt.y, width: 0, height: 0})) { - // textActions.toSelectMode(true); - // } - - if (evt.target !== curtext && mouseX < lastX + 2 && mouseX > lastX - 2 && mouseY < lastY + 2 && mouseY > lastY - 2) { - textActions.toSelectMode(true); - } - }, - - /** - * @function - * @param {Integer} index - * @returns {void} - */ - setCursor: setCursor, - - /** - * @param {Float} x - * @param {Float} y - * @returns {void} - */ - toEditMode: function toEditMode(x, y) { - allowDbl = false; - currentMode = 'textedit'; - selectorManager.requestSelector(curtext).showGrips(false); // Make selector group accept clicks - - /* const selector = */ - - selectorManager.requestSelector(curtext); // Do we need this? Has side effect of setting lock, so keeping for now, but next line wasn't being used - // const sel = selector.selectorRect; - - textActions.init(); - $$a(curtext).css('cursor', 'text'); // if (supportsEditableText()) { - // curtext.setAttribute('editable', 'simple'); - // return; - // } - - if (!arguments.length) { - setCursor(); - } else { - var pt = screenToPt(x, y); - setCursorFromPoint(pt.x, pt.y); - } - - setTimeout(function () { - allowDbl = true; - }, 300); - }, - - /** - * @param {boolean|Element} selectElem - * @fires module:svgcanvas.SvgCanvas#event:selected - * @returns {void} - */ - toSelectMode: function toSelectMode(selectElem) { - currentMode = 'select'; - clearInterval(blinker); - blinker = null; - - if (selblock) { - $$a(selblock).attr('display', 'none'); - } - - if (cursor) { - $$a(cursor).attr('visibility', 'hidden'); - } - - $$a(curtext).css('cursor', 'move'); - - if (selectElem) { - clearSelection(); - $$a(curtext).css('cursor', 'move'); - call('selected', [curtext]); - addToSelection([curtext], true); - } - - if (curtext && !curtext.textContent.length) { - // No content, so delete - canvas.deleteSelectedElements(); - } - - $$a(textinput).blur(); - curtext = false; // if (supportsEditableText()) { - // curtext.removeAttribute('editable'); - // } - }, - - /** - * @param {Element} elem - * @returns {void} - */ - setInputElem: function setInputElem(elem) { - textinput = elem; // $(textinput).blur(hideCursor); - }, - - /** - * @returns {void} - */ - clear: function clear() { - if (currentMode === 'textedit') { - textActions.toSelectMode(); - } - }, - - /** - * @param {Element} inputElem Not in use - * @returns {void} - */ - init: function init(inputElem) { - if (!curtext) { - return; - } - - var i, end; // if (supportsEditableText()) { - // curtext.select(); - // return; - // } - - if (!curtext.parentNode) { - // Result of the ffClone, need to get correct element - curtext = selectedElements[0]; - selectorManager.requestSelector(curtext).showGrips(false); - } - - var str = curtext.textContent; - var len = str.length; - var xform = curtext.getAttribute('transform'); - textbb = getBBox(curtext); - matrix = xform ? getMatrix(curtext) : null; - chardata = []; - chardata.length = len; - textinput.focus(); - $$a(curtext).unbind('dblclick', selectWord).dblclick(selectWord); - - if (!len) { - end = { - x: textbb.x + textbb.width / 2, - width: 0 - }; - } - - for (i = 0; i < len; i++) { - var start = curtext.getStartPositionOfChar(i); - end = curtext.getEndPositionOfChar(i); - - if (!supportsGoodTextCharPos()) { - var offset = canvas.contentW * currentZoom; - start.x -= offset; - end.x -= offset; - start.x /= currentZoom; - end.x /= currentZoom; - } // Get a "bbox" equivalent for each character. Uses the - // bbox data of the actual text for y, height purposes - // TODO: Decide if y, width and height are actually necessary - - - chardata[i] = { - x: start.x, - y: textbb.y, - // start.y? - width: end.x - start.x, - height: textbb.height - }; - } // Add a last bbox for cursor at end of text - - - chardata.push({ - x: end.x, - width: 0 - }); - setSelection(textinput.selectionStart, textinput.selectionEnd, true); - } - } - ); - }(); - /** - * Group: Serialization. - */ - - /** - * Looks at DOM elements inside the `<defs>` to see if they are referred to, - * removes them from the DOM if they are not. - * @function module:svgcanvas.SvgCanvas#removeUnusedDefElems - * @returns {Integer} The number of elements that were removed - */ - - - var removeUnusedDefElems = this.removeUnusedDefElems = function () { - var defs = svgcontent.getElementsByTagNameNS(NS.SVG, 'defs'); - - if (!defs || !defs.length) { - return 0; - } // if (!defs.firstChild) { return; } - - - var defelemUses = []; - var numRemoved = 0; - var attrs = ['fill', 'stroke', 'filter', 'marker-start', 'marker-mid', 'marker-end']; - var alen = attrs.length; - var allEls = svgcontent.getElementsByTagNameNS(NS.SVG, '*'); - var allLen = allEls.length; - var i, j; - - for (i = 0; i < allLen; i++) { - var el = allEls[i]; - - for (j = 0; j < alen; j++) { - var ref = getUrlFromAttr(el.getAttribute(attrs[j])); - - if (ref) { - defelemUses.push(ref.substr(1)); - } - } // gradients can refer to other gradients - - - var href = getHref(el); - - if (href && href.startsWith('#')) { - defelemUses.push(href.substr(1)); - } - } - - var defelems = $$a(defs).find('linearGradient, radialGradient, filter, marker, svg, symbol'); - i = defelems.length; - - while (i--) { - var defelem = defelems[i]; - var id = defelem.id; - - if (!defelemUses.includes(id)) { - // Not found, so remove (but remember) - removedElements[id] = defelem; - defelem.remove(); - numRemoved++; - } - } - - return numRemoved; - }; - /** - * Main function to set up the SVG content for output. - * @function module:svgcanvas.SvgCanvas#svgCanvasToString - * @returns {string} The SVG image for output - */ - - - this.svgCanvasToString = function () { - // keep calling it until there are none to remove - while (removeUnusedDefElems() > 0) {} // eslint-disable-line no-empty - - - pathActions$1.clear(true); // Keep SVG-Edit comment on top - - $$a.each(svgcontent.childNodes, function (i, node) { - if (i && node.nodeType === 8 && node.data.includes('Created with')) { - svgcontent.firstChild.before(node); - } - }); // Move out of in-group editing mode - - if (currentGroup) { - leaveContext(); - selectOnly([currentGroup]); - } - - var nakedSvgs = []; // Unwrap gsvg if it has no special attributes (only id and style) - - $$a(svgcontent).find('g:data(gsvg)').each(function () { - var attrs = this.attributes; - var len = attrs.length; - - for (var i = 0; i < len; i++) { - if (attrs[i].nodeName === 'id' || attrs[i].nodeName === 'style') { - len--; - } - } // No significant attributes, so ungroup - - - if (len <= 0) { - var svg = this.firstChild; - nakedSvgs.push(svg); - $$a(this).replaceWith(svg); - } - }); - var output = this.svgToString(svgcontent, 0); // Rewrap gsvg - - if (nakedSvgs.length) { - $$a(nakedSvgs).each(function () { - groupSvgElem(this); - }); - } - - return output; - }; - /** - * Sub function ran on each SVG element to convert it to a string as desired. - * @function module:svgcanvas.SvgCanvas#svgToString - * @param {Element} elem - The SVG element to convert - * @param {Integer} indent - Number of spaces to indent this tag - * @returns {string} The given element as an SVG tag - */ - - - this.svgToString = function (elem, indent) { - var out = []; - var unit = curConfig.baseUnit; - var unitRe = new RegExp('^-?[\\d\\.]+' + unit + '$'); - - if (elem) { - cleanupElement(elem); - - var attrs = _toConsumableArray(elem.attributes); - - var childs = elem.childNodes; - attrs.sort(function (a, b) { - return a.name > b.name ? -1 : 1; - }); - - for (var i = 0; i < indent; i++) { - out.push(' '); - } - - out.push('<'); - out.push(elem.nodeName); - - if (elem.id === 'svgcontent') { - // Process root element separately - var res = getResolution(); - var vb = ''; // TODO: Allow this by dividing all values by current baseVal - // Note that this also means we should properly deal with this on import - // if (curConfig.baseUnit !== 'px') { - // const unit = curConfig.baseUnit; - // const unitM = getTypeMap()[unit]; - // res.w = shortFloat(res.w / unitM); - // res.h = shortFloat(res.h / unitM); - // vb = ' viewBox="' + [0, 0, res.w, res.h].join(' ') + '"'; - // res.w += unit; - // res.h += unit; - // } - - if (unit !== 'px') { - res.w = convertUnit(res.w, unit) + unit; - res.h = convertUnit(res.h, unit) + unit; - } - - out.push(' width="' + res.w + '" height="' + res.h + '"' + vb + ' xmlns="' + NS.SVG + '"'); - var nsuris = {}; // Check elements for namespaces, add if found - - $$a(elem).find('*').andSelf().each(function () { - // const el = this; - // for some elements have no attribute - var uri = this.namespaceURI; - - if (uri && !nsuris[uri] && nsMap[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml') { - nsuris[uri] = true; - out.push(' xmlns:' + nsMap[uri] + '="' + uri + '"'); - } - - $$a.each(this.attributes, function (i, attr) { - var u = attr.namespaceURI; - - if (u && !nsuris[u] && nsMap[u] !== 'xmlns' && nsMap[u] !== 'xml') { - nsuris[u] = true; - out.push(' xmlns:' + nsMap[u] + '="' + u + '"'); - } - }); - }); - var _i2 = attrs.length; - var attrNames = ['width', 'height', 'xmlns', 'x', 'y', 'viewBox', 'id', 'overflow']; - - while (_i2--) { - var attr = attrs[_i2]; - var attrVal = toXml(attr.value); // Namespaces have already been dealt with, so skip - - if (attr.nodeName.startsWith('xmlns:')) { - continue; - } // only serialize attributes we don't use internally - - - if (attrVal !== '' && !attrNames.includes(attr.localName)) { - if (!attr.namespaceURI || nsMap[attr.namespaceURI]) { - out.push(' '); - out.push(attr.nodeName); - out.push('="'); - out.push(attrVal); - out.push('"'); - } - } - } - } else { - // Skip empty defs - if (elem.nodeName === 'defs' && !elem.firstChild) { - return ''; - } - - var mozAttrs = ['-moz-math-font-style', '_moz-math-font-style']; - - for (var _i3 = attrs.length - 1; _i3 >= 0; _i3--) { - var _attr = attrs[_i3]; - - var _attrVal = toXml(_attr.value); // remove bogus attributes added by Gecko - - - if (mozAttrs.includes(_attr.localName)) { - continue; - } - - if (_attrVal === 'null') { - var styleName = _attr.localName.replace(/-[a-z]/g, function (s) { - return s[1].toUpperCase(); - }); - - if (Object.prototype.hasOwnProperty.call(elem.style, styleName)) { - continue; - } - } - - if (_attrVal !== '') { - if (_attrVal.startsWith('pointer-events')) { - continue; - } - - if (_attr.localName === 'class' && _attrVal.startsWith('se_')) { - continue; - } - - out.push(' '); - - if (_attr.localName === 'd') { - _attrVal = pathActions$1.convertPath(elem, true); - } - - if (!isNaN(_attrVal)) { - _attrVal = shortFloat(_attrVal); - } else if (unitRe.test(_attrVal)) { - _attrVal = shortFloat(_attrVal) + unit; - } // Embed images when saving - - - if (saveOptions.apply && elem.nodeName === 'image' && _attr.localName === 'href' && saveOptions.images && saveOptions.images === 'embed') { - var img = encodableImages[_attrVal]; - - if (img) { - _attrVal = img; - } - } // map various namespaces to our fixed namespace prefixes - // (the default xmlns attribute itself does not get a prefix) - - - if (!_attr.namespaceURI || _attr.namespaceURI === NS.SVG || nsMap[_attr.namespaceURI]) { - out.push(_attr.nodeName); - out.push('="'); - out.push(_attrVal); - out.push('"'); - } - } - } - } - - if (elem.hasChildNodes()) { - out.push('>'); - indent++; - var bOneLine = false; - - for (var _i4 = 0; _i4 < childs.length; _i4++) { - var child = childs.item(_i4); - - switch (child.nodeType) { - case 1: - // element node - out.push('\n'); - out.push(this.svgToString(child, indent)); - break; - - case 3: - { - // text node - var str = child.nodeValue.replace(/^\s+|\s+$/g, ''); - - if (str !== '') { - bOneLine = true; - out.push(String(toXml(str))); - } - - break; - } - - case 4: - // cdata node - out.push('\n'); - out.push(new Array(indent + 1).join(' ')); - out.push('<![CDATA['); - out.push(child.nodeValue); - out.push(']]>'); - break; - - case 8: - // comment - out.push('\n'); - out.push(new Array(indent + 1).join(' ')); - out.push('<!--'); - out.push(child.data); - out.push('-->'); - break; - } // switch on node type - - } - - indent--; - - if (!bOneLine) { - out.push('\n'); - - for (var _i5 = 0; _i5 < indent; _i5++) { - out.push(' '); - } - } - - out.push('</'); - out.push(elem.nodeName); - out.push('>'); - } else { - out.push('/>'); - } - } - - return out.join(''); - }; // end svgToString() - - /** - * Function to run when image data is found. - * @callback module:svgcanvas.ImageEmbeddedCallback - * @param {string|false} result Data URL - * @returns {void} - */ - - /** - * Converts a given image file to a data URL when possible, then runs a given callback. - * @function module:svgcanvas.SvgCanvas#embedImage - * @param {string} src - The path/URL of the image - * @returns {Promise<string|false>} Resolves to a Data URL (string|false) - */ - - - this.embedImage = function (src) { - // Todo: Remove this Promise in favor of making an async/await `Image.load` utility - // eslint-disable-next-line promise/avoid-new - return new Promise(function (resolve, reject) { - // load in the image and once it's loaded, get the dimensions - $$a(new Image()).load(function (response, status, xhr) { - if (status === 'error') { - reject(new Error('Error loading image: ' + xhr.status + ' ' + xhr.statusText)); - return; - } // create a canvas the same size as the raster image - - - var cvs = document.createElement('canvas'); - cvs.width = this.width; - cvs.height = this.height; // load the raster image into the canvas - - cvs.getContext('2d').drawImage(this, 0, 0); // retrieve the data: URL - - try { - var urldata = ';svgedit_url=' + encodeURIComponent(src); - urldata = cvs.toDataURL().replace(';base64', urldata + ';base64'); - encodableImages[src] = urldata; - } catch (e) { - encodableImages[src] = false; - } - - lastGoodImgUrl = src; - resolve(encodableImages[src]); - }).attr('src', src); - }); - }; - /** - * Sets a given URL to be a "last good image" URL. - * @function module:svgcanvas.SvgCanvas#setGoodImage - * @param {string} val - * @returns {void} - */ - - - this.setGoodImage = function (val) { - lastGoodImgUrl = val; - }; - /** - * Does nothing by default, handled by optional widget/extension. - * @function module:svgcanvas.SvgCanvas#open - * @returns {void} - */ - - - this.open = function () { - /* */ - }; - /** - * Serializes the current drawing into SVG XML text and passes it to the 'saved' handler. - * This function also includes the XML prolog. Clients of the `SvgCanvas` bind their save - * function to the 'saved' event. - * @function module:svgcanvas.SvgCanvas#save - * @param {module:svgcanvas.SaveOptions} opts - * @fires module:svgcanvas.SvgCanvas#event:saved - * @returns {void} - */ - - - this.save = function (opts) { - // remove the selected outline before serializing - clearSelection(); // Update save options if provided - - if (opts) { - $$a.extend(saveOptions, opts); - } - - saveOptions.apply = true; // no need for doctype, see https://jwatt.org/svg/authoring/#doctype-declaration - - var str = this.svgCanvasToString(); - call('saved', str); - }; - /** - * @typedef {PlainObject} module:svgcanvas.IssuesAndCodes - * @property {string[]} issueCodes The locale-independent code names - * @property {string[]} issues The localized descriptions - */ - - /** - * Codes only is useful for locale-independent detection. - * @returns {module:svgcanvas.IssuesAndCodes} - */ - - - function getIssues() { - // remove the selected outline before serializing - clearSelection(); // Check for known CanVG issues - - var issues = []; - var issueCodes = []; // Selector and notice - - var issueList = { - feGaussianBlur: uiStrings.exportNoBlur, - foreignObject: uiStrings.exportNoforeignObject, - '[stroke-dasharray]': uiStrings.exportNoDashArray - }; - var content = $$a(svgcontent); // Add font/text check if Canvas Text API is not implemented - - if (!('font' in $$a('<canvas>')[0].getContext('2d'))) { - issueList.text = uiStrings.exportNoText; - } - - $$a.each(issueList, function (sel, descr) { - if (content.find(sel).length) { - issueCodes.push(sel); - issues.push(descr); - } - }); - return { - issues: issues, - issueCodes: issueCodes - }; - } - - var canvg; - /** - * @typedef {"feGaussianBlur"|"foreignObject"|"[stroke-dasharray]"|"text"} module:svgcanvas.IssueCode - */ - - /** - * @typedef {PlainObject} module:svgcanvas.ImageExportedResults - * @property {string} datauri Contents as a Data URL - * @property {string} bloburl May be the empty string - * @property {string} svg The SVG contents as a string - * @property {string[]} issues The localization messages of `issueCodes` - * @property {module:svgcanvas.IssueCode[]} issueCodes CanVG issues found with the SVG - * @property {"PNG"|"JPEG"|"BMP"|"WEBP"|"ICO"} type The chosen image type - * @property {"image/png"|"image/jpeg"|"image/bmp"|"image/webp"} mimeType The image MIME type - * @property {Float} quality A decimal between 0 and 1 (for use with JPEG or WEBP) - * @property {string} exportWindowName A convenience for passing along a `window.name` to target a window on which the export could be added - */ - - /** - * Generates a PNG (or JPG, BMP, WEBP) Data URL based on the current image, - * then calls "exported" with an object including the string, image - * information, and any issues found. - * @function module:svgcanvas.SvgCanvas#rasterExport - * @param {"PNG"|"JPEG"|"BMP"|"WEBP"|"ICO"} [imgType="PNG"] - * @param {Float} [quality] Between 0 and 1 - * @param {string} [exportWindowName] - * @param {PlainObject} [opts] - * @param {boolean} [opts.avoidEvent] - * @fires module:svgcanvas.SvgCanvas#event:exported - * @todo Confirm/fix ICO type - * @returns {Promise<module:svgcanvas.ImageExportedResults>} Resolves to {@link module:svgcanvas.ImageExportedResults} - */ - - this.rasterExport = /*#__PURE__*/function () { - var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(imgType, quality, exportWindowName) { - var opts, - type, - mimeType, - _getIssues, - issues, - issueCodes, - svg, - _yield$importSetGloba, - c, - _args2 = arguments; - - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - opts = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : {}; - type = imgType === 'ICO' ? 'BMP' : imgType || 'PNG'; - mimeType = 'image/' + type.toLowerCase(); - _getIssues = getIssues(), issues = _getIssues.issues, issueCodes = _getIssues.issueCodes; - svg = this.svgCanvasToString(); - - if (canvg) { - _context2.next = 10; - break; - } - - _context2.next = 8; - return importSetGlobal(curConfig.canvgPath + 'canvg.js', { - global: 'canvg' - }); - - case 8: - _yield$importSetGloba = _context2.sent; - canvg = _yield$importSetGloba.canvg; - - case 10: - if (!$$a('#export_canvas').length) { - $$a('<canvas>', { - id: 'export_canvas' - }).hide().appendTo('body'); - } - - c = $$a('#export_canvas')[0]; - c.width = canvas.contentW; - c.height = canvas.contentH; - _context2.next = 16; - return canvg(c, svg); - - case 16: - return _context2.abrupt("return", new Promise(function (resolve, reject) { - var dataURLType = type.toLowerCase(); - var datauri = quality ? c.toDataURL('image/' + dataURLType, quality) : c.toDataURL('image/' + dataURLType); - var bloburl; - /** - * Called when `bloburl` is available for export. - * @returns {void} - */ - - function done() { - var obj = { - datauri: datauri, - bloburl: bloburl, - svg: svg, - issues: issues, - issueCodes: issueCodes, - type: imgType, - mimeType: mimeType, - quality: quality, - exportWindowName: exportWindowName - }; - - if (!opts.avoidEvent) { - call('exported', obj); - } - - resolve(obj); - } - - if (c.toBlob) { - c.toBlob(function (blob) { - bloburl = createObjectURL(blob); - done(); - }, mimeType, quality); - return; - } - - bloburl = dataURLToObjectURL(datauri); - done(); - })); - - case 17: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - return function (_x4, _x5, _x6) { - return _ref5.apply(this, arguments); - }; - }(); - /** - * @external jsPDF - */ - - /** - * @typedef {void|"save"|"arraybuffer"|"blob"|"datauristring"|"dataurlstring"|"dataurlnewwindow"|"datauri"|"dataurl"} external:jsPDF.OutputType - * @todo Newer version to add also allows these `outputType` values "bloburi"|"bloburl" which return strings, so document here and for `outputType` of `module:svgcanvas.PDFExportedResults` below if added - */ - - /** - * @typedef {PlainObject} module:svgcanvas.PDFExportedResults - * @property {string} svg The SVG PDF output - * @property {string|ArrayBuffer|Blob|window} output The output based on the `outputType`; - * if `undefined`, "datauristring", "dataurlstring", "datauri", - * or "dataurl", will be a string (`undefined` gives a document, while the others - * build as Data URLs; "datauri" and "dataurl" change the location of the current page); if - * "arraybuffer", will return `ArrayBuffer`; if "blob", returns a `Blob`; - * if "dataurlnewwindow", will change the current page's location and return a string - * if in Safari and no window object is found; otherwise opens in, and returns, a new `window` - * object; if "save", will have the same return as "dataurlnewwindow" if - * `navigator.getUserMedia` support is found without `URL.createObjectURL` support; otherwise - * returns `undefined` but attempts to save - * @property {external:jsPDF.OutputType} outputType - * @property {string[]} issues The human-readable localization messages of corresponding `issueCodes` - * @property {module:svgcanvas.IssueCode[]} issueCodes - * @property {string} exportWindowName - */ - - /** - * Generates a PDF based on the current image, then calls "exportedPDF" with - * an object including the string, the data URL, and any issues found. - * @function module:svgcanvas.SvgCanvas#exportPDF - * @param {string} [exportWindowName] Will also be used for the download file name here - * @param {external:jsPDF.OutputType} [outputType="dataurlstring"] - * @fires module:svgcanvas.SvgCanvas#event:exportedPDF - * @returns {Promise<module:svgcanvas.PDFExportedResults>} Resolves to {@link module:svgcanvas.PDFExportedResults} - */ - - - this.exportPDF = /*#__PURE__*/function () { - var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(exportWindowName) { - var outputType, - modularVersion, - res, - orientation, - unit, - doc, - docTitle, - _getIssues2, - issues, - issueCodes, - svg, - obj, - _args3 = arguments; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - outputType = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : isChrome() ? 'save' : undefined; - - if (window.jsPDF) { - _context3.next = 7; - break; - } - - _context3.next = 4; - return importScript([// We do not currently have these paths configurable as they are - // currently global-only, so not Rolled-up - 'jspdf/underscore-min.js', // 'jspdf/jspdf.min.js', - '../../svgedit-myfix/editor/jspdf/jspdf-1.0.150.debug.js']); - - case 4: - modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false; // Todo: Switch to `import()` when widely supported and available (also allow customization of path) - - _context3.next = 7; - return importScript(curConfig.jspdfPath + 'jspdf.plugin.svgToPdf.js', { - type: modularVersion ? 'module' : 'text/javascript' - }); - - case 7: - res = getResolution(); - orientation = res.w > res.h ? 'landscape' : 'portrait'; - unit = 'pt'; // curConfig.baseUnit; // We could use baseUnit, but that is presumably not intended for export purposes - // Todo: Give options to use predefined jsPDF formats like "a4", etc. from pull-down (with option to keep customizable) - - doc = jsPDF({ - orientation: orientation, - unit: unit, - format: [res.w, res.h] // , compressPdf: true - - }); - docTitle = getDocumentTitle(); - doc.setProperties({ - title: docTitle - /* , - subject: '', - author: '', - keywords: '', - creator: '' */ - - }); - _getIssues2 = getIssues(), issues = _getIssues2.issues, issueCodes = _getIssues2.issueCodes; - svg = this.svgCanvasToString(); - doc.addSVG(svg, 0, 0); // doc.output('save'); // Works to open in a new - // window; todo: configure this and other export - // options to optionally work in this manner as - // opposed to opening a new tab - - outputType = outputType || 'dataurlstring'; - obj = { - svg: svg, - issues: issues, - issueCodes: issueCodes, - exportWindowName: exportWindowName, - outputType: outputType - }; - obj.output = doc.output(outputType, outputType === 'save' ? exportWindowName || 'svg.pdf' : undefined); - call('exportedPDF', obj); - return _context3.abrupt("return", obj); - - case 21: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - return function (_x7) { - return _ref6.apply(this, arguments); - }; - }(); - /** - * Returns the current drawing as raw SVG XML text. - * @function module:svgcanvas.SvgCanvas#getSvgString - * @returns {string} The current drawing as raw SVG XML text. - */ - - - this.getSvgString = function () { - saveOptions.apply = false; - return this.svgCanvasToString(); - }; - /** - * This function determines whether to use a nonce in the prefix, when - * generating IDs for future documents in SVG-Edit. - * If you're controlling SVG-Edit externally, and want randomized IDs, call - * this BEFORE calling `svgCanvas.setSvgString`. - * @function module:svgcanvas.SvgCanvas#randomizeIds - * @param {boolean} [enableRandomization] If true, adds a nonce to the prefix. Thus - * `svgCanvas.randomizeIds() <==> svgCanvas.randomizeIds(true)` - * @returns {void} - */ - - - this.randomizeIds = function (enableRandomization) { - if (arguments.length > 0 && enableRandomization === false) { - randomizeIds(false, getCurrentDrawing()); - } else { - randomizeIds(true, getCurrentDrawing()); - } - }; - /** - * Ensure each element has a unique ID. - * @function module:svgcanvas.SvgCanvas#uniquifyElems - * @param {Element} g - The parent element of the tree to give unique IDs - * @returns {void} - */ - - - var uniquifyElems = this.uniquifyElems = function (g) { - var ids = {}; // TODO: Handle markers and connectors. These are not yet re-identified properly - // as their referring elements do not get remapped. - // - // <marker id='se_marker_end_svg_7'/> - // <polyline id='svg_7' se:connector='svg_1 svg_6' marker-end='url(#se_marker_end_svg_7)'/> - // - // Problem #1: if svg_1 gets renamed, we do not update the polyline's se:connector attribute - // Problem #2: if the polyline svg_7 gets renamed, we do not update the marker id nor the polyline's marker-end attribute - - var refElems = ['filter', 'linearGradient', 'pattern', 'radialGradient', 'symbol', 'textPath', 'use']; - walkTree(g, function (n) { - // if it's an element node - if (n.nodeType === 1) { - // and the element has an ID - if (n.id) { - // and we haven't tracked this ID yet - if (!(n.id in ids)) { - // add this id to our map - ids[n.id] = { - elem: null, - attrs: [], - hrefs: [] - }; - } - - ids[n.id].elem = n; - } // now search for all attributes on this element that might refer - // to other elements - - - $$a.each(refAttrs, function (i, attr) { - var attrnode = n.getAttributeNode(attr); - - if (attrnode) { - // the incoming file has been sanitized, so we should be able to safely just strip off the leading # - var url = getUrlFromAttr(attrnode.value), - refid = url ? url.substr(1) : null; - - if (refid) { - if (!(refid in ids)) { - // add this id to our map - ids[refid] = { - elem: null, - attrs: [], - hrefs: [] - }; - } - - ids[refid].attrs.push(attrnode); - } - } - }); // check xlink:href now - - var href = getHref(n); // TODO: what if an <image> or <a> element refers to an element internally? - - if (href && refElems.includes(n.nodeName)) { - var refid = href.substr(1); - - if (refid) { - if (!(refid in ids)) { - // add this id to our map - ids[refid] = { - elem: null, - attrs: [], - hrefs: [] - }; - } - - ids[refid].hrefs.push(n); - } - } - } - }); // in ids, we now have a map of ids, elements and attributes, let's re-identify - - for (var oldid in ids) { - if (!oldid) { - continue; - } - - var elem = ids[oldid].elem; - - if (elem) { - var newid = getNextId(); // assign element its new id - - elem.id = newid; // remap all url() attributes - - var attrs = ids[oldid].attrs; - var j = attrs.length; - - while (j--) { - var attr = attrs[j]; - attr.ownerElement.setAttribute(attr.name, 'url(#' + newid + ')'); - } // remap all href attributes - - - var hreffers = ids[oldid].hrefs; - var k = hreffers.length; - - while (k--) { - var hreffer = hreffers[k]; - setHref(hreffer, '#' + newid); - } - } - } - }; - /** - * Assigns reference data for each use element. - * @function module:svgcanvas.SvgCanvas#setUseData - * @param {Element} parent - * @returns {void} - */ - - - var setUseData = this.setUseData = function (parent) { - var elems = $$a(parent); - - if (parent.tagName !== 'use') { - elems = elems.find('use'); - } - - elems.each(function () { - var id = getHref(this).substr(1); - var refElem = getElem(id); - - if (!refElem) { - return; - } - - $$a(this).data('ref', refElem); - - if (refElem.tagName === 'symbol' || refElem.tagName === 'svg') { - $$a(this).data('symbol', refElem).data('ref', refElem); - } - }); - }; - /** - * Converts gradients from userSpaceOnUse to objectBoundingBox. - * @function module:svgcanvas.SvgCanvas#convertGradients - * @param {Element} elem - * @returns {void} - */ - - - var convertGradients = this.convertGradients = function (elem) { - var elems = $$a(elem).find('linearGradient, radialGradient'); - - if (!elems.length && isWebkit()) { - // Bug in webkit prevents regular *Gradient selector search - elems = $$a(elem).find('*').filter(function () { - return this.tagName.includes('Gradient'); - }); - } - - elems.each(function () { - var grad = this; - - if ($$a(grad).attr('gradientUnits') === 'userSpaceOnUse') { - // TODO: Support more than one element with this ref by duplicating parent grad - var fillStrokeElems = $$a(svgcontent).find('[fill="url(#' + grad.id + ')"],[stroke="url(#' + grad.id + ')"]'); - - if (!fillStrokeElems.length) { - return; - } // get object's bounding box - - - var bb = getBBox(fillStrokeElems[0]); // This will occur if the element is inside a <defs> or a <symbol>, - // in which we shouldn't need to convert anyway. - - if (!bb) { - return; - } - - if (grad.tagName === 'linearGradient') { - var gCoords = $$a(grad).attr(['x1', 'y1', 'x2', 'y2']); // If has transform, convert - - var tlist = grad.gradientTransform.baseVal; - - if (tlist && tlist.numberOfItems > 0) { - var m = transformListToTransform(tlist).matrix; - var pt1 = transformPoint(gCoords.x1, gCoords.y1, m); - var pt2 = transformPoint(gCoords.x2, gCoords.y2, m); - gCoords.x1 = pt1.x; - gCoords.y1 = pt1.y; - gCoords.x2 = pt2.x; - gCoords.y2 = pt2.y; - grad.removeAttribute('gradientTransform'); - } - - $$a(grad).attr({ - x1: (gCoords.x1 - bb.x) / bb.width, - y1: (gCoords.y1 - bb.y) / bb.height, - x2: (gCoords.x2 - bb.x) / bb.width, - y2: (gCoords.y2 - bb.y) / bb.height - }); - grad.removeAttribute('gradientUnits'); - } // else { - // Note: radialGradient elements cannot be easily converted - // because userSpaceOnUse will keep circular gradients, while - // objectBoundingBox will x/y scale the gradient according to - // its bbox. - // - // For now we'll do nothing, though we should probably have - // the gradient be updated as the element is moved, as - // inkscape/illustrator do. - // - // const gCoords = $(grad).attr(['cx', 'cy', 'r']); - // - // $(grad).attr({ - // cx: (gCoords.cx - bb.x) / bb.width, - // cy: (gCoords.cy - bb.y) / bb.height, - // r: gCoords.r - // }); - // - // grad.removeAttribute('gradientUnits'); - // } - - } - }); - }; - /** - * Converts selected/given `<use>` or child SVG element to a group. - * @function module:svgcanvas.SvgCanvas#convertToGroup - * @param {Element} elem - * @fires module:svgcanvas.SvgCanvas#event:selected - * @returns {void} - */ - - - var convertToGroup = this.convertToGroup = function (elem) { - if (!elem) { - elem = selectedElements[0]; - } - - var $elem = $$a(elem); - var batchCmd = new BatchCommand$1(); - var ts; - - if ($elem.data('gsvg')) { - // Use the gsvg as the new group - var svg = elem.firstChild; - var pt = $$a(svg).attr(['x', 'y']); - $$a(elem.firstChild.firstChild).unwrap(); - $$a(elem).removeData('gsvg'); - var tlist = getTransformList(elem); - var xform = svgroot.createSVGTransform(); - xform.setTranslate(pt.x, pt.y); - tlist.appendItem(xform); - recalculateDimensions(elem); - call('selected', [elem]); - } else if ($elem.data('symbol')) { - elem = $elem.data('symbol'); - ts = $elem.attr('transform'); - var pos = $elem.attr(['x', 'y']); - var vb = elem.getAttribute('viewBox'); - - if (vb) { - var nums = vb.split(' '); - pos.x -= Number(nums[0]); - pos.y -= Number(nums[1]); - } // Not ideal, but works - - - ts += ' translate(' + (pos.x || 0) + ',' + (pos.y || 0) + ')'; - var prev = $elem.prev(); // Remove <use> element - - batchCmd.addSubCommand(new RemoveElementCommand$1($elem[0], $elem[0].nextSibling, $elem[0].parentNode)); - $elem.remove(); // See if other elements reference this symbol - - var hasMore = $$a(svgcontent).find('use:data(symbol)').length; - var g = svgdoc.createElementNS(NS.SVG, 'g'); - var childs = elem.childNodes; - var i; - - for (i = 0; i < childs.length; i++) { - g.append(childs[i].cloneNode(true)); - } // Duplicate the gradients for Gecko, since they weren't included in the <symbol> - - - if (isGecko()) { - var dupeGrads = $$a(findDefs()).children('linearGradient,radialGradient,pattern').clone(); - $$a(g).append(dupeGrads); - } - - if (ts) { - g.setAttribute('transform', ts); - } - - var parent = elem.parentNode; - uniquifyElems(g); // Put the dupe gradients back into <defs> (after uniquifying them) - - if (isGecko()) { - $$a(findDefs()).append($$a(g).find('linearGradient,radialGradient,pattern')); - } // now give the g itself a new id - - - g.id = getNextId(); - prev.after(g); - - if (parent) { - if (!hasMore) { - // remove symbol/svg element - var _elem = elem, - nextSibling = _elem.nextSibling; - elem.remove(); - batchCmd.addSubCommand(new RemoveElementCommand$1(elem, nextSibling, parent)); - } - - batchCmd.addSubCommand(new InsertElementCommand$1(g)); - } - - setUseData(g); - - if (isGecko()) { - convertGradients(findDefs()); - } else { - convertGradients(g); - } // recalculate dimensions on the top-level children so that unnecessary transforms - // are removed - - - walkTreePost(g, function (n) { - try { - recalculateDimensions(n); - } catch (e) { - console.log(e); // eslint-disable-line no-console - } - }); // Give ID for any visible element missing one - - $$a(g).find(visElems).each(function () { - if (!this.id) { - this.id = getNextId(); - } - }); - selectOnly([g]); - var cm = pushGroupProperties(g, true); - - if (cm) { - batchCmd.addSubCommand(cm); - } - - addCommandToHistory(batchCmd); - } else { - console.log('Unexpected element to ungroup:', elem); // eslint-disable-line no-console - } - }; - /** - * This function sets the current drawing as the input SVG XML. - * @function module:svgcanvas.SvgCanvas#setSvgString - * @param {string} xmlString - The SVG as XML text. - * @param {boolean} [preventUndo=false] - Indicates if we want to do the - * changes without adding them to the undo stack - e.g. for initializing a - * drawing on page load. - * @fires module:svgcanvas.SvgCanvas#event:setnonce - * @fires module:svgcanvas.SvgCanvas#event:unsetnonce - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {boolean} This function returns `false` if the set was - * unsuccessful, `true` otherwise. - */ - - - this.setSvgString = function (xmlString, preventUndo) { - try { - // convert string into XML document - var newDoc = text2xml(xmlString); - - if (newDoc.firstElementChild && newDoc.firstElementChild.namespaceURI !== NS.SVG) { - return false; - } - - this.prepareSvg(newDoc); - var batchCmd = new BatchCommand$1('Change Source'); // remove old svg document - - var _svgcontent = svgcontent, - nextSibling = _svgcontent.nextSibling; - svgcontent.remove(); - var oldzoom = svgcontent; - batchCmd.addSubCommand(new RemoveElementCommand$1(oldzoom, nextSibling, svgroot)); // set new svg document - // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode() - - if (svgdoc.adoptNode) { - svgcontent = svgdoc.adoptNode(newDoc.documentElement); - } else { - svgcontent = svgdoc.importNode(newDoc.documentElement, true); - } - - svgroot.append(svgcontent); - var content = $$a(svgcontent); - canvas.current_drawing_ = new Drawing(svgcontent, idprefix); // retrieve or set the nonce - - var nonce = getCurrentDrawing().getNonce(); - - if (nonce) { - call('setnonce', nonce); - } else { - call('unsetnonce'); - } // change image href vals if possible - - - content.find('image').each(function () { - var image = this; - preventClickDefault(image); - var val = getHref(this); - - if (val) { - if (val.startsWith('data:')) { - // Check if an SVG-edit data URI - var m = val.match(/svgedit_url=(.*?);/); // const m = val.match(/svgedit_url=(?<url>.*?);/); - - if (m) { - var url = decodeURIComponent(m[1]); // const url = decodeURIComponent(m.groups.url); - - $$a(new Image()).load(function () { - image.setAttributeNS(NS.XLINK, 'xlink:href', url); - }).attr('src', url); - } - } // Add to encodableImages if it loads - - - canvas.embedImage(val); - } - }); // Wrap child SVGs in group elements - - content.find('svg').each(function () { - // Skip if it's in a <defs> - if ($$a(this).closest('defs').length) { - return; - } - - uniquifyElems(this); // Check if it already has a gsvg group - - var pa = this.parentNode; - - if (pa.childNodes.length === 1 && pa.nodeName === 'g') { - $$a(pa).data('gsvg', this); - pa.id = pa.id || getNextId(); - } else { - groupSvgElem(this); - } - }); // For Firefox: Put all paint elems in defs - - if (isGecko()) { - content.find('linearGradient, radialGradient, pattern').appendTo(findDefs()); - } // Set ref element for <use> elements - // TODO: This should also be done if the object is re-added through "redo" - - - setUseData(content); - convertGradients(content[0]); - var attrs = { - id: 'svgcontent', - overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden' - }; - var percs = false; // determine proper size - - if (content.attr('viewBox')) { - var vb = content.attr('viewBox').split(' '); - attrs.width = vb[2]; - attrs.height = vb[3]; // handle content that doesn't have a viewBox - } else { - $$a.each(['width', 'height'], function (i, dim) { - // Set to 100 if not given - var val = content.attr(dim) || '100%'; - - if (String(val).substr(-1) === '%') { - // Use user units if percentage given - percs = true; - } else { - attrs[dim] = convertToNum(dim, val); - } - }); - } // identify layers - - - identifyLayers(); // Give ID for any visible layer children missing one - - content.children().find(visElems).each(function () { - if (!this.id) { - this.id = getNextId(); - } - }); // Percentage width/height, so let's base it on visible elements - - if (percs) { - var bb = getStrokedBBoxDefaultVisible(); - attrs.width = bb.width + bb.x; - attrs.height = bb.height + bb.y; - } // Just in case negative numbers are given or - // result from the percs calculation - - - if (attrs.width <= 0) { - attrs.width = 100; - } - - if (attrs.height <= 0) { - attrs.height = 100; - } - - content.attr(attrs); - this.contentW = attrs.width; - this.contentH = attrs.height; - batchCmd.addSubCommand(new InsertElementCommand$1(svgcontent)); // update root to the correct size - - var changes = content.attr(['width', 'height']); - batchCmd.addSubCommand(new ChangeElementCommand$1(svgroot, changes)); // reset zoom - - currentZoom = 1; // reset transform lists - - resetListMap(); - clearSelection(); - clearData(); - svgroot.append(selectorManager.selectorParentGroup); - if (!preventUndo) addCommandToHistory(batchCmd); - call('changed', [svgcontent]); - } catch (e) { - console.log(e); // eslint-disable-line no-console - - return false; - } - - return true; - }; - /** - * This function imports the input SVG XML as a `<symbol>` in the `<defs>`, then adds a - * `<use>` to the current layer. - * @function module:svgcanvas.SvgCanvas#importSvgString - * @param {string} xmlString - The SVG as XML text. - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {null|Element} This function returns null if the import was unsuccessful, or the element otherwise. - * @todo - * - properly handle if namespace is introduced by imported content (must add to svgcontent - * and update all prefixes in the imported node) - * - properly handle recalculating dimensions, `recalculateDimensions()` doesn't handle - * arbitrary transform lists, but makes some assumptions about how the transform list - * was obtained - */ - - - this.importSvgString = function (xmlString) { - var j, ts, useEl; - - try { - // Get unique ID - var uid = encode64(xmlString.length + xmlString).substr(0, 32); - var useExisting = false; // Look for symbol and make sure symbol exists in image - - if (importIds[uid]) { - if ($$a(importIds[uid].symbol).parents('#svgroot').length) { - useExisting = true; - } - } - - var batchCmd = new BatchCommand$1('Import Image'); - var symbol; - - if (useExisting) { - symbol = importIds[uid].symbol; - ts = importIds[uid].xform; - } else { - // convert string into XML document - var newDoc = text2xml(xmlString); - this.prepareSvg(newDoc); // import new svg document into our document - - var svg; // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode() - - if (svgdoc.adoptNode) { - svg = svgdoc.adoptNode(newDoc.documentElement); - } else { - svg = svgdoc.importNode(newDoc.documentElement, true); - } - - uniquifyElems(svg); - var innerw = convertToNum('width', svg.getAttribute('width')), - innerh = convertToNum('height', svg.getAttribute('height')), - innervb = svg.getAttribute('viewBox'), - // if no explicit viewbox, create one out of the width and height - vb = innervb ? innervb.split(' ') : [0, 0, innerw, innerh]; - - for (j = 0; j < 4; ++j) { - vb[j] = Number(vb[j]); - } // TODO: properly handle preserveAspectRatio - - - var // canvasw = +svgcontent.getAttribute('width'), - canvash = Number(svgcontent.getAttribute('height')); // imported content should be 1/3 of the canvas on its largest dimension - - if (innerh > innerw) { - ts = 'scale(' + canvash / 3 / vb[3] + ')'; - } else { - ts = 'scale(' + canvash / 3 / vb[2] + ')'; - } // Hack to make recalculateDimensions understand how to scale - - - ts = 'translate(0) ' + ts + ' translate(0)'; - symbol = svgdoc.createElementNS(NS.SVG, 'symbol'); - var defs = findDefs(); - - if (isGecko()) { - // Move all gradients into root for Firefox, workaround for this bug: - // https://bugzilla.mozilla.org/show_bug.cgi?id=353575 - // TODO: Make this properly undo-able. - $$a(svg).find('linearGradient, radialGradient, pattern').appendTo(defs); - } - - while (svg.firstChild) { - var first = svg.firstChild; - symbol.append(first); - } - - var attrs = svg.attributes; - - var _iterator2 = _createForOfIteratorHelper(attrs), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var attr = _step2.value; - // Ok for `NamedNodeMap` - symbol.setAttribute(attr.nodeName, attr.value); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - symbol.id = getNextId(); // Store data - - importIds[uid] = { - symbol: symbol, - xform: ts - }; - findDefs().append(symbol); - batchCmd.addSubCommand(new InsertElementCommand$1(symbol)); - } - - useEl = svgdoc.createElementNS(NS.SVG, 'use'); - useEl.id = getNextId(); - setHref(useEl, '#' + symbol.id); - (currentGroup || getCurrentDrawing().getCurrentLayer()).append(useEl); - batchCmd.addSubCommand(new InsertElementCommand$1(useEl)); - clearSelection(); - useEl.setAttribute('transform', ts); - recalculateDimensions(useEl); - $$a(useEl).data('symbol', symbol).data('ref', symbol); - addToSelection([useEl]); // TODO: Find way to add this in a recalculateDimensions-parsable way - // if (vb[0] !== 0 || vb[1] !== 0) { - // ts = 'translate(' + (-vb[0]) + ',' + (-vb[1]) + ') ' + ts; - // } - - addCommandToHistory(batchCmd); - call('changed', [svgcontent]); - } catch (e) { - console.log(e); // eslint-disable-line no-console - - return null; - } // we want to return the element so we can automatically select it - - - return useEl; - }; // Could deprecate, but besides external uses, their usage makes clear that - // canvas is a dependency for all of these - - - var dr = { - identifyLayers: identifyLayers, - createLayer: createLayer, - cloneLayer: cloneLayer, - deleteCurrentLayer: deleteCurrentLayer, - setCurrentLayer: setCurrentLayer, - renameCurrentLayer: renameCurrentLayer, - setCurrentLayerPosition: setCurrentLayerPosition, - setLayerVisibility: setLayerVisibility, - moveSelectedToLayer: moveSelectedToLayer, - mergeLayer: mergeLayer, - mergeAllLayers: mergeAllLayers, - leaveContext: leaveContext, - setContext: setContext - }; - Object.entries(dr).forEach(function (_ref7) { - var _ref8 = _slicedToArray(_ref7, 2), - prop = _ref8[0], - propVal = _ref8[1]; - - canvas[prop] = propVal; - }); - init$3( - /** - * @implements {module:draw.DrawCanvasInit} - */ - { - pathActions: pathActions$1, - getCurrentGroup: function getCurrentGroup() { - return currentGroup; - }, - setCurrentGroup: function setCurrentGroup(cg) { - currentGroup = cg; - }, - getSelectedElements: getSelectedElements, - getSVGContent: getSVGContent, - undoMgr: undoMgr, - elData: elData, - getCurrentDrawing: getCurrentDrawing, - clearSelection: clearSelection, - call: call, - addCommandToHistory: addCommandToHistory, - - /** - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - changeSVGContent: function changeSVGContent() { - call('changed', [svgcontent]); - } - }); - /** - * Group: Document functions. - */ - - /** - * Clears the current document. This is not an undoable action. - * @function module:svgcanvas.SvgCanvas#clear - * @fires module:svgcanvas.SvgCanvas#event:cleared - * @returns {void} - */ - - this.clear = function () { - pathActions$1.clear(); - clearSelection(); // clear the svgcontent node - - canvas.clearSvgContentElement(); // create new document - - canvas.current_drawing_ = new Drawing(svgcontent); // create empty first layer - - canvas.createLayer('Layer 1'); // clear the undo stack - - canvas.undoMgr.resetUndoStack(); // reset the selector manager - - selectorManager.initGroup(); // reset the rubber band box - - rubberBox = selectorManager.getRubberBandBox(); - call('cleared'); - }; // Alias function - - - this.linkControlPoints = pathActions$1.linkControlPoints; - /** - * @function module:svgcanvas.SvgCanvas#getContentElem - * @returns {Element} The content DOM element - */ - - this.getContentElem = function () { - return svgcontent; - }; - /** - * @function module:svgcanvas.SvgCanvas#getRootElem - * @returns {SVGSVGElement} The root DOM element - */ - - - this.getRootElem = function () { - return svgroot; - }; - /** - * @typedef {PlainObject} DimensionsAndZoom - * @property {Float} w Width - * @property {Float} h Height - * @property {Float} zoom Zoom - */ - - /** - * @function module:svgcanvas.SvgCanvas#getResolution - * @returns {DimensionsAndZoom} The current dimensions and zoom level in an object - */ - - - var getResolution = this.getResolution = function () { - // const vb = svgcontent.getAttribute('viewBox').split(' '); - // return {w:vb[2], h:vb[3], zoom: currentZoom}; - var w = svgcontent.getAttribute('width') / currentZoom; - var h = svgcontent.getAttribute('height') / currentZoom; - return { - w: w, - h: h, - zoom: currentZoom - }; - }; - /** - * @function module:svgcanvas.SvgCanvas#getSnapToGrid - * @returns {boolean} The current snap to grid setting - */ - - - this.getSnapToGrid = function () { - return curConfig.gridSnapping; - }; - /** - * @function module:svgcanvas.SvgCanvas#getVersion - * @returns {string} A string which describes the revision number of SvgCanvas. - */ - - - this.getVersion = function () { - return 'svgcanvas.js ($Rev$)'; - }; - /** - * Update interface strings with given values. - * @function module:svgcanvas.SvgCanvas#setUiStrings - * @param {module:path.uiStrings} strs - Object with strings (see the [locales API]{@link module:locale.LocaleStrings} and the [tutorial]{@tutorial LocaleDocs}) - * @returns {void} - */ - - - this.setUiStrings = function (strs) { - Object.assign(uiStrings, strs.notification); - $$a = jQueryPluginDBox($$a, strs.common); - setUiStrings(strs); - }; - /** - * Update configuration options with given values. - * @function module:svgcanvas.SvgCanvas#setConfig - * @param {module:SVGEditor.Config} opts - Object with options - * @returns {void} - */ - - - this.setConfig = function (opts) { - Object.assign(curConfig, opts); - }; - /** - * @function module:svgcanvas.SvgCanvas#getTitle - * @param {Element} [elem] - * @returns {string|void} the current group/SVG's title contents or - * `undefined` if no element is passed nd there are no selected elements. - */ - - - this.getTitle = function (elem) { - elem = elem || selectedElements[0]; - - if (!elem) { - return undefined; - } - - elem = $$a(elem).data('gsvg') || $$a(elem).data('symbol') || elem; - var childs = elem.childNodes; - - var _iterator3 = _createForOfIteratorHelper(childs), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var child = _step3.value; - - if (child.nodeName === 'title') { - return child.textContent; - } - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - return ''; - }; - /** - * Sets the group/SVG's title content. - * @function module:svgcanvas.SvgCanvas#setGroupTitle - * @param {string} val - * @todo Combine this with `setDocumentTitle` - * @returns {void} - */ - - - this.setGroupTitle = function (val) { - var elem = selectedElements[0]; - elem = $$a(elem).data('gsvg') || elem; - var ts = $$a(elem).children('title'); - var batchCmd = new BatchCommand$1('Set Label'); - var title; - - if (!val.length) { - // Remove title element - var tsNextSibling = ts.nextSibling; - batchCmd.addSubCommand(new RemoveElementCommand$1(ts[0], tsNextSibling, elem)); - ts.remove(); - } else if (ts.length) { - // Change title contents - title = ts[0]; - batchCmd.addSubCommand(new ChangeElementCommand$1(title, { - '#text': title.textContent - })); - title.textContent = val; - } else { - // Add title element - title = svgdoc.createElementNS(NS.SVG, 'title'); - title.textContent = val; - $$a(elem).prepend(title); - batchCmd.addSubCommand(new InsertElementCommand$1(title)); - } - - addCommandToHistory(batchCmd); - }; - /** - * @function module:svgcanvas.SvgCanvas#getDocumentTitle - * @returns {string|void} The current document title or an empty string if not found - */ - - - var getDocumentTitle = this.getDocumentTitle = function () { - return canvas.getTitle(svgcontent); - }; - /** - * Adds/updates a title element for the document with the given name. - * This is an undoable action. - * @function module:svgcanvas.SvgCanvas#setDocumentTitle - * @param {string} newTitle - String with the new title - * @returns {void} - */ - - - this.setDocumentTitle = function (newTitle) { - var childs = svgcontent.childNodes; - var docTitle = false, - oldTitle = ''; - var batchCmd = new BatchCommand$1('Change Image Title'); - - var _iterator4 = _createForOfIteratorHelper(childs), - _step4; - - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var child = _step4.value; - - if (child.nodeName === 'title') { - docTitle = child; - oldTitle = docTitle.textContent; - break; - } - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); - } - - if (!docTitle) { - docTitle = svgdoc.createElementNS(NS.SVG, 'title'); - svgcontent.insertBefore(docTitle, svgcontent.firstChild); // svgcontent.firstChild.before(docTitle); // Ok to replace above with this? - } - - if (newTitle.length) { - docTitle.textContent = newTitle; - } else { - // No title given, so element is not necessary - docTitle.remove(); - } - - batchCmd.addSubCommand(new ChangeElementCommand$1(docTitle, { - '#text': oldTitle - })); - addCommandToHistory(batchCmd); - }; - /** - * Returns the editor's namespace URL, optionally adding it to the root element. - * @function module:svgcanvas.SvgCanvas#getEditorNS - * @param {boolean} [add] - Indicates whether or not to add the namespace value - * @returns {string} The editor's namespace URL - */ - - - this.getEditorNS = function (add) { - if (add) { - svgcontent.setAttribute('xmlns:se', NS.SE); - } - - return NS.SE; - }; - /** - * Changes the document's dimensions to the given size. - * @function module:svgcanvas.SvgCanvas#setResolution - * @param {Float|"fit"} x - Number with the width of the new dimensions in user units. - * Can also be the string "fit" to indicate "fit to content". - * @param {Float} y - Number with the height of the new dimensions in user units. - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {boolean} Indicates if resolution change was successful. - * It will fail on "fit to content" option with no content to fit to. - */ - - - this.setResolution = function (x, y) { - var res = getResolution(); - var w = res.w, - h = res.h; - var batchCmd; - - if (x === 'fit') { - // Get bounding box - var bbox = getStrokedBBoxDefaultVisible(); - - if (bbox) { - batchCmd = new BatchCommand$1('Fit Canvas to Content'); - var visEls = getVisibleElements(); - addToSelection(visEls); - var dx = [], - dy = []; - $$a.each(visEls, function (i, item) { - dx.push(bbox.x * -1); - dy.push(bbox.y * -1); - }); - var cmd = canvas.moveSelectedElements(dx, dy, true); - batchCmd.addSubCommand(cmd); - clearSelection(); - x = Math.round(bbox.width); - y = Math.round(bbox.height); - } else { - return false; - } - } - - if (x !== w || y !== h) { - if (!batchCmd) { - batchCmd = new BatchCommand$1('Change Image Dimensions'); - } - - x = convertToNum('width', x); - y = convertToNum('height', y); - svgcontent.setAttribute('width', x); - svgcontent.setAttribute('height', y); - this.contentW = x; - this.contentH = y; - batchCmd.addSubCommand(new ChangeElementCommand$1(svgcontent, { - width: w, - height: h - })); - svgcontent.setAttribute('viewBox', [0, 0, x / currentZoom, y / currentZoom].join(' ')); - batchCmd.addSubCommand(new ChangeElementCommand$1(svgcontent, { - viewBox: ['0 0', w, h].join(' ') - })); - addCommandToHistory(batchCmd); - call('changed', [svgcontent]); - } - - return true; - }; - /** - * @typedef {module:jQueryAttr.Attributes} module:svgcanvas.ElementPositionInCanvas - * @property {Float} x - * @property {Float} y - */ - - /** - * @function module:svgcanvas.SvgCanvas#getOffset - * @returns {module:svgcanvas.ElementPositionInCanvas} An object with `x`, `y` values indicating the svgcontent element's - * position in the editor's canvas. - */ - - - this.getOffset = function () { - return $$a(svgcontent).attr(['x', 'y']); - }; - /** - * @typedef {PlainObject} module:svgcanvas.ZoomAndBBox - * @property {Float} zoom - * @property {module:utilities.BBoxObject} bbox - */ - - /** - * Sets the zoom level on the canvas-side based on the given value. - * @function module:svgcanvas.SvgCanvas#setBBoxZoom - * @param {"selection"|"canvas"|"content"|"layer"|module:SVGEditor.BBoxObjectWithFactor} val - Bounding box object to zoom to or string indicating zoom option. Note: the object value type is defined in `svg-editor.js` - * @param {Integer} editorW - The editor's workarea box's width - * @param {Integer} editorH - The editor's workarea box's height - * @returns {module:svgcanvas.ZoomAndBBox|void} - */ - - - this.setBBoxZoom = function (val, editorW, editorH) { - var spacer = 0.85; - var bb; - - var calcZoom = function calcZoom(bb) { - // eslint-disable-line no-shadow - if (!bb) { - return false; - } - - var wZoom = Math.round(editorW / bb.width * 100 * spacer) / 100; - var hZoom = Math.round(editorH / bb.height * 100 * spacer) / 100; - var zoom = Math.min(wZoom, hZoom); - canvas.setZoom(zoom); - return { - zoom: zoom, - bbox: bb - }; - }; - - if (_typeof(val) === 'object') { - bb = val; - - if (bb.width === 0 || bb.height === 0) { - var newzoom = bb.zoom ? bb.zoom : currentZoom * bb.factor; - canvas.setZoom(newzoom); - return { - zoom: currentZoom, - bbox: bb - }; - } - - return calcZoom(bb); - } - - switch (val) { - case 'selection': - { - if (!selectedElements[0]) { - return undefined; - } - - var selectedElems = $$a.map(selectedElements, function (n) { - if (n) { - return n; - } - - return undefined; - }); - bb = getStrokedBBoxDefaultVisible(selectedElems); - break; - } - - case 'canvas': - { - var res = getResolution(); - spacer = 0.95; - bb = { - width: res.w, - height: res.h, - x: 0, - y: 0 - }; - break; - } - - case 'content': - bb = getStrokedBBoxDefaultVisible(); - break; - - case 'layer': - bb = getStrokedBBoxDefaultVisible(getVisibleElements(getCurrentDrawing().getCurrentLayer())); - break; - - default: - return undefined; - } - - return calcZoom(bb); - }; - /** - * The zoom level has changed. Supplies the new zoom level as a number (not percentage). - * @event module:svgcanvas.SvgCanvas#event:ext_zoomChanged - * @type {Float} - */ - - /** - * The bottom panel was updated. - * @event module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate - * @type {PlainObject} - * @property {boolean} nofill Indicates fill is disabled - * @property {boolean} nostroke Indicates stroke is disabled - */ - - /** - * The element selection has changed (elements were added/removed from selection). - * @event module:svgcanvas.SvgCanvas#event:ext_selectedChanged - * @type {PlainObject} - * @property {Element[]} elems Array of the newly selected elements - * @property {Element|null} selectedElement The single selected element - * @property {boolean} multiselected Indicates whether one or more elements were selected - */ - - /** - * Called when part of element is in process of changing, generally on - * mousemove actions like rotate, move, etc. - * @event module:svgcanvas.SvgCanvas#event:ext_elementTransition - * @type {PlainObject} - * @property {Element[]} elems Array of transitioning elements - */ - - /** - * One or more elements were changed. - * @event module:svgcanvas.SvgCanvas#event:ext_elementChanged - * @type {PlainObject} - * @property {Element[]} elems Array of the affected elements - */ - - /** - * Invoked as soon as the locale is ready. - * @event module:svgcanvas.SvgCanvas#event:ext_langReady - * @type {PlainObject} - * @property {string} lang The two-letter language code - * @property {module:SVGEditor.uiStrings} uiStrings - * @property {module:SVGEditor~ImportLocale} importLocale - */ - - /** - * The language was changed. Two-letter code of the new language. - * @event module:svgcanvas.SvgCanvas#event:ext_langChanged - * @type {string} - */ - - /** - * Means for an extension to add locale data. The two-letter language code. - * @event module:svgcanvas.SvgCanvas#event:ext_addLangData - * @type {PlainObject} - * @property {string} lang - * @property {module:SVGEditor~ImportLocale} importLocale - */ - - /** - * Called when new image is created. - * @event module:svgcanvas.SvgCanvas#event:ext_onNewDocument - * @type {void} - */ - - /** - * Called when sidepanel is resized or toggled. - * @event module:svgcanvas.SvgCanvas#event:ext_workareaResized - * @type {void} - */ - - /** - * Called upon addition of the extension, or, if svgicons are set, - * after the icons are ready when extension SVG icons have loaded. - * @event module:svgcanvas.SvgCanvas#event:ext_callback - * @type {void} - */ - - /** - * Sets the zoom to the given level. - * @function module:svgcanvas.SvgCanvas#setZoom - * @param {Float} zoomLevel - Float indicating the zoom level to change to - * @fires module:svgcanvas.SvgCanvas#event:ext_zoomChanged - * @returns {void} - */ - - - this.setZoom = function (zoomLevel) { - var res = getResolution(); - svgcontent.setAttribute('viewBox', '0 0 ' + res.w / zoomLevel + ' ' + res.h / zoomLevel); - currentZoom = zoomLevel; - $$a.each(selectedElements, function (i, elem) { - if (!elem) { - return; - } - - selectorManager.requestSelector(elem).resize(); - }); - pathActions$1.zoomChange(); - runExtensions('zoomChanged', - /** @type {module:svgcanvas.SvgCanvas#event:ext_zoomChanged} */ - zoomLevel); - }; - /** - * @function module:svgcanvas.SvgCanvas#getMode - * @returns {string} The current editor mode string - */ - - - this.getMode = function () { - return currentMode; - }; - /** - * Sets the editor's mode to the given string. - * @function module:svgcanvas.SvgCanvas#setMode - * @param {string} name - String with the new mode to change to - * @returns {void} - */ - - - this.setMode = function (name) { - pathActions$1.clear(true); - textActions.clear(); - curProperties = selectedElements[0] && selectedElements[0].nodeName === 'text' ? curText : curShape; - currentMode = name; - }; - /** - * Group: Element Styling. - */ - - /** - * @typedef {PlainObject} module:svgcanvas.PaintOptions - * @property {"solidColor"} type - */ - - /** - * @function module:svgcanvas.SvgCanvas#getColor - * @param {string} type - * @returns {string|module:svgcanvas.PaintOptions|Float|module:jGraduate~Paint} The current fill/stroke option - */ - - - this.getColor = function (type) { - return curProperties[type]; - }; - /** - * Change the current stroke/fill color/gradient value. - * @function module:svgcanvas.SvgCanvas#setColor - * @param {string} type - String indicating fill or stroke - * @param {string} val - The value to set the stroke attribute to - * @param {boolean} preventUndo - Boolean indicating whether or not this should be an undoable option - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.setColor = function (type, val, preventUndo) { - curShape[type] = val; - curProperties[type + '_paint'] = { - type: 'solidColor' - }; - var elems = []; - /** - * - * @param {Element} e - * @returns {void} - */ - - function addNonG(e) { - if (e.nodeName !== 'g') { - elems.push(e); - } - } - - var i = selectedElements.length; - - while (i--) { - var elem = selectedElements[i]; - - if (elem) { - if (elem.tagName === 'g') { - walkTree(elem, addNonG); - } else if (type === 'fill') { - if (elem.tagName !== 'polyline' && elem.tagName !== 'line') { - elems.push(elem); - } - } else { - elems.push(elem); - } - } - } - - if (elems.length > 0) { - if (!preventUndo) { - changeSelectedAttribute(type, val, elems); - call('changed', elems); - } else { - changeSelectedAttributeNoUndo(type, val, elems); - } - } - }; - /** - * Apply the current gradient to selected element's fill or stroke. - * @function module:svgcanvas.SvgCanvas#setGradient - * @param {"fill"|"stroke"} type - String indicating "fill" or "stroke" to apply to an element - * @returns {void} - */ - - - var setGradient = this.setGradient = function (type) { - if (!curProperties[type + '_paint'] || curProperties[type + '_paint'].type === 'solidColor') { - return; - } - - var grad = canvas[type + 'Grad']; // find out if there is a duplicate gradient already in the defs - - var duplicateGrad = findDuplicateGradient(grad); - var defs = findDefs(); // no duplicate found, so import gradient into defs - - if (!duplicateGrad) { - // const origGrad = grad; - grad = defs.appendChild(svgdoc.importNode(grad, true)); // get next id and set it on the grad - - grad.id = getNextId(); - } else { - // use existing gradient - grad = duplicateGrad; - } - - canvas.setColor(type, 'url(#' + grad.id + ')'); - }; - /** - * Check if exact gradient already exists. - * @function module:svgcanvas~findDuplicateGradient - * @param {SVGGradientElement} grad - The gradient DOM element to compare to others - * @returns {SVGGradientElement} The existing gradient if found, `null` if not - */ - - - var findDuplicateGradient = function findDuplicateGradient(grad) { - var defs = findDefs(); - var existingGrads = $$a(defs).find('linearGradient, radialGradient'); - var i = existingGrads.length; - var radAttrs = ['r', 'cx', 'cy', 'fx', 'fy']; - - while (i--) { - var og = existingGrads[i]; - - if (grad.tagName === 'linearGradient') { - if (grad.getAttribute('x1') !== og.getAttribute('x1') || grad.getAttribute('y1') !== og.getAttribute('y1') || grad.getAttribute('x2') !== og.getAttribute('x2') || grad.getAttribute('y2') !== og.getAttribute('y2')) { - continue; - } - } else { - var _ret = function () { - var gradAttrs = $$a(grad).attr(radAttrs); - var ogAttrs = $$a(og).attr(radAttrs); - var diff = false; - $$a.each(radAttrs, function (j, attr) { - if (gradAttrs[attr] !== ogAttrs[attr]) { - diff = true; - } - }); - - if (diff) { - return "continue"; - } - }(); - - if (_ret === "continue") continue; - } // else could be a duplicate, iterate through stops - - - var stops = grad.getElementsByTagNameNS(NS.SVG, 'stop'); - var ostops = og.getElementsByTagNameNS(NS.SVG, 'stop'); - - if (stops.length !== ostops.length) { - continue; - } - - var j = stops.length; - - while (j--) { - var stop = stops[j]; - var ostop = ostops[j]; - - if (stop.getAttribute('offset') !== ostop.getAttribute('offset') || stop.getAttribute('stop-opacity') !== ostop.getAttribute('stop-opacity') || stop.getAttribute('stop-color') !== ostop.getAttribute('stop-color')) { - break; - } - } - - if (j === -1) { - return og; - } - } // for each gradient in defs - - - return null; - }; - /** - * Set a color/gradient to a fill/stroke. - * @function module:svgcanvas.SvgCanvas#setPaint - * @param {"fill"|"stroke"} type - String with "fill" or "stroke" - * @param {module:jGraduate.jGraduatePaintOptions} paint - The jGraduate paint object to apply - * @returns {void} - */ - - - this.setPaint = function (type, paint) { - // make a copy - var p = new $$a.jGraduate.Paint(paint); - this.setPaintOpacity(type, p.alpha / 100, true); // now set the current paint object - - curProperties[type + '_paint'] = p; - - switch (p.type) { - case 'solidColor': - this.setColor(type, p.solidColor !== 'none' ? '#' + p.solidColor : 'none'); - break; - - case 'linearGradient': - case 'radialGradient': - canvas[type + 'Grad'] = p[p.type]; - setGradient(type); - break; - } - }; - /** - * @function module:svgcanvas.SvgCanvas#setStrokePaint - * @param {module:jGraduate~Paint} paint - * @returns {void} - */ - - - this.setStrokePaint = function (paint) { - this.setPaint('stroke', paint); - }; - /** - * @function module:svgcanvas.SvgCanvas#setFillPaint - * @param {module:jGraduate~Paint} paint - * @returns {void} - */ - - - this.setFillPaint = function (paint) { - this.setPaint('fill', paint); - }; - /** - * @function module:svgcanvas.SvgCanvas#getStrokeWidth - * @returns {Float|string} The current stroke-width value - */ - - - this.getStrokeWidth = function () { - return curProperties.stroke_width; - }; - /** - * Sets the stroke width for the current selected elements. - * When attempting to set a line's width to 0, this changes it to 1 instead. - * @function module:svgcanvas.SvgCanvas#setStrokeWidth - * @param {Float} val - A Float indicating the new stroke width value - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.setStrokeWidth = function (val) { - if (val === 0 && ['line', 'path'].includes(currentMode)) { - canvas.setStrokeWidth(1); - return; - } - - curProperties.stroke_width = val; - var elems = []; - /** - * - * @param {Element} e - * @returns {void} - */ - - function addNonG(e) { - if (e.nodeName !== 'g') { - elems.push(e); - } - } - - var i = selectedElements.length; - - while (i--) { - var elem = selectedElements[i]; - - if (elem) { - if (elem.tagName === 'g') { - walkTree(elem, addNonG); - } else { - elems.push(elem); - } - } - } - - if (elems.length > 0) { - changeSelectedAttribute('stroke-width', val, elems); - call('changed', selectedElements); - } - }; - /** - * Set the given stroke-related attribute the given value for selected elements. - * @function module:svgcanvas.SvgCanvas#setStrokeAttr - * @param {string} attr - String with the attribute name - * @param {string|Float} val - String or number with the attribute value - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.setStrokeAttr = function (attr, val) { - curShape[attr.replace('-', '_')] = val; - var elems = []; - var i = selectedElements.length; - - while (i--) { - var elem = selectedElements[i]; - - if (elem) { - if (elem.tagName === 'g') { - walkTree(elem, function (e) { - if (e.nodeName !== 'g') { - elems.push(e); - } - }); - } else { - elems.push(elem); - } - } - } - - if (elems.length > 0) { - changeSelectedAttribute(attr, val, elems); - call('changed', selectedElements); - } - }; - /** - * @typedef {PlainObject} module:svgcanvas.StyleOptions - * @property {string} fill - * @property {Float} fill_opacity - * @property {string} stroke - * @property {Float} stroke_width - * @property {string} stroke_dasharray - * @property {string} stroke_linejoin - * @property {string} stroke_linecap - * @property {Float} stroke_opacity - * @property {Float} opacity - */ - - /** - * @function module:svgcanvas.SvgCanvas#getStyle - * @returns {module:svgcanvas.StyleOptions} current style options - */ - - - this.getStyle = function () { - return curShape; - }; - /** - * @function module:svgcanvas.SvgCanvas#getOpacity - * @returns {Float} the current opacity - */ - - - this.getOpacity = getOpacity; - /** - * Sets the given opacity on the current selected elements. - * @function module:svgcanvas.SvgCanvas#setOpacity - * @param {string} val - * @returns {void} - */ - - this.setOpacity = function (val) { - curShape.opacity = val; - changeSelectedAttribute('opacity', val); - }; - /** - * @function module:svgcanvas.SvgCanvas#getFillOpacity - * @returns {Float} the current fill opacity - */ - - - this.getFillOpacity = function () { - return curShape.fill_opacity; - }; - /** - * @function module:svgcanvas.SvgCanvas#getStrokeOpacity - * @returns {string} the current stroke opacity - */ - - - this.getStrokeOpacity = function () { - return curShape.stroke_opacity; - }; - /** - * Sets the current fill/stroke opacity. - * @function module:svgcanvas.SvgCanvas#setPaintOpacity - * @param {string} type - String with "fill" or "stroke" - * @param {Float} val - Float with the new opacity value - * @param {boolean} preventUndo - Indicates whether or not this should be an undoable action - * @returns {void} - */ - - - this.setPaintOpacity = function (type, val, preventUndo) { - curShape[type + '_opacity'] = val; - - if (!preventUndo) { - changeSelectedAttribute(type + '-opacity', val); - } else { - changeSelectedAttributeNoUndo(type + '-opacity', val); - } - }; - /** - * Gets the current fill/stroke opacity. - * @function module:svgcanvas.SvgCanvas#getPaintOpacity - * @param {"fill"|"stroke"} type - String with "fill" or "stroke" - * @returns {Float} Fill/stroke opacity - */ - - - this.getPaintOpacity = function (type) { - return type === 'fill' ? this.getFillOpacity() : this.getStrokeOpacity(); - }; - /** - * Gets the `stdDeviation` blur value of the given element. - * @function module:svgcanvas.SvgCanvas#getBlur - * @param {Element} elem - The element to check the blur value for - * @returns {string} stdDeviation blur attribute value - */ - - - this.getBlur = function (elem) { - var val = 0; // const elem = selectedElements[0]; - - if (elem) { - var filterUrl = elem.getAttribute('filter'); - - if (filterUrl) { - var blur = getElem(elem.id + '_blur'); - - if (blur) { - val = blur.firstChild.getAttribute('stdDeviation'); - } - } - } - - return val; - }; - - (function () { - var curCommand = null; - var filter = null; - var filterHidden = false; - /** - * Sets the `stdDeviation` blur value on the selected element without being undoable. - * @function module:svgcanvas.SvgCanvas#setBlurNoUndo - * @param {Float} val - The new `stdDeviation` value - * @returns {void} - */ - - canvas.setBlurNoUndo = function (val) { - if (!filter) { - canvas.setBlur(val); - return; - } - - if (val === 0) { - // Don't change the StdDev, as that will hide the element. - // Instead, just remove the value for "filter" - changeSelectedAttributeNoUndo('filter', ''); - filterHidden = true; - } else { - var elem = selectedElements[0]; - - if (filterHidden) { - changeSelectedAttributeNoUndo('filter', 'url(#' + elem.id + '_blur)'); - } - - if (isWebkit()) { - // console.log('e', elem); // eslint-disable-line no-console - elem.removeAttribute('filter'); - elem.setAttribute('filter', 'url(#' + elem.id + '_blur)'); - } - - changeSelectedAttributeNoUndo('stdDeviation', val, [filter.firstChild]); - canvas.setBlurOffsets(filter, val); - } - }; - /** - * - * @returns {void} - */ - - - function finishChange() { - var bCmd = canvas.undoMgr.finishUndoableChange(); - curCommand.addSubCommand(bCmd); - addCommandToHistory(curCommand); - curCommand = null; - filter = null; - } - /** - * Sets the `x`, `y`, `width`, `height` values of the filter element in order to - * make the blur not be clipped. Removes them if not neeeded. - * @function module:svgcanvas.SvgCanvas#setBlurOffsets - * @param {Element} filterElem - The filter DOM element to update - * @param {Float} stdDev - The standard deviation value on which to base the offset size - * @returns {void} - */ - - - canvas.setBlurOffsets = function (filterElem, stdDev) { - if (stdDev > 3) { - // TODO: Create algorithm here where size is based on expected blur - assignAttributes(filterElem, { - x: '-50%', - y: '-50%', - width: '200%', - height: '200%' - }); // Removing these attributes hides text in Chrome (see Issue 579) - } else if (!isWebkit()) { - filterElem.removeAttribute('x'); - filterElem.removeAttribute('y'); - filterElem.removeAttribute('width'); - filterElem.removeAttribute('height'); - } - }; - /** - * Adds/updates the blur filter to the selected element. - * @function module:svgcanvas.SvgCanvas#setBlur - * @param {Float} val - Float with the new `stdDeviation` blur value - * @param {boolean} complete - Whether or not the action should be completed (to add to the undo manager) - * @returns {void} - */ - - - canvas.setBlur = function (val, complete) { - if (curCommand) { - finishChange(); - return; - } // Looks for associated blur, creates one if not found - - - var elem = selectedElements[0]; - var elemId = elem.id; - filter = getElem(elemId + '_blur'); - val -= 0; - var batchCmd = new BatchCommand$1(); // Blur found! - - if (filter) { - if (val === 0) { - filter = null; - } - } else { - // Not found, so create - var newblur = addSVGElementFromJson({ - element: 'feGaussianBlur', - attr: { - "in": 'SourceGraphic', - stdDeviation: val - } - }); - filter = addSVGElementFromJson({ - element: 'filter', - attr: { - id: elemId + '_blur' - } - }); - filter.append(newblur); - findDefs().append(filter); - batchCmd.addSubCommand(new InsertElementCommand$1(filter)); - } - - var changes = { - filter: elem.getAttribute('filter') - }; - - if (val === 0) { - elem.removeAttribute('filter'); - batchCmd.addSubCommand(new ChangeElementCommand$1(elem, changes)); - return; - } - - changeSelectedAttribute('filter', 'url(#' + elemId + '_blur)'); - batchCmd.addSubCommand(new ChangeElementCommand$1(elem, changes)); - canvas.setBlurOffsets(filter, val); - curCommand = batchCmd; - canvas.undoMgr.beginUndoableChange('stdDeviation', [filter ? filter.firstChild : null]); - - if (complete) { - canvas.setBlurNoUndo(val); - finishChange(); - } - }; - })(); - /** - * Check whether selected element is bold or not. - * @function module:svgcanvas.SvgCanvas#getBold - * @returns {boolean} Indicates whether or not element is bold - */ - - - this.getBold = function () { - // should only have one element selected - var selected = selectedElements[0]; - - if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { - return selected.getAttribute('font-weight') === 'bold'; - } - - return false; - }; - /** - * Make the selected element bold or normal. - * @function module:svgcanvas.SvgCanvas#setBold - * @param {boolean} b - Indicates bold (`true`) or normal (`false`) - * @returns {void} - */ - - - this.setBold = function (b) { - var selected = selectedElements[0]; - - if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { - changeSelectedAttribute('font-weight', b ? 'bold' : 'normal'); - } - - if (!selectedElements[0].textContent) { - textActions.setCursor(); - } - }; - /** - * Check whether selected element is in italics or not. - * @function module:svgcanvas.SvgCanvas#getItalic - * @returns {boolean} Indicates whether or not element is italic - */ - - - this.getItalic = function () { - var selected = selectedElements[0]; - - if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { - return selected.getAttribute('font-style') === 'italic'; - } - - return false; - }; - /** - * Make the selected element italic or normal. - * @function module:svgcanvas.SvgCanvas#setItalic - * @param {boolean} i - Indicates italic (`true`) or normal (`false`) - * @returns {void} - */ - - - this.setItalic = function (i) { - var selected = selectedElements[0]; - - if (!isNullish(selected) && selected.tagName === 'text' && isNullish(selectedElements[1])) { - changeSelectedAttribute('font-style', i ? 'italic' : 'normal'); - } - - if (!selectedElements[0].textContent) { - textActions.setCursor(); - } - }; - /** - * @function module:svgcanvas.SvgCanvas#getFontFamily - * @returns {string} The current font family - */ - - - this.getFontFamily = function () { - return curText.font_family; - }; - /** - * Set the new font family. - * @function module:svgcanvas.SvgCanvas#setFontFamily - * @param {string} val - String with the new font family - * @returns {void} - */ - - - this.setFontFamily = function (val) { - curText.font_family = val; - changeSelectedAttribute('font-family', val); - - if (selectedElements[0] && !selectedElements[0].textContent) { - textActions.setCursor(); - } - }; - /** - * Set the new font color. - * @function module:svgcanvas.SvgCanvas#setFontColor - * @param {string} val - String with the new font color - * @returns {void} - */ - - - this.setFontColor = function (val) { - curText.fill = val; - changeSelectedAttribute('fill', val); - }; - /** - * @function module:svgcanvas.SvgCanvas#getFontColor - * @returns {string} The current font color - */ - - - this.getFontColor = function () { - return curText.fill; - }; - /** - * @function module:svgcanvas.SvgCanvas#getFontSize - * @returns {Float} The current font size - */ - - - this.getFontSize = function () { - return curText.font_size; - }; - /** - * Applies the given font size to the selected element. - * @function module:svgcanvas.SvgCanvas#setFontSize - * @param {Float} val - Float with the new font size - * @returns {void} - */ - - - this.setFontSize = function (val) { - curText.font_size = val; - changeSelectedAttribute('font-size', val); - - if (!selectedElements[0].textContent) { - textActions.setCursor(); - } - }; - /** - * @function module:svgcanvas.SvgCanvas#getText - * @returns {string} The current text (`textContent`) of the selected element - */ - - - this.getText = function () { - var selected = selectedElements[0]; - - if (isNullish(selected)) { - return ''; - } - - return selected.textContent; - }; - /** - * Updates the text element with the given string. - * @function module:svgcanvas.SvgCanvas#setTextContent - * @param {string} val - String with the new text - * @returns {void} - */ - - - this.setTextContent = function (val) { - changeSelectedAttribute('#text', val); - textActions.init(val); - textActions.setCursor(); - }; - /** - * Sets the new image URL for the selected image element. Updates its size if - * a new URL is given. - * @function module:svgcanvas.SvgCanvas#setImageURL - * @param {string} val - String with the image URL/path - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.setImageURL = function (val) { - var elem = selectedElements[0]; - - if (!elem) { - return; - } - - var attrs = $$a(elem).attr(['width', 'height']); - var setsize = !attrs.width || !attrs.height; - var curHref = getHref(elem); // Do nothing if no URL change or size change - - if (curHref === val && !setsize) { - return; - } - - var batchCmd = new BatchCommand$1('Change Image URL'); - setHref(elem, val); - batchCmd.addSubCommand(new ChangeElementCommand$1(elem, { - '#href': curHref - })); - $$a(new Image()).load(function () { - var changes = $$a(elem).attr(['width', 'height']); - $$a(elem).attr({ - width: this.width, - height: this.height - }); - selectorManager.requestSelector(elem).resize(); - batchCmd.addSubCommand(new ChangeElementCommand$1(elem, changes)); - addCommandToHistory(batchCmd); - call('changed', [elem]); - }).attr('src', val); - }; - /** - * Sets the new link URL for the selected anchor element. - * @function module:svgcanvas.SvgCanvas#setLinkURL - * @param {string} val - String with the link URL/path - * @returns {void} - */ - - - this.setLinkURL = function (val) { - var elem = selectedElements[0]; - - if (!elem) { - return; - } - - if (elem.tagName !== 'a') { - // See if parent is an anchor - var parentsA = $$a(elem).parents('a'); - - if (parentsA.length) { - elem = parentsA[0]; - } else { - return; - } - } - - var curHref = getHref(elem); - - if (curHref === val) { - return; - } - - var batchCmd = new BatchCommand$1('Change Link URL'); - setHref(elem, val); - batchCmd.addSubCommand(new ChangeElementCommand$1(elem, { - '#href': curHref - })); - addCommandToHistory(batchCmd); - }; - /** - * Sets the `rx` and `ry` values to the selected `rect` element - * to change its corner radius. - * @function module:svgcanvas.SvgCanvas#setRectRadius - * @param {string|Float} val - The new radius - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.setRectRadius = function (val) { - var selected = selectedElements[0]; - - if (!isNullish(selected) && selected.tagName === 'rect') { - var r = selected.getAttribute('rx'); - - if (r !== String(val)) { - selected.setAttribute('rx', val); - selected.setAttribute('ry', val); - addCommandToHistory(new ChangeElementCommand$1(selected, { - rx: r, - ry: r - }, 'Radius')); - call('changed', [selected]); - } - } - }; - /** - * Wraps the selected element(s) in an anchor element or converts group to one. - * @function module:svgcanvas.SvgCanvas#makeHyperlink - * @param {string} url - * @returns {void} - */ - - - this.makeHyperlink = function (url) { - canvas.groupSelectedElements('a', url); // TODO: If element is a single "g", convert to "a" - // if (selectedElements.length > 1 && selectedElements[1]) { - }; - /** - * @function module:svgcanvas.SvgCanvas#removeHyperlink - * @returns {void} - */ - - - this.removeHyperlink = function () { - canvas.ungroupSelectedElement(); - }; - /** - * Group: Element manipulation. - */ - - /** - * Sets the new segment type to the selected segment(s). - * @function module:svgcanvas.SvgCanvas#setSegType - * @param {Integer} newType - New segment type. See {@link https://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg} for list - * @returns {void} - */ - - - this.setSegType = function (newType) { - pathActions$1.setSegType(newType); - }; - /** - * Convert selected element to a path, or get the BBox of an element-as-path. - * @function module:svgcanvas.SvgCanvas#convertToPath - * @todo (codedread): Remove the getBBox argument and split this function into two. - * @param {Element} elem - The DOM element to be converted - * @param {boolean} getBBox - Boolean on whether or not to only return the path's BBox - * @returns {void|DOMRect|false|SVGPathElement|null} If the getBBox flag is true, the resulting path's bounding box object. - * Otherwise the resulting path element is returned. - */ - - - this.convertToPath = function (elem, getBBox) { - if (isNullish(elem)) { - var elems = selectedElements; - $$a.each(elems, function (i, el) { - if (el) { - canvas.convertToPath(el); - } - }); - return undefined; - } - - if (getBBox) { - return getBBoxOfElementAsPath(elem, addSVGElementFromJson, pathActions$1); - } // TODO: Why is this applying attributes from curShape, then inside utilities.convertToPath it's pulling addition attributes from elem? - // TODO: If convertToPath is called with one elem, curShape and elem are probably the same; but calling with multiple is a bug or cool feature. - - - var attrs = { - fill: curShape.fill, - 'fill-opacity': curShape.fill_opacity, - stroke: curShape.stroke, - 'stroke-width': curShape.stroke_width, - 'stroke-dasharray': curShape.stroke_dasharray, - 'stroke-linejoin': curShape.stroke_linejoin, - 'stroke-linecap': curShape.stroke_linecap, - 'stroke-opacity': curShape.stroke_opacity, - opacity: curShape.opacity, - visibility: 'hidden' - }; - return convertToPath(elem, attrs, addSVGElementFromJson, pathActions$1, clearSelection, addToSelection, hstry, addCommandToHistory); - }; - /** - * This function makes the changes to the elements. It does not add the change - * to the history stack. - * @param {string} attr - Attribute name - * @param {string|Float} newValue - String or number with the new attribute value - * @param {Element[]} elems - The DOM elements to apply the change to - * @returns {void} - */ - - - var changeSelectedAttributeNoUndo = function changeSelectedAttributeNoUndo(attr, newValue, elems) { - if (currentMode === 'pathedit') { - // Editing node - pathActions$1.moveNode(attr, newValue); - } - - elems = elems || selectedElements; - var i = elems.length; - var noXYElems = ['g', 'polyline', 'path']; // const goodGAttrs = ['transform', 'opacity', 'filter']; - - var _loop = function _loop() { - var elem = elems[i]; - - if (isNullish(elem)) { - return "continue"; - } // Set x,y vals on elements that don't have them - - - if ((attr === 'x' || attr === 'y') && noXYElems.includes(elem.tagName)) { - var bbox = getStrokedBBoxDefaultVisible([elem]); - var diffX = attr === 'x' ? newValue - bbox.x : 0; - var diffY = attr === 'y' ? newValue - bbox.y : 0; - canvas.moveSelectedElements(diffX * currentZoom, diffY * currentZoom, true); - return "continue"; - } // only allow the transform/opacity/filter attribute to change on <g> elements, slightly hacky - // TODO: Missing statement body - // if (elem.tagName === 'g' && goodGAttrs.includes(attr)) {} - - - var oldval = attr === '#text' ? elem.textContent : elem.getAttribute(attr); - - if (isNullish(oldval)) { - oldval = ''; - } - - if (oldval !== String(newValue)) { - if (attr === '#text') { - // const oldW = utilsGetBBox(elem).width; - elem.textContent = newValue; // FF bug occurs on on rotated elements - - if (/rotate/.test(elem.getAttribute('transform'))) { - elem = ffClone(elem); - } // Hoped to solve the issue of moving text with text-anchor="start", - // but this doesn't actually fix it. Hopefully on the right track, though. -Fyrd - // const box = getBBox(elem), left = box.x, top = box.y, {width, height} = box, - // dx = width - oldW, dy = 0; - // const angle = getRotationAngle(elem, true); - // if (angle) { - // const r = Math.sqrt(dx * dx + dy * dy); - // const theta = Math.atan2(dy, dx) - angle; - // dx = r * Math.cos(theta); - // dy = r * Math.sin(theta); - // - // elem.setAttribute('x', elem.getAttribute('x') - dx); - // elem.setAttribute('y', elem.getAttribute('y') - dy); - // } - - } else if (attr === '#href') { - setHref(elem, newValue); - } else { - elem.setAttribute(attr, newValue); - } // Go into "select" mode for text changes - // NOTE: Important that this happens AFTER elem.setAttribute() or else attributes like - // font-size can get reset to their old value, ultimately by svgEditor.updateContextPanel(), - // after calling textActions.toSelectMode() below - - - if (currentMode === 'textedit' && attr !== '#text' && elem.textContent.length) { - textActions.toSelectMode(elem); - } // if (i === 0) { - // selectedBBoxes[0] = utilsGetBBox(elem); - // } - // Use the Firefox ffClone hack for text elements with gradients or - // where other text attributes are changed. - - - if (isGecko() && elem.nodeName === 'text' && /rotate/.test(elem.getAttribute('transform'))) { - if (String(newValue).startsWith('url') || ['font-size', 'font-family', 'x', 'y'].includes(attr) && elem.textContent) { - elem = ffClone(elem); - } - } // Timeout needed for Opera & Firefox - // codedread: it is now possible for this function to be called with elements - // that are not in the selectedElements array, we need to only request a - // selector if the element is in that array - - - if (selectedElements.includes(elem)) { - setTimeout(function () { - // Due to element replacement, this element may no longer - // be part of the DOM - if (!elem.parentNode) { - return; - } - - selectorManager.requestSelector(elem).resize(); - }, 0); - } // if this element was rotated, and we changed the position of this element - // we need to update the rotational transform attribute - - - var angle = getRotationAngle(elem); - - if (angle !== 0 && attr !== 'transform') { - var tlist = getTransformList(elem); - var n = tlist.numberOfItems; - - while (n--) { - var xform = tlist.getItem(n); - - if (xform.type === 4) { - // remove old rotate - tlist.removeItem(n); - var box = getBBox(elem); - var center = transformPoint(box.x + box.width / 2, box.y + box.height / 2, transformListToTransform(tlist).matrix); - var cx = center.x, - cy = center.y; - var newrot = svgroot.createSVGTransform(); - newrot.setRotate(angle, cx, cy); - tlist.insertItemBefore(newrot, n); - break; - } - } - } - } // if oldValue != newValue - - }; - - while (i--) { - var _ret2 = _loop(); - - if (_ret2 === "continue") continue; - } // for each elem - - }; - /** - * Change the given/selected element and add the original value to the history stack. - * If you want to change all `selectedElements`, ignore the `elems` argument. - * If you want to change only a subset of `selectedElements`, then send the - * subset to this function in the `elems` argument. - * @function module:svgcanvas.SvgCanvas#changeSelectedAttribute - * @param {string} attr - String with the attribute name - * @param {string|Float} val - String or number with the new attribute value - * @param {Element[]} elems - The DOM elements to apply the change to - * @returns {void} - */ - - - var changeSelectedAttribute = this.changeSelectedAttribute = function (attr, val, elems) { - elems = elems || selectedElements; - canvas.undoMgr.beginUndoableChange(attr, elems); // const i = elems.length; - - changeSelectedAttributeNoUndo(attr, val, elems); - var batchCmd = canvas.undoMgr.finishUndoableChange(); - - if (!batchCmd.isEmpty()) { - addCommandToHistory(batchCmd); - } - }; - /** - * Removes all selected elements from the DOM and adds the change to the - * history stack. - * @function module:svgcanvas.SvgCanvas#deleteSelectedElements - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.deleteSelectedElements = function () { - var batchCmd = new BatchCommand$1('Delete Elements'); - var len = selectedElements.length; - var selectedCopy = []; // selectedElements is being deleted - - for (var i = 0; i < len; ++i) { - var selected = selectedElements[i]; - - if (isNullish(selected)) { - break; - } - - var parent = selected.parentNode; - var t = selected; // this will unselect the element and remove the selectedOutline - - selectorManager.releaseSelector(t); // Remove the path if present. - - removePath_(t.id); // Get the parent if it's a single-child anchor - - if (parent.tagName === 'a' && parent.childNodes.length === 1) { - t = parent; - parent = parent.parentNode; - } - - var _t = t, - nextSibling = _t.nextSibling; - t.remove(); - var elem = t; - selectedCopy.push(selected); // for the copy - - batchCmd.addSubCommand(new RemoveElementCommand$1(elem, nextSibling, parent)); - } - - selectedElements = []; - - if (!batchCmd.isEmpty()) { - addCommandToHistory(batchCmd); - } - - call('changed', selectedCopy); - clearSelection(); - }; - /** - * Removes all selected elements from the DOM and adds the change to the - * history stack. Remembers removed elements on the clipboard. - * @function module:svgcanvas.SvgCanvas#cutSelectedElements - * @returns {void} - */ - - - this.cutSelectedElements = function () { - canvas.copySelectedElements(); - canvas.deleteSelectedElements(); - }; - - var CLIPBOARD_ID = 'svgedit_clipboard'; - /** - * Flash the clipboard data momentarily on localStorage so all tabs can see. - * @returns {void} - */ - - function flashStorage() { - var data = sessionStorage.getItem(CLIPBOARD_ID); - localStorage.setItem(CLIPBOARD_ID, data); - setTimeout(function () { - localStorage.removeItem(CLIPBOARD_ID); - }, 1); - } - /** - * Transfers sessionStorage from one tab to another. - * @param {!Event} ev Storage event. - * @returns {void} - */ - - - function storageChange(ev) { - if (!ev.newValue) return; // This is a call from removeItem. - - if (ev.key === CLIPBOARD_ID + '_startup') { - // Another tab asked for our sessionStorage. - localStorage.removeItem(CLIPBOARD_ID + '_startup'); - flashStorage(); - } else if (ev.key === CLIPBOARD_ID) { - // Another tab sent data. - sessionStorage.setItem(CLIPBOARD_ID, ev.newValue); - } - } // Listen for changes to localStorage. - - - window.addEventListener('storage', storageChange, false); // Ask other tabs for sessionStorage (this is ONLY to trigger event). - - localStorage.setItem(CLIPBOARD_ID + '_startup', Math.random()); - /** - * Remembers the current selected elements on the clipboard. - * @function module:svgcanvas.SvgCanvas#copySelectedElements - * @returns {void} - */ - - this.copySelectedElements = function () { - var data = JSON.stringify(selectedElements.map(function (x) { - return getJsonFromSvgElement(x); - })); // Use sessionStorage for the clipboard data. - - sessionStorage.setItem(CLIPBOARD_ID, data); - flashStorage(); - var menu = $$a('#cmenu_canvas'); // Context menu might not exist (it is provided by editor.js). - - if (menu.enableContextMenuItems) { - menu.enableContextMenuItems('#paste,#paste_in_place'); - } - }; - /** - * @function module:svgcanvas.SvgCanvas#pasteElements - * @param {"in_place"|"point"|void} type - * @param {Integer|void} x Expected if type is "point" - * @param {Integer|void} y Expected if type is "point" - * @fires module:svgcanvas.SvgCanvas#event:changed - * @fires module:svgcanvas.SvgCanvas#event:ext_IDsUpdated - * @returns {void} - */ - - - this.pasteElements = function (type, x, y) { - var clipb = JSON.parse(sessionStorage.getItem(CLIPBOARD_ID)); - if (!clipb) return; - var len = clipb.length; - if (!len) return; - var pasted = []; - var batchCmd = new BatchCommand$1('Paste elements'); // const drawing = getCurrentDrawing(); - - /** - * @typedef {PlainObject<string, string>} module:svgcanvas.ChangedIDs - */ - - /** - * @type {module:svgcanvas.ChangedIDs} - */ - - var changedIDs = {}; // Recursively replace IDs and record the changes - - /** - * - * @param {module:svgcanvas.SVGAsJSON} elem - * @returns {void} - */ - - function checkIDs(elem) { - if (elem.attr && elem.attr.id) { - changedIDs[elem.attr.id] = getNextId(); - elem.attr.id = changedIDs[elem.attr.id]; - } - - if (elem.children) elem.children.forEach(function (child) { - return checkIDs(child); - }); - } - - clipb.forEach(function (elem) { - return checkIDs(elem); - }); // Give extensions like the connector extension a chance to reflect new IDs and remove invalid elements - - /** - * Triggered when `pasteElements` is called from a paste action (context menu or key). - * @event module:svgcanvas.SvgCanvas#event:ext_IDsUpdated - * @type {PlainObject} - * @property {module:svgcanvas.SVGAsJSON[]} elems - * @property {module:svgcanvas.ChangedIDs} changes Maps past ID (on attribute) to current ID - */ - - runExtensions('IDsUpdated', - /** @type {module:svgcanvas.SvgCanvas#event:ext_IDsUpdated} */ - { - elems: clipb, - changes: changedIDs - }, true).forEach(function (extChanges) { - if (!extChanges || !('remove' in extChanges)) return; - extChanges.remove.forEach(function (removeID) { - clipb = clipb.filter(function (clipBoardItem) { - return clipBoardItem.attr.id !== removeID; - }); - }); - }); // Move elements to lastClickPoint - - while (len--) { - var elem = clipb[len]; - - if (!elem) { - continue; - } - - var copy = addSVGElementFromJson(elem); - pasted.push(copy); - batchCmd.addSubCommand(new InsertElementCommand$1(copy)); - restoreRefElems(copy); - } - - selectOnly(pasted); - - if (type !== 'in_place') { - var ctrX, ctrY; - - if (!type) { - ctrX = lastClickPoint.x; - ctrY = lastClickPoint.y; - } else if (type === 'point') { - ctrX = x; - ctrY = y; - } - - var bbox = getStrokedBBoxDefaultVisible(pasted); - var cx = ctrX - (bbox.x + bbox.width / 2), - cy = ctrY - (bbox.y + bbox.height / 2), - dx = [], - dy = []; - $$a.each(pasted, function (i, item) { - dx.push(cx); - dy.push(cy); - }); - var cmd = canvas.moveSelectedElements(dx, dy, false); - if (cmd) batchCmd.addSubCommand(cmd); - } - - addCommandToHistory(batchCmd); - call('changed', pasted); - }; - /** - * Wraps all the selected elements in a group (`g`) element. - * @function module:svgcanvas.SvgCanvas#groupSelectedElements - * @param {"a"|"g"} [type="g"] - type of element to group into, defaults to `<g>` - * @param {string} [urlArg] - * @returns {void} - */ - - - this.groupSelectedElements = function (type, urlArg) { - if (!type) { - type = 'g'; - } - - var cmdStr = ''; - var url; - - switch (type) { - case 'a': - { - cmdStr = 'Make hyperlink'; - url = urlArg || ''; - break; - } - - default: - { - type = 'g'; - cmdStr = 'Group Elements'; - break; - } - } - - var batchCmd = new BatchCommand$1(cmdStr); // create and insert the group element - - var g = addSVGElementFromJson({ - element: type, - attr: { - id: getNextId() - } - }); - - if (type === 'a') { - setHref(g, url); - } - - batchCmd.addSubCommand(new InsertElementCommand$1(g)); // now move all children into the group - - var i = selectedElements.length; - - while (i--) { - var elem = selectedElements[i]; - - if (isNullish(elem)) { - continue; - } - - if (elem.parentNode.tagName === 'a' && elem.parentNode.childNodes.length === 1) { - elem = elem.parentNode; - } - - var oldNextSibling = elem.nextSibling; - var oldParent = elem.parentNode; - g.append(elem); - batchCmd.addSubCommand(new MoveElementCommand$1(elem, oldNextSibling, oldParent)); - } - - if (!batchCmd.isEmpty()) { - addCommandToHistory(batchCmd); - } // update selection - - - selectOnly([g], true); - }; - /** - * Pushes all appropriate parent group properties down to its children, then - * removes them from the group. - * @function module:svgcanvas.SvgCanvas#pushGroupProperties - * @param {SVGAElement|SVGGElement} g - * @param {boolean} undoable - * @returns {BatchCommand|void} - */ - - - var pushGroupProperties = this.pushGroupProperties = function (g, undoable) { - var children = g.childNodes; - var len = children.length; - var xform = g.getAttribute('transform'); - var glist = getTransformList(g); - var m = transformListToTransform(glist).matrix; - var batchCmd = new BatchCommand$1('Push group properties'); // TODO: get all fill/stroke properties from the group that we are about to destroy - // "fill", "fill-opacity", "fill-rule", "stroke", "stroke-dasharray", "stroke-dashoffset", - // "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", - // "stroke-width" - // and then for each child, if they do not have the attribute (or the value is 'inherit') - // then set the child's attribute - - var gangle = getRotationAngle(g); - var gattrs = $$a(g).attr(['filter', 'opacity']); - var gfilter, gblur, changes; - var drawing = getCurrentDrawing(); - - for (var i = 0; i < len; i++) { - var elem = children[i]; - - if (elem.nodeType !== 1) { - continue; - } - - if (gattrs.opacity !== null && gattrs.opacity !== 1) { - // const c_opac = elem.getAttribute('opacity') || 1; - var newOpac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100) / 100; - changeSelectedAttribute('opacity', newOpac, [elem]); - } - - if (gattrs.filter) { - var cblur = this.getBlur(elem); - var origCblur = cblur; - - if (!gblur) { - gblur = this.getBlur(g); - } - - if (cblur) { - // Is this formula correct? - cblur = Number(gblur) + Number(cblur); - } else if (cblur === 0) { - cblur = gblur; - } // If child has no current filter, get group's filter or clone it. - - - if (!origCblur) { - // Set group's filter to use first child's ID - if (!gfilter) { - gfilter = getRefElem(gattrs.filter); - } else { - // Clone the group's filter - gfilter = drawing.copyElem(gfilter); - findDefs().append(gfilter); - } - } else { - gfilter = getRefElem(elem.getAttribute('filter')); - } // Change this in future for different filters - - - var suffix = gfilter.firstChild.tagName === 'feGaussianBlur' ? 'blur' : 'filter'; - gfilter.id = elem.id + '_' + suffix; - changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]); // Update blur value - - if (cblur) { - changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]); - canvas.setBlurOffsets(gfilter, cblur); - } - } - - var chtlist = getTransformList(elem); // Don't process gradient transforms - - if (elem.tagName.includes('Gradient')) { - chtlist = null; - } // Hopefully not a problem to add this. Necessary for elements like <desc/> - - - if (!chtlist) { - continue; - } // Apparently <defs> can get get a transformlist, but we don't want it to have one! - - - if (elem.tagName === 'defs') { - continue; - } - - if (glist.numberOfItems) { - // TODO: if the group's transform is just a rotate, we can always transfer the - // rotate() down to the children (collapsing consecutive rotates and factoring - // out any translates) - if (gangle && glist.numberOfItems === 1) { - // [Rg] [Rc] [Mc] - // we want [Tr] [Rc2] [Mc] where: - // - [Rc2] is at the child's current center but has the - // sum of the group and child's rotation angles - // - [Tr] is the equivalent translation that this child - // undergoes if the group wasn't there - // [Tr] = [Rg] [Rc] [Rc2_inv] - // get group's rotation matrix (Rg) - var rgm = glist.getItem(0).matrix; // get child's rotation matrix (Rc) - - var rcm = svgroot.createSVGMatrix(); - var cangle = getRotationAngle(elem); - - if (cangle) { - rcm = chtlist.getItem(0).matrix; - } // get child's old center of rotation - - - var cbox = getBBox(elem); - var ceqm = transformListToTransform(chtlist).matrix; - var coldc = transformPoint(cbox.x + cbox.width / 2, cbox.y + cbox.height / 2, ceqm); // sum group and child's angles - - var sangle = gangle + cangle; // get child's rotation at the old center (Rc2_inv) - - var r2 = svgroot.createSVGTransform(); - r2.setRotate(sangle, coldc.x, coldc.y); // calculate equivalent translate - - var trm = matrixMultiply(rgm, rcm, r2.matrix.inverse()); // set up tlist - - if (cangle) { - chtlist.removeItem(0); - } - - if (sangle) { - if (chtlist.numberOfItems) { - chtlist.insertItemBefore(r2, 0); - } else { - chtlist.appendItem(r2); - } - } - - if (trm.e || trm.f) { - var tr = svgroot.createSVGTransform(); - tr.setTranslate(trm.e, trm.f); - - if (chtlist.numberOfItems) { - chtlist.insertItemBefore(tr, 0); - } else { - chtlist.appendItem(tr); - } - } - } else { - // more complicated than just a rotate - // transfer the group's transform down to each child and then - // call recalculateDimensions() - var oldxform = elem.getAttribute('transform'); - changes = {}; - changes.transform = oldxform || ''; - var newxform = svgroot.createSVGTransform(); // [ gm ] [ chm ] = [ chm ] [ gm' ] - // [ gm' ] = [ chmInv ] [ gm ] [ chm ] - - var chm = transformListToTransform(chtlist).matrix, - chmInv = chm.inverse(); - var gm = matrixMultiply(chmInv, m, chm); - newxform.setMatrix(gm); - chtlist.appendItem(newxform); - } - - var cmd = recalculateDimensions(elem); - - if (cmd) { - batchCmd.addSubCommand(cmd); - } - } - } // remove transform and make it undo-able - - - if (xform) { - changes = {}; - changes.transform = xform; - g.setAttribute('transform', ''); - g.removeAttribute('transform'); - batchCmd.addSubCommand(new ChangeElementCommand$1(g, changes)); - } - - if (undoable && !batchCmd.isEmpty()) { - return batchCmd; - } - - return undefined; - }; - /** - * Unwraps all the elements in a selected group (`g`) element. This requires - * significant recalculations to apply group's transforms, etc. to its children. - * @function module:svgcanvas.SvgCanvas#ungroupSelectedElement - * @returns {void} - */ - - - this.ungroupSelectedElement = function () { - var g = selectedElements[0]; - - if (!g) { - return; - } - - if ($$a(g).data('gsvg') || $$a(g).data('symbol')) { - // Is svg, so actually convert to group - convertToGroup(g); - return; - } - - if (g.tagName === 'use') { - // Somehow doesn't have data set, so retrieve - var symbol = getElem(getHref(g).substr(1)); - $$a(g).data('symbol', symbol).data('ref', symbol); - convertToGroup(g); - return; - } - - var parentsA = $$a(g).parents('a'); - - if (parentsA.length) { - g = parentsA[0]; - } // Look for parent "a" - - - if (g.tagName === 'g' || g.tagName === 'a') { - var batchCmd = new BatchCommand$1('Ungroup Elements'); - var cmd = pushGroupProperties(g, true); - - if (cmd) { - batchCmd.addSubCommand(cmd); - } - - var parent = g.parentNode; - var anchor = g.nextSibling; - var children = new Array(g.childNodes.length); - var i = 0; - - while (g.firstChild) { - var elem = g.firstChild; - var oldNextSibling = elem.nextSibling; - var oldParent = elem.parentNode; // Remove child title elements - - if (elem.tagName === 'title') { - var nextSibling = elem.nextSibling; - batchCmd.addSubCommand(new RemoveElementCommand$1(elem, nextSibling, oldParent)); - elem.remove(); - continue; - } - - if (anchor) { - anchor.before(elem); - } else { - g.after(elem); - } - - children[i++] = elem; - batchCmd.addSubCommand(new MoveElementCommand$1(elem, oldNextSibling, oldParent)); - } // remove the group from the selection - - - clearSelection(); // delete the group element (but make undo-able) - - var gNextSibling = g.nextSibling; - g.remove(); - batchCmd.addSubCommand(new RemoveElementCommand$1(g, gNextSibling, parent)); - - if (!batchCmd.isEmpty()) { - addCommandToHistory(batchCmd); - } // update selection - - - addToSelection(children); - } - }; - /** - * Repositions the selected element to the bottom in the DOM to appear on top of - * other elements. - * @function module:svgcanvas.SvgCanvas#moveToTopSelectedElement - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.moveToTopSelectedElement = function () { - var _selectedElements = selectedElements, - _selectedElements2 = _slicedToArray(_selectedElements, 1), - selected = _selectedElements2[0]; - - if (!isNullish(selected)) { - var t = selected; - var oldParent = t.parentNode; - var oldNextSibling = t.nextSibling; - t = t.parentNode.appendChild(t); // If the element actually moved position, add the command and fire the changed - // event handler. - - if (oldNextSibling !== t.nextSibling) { - addCommandToHistory(new MoveElementCommand$1(t, oldNextSibling, oldParent, 'top')); - call('changed', [t]); - } - } - }; - /** - * Repositions the selected element to the top in the DOM to appear under - * other elements. - * @function module:svgcanvas.SvgCanvas#moveToBottomSelectedElement - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.moveToBottomSelectedElement = function () { - var _selectedElements3 = selectedElements, - _selectedElements4 = _slicedToArray(_selectedElements3, 1), - selected = _selectedElements4[0]; - - if (!isNullish(selected)) { - var t = selected; - var oldParent = t.parentNode; - var oldNextSibling = t.nextSibling; - var firstChild = t.parentNode.firstChild; - - if (firstChild.tagName === 'title') { - firstChild = firstChild.nextSibling; - } // This can probably be removed, as the defs should not ever apppear - // inside a layer group - - - if (firstChild.tagName === 'defs') { - firstChild = firstChild.nextSibling; - } - - t = t.parentNode.insertBefore(t, firstChild); // If the element actually moved position, add the command and fire the changed - // event handler. - - if (oldNextSibling !== t.nextSibling) { - addCommandToHistory(new MoveElementCommand$1(t, oldNextSibling, oldParent, 'bottom')); - call('changed', [t]); - } - } - }; - /** - * Moves the select element up or down the stack, based on the visibly - * intersecting elements. - * @function module:svgcanvas.SvgCanvas#moveUpDownSelected - * @param {"Up"|"Down"} dir - String that's either 'Up' or 'Down' - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {void} - */ - - - this.moveUpDownSelected = function (dir) { - var selected = selectedElements[0]; - - if (!selected) { - return; - } - - curBBoxes = []; - var closest, foundCur; // jQuery sorts this list - - var list = $$a(getIntersectionList(getStrokedBBoxDefaultVisible([selected]))).toArray(); - - if (dir === 'Down') { - list.reverse(); - } - - $$a.each(list, function () { - if (!foundCur) { - if (this === selected) { - foundCur = true; - } - - return true; - } - - closest = this; - return false; - }); - - if (!closest) { - return; - } - - var t = selected; - var oldParent = t.parentNode; - var oldNextSibling = t.nextSibling; - $$a(closest)[dir === 'Down' ? 'before' : 'after'](t); // If the element actually moved position, add the command and fire the changed - // event handler. - - if (oldNextSibling !== t.nextSibling) { - addCommandToHistory(new MoveElementCommand$1(t, oldNextSibling, oldParent, 'Move ' + dir)); - call('changed', [t]); - } - }; - /** - * Moves selected elements on the X/Y axis. - * @function module:svgcanvas.SvgCanvas#moveSelectedElements - * @param {Float} dx - Float with the distance to move on the x-axis - * @param {Float} dy - Float with the distance to move on the y-axis - * @param {boolean} undoable - Boolean indicating whether or not the action should be undoable - * @fires module:svgcanvas.SvgCanvas#event:changed - * @returns {BatchCommand|void} Batch command for the move - */ - - - this.moveSelectedElements = function (dx, dy, undoable) { - // if undoable is not sent, default to true - // if single values, scale them to the zoom - if (dx.constructor !== Array) { - dx /= currentZoom; - dy /= currentZoom; - } - - undoable = undoable || true; - var batchCmd = new BatchCommand$1('position'); - var i = selectedElements.length; - - while (i--) { - var selected = selectedElements[i]; - - if (!isNullish(selected)) { - // if (i === 0) { - // selectedBBoxes[0] = utilsGetBBox(selected); - // } - // const b = {}; - // for (const j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j]; - // selectedBBoxes[i] = b; - var xform = svgroot.createSVGTransform(); - var tlist = getTransformList(selected); // dx and dy could be arrays - - if (dx.constructor === Array) { - // if (i === 0) { - // selectedBBoxes[0].x += dx[0]; - // selectedBBoxes[0].y += dy[0]; - // } - xform.setTranslate(dx[i], dy[i]); - } else { - // if (i === 0) { - // selectedBBoxes[0].x += dx; - // selectedBBoxes[0].y += dy; - // } - xform.setTranslate(dx, dy); - } - - if (tlist.numberOfItems) { - tlist.insertItemBefore(xform, 0); - } else { - tlist.appendItem(xform); - } - - var cmd = recalculateDimensions(selected); - - if (cmd) { - batchCmd.addSubCommand(cmd); - } - - selectorManager.requestSelector(selected).resize(); - } - } - - if (!batchCmd.isEmpty()) { - if (undoable) { - addCommandToHistory(batchCmd); - } - - call('changed', selectedElements); - return batchCmd; - } - - return undefined; - }; - /** - * Create deep DOM copies (clones) of all selected elements and move them slightly - * from their originals. - * @function module:svgcanvas.SvgCanvas#cloneSelectedElements - * @param {Float} x Float with the distance to move on the x-axis - * @param {Float} y Float with the distance to move on the y-axis - * @returns {void} - */ - - - this.cloneSelectedElements = function (x, y) { - var i, elem; - var batchCmd = new BatchCommand$1('Clone Elements'); // find all the elements selected (stop at first null) - - var len = selectedElements.length; - /** - * Sorts an array numerically and ascending. - * @param {Element} a - * @param {Element} b - * @returns {Integer} - */ - - function sortfunction(a, b) { - return $$a(b).index() - $$a(a).index(); - } - - selectedElements.sort(sortfunction); - - for (i = 0; i < len; ++i) { - elem = selectedElements[i]; - - if (isNullish(elem)) { - break; - } - } // use slice to quickly get the subset of elements we need - - - var copiedElements = selectedElements.slice(0, i); - this.clearSelection(true); // note that we loop in the reverse way because of the way elements are added - // to the selectedElements array (top-first) - - var drawing = getCurrentDrawing(); - i = copiedElements.length; - - while (i--) { - // clone each element and replace it within copiedElements - elem = copiedElements[i] = drawing.copyElem(copiedElements[i]); - (currentGroup || drawing.getCurrentLayer()).append(elem); - batchCmd.addSubCommand(new InsertElementCommand$1(elem)); - } - - if (!batchCmd.isEmpty()) { - addToSelection(copiedElements.reverse()); // Need to reverse for correct selection-adding - - this.moveSelectedElements(x, y, false); - addCommandToHistory(batchCmd); - } - }; - /** - * Aligns selected elements. - * @function module:svgcanvas.SvgCanvas#alignSelectedElements - * @param {string} type - String with single character indicating the alignment type - * @param {"selected"|"largest"|"smallest"|"page"} relativeTo - * @returns {void} - */ - - - this.alignSelectedElements = function (type, relativeTo) { - var bboxes = []; // angles = []; - - var len = selectedElements.length; - - if (!len) { - return; - } - - var minx = Number.MAX_VALUE, - maxx = Number.MIN_VALUE, - miny = Number.MAX_VALUE, - maxy = Number.MIN_VALUE; - var curwidth = Number.MIN_VALUE, - curheight = Number.MIN_VALUE; - - for (var i = 0; i < len; ++i) { - if (isNullish(selectedElements[i])) { - break; - } - - var elem = selectedElements[i]; - bboxes[i] = getStrokedBBoxDefaultVisible([elem]); // now bbox is axis-aligned and handles rotation - - switch (relativeTo) { - case 'smallest': - if ((type === 'l' || type === 'c' || type === 'r') && (curwidth === Number.MIN_VALUE || curwidth > bboxes[i].width) || (type === 't' || type === 'm' || type === 'b') && (curheight === Number.MIN_VALUE || curheight > bboxes[i].height)) { - minx = bboxes[i].x; - miny = bboxes[i].y; - maxx = bboxes[i].x + bboxes[i].width; - maxy = bboxes[i].y + bboxes[i].height; - curwidth = bboxes[i].width; - curheight = bboxes[i].height; - } - - break; - - case 'largest': - if ((type === 'l' || type === 'c' || type === 'r') && (curwidth === Number.MIN_VALUE || curwidth < bboxes[i].width) || (type === 't' || type === 'm' || type === 'b') && (curheight === Number.MIN_VALUE || curheight < bboxes[i].height)) { - minx = bboxes[i].x; - miny = bboxes[i].y; - maxx = bboxes[i].x + bboxes[i].width; - maxy = bboxes[i].y + bboxes[i].height; - curwidth = bboxes[i].width; - curheight = bboxes[i].height; - } - - break; - - default: - // 'selected' - if (bboxes[i].x < minx) { - minx = bboxes[i].x; - } - - if (bboxes[i].y < miny) { - miny = bboxes[i].y; - } - - if (bboxes[i].x + bboxes[i].width > maxx) { - maxx = bboxes[i].x + bboxes[i].width; - } - - if (bboxes[i].y + bboxes[i].height > maxy) { - maxy = bboxes[i].y + bboxes[i].height; - } - - break; - } - } // loop for each element to find the bbox and adjust min/max - - - if (relativeTo === 'page') { - minx = 0; - miny = 0; - maxx = canvas.contentW; - maxy = canvas.contentH; - } - - var dx = new Array(len); - var dy = new Array(len); - - for (var _i6 = 0; _i6 < len; ++_i6) { - if (isNullish(selectedElements[_i6])) { - break; - } // const elem = selectedElements[i]; - - - var bbox = bboxes[_i6]; - dx[_i6] = 0; - dy[_i6] = 0; - - switch (type) { - case 'l': - // left (horizontal) - dx[_i6] = minx - bbox.x; - break; - - case 'c': - // center (horizontal) - dx[_i6] = (minx + maxx) / 2 - (bbox.x + bbox.width / 2); - break; - - case 'r': - // right (horizontal) - dx[_i6] = maxx - (bbox.x + bbox.width); - break; - - case 't': - // top (vertical) - dy[_i6] = miny - bbox.y; - break; - - case 'm': - // middle (vertical) - dy[_i6] = (miny + maxy) / 2 - (bbox.y + bbox.height / 2); - break; - - case 'b': - // bottom (vertical) - dy[_i6] = maxy - (bbox.y + bbox.height); - break; - } - } - - this.moveSelectedElements(dx, dy); - }; - /** - * Group: Additional editor tools. - */ - - /** - * @name module:svgcanvas.SvgCanvas#contentW - * @type {Float} - */ - - - this.contentW = getResolution().w; - /** - * @name module:svgcanvas.SvgCanvas#contentH - * @type {Float} - */ - - this.contentH = getResolution().h; - /** - * @typedef {PlainObject} module:svgcanvas.CanvasInfo - * @property {Float} x - The canvas' new x coordinate - * @property {Float} y - The canvas' new y coordinate - * @property {string} oldX - The canvas' old x coordinate - * @property {string} oldY - The canvas' old y coordinate - * @property {Float} d_x - The x position difference - * @property {Float} d_y - The y position difference - */ - - /** - * Updates the editor canvas width/height/position after a zoom has occurred. - * @function module:svgcanvas.SvgCanvas#updateCanvas - * @param {Float} w - Float with the new width - * @param {Float} h - Float with the new height - * @fires module:svgcanvas.SvgCanvas#event:ext_canvasUpdated - * @returns {module:svgcanvas.CanvasInfo} - */ - - this.updateCanvas = function (w, h) { - svgroot.setAttribute('width', w); - svgroot.setAttribute('height', h); - var bg = $$a('#canvasBackground')[0]; - var oldX = svgcontent.getAttribute('x'); - var oldY = svgcontent.getAttribute('y'); - var x = (w - this.contentW * currentZoom) / 2; - var y = (h - this.contentH * currentZoom) / 2; - assignAttributes(svgcontent, { - width: this.contentW * currentZoom, - height: this.contentH * currentZoom, - x: x, - y: y, - viewBox: '0 0 ' + this.contentW + ' ' + this.contentH - }); - assignAttributes(bg, { - width: svgcontent.getAttribute('width'), - height: svgcontent.getAttribute('height'), - x: x, - y: y - }); - var bgImg = getElem('background_image'); - - if (bgImg) { - assignAttributes(bgImg, { - width: '100%', - height: '100%' - }); - } - - selectorManager.selectorParentGroup.setAttribute('transform', 'translate(' + x + ',' + y + ')'); - /** - * Invoked upon updates to the canvas. - * @event module:svgcanvas.SvgCanvas#event:ext_canvasUpdated - * @type {PlainObject} - * @property {Integer} new_x - * @property {Integer} new_y - * @property {string} old_x (Of Integer) - * @property {string} old_y (Of Integer) - * @property {Integer} d_x - * @property {Integer} d_y - */ - - runExtensions('canvasUpdated', - /** - * @type {module:svgcanvas.SvgCanvas#event:ext_canvasUpdated} - */ - { - new_x: x, - new_y: y, - old_x: oldX, - old_y: oldY, - d_x: x - oldX, - d_y: y - oldY - }); - return { - x: x, - y: y, - old_x: oldX, - old_y: oldY, - d_x: x - oldX, - d_y: y - oldY - }; - }; - /** - * Set the background of the editor (NOT the actual document). - * @function module:svgcanvas.SvgCanvas#setBackground - * @param {string} color - String with fill color to apply - * @param {string} url - URL or path to image to use - * @returns {void} - */ - - - this.setBackground = function (color, url) { - var bg = getElem('canvasBackground'); - var border = $$a(bg).find('rect')[0]; - var bgImg = getElem('background_image'); - var bgPattern = getElem('background_pattern'); - border.setAttribute('fill', color === 'chessboard' ? '#fff' : color); - - if (color === 'chessboard') { - if (!bgPattern) { - bgPattern = svgdoc.createElementNS(NS.SVG, 'foreignObject'); - assignAttributes(bgPattern, { - id: 'background_pattern', - width: '100%', - height: '100%', - preserveAspectRatio: 'xMinYMin', - style: 'pointer-events:none' - }); - var div = document.createElement('div'); - assignAttributes(div, { - style: 'pointer-events:none;width:100%;height:100%;' + 'background-image:url(data:image/gif;base64,' + 'R0lGODlhEAAQAIAAAP///9bW1iH5BAAAAAAALAAAAAAQABAAAAIfjG+' + 'gq4jM3IFLJgpswNly/XkcBpIiVaInlLJr9FZWAQA7);' - }); - bgPattern.appendChild(div); - bg.append(bgPattern); - } - } else if (bgPattern) { - bgPattern.remove(); - } - - if (url) { - if (!bgImg) { - bgImg = svgdoc.createElementNS(NS.SVG, 'image'); - assignAttributes(bgImg, { - id: 'background_image', - width: '100%', - height: '100%', - preserveAspectRatio: 'xMinYMin', - style: 'pointer-events:none' - }); - } - - setHref(bgImg, url); - bg.append(bgImg); - } else if (bgImg) { - bgImg.remove(); - } - }; - /** - * Select the next/previous element within the current layer. - * @function module:svgcanvas.SvgCanvas#cycleElement - * @param {boolean} next - true = next and false = previous element - * @fires module:svgcanvas.SvgCanvas#event:selected - * @returns {void} - */ - - - this.cycleElement = function (next) { - var num; - var curElem = selectedElements[0]; - var elem = false; - var allElems = getVisibleElements(currentGroup || getCurrentDrawing().getCurrentLayer()); - - if (!allElems.length) { - return; - } - - if (isNullish(curElem)) { - num = next ? allElems.length - 1 : 0; - elem = allElems[num]; - } else { - var i = allElems.length; - - while (i--) { - if (allElems[i] === curElem) { - num = next ? i - 1 : i + 1; - - if (num >= allElems.length) { - num = 0; - } else if (num < 0) { - num = allElems.length - 1; - } - - elem = allElems[num]; - break; - } - } - } - - selectOnly([elem], true); - call('selected', selectedElements); - }; - - this.clear(); - /** - * @interface module:svgcanvas.PrivateMethods - * @type {PlainObject} - * @property {module:svgcanvas~addCommandToHistory} addCommandToHistory - * @property {module:history.HistoryCommand} BatchCommand - * @property {module:history.HistoryCommand} ChangeElementCommand - * @property {module:utilities.decode64} decode64 - * @property {module:utilities.dropXMLInternalSubset} dropXMLInternalSubset - * @property {module:utilities.encode64} encode64 - * @property {module:svgcanvas~ffClone} ffClone - * @property {module:svgcanvas~findDuplicateGradient} findDuplicateGradient - * @property {module:utilities.getPathBBox} getPathBBox - * @property {module:units.getTypeMap} getTypeMap - * @property {module:draw.identifyLayers} identifyLayers - * @property {module:history.HistoryCommand} InsertElementCommand - * @property {module:browser.isChrome} isChrome - * @property {module:math.isIdentity} isIdentity - * @property {module:browser.isIE} isIE - * @property {module:svgcanvas~logMatrix} logMatrix - * @property {module:history.HistoryCommand} MoveElementCommand - * @property {module:namespaces.NS} NS - * @property {module:utilities.preventClickDefault} preventClickDefault - * @property {module:history.HistoryCommand} RemoveElementCommand - * @property {module:SVGTransformList.SVGEditTransformList} SVGEditTransformList - * @property {module:utilities.text2xml} text2xml - * @property {module:math.transformBox} transformBox - * @property {module:math.transformPoint} transformPoint - * @property {module:utilities.walkTree} walkTree - */ - - /** - * @deprecated getPrivateMethods - * Since all methods are/should be public somehow, this function should be removed; - * we might require `import` in place of this in the future once ES6 Modules - * widespread - - * Being able to access private methods publicly seems wrong somehow, - * but currently appears to be the best way to allow testing and provide - * access to them to plugins. - * @function module:svgcanvas.SvgCanvas#getPrivateMethods - * @returns {module:svgcanvas.PrivateMethods} - */ - - this.getPrivateMethods = function () { - var obj = { - addCommandToHistory: addCommandToHistory, - BatchCommand: BatchCommand$1, - ChangeElementCommand: ChangeElementCommand$1, - decode64: decode64, - dropXMLInternalSubset: dropXMLInternalSubset, - encode64: encode64, - ffClone: ffClone, - findDefs: findDefs, - findDuplicateGradient: findDuplicateGradient, - getElem: getElem, - getPathBBox: getPathBBox, - getTypeMap: getTypeMap, - getUrlFromAttr: getUrlFromAttr, - identifyLayers: identifyLayers, - InsertElementCommand: InsertElementCommand$1, - isChrome: isChrome, - isIdentity: isIdentity, - isIE: isIE, - logMatrix: logMatrix, - MoveElementCommand: MoveElementCommand$1, - NS: NS, - preventClickDefault: preventClickDefault, - RemoveElementCommand: RemoveElementCommand$1, - SVGEditTransformList: SVGTransformList, - text2xml: text2xml, - transformBox: transformBox, - transformPoint: transformPoint, - walkTree: walkTree - }; - return obj; - }; -} // End constructor -; // End class - -// Todo: Update: https://github.com/jeresig/jquery.hotkeys - -/* - * jQuery Hotkeys Plugin - * Copyright 2010, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * - * http://github.com/jeresig/jquery.hotkeys - * - * Based upon the plugin by Tzury Bar Yochay: - * http://github.com/tzuryby/hotkeys - * - * Original idea by: - * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/ -*/ -// We *do* want to allow the escape key within textareas (and possibly tab too), so add the condition `n.which !== 27` -function jQueryPluginJSHotkeys (b) { - b.hotkeys = { - version: "0.8", - specialKeys: { - 8: "backspace", - 9: "tab", - 13: "return", - 16: "shift", - 17: "ctrl", - 18: "alt", - 19: "pause", - 20: "capslock", - 27: "esc", - 32: "space", - 33: "pageup", - 34: "pagedown", - 35: "end", - 36: "home", - 37: "left", - 38: "up", - 39: "right", - 40: "down", - 45: "insert", - 46: "del", - 96: "0", - 97: "1", - 98: "2", - 99: "3", - 100: "4", - 101: "5", - 102: "6", - 103: "7", - 104: "8", - 105: "9", - 106: "*", - 107: "+", - 109: "-", - 110: ".", - 111: "/", - 112: "f1", - 113: "f2", - 114: "f3", - 115: "f4", - 116: "f5", - 117: "f6", - 118: "f7", - 119: "f8", - 120: "f9", - 121: "f10", - 122: "f11", - 123: "f12", - 144: "numlock", - 145: "scroll", - 191: "/", - 224: "meta", - 219: "[", - 221: "]" - }, - shiftNums: { - "`": "~", - "1": "!", - "2": "@", - "3": "#", - "4": "$", - "5": "%", - "6": "^", - "7": "&", - "8": "*", - "9": "(", - "0": ")", - "-": "_", - "=": "+", - ";": ": ", - "'": '"', - ",": "<", - ".": ">", - "/": "?", - "\\": "|" - } - }; - - function a(d) { - if (typeof d.data !== "string") { - return; - } - - var c = d.handler, - e = d.data.toLowerCase().split(" "); - - d.handler = function (n) { - if (this !== n.target && n.which !== 27 && (/textarea|select/i.test(n.target.nodeName) || n.target.type === "text")) { - return; - } - - var h = n.type !== "keypress" && b.hotkeys.specialKeys[n.which], - o = String.fromCharCode(n.which).toLowerCase(), - m = "", - g = {}; - - if (n.altKey && h !== "alt") { - m += "alt+"; - } - - if (n.ctrlKey && h !== "ctrl") { - m += "ctrl+"; - } - - if (n.metaKey && !n.ctrlKey && h !== "meta") { - m += "meta+"; - } - - if (n.shiftKey && h !== "shift") { - m += "shift+"; - } - - if (h) { - g[m + h] = true; - } else { - g[m + o] = true; - g[m + b.hotkeys.shiftNums[o]] = true; - - if (m === "shift+") { - g[b.hotkeys.shiftNums[o]] = true; - } - } - - for (var j = 0, f = e.length; j < f; j++) { - if (g[e[j]]) { - return c.apply(this, arguments); - } - } - }; - } - - b.each(["keydown", "keyup", "keypress"], function () { - b.event.special[this] = { - add: a - }; - }); - return b; -} - -/** - * @file SVG Icon Loader 2.0 - * - * jQuery Plugin for loading SVG icons from a single file - * - * Adds {@link external:jQuery.svgIcons}, {@link external:jQuery.getSvgIcon}, {@link external:jQuery.resizeSvgIcons} - * - * How to use: - -1. Create the SVG master file that includes all icons: - -The master SVG icon-containing file is an SVG file that contains -`<g>` elements. Each `<g>` element should contain the markup of an SVG -icon. The `<g>` element has an ID that should -correspond with the ID of the HTML element used on the page that should contain -or optionally be replaced by the icon. Additionally, one empty element should be -added at the end with id "svg_eof". - -2. Optionally create fallback raster images for each SVG icon. - -3. Include the jQuery and the SVG Icon Loader scripts on your page. - -4. Run `$.svgIcons()` when the document is ready. See its signature - -5. To access an icon at a later point without using the callback, use this: - `$.getSvgIcon(id (string), uniqueClone (boolean))`; - -This will return the icon (as jQuery object) with a given ID. - -6. To resize icons at a later point without using the callback, use this: - `$.resizeSvgIcons(resizeOptions)` (use the same way as the "resize" parameter) - * - * @module jQuerySVGIcons - * @license MIT - * @copyright (c) 2009 Alexis Deveria - * {@link http://a.deveria.com} - * @example - $(function () { - $.svgIcons('my_icon_set.svg'); // The SVG file that contains all icons - // No options have been set, so all icons will automatically be inserted - // into HTML elements that match the same IDs. - }); - - * @example - $(function () { - // The SVG file that contains all icons - $.svgIcons('my_icon_set.svg', { - callback (icons) { // Custom callback function that sets click - // events for each icon - $.each(icons, function (id, icon) { - icon.click(function () { - alert('You clicked on the icon with id ' + id); - }); - }); - } - }); - }); - - * @example - $(function () { - // The SVGZ file that contains all icons - $.svgIcons('my_icon_set.svgz', { - w: 32, // All icons will be 32px wide - h: 32, // All icons will be 32px high - fallback_path: 'icons/', // All fallback files can be found here - fallback: { - '#open_icon': 'open.png', // The "open.png" will be appended to the - // HTML element with ID "open_icon" - '#close_icon': 'close.png', - '#save_icon': 'save.png' - }, - placement: {'.open_icon': 'open'}, // The "open" icon will be added - // to all elements with class "open_icon" - resize: { - '#save_icon .svg_icon': 64 // The "save" icon will be resized to 64 x 64px - }, - - callback (icons) { // Sets background color for "close" icon - icons.close.css('background', 'red'); - }, - - svgz: true // Indicates that an SVGZ file is being used - }); - }); -*/ -var isOpera$1 = Boolean(window.opera); - -var fixIDs = function fixIDs(svgEl, svgNum, force) { - var defs = svgEl.find('defs'); - if (!defs.length) return svgEl; - var idElems; - - if (isOpera$1) { - idElems = defs.find('*').filter(function () { - return Boolean(this.id); - }); - } else { - idElems = defs.find('[id]'); - } - - var allElems = svgEl[0].getElementsByTagName('*'), - len = allElems.length; - idElems.each(function (i) { - var id = this.id; - /* - const noDupes = ($(svgdoc).find('#' + id).length <= 1); - if (isOpera) noDupes = false; // Opera didn't clone svgEl, so not reliable - if(!force && noDupes) return; - */ - - var newId = 'x' + id + svgNum + i; - this.id = newId; - var oldVal = 'url(#' + id + ')'; - var newVal = 'url(#' + newId + ')'; // Selector method, possibly faster but fails in Opera / jQuery 1.4.3 - // svgEl.find('[fill="url(#' + id + ')"]').each(function() { - // this.setAttribute('fill', 'url(#' + newId + ')'); - // }).end().find('[stroke="url(#' + id + ')"]').each(function() { - // this.setAttribute('stroke', 'url(#' + newId + ')'); - // }).end().find('use').each(function() { - // if(this.getAttribute('xlink:href') == '#' + id) { - // this.setAttributeNS(xlinkns,'href','#' + newId); - // } - // }).end().find('[filter="url(#' + id + ')"]').each(function() { - // this.setAttribute('filter', 'url(#' + newId + ')'); - // }); - - for (i = 0; i < len; i++) { - var elem = allElems[i]; - - if (elem.getAttribute('fill') === oldVal) { - elem.setAttribute('fill', newVal); - } - - if (elem.getAttribute('stroke') === oldVal) { - elem.setAttribute('stroke', newVal); - } - - if (elem.getAttribute('filter') === oldVal) { - elem.setAttribute('filter', newVal); - } - } - }); - return svgEl; -}; -/** -* @callback module:jQuerySVGIcons.SVGIconsLoadedCallback -* @param {PlainObject<string, external:jQuery>} svgIcons IDs keyed to jQuery objects of images -* @returns {void} -*/ - -/** - * @function module:jQuerySVGIcons.jQuerySVGIcons - * @param {external:jQuery} $ Its keys include all icon IDs and the values, the icon as a jQuery object - * @returns {external:jQuery} The enhanced jQuery object -*/ - - -function jQueryPluginSVGIcons($) { - var svgIcons = {}; - /** - * Map of raster images with each key being the SVG icon ID - * to replace, and the value the image file name. - * @typedef {PlainObject<string, string>} external:jQuery.svgIcons.Fallback - */ - - /** - * Map of raster images with each key being the SVG icon ID - * whose `alt` will be set, and the value being the `alt` text. - * @typedef {PlainObject<string, string>} external:jQuery.svgIcons.Alts - */ - - /** - * @function external:jQuery.svgIcons - * @param {string} file The location of a local SVG or SVGz file - * @param {PlainObject} [opts] - * @param {Float} [opts.w] The icon widths - * @param {Float} [opts.h] The icon heights - * @param {external:jQuery.svgIcons.Fallback} [opts.fallback] - * @param {string} [opts.fallback_path] The path to use for all images - * listed under "fallback" - * @param {boolean} [opts.replace] If set to `true`, HTML elements will - * be replaced by, rather than include the SVG icon. - * @param {PlainObject<string, string>} [opts.placement] Map with selectors - * for keys and SVG icon ids as values. This provides a custom method of - * adding icons. - * @param {PlainObject<string, module:jQuerySVGIcons.Size>} [opts.resize] Map - * with selectors for keys and numbers as values. This allows an easy way to - * resize specific icons. - * @param {module:jQuerySVGIcons.SVGIconsLoadedCallback} [opts.callback] A - * function to call when all icons have been loaded. - * @param {boolean} [opts.id_match=true] Automatically attempt to match - * SVG icon ids with corresponding HTML id - * @param {boolean} [opts.no_img] Prevent attempting to convert the icon - * into an `<img>` element (may be faster, help for browser consistency) - * @param {boolean} [opts.svgz] Indicate that the file is an SVGZ file, and - * thus not to parse as XML. SVGZ files add compression benefits, but - * getting data from them fails in Firefox 2 and older. - * @param {jQuery.svgIcons.Alts} [opts.alts] Map of images with each key - * being the SVG icon ID whose `alt` will be set, and the value being - * the `alt` text - * @param {string} [opts.testIconAlt="icon"] Alt text for the injected test image. - * In case wish to ensure have one for accessibility - * @returns {void} - */ - - $.svgIcons = function (file) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var svgns = 'http://www.w3.org/2000/svg', - xlinkns = 'http://www.w3.org/1999/xlink', - iconW = opts.w || 24, - iconH = opts.h || 24; - var elems, - svgdoc, - testImg, - iconsMade = false, - dataLoaded = false, - loadAttempts = 0; - var // ua = navigator.userAgent, - // isSafari = (ua.includes('Safari/') && !ua.includes('Chrome/')), - dataPre = 'data:image/svg+xml;charset=utf-8;base64,'; - var dataEl; - - if (opts.svgz) { - dataEl = $('<object data="' + file + '" type=image/svg+xml>').appendTo('body').hide(); - - try { - svgdoc = dataEl[0].contentDocument; - dataEl.load(getIcons); - getIcons(0, true); // Opera will not run "load" event if file is already cached - } catch (err1) { - useFallback(); - } - } else { - var parser = new DOMParser(); - $.ajax({ - url: file, - dataType: 'string', - success: function success(data) { - if (!data) { - $(useFallback); - return; - } - - svgdoc = parser.parseFromString(data, 'text/xml'); - $(function () { - getIcons('ajax'); - }); - }, - error: function error(err) { - // TODO: Fix Opera widget icon bug - if (window.opera) { - $(function () { - useFallback(); - }); - } else if (err.responseText) { - svgdoc = parser.parseFromString(err.responseText, 'text/xml'); - - if (!svgdoc.childNodes.length) { - $(useFallback); - } - - $(function () { - getIcons('ajax'); - }); - } else { - $(useFallback); - } - } - }); - } - /** - * - * @param {"ajax"|0|void} evt - * @param {boolean} [noWait] - * @returns {void} - */ - - - function getIcons(evt, noWait) { - if (evt !== 'ajax') { - if (dataLoaded) return; // Webkit sometimes says svgdoc is undefined, other times - // it fails to load all nodes. Thus we must make sure the "eof" - // element is loaded. - - svgdoc = dataEl[0].contentDocument; // Needed again for Webkit - - var isReady = svgdoc && svgdoc.getElementById('svg_eof'); - - if (!isReady && !(noWait && isReady)) { - loadAttempts++; - - if (loadAttempts < 50) { - setTimeout(getIcons, 20); - } else { - useFallback(); - dataLoaded = true; - } - - return; - } - - dataLoaded = true; - } - - elems = $(svgdoc.firstChild).children(); // .getElementsByTagName('foreignContent'); - - if (!opts.no_img) { - var testSrc = dataPre + 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zd' + 'mciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D'; - testImg = $(new Image()).attr({ - src: testSrc, - width: 0, - height: 0, - alt: opts.testIconAlt || 'icon' - }).appendTo('body').load(function () { - // Safari 4 crashes, Opera and Chrome don't - makeIcons(true); - }).error(function () { - makeIcons(); - }); - } else { - setTimeout(function () { - if (!iconsMade) makeIcons(); - }, 500); - } - } - /** - * - * @param {external:jQuery} target - * @param {external:jQuery} icon A wrapped `defs` or Image - * @param {string} id SVG icon ID - * @param {boolean} setID Whether to set the ID attribute (with `id`) - * @returns {void} - */ - - - function setIcon(target, icon, id, setID) { - if (isOpera$1) icon.css('visibility', 'hidden'); - - if (opts.replace) { - if (setID) icon.attr('id', id); - var cl = target.attr('class'); - if (cl) icon.attr('class', 'svg_icon ' + cl); - - if (!target.alt) { - var alt = 'icon'; - - if (opts.alts) { - alt = opts.alts[id] || alt; - } - - icon.attr('alt', alt); - } - - target.replaceWith(icon); - } else { - target.append(icon); - } - - if (isOpera$1) { - setTimeout(function () { - icon.removeAttr('style'); - }, 1); - } - } - - var holder; - /** - * @param {external:jQuery} icon A wrapped `defs` or Image - * @param {string} id SVG icon ID - * @returns {void} - */ - - function addIcon(icon, id) { - if (opts.id_match === undefined || opts.id_match !== false) { - setIcon(holder, icon, id, true); - } - - svgIcons[id] = icon; - } - /** - * - * @param {boolean} [toImage] - * @param {external:jQuery.svgIcons.Fallback} [fallback=false] - * @returns {void} - */ - - - function makeIcons() { - var toImage = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var fallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - if (iconsMade) return; - if (opts.no_img) toImage = false; - var tempHolder; - - if (toImage) { - tempHolder = $(document.createElement('div')); - tempHolder.hide().appendTo('body'); - } - - if (fallback) { - var path = opts.fallback_path || ''; - $.each(fallback, function (id, imgsrc) { - holder = $('#' + id); - var alt = 'icon'; - - if (opts.alts) { - alt = opts.alts[id] || alt; - } - - var icon = $(new Image()).attr({ - "class": 'svg_icon', - src: path + imgsrc, - width: iconW, - height: iconH, - alt: alt - }); - addIcon(icon, id); - }); - } else { - var len = elems.length; - - for (var i = 0; i < len; i++) { - var elem = elems[i]; - var id = elem.id; - if (id === 'svg_eof') break; - holder = $('#' + id); - var svgroot = document.createElementNS(svgns, 'svg'); // Per https://www.w3.org/TR/xml-names11/#defaulting, the namespace for - // attributes should have no value. - - svgroot.setAttribute('viewBox', [0, 0, iconW, iconH].join(' ')); - var svg = elem.getElementsByTagNameNS(svgns, 'svg')[0]; // Make flexible by converting width/height to viewBox - - var w = svg.getAttribute('width'); - var h = svg.getAttribute('height'); - svg.removeAttribute('width'); - svg.removeAttribute('height'); - var vb = svg.getAttribute('viewBox'); - - if (!vb) { - svg.setAttribute('viewBox', [0, 0, w, h].join(' ')); - } // Not using jQuery to be a bit faster - - - svgroot.setAttribute('xmlns', svgns); - svgroot.setAttribute('width', iconW); - svgroot.setAttribute('height', iconH); - svgroot.setAttribute('xmlns:xlink', xlinkns); - svgroot.setAttribute('class', 'svg_icon'); // Without cloning, Firefox will make another GET request. - // With cloning, causes issue in Opera/Win/Non-EN - - if (!isOpera$1) svg = svg.cloneNode(true); - svgroot.append(svg); - var icon = void 0; - - if (toImage) { - tempHolder.empty().append(svgroot); - var str = dataPre + encode64(unescape(encodeURIComponent(new XMLSerializer().serializeToString(svgroot)))); - var alt = 'icon'; - - if (opts.alts) { - alt = opts.alts[id] || alt; - } - - icon = $(new Image()).attr({ - "class": 'svg_icon', - src: str, - alt: alt - }); - } else { - icon = fixIDs($(svgroot), i); - } - - addIcon(icon, id); - } - } - - if (opts.placement) { - $.each(opts.placement, function (sel, id) { - if (!svgIcons[id]) return; - $(sel).each(function (i) { - var copy = svgIcons[id].clone(); - if (i > 0 && !toImage) copy = fixIDs(copy, i); - setIcon($(this), copy, id); - }); - }); - } - - if (!fallback) { - if (toImage) tempHolder.remove(); - if (dataEl) dataEl.remove(); - if (testImg) testImg.remove(); - } - - if (opts.resize) $.resizeSvgIcons(opts.resize); - iconsMade = true; - if (opts.callback) opts.callback(svgIcons); - } - /** - * @returns {void} - */ - - - function useFallback() { - if (file.includes('.svgz')) { - var regFile = file.replace('.svgz', '.svg'); - - if (window.console) { - console.log('.svgz failed, trying with .svg'); // eslint-disable-line no-console - } - - $.svgIcons(regFile, opts); - } else if (opts.fallback) { - makeIcons(false, opts.fallback); - } - } - }; - /** - * @function external:jQuery.getSvgIcon - * @param {string} id - * @param {boolean} uniqueClone Whether to clone - * @returns {external:jQuery} The icon (optionally cloned) - */ - - - $.getSvgIcon = function (id, uniqueClone) { - var icon = svgIcons[id]; - - if (uniqueClone && icon) { - icon = fixIDs(icon, 0).clone(true); - } - - return icon; - }; - /** - * @typedef {GenericArray} module:jQuerySVGIcons.Dimensions - * @property {Integer} length 2 - * @property {Float} 0 Width - * @property {Float} 1 Height - */ - - /** - * If a Float is used, it will represent width and height. Arrays contain - * the width and height. - * @typedef {module:jQuerySVGIcons.Dimensions|Float} module:jQuerySVGIcons.Size - */ - - /** - * @function external:jQuery.resizeSvgIcons - * @param {PlainObject<string, module:jQuerySVGIcons.Size>} obj Object with - * selectors as keys. The values are sizes. - * @returns {void} - */ - - - $.resizeSvgIcons = function (obj) { - // FF2 and older don't detect .svg_icon, so we change it detect svg elems instead - var changeSel = !$('.svg_icon:first').length; - $.each(obj, function (sel, size) { - var arr = Array.isArray(size); - var w = arr ? size[0] : size, - h = arr ? size[1] : size; - - if (changeSel) { - sel = sel.replace(/\.svg_icon/g, 'svg'); - } - - $(sel).each(function () { - this.setAttribute('width', w); - this.setAttribute('height', h); - - if (window.opera && window.widget) { - this.parentNode.style.width = w + 'px'; - this.parentNode.style.height = h + 'px'; - } - }); - }); - }; - - return $; -} - -/** - * @file jGraduate 0.4 - * - * jQuery Plugin for a gradient picker - * - * @module jGraduate - * @copyright 2010 Jeff Schiller {@link http://blog.codedread.com/}, 2010 Alexis Deveria {@link http://a.deveria.com/} - * - * @license Apache-2.0 - * @example - * // The Paint object is described below. - * $.jGraduate.Paint(); // constructs a 'none' color - * @example $.jGraduate.Paint({copy: o}); // creates a copy of the paint o - * @example $.jGraduate.Paint({hex: '#rrggbb'}); // creates a solid color paint with hex = "#rrggbb" - * @example $.jGraduate.Paint({linearGradient: o, a: 50}); // creates a linear gradient paint with opacity=0.5 - * @example $.jGraduate.Paint({radialGradient: o, a: 7}); // creates a radial gradient paint with opacity=0.07 - * @example $.jGraduate.Paint({hex: '#rrggbb', linearGradient: o}); // throws an exception? -*/ - -/* eslint-disable jsdoc/require-property */ - -/** - * The jQuery namespace. - * @external jQuery -*/ - -/** - * The jQuery plugin namespace. - * @namespace {PlainObject} fn - * @memberof external:jQuery - * @see {@link http://learn.jquery.com/plugins/|jQuery Plugins} - */ - -/* eslint-enable jsdoc/require-property */ -var ns = { - svg: 'http://www.w3.org/2000/svg', - xlink: 'http://www.w3.org/1999/xlink' -}; - -if (!window.console) { - window.console = { - log: function log(str) { - /* */ - }, - dir: function dir(str) { - /* */ - } - }; -} -/** -* Adds {@link external:jQuery.jGraduate.Paint}, -* {@link external:jQuery.fn.jGraduateDefaults}, -* {@link external:jQuery.fn.jGraduate}. -* @function module:jGraduate.jGraduate -* @param {external:jQuery} $ The jQuery instance to wrap -* @returns {external:jQuery} -*/ - - -function jQueryPluginJGraduate($) { - if (!$.loadingStylesheets) { - $.loadingStylesheets = []; - } - - var stylesheet = 'jgraduate/css/jGraduate.css'; - - if (!$.loadingStylesheets.includes(stylesheet)) { - $.loadingStylesheets.push(stylesheet); - } - /** - * @typedef {PlainObject} module:jGraduate.jGraduatePaintOptions - * @property {Float} [alpha] - * @property {module:jGraduate~Paint} [copy] Copy paint object - * @property {SVGLinearGradientElement} [linearGradient] - * @property {SVGRadialGradientElement} [radialGradient] - * @property {string} [solidColor] - */ - - /** - * @memberof module:jGraduate~ - */ - - - var Paint = - /** - * @param {module:jGraduate.jGraduatePaintOptions} [opt] - */ - function Paint(opt) { - _classCallCheck(this, Paint); - - var options = opt || {}; - this.alpha = isNaN(options.alpha) ? 100 : options.alpha; // copy paint object - - if (options.copy) { - /** - * @name module:jGraduate~Paint#type - * @type {"none"|"solidColor"|"linearGradient"|"radialGradient"} - */ - this.type = options.copy.type; - /** - * Represents opacity (0-100). - * @name module:jGraduate~Paint#alpha - * @type {Float} - */ - - this.alpha = options.copy.alpha; - /** - * Represents #RRGGBB hex of color. - * @name module:jGraduate~Paint#solidColor - * @type {string} - */ - - this.solidColor = null; - /** - * @name module:jGraduate~Paint#linearGradient - * @type {SVGLinearGradientElement} - */ - - this.linearGradient = null; - /** - * @name module:jGraduate~Paint#radialGradient - * @type {SVGRadialGradientElement} - */ - - this.radialGradient = null; - - switch (this.type) { - case 'none': - break; - - case 'solidColor': - this.solidColor = options.copy.solidColor; - break; - - case 'linearGradient': - this.linearGradient = options.copy.linearGradient.cloneNode(true); - break; - - case 'radialGradient': - this.radialGradient = options.copy.radialGradient.cloneNode(true); - break; - } // create linear gradient paint - - } else if (options.linearGradient) { - this.type = 'linearGradient'; - this.solidColor = null; - this.radialGradient = null; - this.linearGradient = options.linearGradient.cloneNode(true); // create linear gradient paint - } else if (options.radialGradient) { - this.type = 'radialGradient'; - this.solidColor = null; - this.linearGradient = null; - this.radialGradient = options.radialGradient.cloneNode(true); // create solid color paint - } else if (options.solidColor) { - this.type = 'solidColor'; - this.solidColor = options.solidColor; // create empty paint - } else { - this.type = 'none'; - this.solidColor = null; - this.linearGradient = null; - this.radialGradient = null; - } - }; - /* eslint-disable jsdoc/require-property */ - - /** - * @namespace {PlainObject} jGraduate - * @memberof external:jQuery - */ - - - $.jGraduate = - /** @lends external:jQuery.jGraduate */ - { - /* eslint-enable jsdoc/require-property */ - - /** - * @class external:jQuery.jGraduate.Paint - * @see module:jGraduate~Paint - */ - Paint: Paint - }; // JSDoc doesn't show this as belonging to our `module:jGraduate.Options` type, - // so we use `@see` - - /** - * @namespace {module:jGraduate.Options} jGraduateDefaults - * @memberof external:jQuery.fn - */ - - $.fn.jGraduateDefaults = - /** @lends external:jQuery.fn.jGraduateDefaults */ - { - /** - * Creates an object with a 'none' color. - * @type {external:jQuery.jGraduate.Paint} - * @see module:jGraduate.Options - */ - paint: new $.jGraduate.Paint(), - - /** - * @namespace - */ - window: { - /** - * @type {string} - * @see module:jGraduate.Options - */ - pickerTitle: 'Drag markers to pick a paint' - }, - - /** - * @namespace - */ - images: { - /** - * @type {string} - * @see module:jGraduate.Options - */ - clientPath: 'images/' - }, - - /** - * @type {string} - * @see module:jGraduate.Options - */ - newstop: 'inverse' // same, inverse, black, white - - }; - var isGecko = navigator.userAgent.includes('Gecko/'); - /** - * @typedef {PlainObject<string, string>} module:jGraduate.Attrs - */ - - /** - * @param {SVGElement} elem - * @param {module:jGraduate.Attrs} attrs - * @returns {void} - */ - - function setAttrs(elem, attrs) { - if (isGecko) { - Object.entries(attrs).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - aname = _ref2[0], - val = _ref2[1]; - - elem.setAttribute(aname, val); - }); - } else { - Object.entries(attrs).forEach(function (_ref3) { - var _ref4 = _slicedToArray(_ref3, 2), - aname = _ref4[0], - val = _ref4[1]; - - var prop = elem[aname]; - - if (prop && prop.constructor === 'SVGLength') { - prop.baseVal.value = val; - } else { - elem.setAttribute(aname, val); - } - }); - } - } - /** - * @param {string} name - * @param {module:jGraduate.Attrs} attrs - * @param {Element} newparent - * @returns {SVGElement} - */ - - - function mkElem(name, attrs, newparent) { - var elem = document.createElementNS(ns.svg, name); - setAttrs(elem, attrs); - - if (newparent) { - newparent.append(elem); - } - - return elem; - } - /** - * @typedef {PlainObject} module:jGraduate.ColorOpac Object may have one or both values - * @property {string} [color] #Hex color - * @property {Float} [opac] 0-1 - */ - - /** - * @typedef {PlainObject} module:jGraduate.Options - * @property {module:jGraduate~Paint} [paint] A Paint object object describing the paint to display initially; defaults to a new instance without options (defaults to opaque white) - * @property {external:Window} [window] - * @property {string} [window.pickerTitle='Drag markers to pick a paint'] - * @property {PlainObject} [images] - * @property {string} [images.clientPath='images/'] - * @property {"same"|"inverse"|"black"|"white"|module:jGraduate.ColorOpac} [newstop="inverse"] - */ - - /** - * @callback external:jQuery.fn.jGraduate.OkCallback - * @param {external:jQuery.jGraduate.Paint} paint - * @returns {void} - */ - - /** - * @callback external:jQuery.fn.jGraduate.CancelCallback - * @returns {void} - */ - - /** - * @function external:jQuery.fn.jGraduate - * @param {module:jGraduate.Options} [options] - * @param {external:jQuery.fn.jGraduate.OkCallback} [okCallback] Called with a Paint object when Ok is pressed - * @param {external:jQuery.fn.jGraduate.CancelCallback} [cancelCallback] Called with no arguments when Cancel is pressed - * @returns {external:jQuery} - */ - - - $.fn.jGraduate = function (options, okCallback, cancelCallback) { - return this.each(function () { - var $this = $(this), - $settings = $.extend(true, {}, $.fn.jGraduateDefaults, options || {}), - id = $this.attr('id'), - idref = '#' + $this.attr('id') + ' '; - - if (!idref) { - /* await */ - $.alert('Container element must have an id attribute to maintain unique id strings for sub-elements.'); - return; - } - - var okClicked = function okClicked() { - switch ($this.paint.type) { - case 'radialGradient': - $this.paint.linearGradient = null; - break; - - case 'linearGradient': - $this.paint.radialGradient = null; - break; - - case 'solidColor': - $this.paint.radialGradient = $this.paint.linearGradient = null; - break; - } - - typeof $this.okCallback === 'function' && $this.okCallback($this.paint); - $this.hide(); - }; - - var cancelClicked = function cancelClicked() { - typeof $this.cancelCallback === 'function' && $this.cancelCallback(); - $this.hide(); - }; - - $.extend(true, $this, // public properties, methods, and callbacks - { - // make a copy of the incoming paint - paint: new $.jGraduate.Paint({ - copy: $settings.paint - }), - okCallback: typeof okCallback === 'function' ? okCallback : null, - cancelCallback: typeof cancelCallback === 'function' ? cancelCallback : null - }); - var // pos = $this.position(), - color = null; - var $win = $(window); - - if ($this.paint.type === 'none') { - $this.paint = new $.jGraduate.Paint({ - solidColor: 'ffffff' - }); - } - - $this.addClass('jGraduate_Picker'); - /* eslint-disable max-len */ - - $this.html('<ul class="jGraduate_tabs">' + '<li class="jGraduate_tab_color jGraduate_tab_current" data-type="col">Solid Color</li>' + '<li class="jGraduate_tab_lingrad" data-type="lg">Linear Gradient</li>' + '<li class="jGraduate_tab_radgrad" data-type="rg">Radial Gradient</li>' + '</ul>' + '<div class="jGraduate_colPick"></div>' + '<div class="jGraduate_gradPick"></div>' + '<div class="jGraduate_LightBox"></div>' + '<div id="' + id + '_jGraduate_stopPicker" class="jGraduate_stopPicker"></div>'); - var colPicker = $(idref + '> .jGraduate_colPick'); - var gradPicker = $(idref + '> .jGraduate_gradPick'); - gradPicker.html('<div id="' + id + '_jGraduate_Swatch" class="jGraduate_Swatch">' + '<h2 class="jGraduate_Title">' + $settings.window.pickerTitle + '</h2>' + '<div id="' + id + '_jGraduate_GradContainer" class="jGraduate_GradContainer"></div>' + '<div id="' + id + '_jGraduate_StopSlider" class="jGraduate_StopSlider"></div>' + '</div>' + '<div class="jGraduate_Form jGraduate_Points jGraduate_lg_field">' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">Begin Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_x1" size="3" title="Enter starting x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_y1" size="3" title="Enter starting y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">End Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_x2" size="3" title="Enter ending x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_y2" size="3" title="Enter ending y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '</div>' + '<div class="jGraduate_Form jGraduate_Points jGraduate_rg_field">' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">Center Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_cx" size="3" title="Enter x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_cy" size="3" title="Enter y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '<div class="jGraduate_StopSection">' + '<label class="jGraduate_Form_Heading">Focal Point</label>' + '<div class="jGraduate_Form_Section">' + '<label>Match center: <input type="checkbox" checked="checked" id="' + id + '_jGraduate_match_ctr"/></label><br/>' + '<label>x:</label>' + '<input type="text" id="' + id + '_jGraduate_fx" size="3" title="Enter x value between 0.0 and 1.0"/>' + '<label>y:</label>' + '<input type="text" id="' + id + '_jGraduate_fy" size="3" title="Enter y value between 0.0 and 1.0"/>' + '</div>' + '</div>' + '</div>' + '<div class="jGraduate_StopSection jGraduate_SpreadMethod">' + '<label class="jGraduate_Form_Heading">Spread method</label>' + '<div class="jGraduate_Form_Section">' + '<select class="jGraduate_spreadMethod">' + '<option value=pad selected>Pad</option>' + '<option value=reflect>Reflect</option>' + '<option value=repeat>Repeat</option>' + '</select>' + '</div>' + '</div>' + '<div class="jGraduate_Form">' + '<div class="jGraduate_Slider jGraduate_RadiusField jGraduate_rg_field">' + '<label class="prelabel">Radius:</label>' + '<div id="' + id + '_jGraduate_Radius" class="jGraduate_SliderBar jGraduate_Radius" title="Click to set radius">' + '<img id="' + id + '_jGraduate_RadiusArrows" class="jGraduate_RadiusArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_RadiusInput" size="3" value="100"/>%</label>' + '</div>' + '<div class="jGraduate_Slider jGraduate_EllipField jGraduate_rg_field">' + '<label class="prelabel">Ellip:</label>' + '<div id="' + id + '_jGraduate_Ellip" class="jGraduate_SliderBar jGraduate_Ellip" title="Click to set Ellip">' + '<img id="' + id + '_jGraduate_EllipArrows" class="jGraduate_EllipArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_EllipInput" size="3" value="0"/>%</label>' + '</div>' + '<div class="jGraduate_Slider jGraduate_AngleField jGraduate_rg_field">' + '<label class="prelabel">Angle:</label>' + '<div id="' + id + '_jGraduate_Angle" class="jGraduate_SliderBar jGraduate_Angle" title="Click to set Angle">' + '<img id="' + id + '_jGraduate_AngleArrows" class="jGraduate_AngleArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_AngleInput" size="3" value="0"/>deg</label>' + '</div>' + '<div class="jGraduate_Slider jGraduate_OpacField">' + '<label class="prelabel">Opac:</label>' + '<div id="' + id + '_jGraduate_Opac" class="jGraduate_SliderBar jGraduate_Opac" title="Click to set Opac">' + '<img id="' + id + '_jGraduate_OpacArrows" class="jGraduate_OpacArrows" src="' + $settings.images.clientPath + 'rangearrows2.gif">' + '</div>' + '<label><input type="text" id="' + id + '_jGraduate_OpacInput" size="3" value="100"/>%</label>' + '</div>' + '</div>' + '<div class="jGraduate_OkCancel">' + '<input type="button" id="' + id + '_jGraduate_Ok" class="jGraduate_Ok" value="OK"/>' + '<input type="button" id="' + id + '_jGraduate_Cancel" class="jGraduate_Cancel" value="Cancel"/>' + '</div>'); - /* eslint-enable max-len */ - // -------------- - // Set up all the SVG elements (the gradient, stops and rectangle) - - var MAX = 256, - MARGINX = 0, - MARGINY = 0, - // STOP_RADIUS = 15 / 2, - SIZEX = MAX - 2 * MARGINX, - SIZEY = MAX - 2 * MARGINY; - var attrInput = {}; - var SLIDERW = 145; - $('.jGraduate_SliderBar').width(SLIDERW); - var container = $('#' + id + '_jGraduate_GradContainer')[0]; - var svg = mkElem('svg', { - id: id + '_jgraduate_svg', - width: MAX, - height: MAX, - xmlns: ns.svg - }, container); // This wasn't working as designed - // let curType; - // curType = curType || $this.paint.type; - // if we are sent a gradient, import it - - var curType = $this.paint.type; - var grad = $this.paint[curType]; - var curGradient = grad; - var gradalpha = $this.paint.alpha; - var isSolid = curType === 'solidColor'; // Make any missing gradients - - switch (curType) { - case 'solidColor': // fall through - - case 'linearGradient': - if (!isSolid) { - curGradient.id = id + '_lg_jgraduate_grad'; - grad = curGradient = svg.appendChild(curGradient); // .cloneNode(true)); - } - - mkElem('radialGradient', { - id: id + '_rg_jgraduate_grad' - }, svg); - - if (curType === 'linearGradient') { - break; - } - - // fall through - - case 'radialGradient': - if (!isSolid) { - curGradient.id = id + '_rg_jgraduate_grad'; - grad = curGradient = svg.appendChild(curGradient); // .cloneNode(true)); - } - - mkElem('linearGradient', { - id: id + '_lg_jgraduate_grad' - }, svg); - } - - var stopGroup; // eslint-disable-line prefer-const - - if (isSolid) { - grad = curGradient = $('#' + id + '_lg_jgraduate_grad')[0]; - color = $this.paint[curType]; - mkStop(0, '#' + color, 1); - - var type = _typeof($settings.newstop); - - if (type === 'string') { - switch ($settings.newstop) { - case 'same': - mkStop(1, '#' + color, 1); - break; - - case 'inverse': - { - // Invert current color for second stop - var inverted = ''; - - for (var i = 0; i < 6; i += 2) { - // const ch = color.substr(i, 2); - var inv = (255 - Number.parseInt(color.substr(i, 2), 16)).toString(16); - if (inv.length < 2) inv = 0 + inv; - inverted += inv; - } - - mkStop(1, '#' + inverted, 1); - break; - } - - case 'white': - mkStop(1, '#ffffff', 1); - break; - - case 'black': - mkStop(1, '#000000', 1); - break; - } - } else if (type === 'object') { - var opac = 'opac' in $settings.newstop ? $settings.newstop.opac : 1; - mkStop(1, $settings.newstop.color || '#' + color, opac); - } - } - - var x1 = Number.parseFloat(grad.getAttribute('x1') || 0.0), - y1 = Number.parseFloat(grad.getAttribute('y1') || 0.0), - x2 = Number.parseFloat(grad.getAttribute('x2') || 1.0), - y2 = Number.parseFloat(grad.getAttribute('y2') || 0.0); - var cx = Number.parseFloat(grad.getAttribute('cx') || 0.5), - cy = Number.parseFloat(grad.getAttribute('cy') || 0.5), - fx = Number.parseFloat(grad.getAttribute('fx') || cx), - fy = Number.parseFloat(grad.getAttribute('fy') || cy); - var previewRect = mkElem('rect', { - id: id + '_jgraduate_rect', - x: MARGINX, - y: MARGINY, - width: SIZEX, - height: SIZEY, - fill: 'url(#' + id + '_jgraduate_grad)', - 'fill-opacity': gradalpha / 100 - }, svg); // stop visuals created here - - var beginCoord = $('<div/>').attr({ - "class": 'grad_coord jGraduate_lg_field', - title: 'Begin Stop' - }).text(1).css({ - top: y1 * MAX, - left: x1 * MAX - }).data('coord', 'start').appendTo(container); - var endCoord = beginCoord.clone().text(2).css({ - top: y2 * MAX, - left: x2 * MAX - }).attr('title', 'End stop').data('coord', 'end').appendTo(container); - var centerCoord = $('<div/>').attr({ - "class": 'grad_coord jGraduate_rg_field', - title: 'Center stop' - }).text('C').css({ - top: cy * MAX, - left: cx * MAX - }).data('coord', 'center').appendTo(container); - var focusCoord = centerCoord.clone().text('F').css({ - top: fy * MAX, - left: fx * MAX, - display: 'none' - }).attr('title', 'Focus point').data('coord', 'focus').appendTo(container); - focusCoord[0].id = id + '_jGraduate_focusCoord'; // const coords = $(idref + ' .grad_coord'); - // $(container).hover(function () { - // coords.animate({ - // opacity: 1 - // }, 500); - // }, function () { - // coords.animate({ - // opacity: .2 - // }, 500); - // }); - - var showFocus; - $.each(['x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'fx', 'fy'], function (i, attr) { - var isRadial = isNaN(attr[1]); - var attrval = curGradient.getAttribute(attr); - - if (!attrval) { - // Set defaults - if (isRadial) { - // For radial points - attrval = '0.5'; - } else { - // Only x2 is 1 - attrval = attr === 'x2' ? '1.0' : '0.0'; - } - } - - attrInput[attr] = $('#' + id + '_jGraduate_' + attr).val(attrval).change(function () { - // TODO: Support values < 0 and > 1 (zoomable preview?) - if (isNaN(Number.parseFloat(this.value)) || this.value < 0) { - this.value = 0.0; - } else if (this.value > 1) { - this.value = 1.0; - } - - if (!(attr[0] === 'f' && !showFocus)) { - if (isRadial && curType === 'radialGradient' || !isRadial && curType === 'linearGradient') { - curGradient.setAttribute(attr, this.value); - } - } - - var $elem = isRadial ? attr[0] === 'c' ? centerCoord : focusCoord : attr[1] === '1' ? beginCoord : endCoord; - var cssName = attr.includes('x') ? 'left' : 'top'; - $elem.css(cssName, this.value * MAX); - }).change(); - }); - /** - * - * @param {Float} n - * @param {Float|string} colr - * @param {Float} opac - * @param {boolean} [sel] - * @param {SVGStopElement} [stopElem] - * @returns {SVGStopElement} - */ - - function mkStop(n, colr, opac, sel, stopElem) { - var stop = stopElem || mkElem('stop', { - 'stop-color': colr, - 'stop-opacity': opac, - offset: n - }, curGradient); - - if (stopElem) { - colr = stopElem.getAttribute('stop-color'); - opac = stopElem.getAttribute('stop-opacity'); - n = stopElem.getAttribute('offset'); - } else { - curGradient.append(stop); - } - - if (opac === null) opac = 1; - var pickerD = 'M-6.2,0.9c3.6-4,6.7-4.3,6.7-12.4c-0.2,7.9,' + '3.1,8.8,6.5,12.4c3.5,3.8,2.9,9.6,0,12.3c-3.1,2.8-10.4,' + '2.7-13.2,0C-9.6,9.9-9.4,4.4-6.2,0.9z'; - var pathbg = mkElem('path', { - d: pickerD, - fill: 'url(#jGraduate_trans)', - transform: 'translate(' + (10 + n * MAX) + ', 26)' - }, stopGroup); - var path = mkElem('path', { - d: pickerD, - fill: colr, - 'fill-opacity': opac, - transform: 'translate(' + (10 + n * MAX) + ', 26)', - stroke: '#000', - 'stroke-width': 1.5 - }, stopGroup); - $(path).mousedown(function (e) { - selectStop(this); - drag = curStop; - $win.mousemove(dragColor).mouseup(remDrags); - stopOffset = stopMakerDiv.offset(); - e.preventDefault(); - return false; - }).data('stop', stop).data('bg', pathbg).dblclick(function () { - $('div.jGraduate_LightBox').show(); - var colorhandle = this; - var stopOpacity = Number(stop.getAttribute('stop-opacity')) || 1; - var stopColor = stop.getAttribute('stop-color') || 1; - var thisAlpha = (Number.parseFloat(stopOpacity) * 255).toString(16); - - while (thisAlpha.length < 2) { - thisAlpha = '0' + thisAlpha; - } - - colr = stopColor.substr(1) + thisAlpha; - $('#' + id + '_jGraduate_stopPicker').css({ - left: 100, - bottom: 15 - }).jPicker({ - window: { - title: 'Pick the start color and opacity for the gradient' - }, - images: { - clientPath: $settings.images.clientPath - }, - color: { - active: colr, - alphaSupport: true - } - }, function (clr, arg2) { - stopColor = clr.val('hex') ? '#' + clr.val('hex') : 'none'; - stopOpacity = clr.val('a') !== null ? clr.val('a') / 256 : 1; - colorhandle.setAttribute('fill', stopColor); - colorhandle.setAttribute('fill-opacity', stopOpacity); - stop.setAttribute('stop-color', stopColor); - stop.setAttribute('stop-opacity', stopOpacity); - $('div.jGraduate_LightBox').hide(); - $('#' + id + '_jGraduate_stopPicker').hide(); - }, null, function () { - $('div.jGraduate_LightBox').hide(); - $('#' + id + '_jGraduate_stopPicker').hide(); - }); - }); - $(curGradient).find('stop').each(function () { - var curS = $(this); - - if (Number(this.getAttribute('offset')) > n) { - if (!colr) { - var newcolor = this.getAttribute('stop-color'); - var newopac = this.getAttribute('stop-opacity'); - stop.setAttribute('stop-color', newcolor); - path.setAttribute('fill', newcolor); - stop.setAttribute('stop-opacity', newopac === null ? 1 : newopac); - path.setAttribute('fill-opacity', newopac === null ? 1 : newopac); - } - - curS.before(stop); - return false; - } - - return true; - }); - if (sel) selectStop(path); - return stop; - } - /** - * - * @returns {void} - */ - - - function remStop() { - delStop.setAttribute('display', 'none'); - var path = $(curStop); - var stop = path.data('stop'); - var bg = path.data('bg'); - $([curStop, stop, bg]).remove(); - } - - var stopMakerDiv = $('#' + id + '_jGraduate_StopSlider'); - var stops, curStop, drag; - var delStop = mkElem('path', { - d: 'm9.75,-6l-19.5,19.5m0,-19.5l19.5,19.5', - fill: 'none', - stroke: '#D00', - 'stroke-width': 5, - display: 'none' - }, undefined); // stopMakerSVG); - - /** - * @param {Element} item - * @returns {void} - */ - - function selectStop(item) { - if (curStop) curStop.setAttribute('stroke', '#000'); - item.setAttribute('stroke', 'blue'); - curStop = item; // stops = $('stop'); - // opac_select.val(curStop.attr('fill-opacity') || 1); - // root.append(delStop); - } - - var stopOffset; - /** - * - * @returns {void} - */ - - function remDrags() { - $win.unbind('mousemove', dragColor); - - if (delStop.getAttribute('display') !== 'none') { - remStop(); - } - - drag = null; - } - - var scaleX = 1, - scaleY = 1, - angle = 0; - var cX = cx; - var cY = cy; - /** - * - * @returns {void} - */ - - function xform() { - var rot = angle ? 'rotate(' + angle + ',' + cX + ',' + cY + ') ' : ''; - - if (scaleX === 1 && scaleY === 1) { - curGradient.removeAttribute('gradientTransform'); // $('#ang').addClass('dis'); - } else { - var x = -cX * (scaleX - 1); - var y = -cY * (scaleY - 1); - curGradient.setAttribute('gradientTransform', rot + 'translate(' + x + ',' + y + ') scale(' + scaleX + ',' + scaleY + ')'); // $('#ang').removeClass('dis'); - } - } - /** - * @param {Event} evt - * @returns {void} - */ - - - function dragColor(evt) { - var x = evt.pageX - stopOffset.left; - var y = evt.pageY - stopOffset.top; - x = x < 10 ? 10 : x > MAX + 10 ? MAX + 10 : x; - var xfStr = 'translate(' + x + ', 26)'; - - if (y < -60 || y > 130) { - delStop.setAttribute('display', 'block'); - delStop.setAttribute('transform', xfStr); - } else { - delStop.setAttribute('display', 'none'); - } - - drag.setAttribute('transform', xfStr); - $.data(drag, 'bg').setAttribute('transform', xfStr); - var stop = $.data(drag, 'stop'); - var sX = (x - 10) / MAX; - stop.setAttribute('offset', sX); - var last = 0; - $(curGradient).find('stop').each(function (i) { - var cur = this.getAttribute('offset'); - var t = $(this); - - if (cur < last) { - t.prev().before(t); - stops = $(curGradient).find('stop'); - } - - last = cur; - }); - } - - var stopMakerSVG = mkElem('svg', { - width: '100%', - height: 45 - }, stopMakerDiv[0]); - var transPattern = mkElem('pattern', { - width: 16, - height: 16, - patternUnits: 'userSpaceOnUse', - id: 'jGraduate_trans' - }, stopMakerSVG); - var transImg = mkElem('image', { - width: 16, - height: 16 - }, transPattern); - var bgImage = $settings.images.clientPath + 'map-opacity.png'; - transImg.setAttributeNS(ns.xlink, 'xlink:href', bgImage); - $(stopMakerSVG).click(function (evt) { - stopOffset = stopMakerDiv.offset(); - var target = evt.target; - if (target.tagName === 'path') return; - var x = evt.pageX - stopOffset.left - 8; - x = x < 10 ? 10 : x > MAX + 10 ? MAX + 10 : x; - mkStop(x / MAX, 0, 0, true); - evt.stopPropagation(); - }); - $(stopMakerSVG).mouseover(function () { - stopMakerSVG.append(delStop); - }); - stopGroup = mkElem('g', {}, stopMakerSVG); - mkElem('line', { - x1: 10, - y1: 15, - x2: MAX + 10, - y2: 15, - 'stroke-width': 2, - stroke: '#000' - }, stopMakerSVG); - var spreadMethodOpt = gradPicker.find('.jGraduate_spreadMethod').change(function () { - curGradient.setAttribute('spreadMethod', $(this).val()); - }); // handle dragging the stop around the swatch - - var draggingCoord = null; - - var onCoordDrag = function onCoordDrag(evt) { - var x = evt.pageX - offset.left; - var y = evt.pageY - offset.top; // clamp stop to the swatch - - x = x < 0 ? 0 : x > MAX ? MAX : x; - y = y < 0 ? 0 : y > MAX ? MAX : y; - draggingCoord.css('left', x).css('top', y); // calculate stop offset - - var fracx = x / SIZEX; - var fracy = y / SIZEY; - var type = draggingCoord.data('coord'); - var grd = curGradient; - - switch (type) { - case 'start': - attrInput.x1.val(fracx); - attrInput.y1.val(fracy); - grd.setAttribute('x1', fracx); - grd.setAttribute('y1', fracy); - break; - - case 'end': - attrInput.x2.val(fracx); - attrInput.y2.val(fracy); - grd.setAttribute('x2', fracx); - grd.setAttribute('y2', fracy); - break; - - case 'center': - attrInput.cx.val(fracx); - attrInput.cy.val(fracy); - grd.setAttribute('cx', fracx); - grd.setAttribute('cy', fracy); - cX = fracx; - cY = fracy; - xform(); - break; - - case 'focus': - attrInput.fx.val(fracx); - attrInput.fy.val(fracy); - grd.setAttribute('fx', fracx); - grd.setAttribute('fy', fracy); - xform(); - } - - evt.preventDefault(); - }; - - var onCoordUp = function onCoordUp() { - draggingCoord = null; - $win.unbind('mousemove', onCoordDrag).unbind('mouseup', onCoordUp); - }; // Linear gradient - // (function () { - - - stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); - var numstops = stops.length; // if there are not at least two stops, then - - if (numstops < 2) { - while (numstops < 2) { - curGradient.append(document.createElementNS(ns.svg, 'stop')); - ++numstops; - } - - stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); - } - - for (var _i = 0; _i < numstops; _i++) { - mkStop(0, 0, 0, 0, stops[_i]); - } - - spreadMethodOpt.val(curGradient.getAttribute('spreadMethod') || 'pad'); - var offset; // No match, so show focus point - - showFocus = false; - previewRect.setAttribute('fill-opacity', gradalpha / 100); - $('#' + id + ' div.grad_coord').mousedown(function (evt) { - evt.preventDefault(); - draggingCoord = $(this); // const sPos = draggingCoord.offset(); - - offset = draggingCoord.parent().offset(); - $win.mousemove(onCoordDrag).mouseup(onCoordUp); - }); // bind GUI elements - - $('#' + id + '_jGraduate_Ok').bind('click', function () { - $this.paint.type = curType; - $this.paint[curType] = curGradient.cloneNode(true); - $this.paint.solidColor = null; - okClicked(); - }); - $('#' + id + '_jGraduate_Cancel').bind('click', function (paint) { - cancelClicked(); - }); - - if (curType === 'radialGradient') { - if (showFocus) { - focusCoord.show(); - } else { - focusCoord.hide(); - attrInput.fx.val(''); - attrInput.fy.val(''); - } - } - - $('#' + id + '_jGraduate_match_ctr')[0].checked = !showFocus; - var lastfx, lastfy; - $('#' + id + '_jGraduate_match_ctr').change(function () { - showFocus = !this.checked; - focusCoord.toggle(showFocus); - attrInput.fx.val(''); - attrInput.fy.val(''); - var grd = curGradient; - - if (!showFocus) { - lastfx = grd.getAttribute('fx'); - lastfy = grd.getAttribute('fy'); - grd.removeAttribute('fx'); - grd.removeAttribute('fy'); - } else { - var fX = lastfx || 0.5; - var fY = lastfy || 0.5; - grd.setAttribute('fx', fX); - grd.setAttribute('fy', fY); - attrInput.fx.val(fX); - attrInput.fy.val(fY); - } - }); - stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); - numstops = stops.length; // if there are not at least two stops, then - - if (numstops < 2) { - while (numstops < 2) { - curGradient.append(document.createElementNS(ns.svg, 'stop')); - ++numstops; - } - - stops = curGradient.getElementsByTagNameNS(ns.svg, 'stop'); - } - - var slider; - - var setSlider = function setSlider(e) { - var _slider = slider, - left = _slider.offset.left; - var div = slider.parent; - var x = e.pageX - left - Number.parseInt(div.css('border-left-width')); - if (x > SLIDERW) x = SLIDERW; - if (x <= 0) x = 0; - var posx = x - 5; - x /= SLIDERW; - - switch (slider.type) { - case 'radius': - x = Math.pow(x * 2, 2.5); - if (x > 0.98 && x < 1.02) x = 1; - if (x <= 0.01) x = 0.01; - curGradient.setAttribute('r', x); - break; - - case 'opacity': - $this.paint.alpha = Number.parseInt(x * 100); - previewRect.setAttribute('fill-opacity', x); - break; - - case 'ellip': - scaleX = 1; - scaleY = 1; - - if (x < 0.5) { - x /= 0.5; // 0.001 - - scaleX = x <= 0 ? 0.01 : x; - } else if (x > 0.5) { - x /= 0.5; // 2 - - x = 2 - x; - scaleY = x <= 0 ? 0.01 : x; - } - - xform(); - x -= 1; - - if (scaleY === x + 1) { - x = Math.abs(x); - } - - break; - - case 'angle': - x -= 0.5; - angle = x *= 180; - xform(); - x /= 100; - break; - } - - slider.elem.css({ - 'margin-left': posx - }); - x = Math.round(x * 100); - slider.input.val(x); - }; - - var ellipVal = 0, - angleVal = 0; - - if (curType === 'radialGradient') { - var tlist = curGradient.gradientTransform.baseVal; - - if (tlist.numberOfItems === 2) { - var t = tlist.getItem(0); - var s = tlist.getItem(1); - - if (t.type === 2 && s.type === 3) { - var m = s.matrix; - - if (m.a !== 1) { - ellipVal = Math.round(-(1 - m.a) * 100); - } else if (m.d !== 1) { - ellipVal = Math.round((1 - m.d) * 100); - } - } - } else if (tlist.numberOfItems === 3) { - // Assume [R][T][S] - var r = tlist.getItem(0); - - var _t = tlist.getItem(1); - - var _s = tlist.getItem(2); - - if (r.type === 4 && _t.type === 2 && _s.type === 3) { - angleVal = Math.round(r.angle); - var _m = _s.matrix; - - if (_m.a !== 1) { - ellipVal = Math.round(-(1 - _m.a) * 100); - } else if (_m.d !== 1) { - ellipVal = Math.round((1 - _m.d) * 100); - } - } - } - } - - var sliders = { - radius: { - handle: '#' + id + '_jGraduate_RadiusArrows', - input: '#' + id + '_jGraduate_RadiusInput', - val: (curGradient.getAttribute('r') || 0.5) * 100 - }, - opacity: { - handle: '#' + id + '_jGraduate_OpacArrows', - input: '#' + id + '_jGraduate_OpacInput', - val: $this.paint.alpha || 100 - }, - ellip: { - handle: '#' + id + '_jGraduate_EllipArrows', - input: '#' + id + '_jGraduate_EllipInput', - val: ellipVal - }, - angle: { - handle: '#' + id + '_jGraduate_AngleArrows', - input: '#' + id + '_jGraduate_AngleInput', - val: angleVal - } - }; - $.each(sliders, function (type, data) { - var handle = $(data.handle); - handle.mousedown(function (evt) { - var parent = handle.parent(); - slider = { - type: type, - elem: handle, - input: $(data.input), - parent: parent, - offset: parent.offset() - }; - $win.mousemove(dragSlider).mouseup(stopSlider); - evt.preventDefault(); - }); - $(data.input).val(data.val).change(function () { - var isRad = curType === 'radialGradient'; - var val = Number(this.value); - var xpos = 0; - - switch (type) { - case 'radius': - if (isRad) curGradient.setAttribute('r', val / 100); - xpos = Math.pow(val / 100, 1 / 2.5) / 2 * SLIDERW; - break; - - case 'opacity': - $this.paint.alpha = val; - previewRect.setAttribute('fill-opacity', val / 100); - xpos = val * (SLIDERW / 100); - break; - - case 'ellip': - scaleX = scaleY = 1; - - if (val === 0) { - xpos = SLIDERW * 0.5; - break; - } - - if (val > 99.5) val = 99.5; - - if (val > 0) { - scaleY = 1 - val / 100; - } else { - scaleX = -(val / 100) - 1; - } - - xpos = SLIDERW * ((val + 100) / 2) / 100; - if (isRad) xform(); - break; - - case 'angle': - angle = val; - xpos = angle / 180; - xpos += 0.5; - xpos *= SLIDERW; - if (isRad) xform(); - } - - if (xpos > SLIDERW) { - xpos = SLIDERW; - } else if (xpos < 0) { - xpos = 0; - } - - handle.css({ - 'margin-left': xpos - 5 - }); - }).change(); - }); - - var dragSlider = function dragSlider(evt) { - setSlider(evt); - evt.preventDefault(); - }; - - var stopSlider = function stopSlider(evt) { - $win.unbind('mousemove', dragSlider).unbind('mouseup', stopSlider); - slider = null; - }; // -------------- - - - var thisAlpha = ($this.paint.alpha * 255 / 100).toString(16); - - while (thisAlpha.length < 2) { - thisAlpha = '0' + thisAlpha; - } - - thisAlpha = thisAlpha.split('.')[0]; - color = $this.paint.solidColor === 'none' ? '' : $this.paint.solidColor + thisAlpha; - - if (!isSolid) { - color = stops[0].getAttribute('stop-color'); - } // This should be done somewhere else, probably - - - $.extend($.fn.jPicker.defaults.window, { - alphaSupport: true, - effects: { - type: 'show', - speed: 0 - } - }); - colPicker.jPicker({ - window: { - title: $settings.window.pickerTitle - }, - images: { - clientPath: $settings.images.clientPath - }, - color: { - active: color, - alphaSupport: true - } - }, function (clr) { - $this.paint.type = 'solidColor'; - $this.paint.alpha = clr.val('ahex') ? Math.round(clr.val('a') / 255 * 100) : 100; - $this.paint.solidColor = clr.val('hex') ? clr.val('hex') : 'none'; - $this.paint.radialGradient = null; - okClicked(); - }, null, function () { - cancelClicked(); - }); - var tabs = $(idref + ' .jGraduate_tabs li'); - tabs.click(function () { - tabs.removeClass('jGraduate_tab_current'); - $(this).addClass('jGraduate_tab_current'); - $(idref + ' > div').hide(); - var type = $(this).attr('data-type'); - /* const container = */ - - $(idref + ' .jGraduate_gradPick').show(); - - if (type === 'rg' || type === 'lg') { - // Show/hide appropriate fields - $('.jGraduate_' + type + '_field').show(); - $('.jGraduate_' + (type === 'lg' ? 'rg' : 'lg') + '_field').hide(); - $('#' + id + '_jgraduate_rect')[0].setAttribute('fill', 'url(#' + id + '_' + type + '_jgraduate_grad)'); // Copy stops - - curType = type === 'lg' ? 'linearGradient' : 'radialGradient'; - $('#' + id + '_jGraduate_OpacInput').val($this.paint.alpha).change(); - var newGrad = $('#' + id + '_' + type + '_jgraduate_grad')[0]; - - if (curGradient !== newGrad) { - var curStops = $(curGradient).find('stop'); - $(newGrad).empty().append(curStops); - curGradient = newGrad; - var sm = spreadMethodOpt.val(); - curGradient.setAttribute('spreadMethod', sm); - } - - showFocus = type === 'rg' && curGradient.getAttribute('fx') !== null && !(cx === fx && cy === fy); - $('#' + id + '_jGraduate_focusCoord').toggle(showFocus); - - if (showFocus) { - $('#' + id + '_jGraduate_match_ctr')[0].checked = false; - } - } else { - $(idref + ' .jGraduate_gradPick').hide(); - $(idref + ' .jGraduate_colPick').show(); - } - }); - $(idref + ' > div').hide(); - tabs.removeClass('jGraduate_tab_current'); - var tab; - - switch ($this.paint.type) { - case 'linearGradient': - tab = $(idref + ' .jGraduate_tab_lingrad'); - break; - - case 'radialGradient': - tab = $(idref + ' .jGraduate_tab_radgrad'); - break; - - default: - tab = $(idref + ' .jGraduate_tab_color'); - break; - } - - $this.show(); // jPicker will try to show after a 0ms timeout, so need to fire this after that - - setTimeout(function () { - tab.addClass('jGraduate_tab_current').click(); - }, 10); - }); - }; - - return $; -} - -/** - * SpinButton control. - * - * Adds bells and whistles to any ordinary textbox to - * make it look and feel like a SpinButton Control. - * - * Supplies {@link external:jQuery.fn.SpinButton} (and also {@link external:jQuery.loadingStylesheets}). - * - * Originally written by George Adamson, Software Unity (george.jquery@softwareunity.com) August 2006: - * - Added min/max options. - * - Added step size option. - * - Added bigStep (page up/down) option. - * - * Modifications made by Mark Gibson, (mgibson@designlinks.net) September 2006: - * - Converted to jQuery plugin. - * - Allow limited or unlimited min/max values. - * - Allow custom class names, and add class to input element. - * - Removed global vars. - * - Reset (to original or through config) when invalid value entered. - * - Repeat whilst holding mouse button down (with initial pause, like keyboard repeat). - * - Support mouse wheel in Firefox. - * - Fix double click in IE. - * - Refactored some code and renamed some vars. - * - * Modifications by Jeff Schiller, June 2009: - * - provide callback function for when the value changes based on the following - * {@link https://www.mail-archive.com/jquery-en@googlegroups.com/msg36070.html}. - * - * Modifications by Jeff Schiller, July 2009: - * - improve styling for widget in Opera. - * - consistent key-repeat handling cross-browser. - * - * Modifications by Alexis Deveria, October 2009: - * - provide "stepfunc" callback option to allow custom function to run when changing a value. - * - Made adjustValue(0) only run on certain keyup events, not all. - * - * Tested in IE6, Opera9, Firefox 1.5. - * - * | Version | Date | Author | Notes | - * |---------|------|--------|-------| - * | v1.0 | 11 Aug 2006 | George Adamson | First release | - * | v1.1 | Aug 2006 | George Adamson | Minor enhancements | - * | v1.2 | 27 Sep 2006 | Mark Gibson | Major enhancements | - * | v1.3a | 28 Sep 2006 | George Adamson | Minor enhancements | - * | v1.4 | 18 Jun 2009 | Jeff Schiller | Added callback function | - * | v1.5 | 06 Jul 2009 | Jeff Schiller | Fixes for Opera. | - * | v1.6 | 13 Oct 2009 | Alexis Deveria | Added stepfunc function | - * | v1.7 | 21 Oct 2009 | Alexis Deveria | Minor fixes.<br />Fast-repeat for keys and live updating as you type. | - * | v1.8 | 12 Jan 2010 | Benjamin Thomas | Fixes for mouseout behavior.<br />Added smallStep | - * | v1.9 | 20 May 2018 | Brett Zamir | Avoid SVGEdit dependency via `stateObj` config;<br />convert to ES6 module | - * . - * - * @module jQuerySpinButton - * @example - // Create group of settings to initialise spinbutton(s). (Optional) - const myOptions = { - min: 0, // Set lower limit. - max: 100, // Set upper limit. - step: 1, // Set increment size. - smallStep: 0.5, // Set shift-click increment size. - stateObj: {tool_scale: 1}, // Object to allow passing in live-updating scale - spinClass: mySpinBtnClass, // CSS class to style the spinbutton. (Class also specifies url of the up/down button image.) - upClass: mySpinUpClass, // CSS class for style when mouse over up button. - downClass: mySpinDnClass // CSS class for style when mouse over down button. - }; - - $(function () { - // Initialise INPUT element(s) as SpinButtons: (passing options if desired) - $('#myInputElement').SpinButton(myOptions); - }); - */ - -/** - * @function module:jQuerySpinButton.jQuerySpinButton - * @param {external:jQuery} $ The jQuery object to which to add the plug-in - * @returns {external:jQuery} -*/ -function jQueryPluginSpinButton($) { - if (!$.loadingStylesheets) { - $.loadingStylesheets = []; - } - - var stylesheet = 'spinbtn/jQuery.SpinButton.css'; - - if (!$.loadingStylesheets.includes(stylesheet)) { - $.loadingStylesheets.push(stylesheet); - } - /** - * @callback module:jQuerySpinButton.StepCallback - * @param {external:jQuery} thisArg Value of `this` - * @param {Float} i Value to adjust - * @returns {Float} - */ - - /** - * @callback module:jQuerySpinButton.ValueCallback - * @param {external:jQuery.fn.SpinButton} thisArg Spin Button; check its `value` to see how it was changed. - * @returns {void} - */ - - /** - * @typedef {PlainObject} module:jQuerySpinButton.SpinButtonConfig - * @property {Float} min Set lower limit - * @property {Float} max Set upper limit. - * @property {Float} step Set increment size. - * @property {module:jQuerySpinButton.StepCallback} stepfunc Custom function to run when changing a value; called with `this` of object and the value to adjust and returns a float. - * @property {module:jQuerySpinButton.ValueCallback} callback Called after value adjusted (with `this` of object) - * @property {Float} smallStep Set shift-click increment size. - * @property {PlainObject} stateObj Object to allow passing in live-updating scale - * @property {Float} stateObj.tool_scale - * @property {string} spinClass CSS class to style the spinbutton. (Class also specifies url of the up/down button image.) - * @property {string} upClass CSS class for style when mouse over up button. - * @property {string} downClass CSS class for style when mouse over down button. - * @property {Float} page Value to be adjusted on page up/page down - * @property {Float} reset Reset value when invalid value entered - * @property {Float} delay Millisecond delay - * @property {Float} interval Millisecond interval - */ - - /** - * @function external:jQuery.fn.SpinButton - * @param {module:jQuerySpinButton.SpinButtonConfig} cfg - * @returns {external:jQuery} - */ - - - $.fn.SpinButton = function (cfg) { - cfg = cfg || {}; - /** - * - * @param {Element} el - * @param {"offsetLeft"|"offsetTop"} prop - * @returns {Integer} - */ - - function coord(el, prop) { - var b = document.body; - var c = el[prop]; - - while ((el = el.offsetParent) && el !== b) { - if (!$.browser.msie || el.currentStyle.position !== 'relative') { - c += el[prop]; - } - } - - return c; - } - - return this.each(function () { - this.repeating = false; // Apply specified options or defaults: - // (Ought to refactor this some day to use $.extend() instead) - - this.spinCfg = { - // min: cfg.min ? Number(cfg.min) : null, - // max: cfg.max ? Number(cfg.max) : null, - min: !isNaN(Number.parseFloat(cfg.min)) ? Number(cfg.min) : null, - // Fixes bug with min:0 - max: !isNaN(Number.parseFloat(cfg.max)) ? Number(cfg.max) : null, - step: cfg.step ? Number(cfg.step) : 1, - stepfunc: cfg.stepfunc || false, - page: cfg.page ? Number(cfg.page) : 10, - upClass: cfg.upClass || 'up', - downClass: cfg.downClass || 'down', - reset: cfg.reset || this.value, - delay: cfg.delay ? Number(cfg.delay) : 500, - interval: cfg.interval ? Number(cfg.interval) : 100, - _btn_width: 20, - _direction: null, - _delay: null, - _repeat: null, - callback: cfg.callback || null - }; // if a smallStep isn't supplied, use half the regular step - - this.spinCfg.smallStep = cfg.smallStep || this.spinCfg.step / 2; - - this.adjustValue = function (i) { - var v; - - if (isNaN(this.value)) { - v = this.spinCfg.reset; - } else if (typeof this.spinCfg.stepfunc === 'function') { - v = this.spinCfg.stepfunc(this, i); - } else { - // weirdest JavaScript bug ever: 5.1 + 0.1 = 5.199999999 - v = Number((Number(this.value) + Number(i)).toFixed(5)); - } - - if (this.spinCfg.min !== null) { - v = Math.max(v, this.spinCfg.min); - } - - if (this.spinCfg.max !== null) { - v = Math.min(v, this.spinCfg.max); - } - - this.value = v; - - if (typeof this.spinCfg.callback === 'function') { - this.spinCfg.callback(this); - } - }; - - $(this).addClass(cfg.spinClass || 'spin-button').mousemove(function (e) { - // Determine which button mouse is over, or not (spin direction): - var x = e.pageX || e.x; - var y = e.pageY || e.y; - var el = e.target; - var scale = cfg.stateObj.tool_scale || 1; - var height = $(el).height() / 2; - var direction = x > coord(el, 'offsetLeft') + el.offsetWidth * scale - this.spinCfg._btn_width ? y < coord(el, 'offsetTop') + height * scale ? 1 : -1 : 0; - - if (direction !== this.spinCfg._direction) { - // Style up/down buttons: - switch (direction) { - case 1: - // Up arrow: - $(this).removeClass(this.spinCfg.downClass).addClass(this.spinCfg.upClass); - break; - - case -1: - // Down arrow: - $(this).removeClass(this.spinCfg.upClass).addClass(this.spinCfg.downClass); - break; - - default: - // Mouse is elsewhere in the textbox - $(this).removeClass(this.spinCfg.upClass).removeClass(this.spinCfg.downClass); - } // Set spin direction: - - - this.spinCfg._direction = direction; - } - }).mouseout(function () { - // Reset up/down buttons to their normal appearance when mouse moves away: - $(this).removeClass(this.spinCfg.upClass).removeClass(this.spinCfg.downClass); - this.spinCfg._direction = null; - window.clearInterval(this.spinCfg._repeat); - window.clearTimeout(this.spinCfg._delay); - }).mousedown(function (e) { - var _this = this; - - if (e.button === 0 && this.spinCfg._direction !== 0) { - // Respond to click on one of the buttons: - var stepSize = e.shiftKey ? this.spinCfg.smallStep : this.spinCfg.step; - - var adjust = function adjust() { - _this.adjustValue(_this.spinCfg._direction * stepSize); - }; - - adjust(); // Initial delay before repeating adjustment - - this.spinCfg._delay = window.setTimeout(function () { - adjust(); // Repeat adjust at regular intervals - - _this.spinCfg._repeat = window.setInterval(adjust, _this.spinCfg.interval); - }, this.spinCfg.delay); - } - }).mouseup(function (e) { - // Cancel repeating adjustment - window.clearInterval(this.spinCfg._repeat); - window.clearTimeout(this.spinCfg._delay); - }).dblclick(function (e) { - if ($.browser.msie) { - this.adjustValue(this.spinCfg._direction * this.spinCfg.step); - } - }).keydown(function (e) { - // Respond to up/down arrow keys. - switch (e.keyCode) { - case 38: - this.adjustValue(this.spinCfg.step); - break; - // Up - - case 40: - this.adjustValue(-this.spinCfg.step); - break; - // Down - - case 33: - this.adjustValue(this.spinCfg.page); - break; - // PageUp - - case 34: - this.adjustValue(-this.spinCfg.page); - break; - // PageDown - } - }) - /* - http://unixpapa.com/js/key.html describes the current state-of-affairs for - key repeat events: - - Safari 3.1 changed their model so that keydown is reliably repeated going forward - - Firefox and Opera still only repeat the keypress event, not the keydown - */ - .keypress(function (e) { - if (this.repeating) { - // Respond to up/down arrow keys. - switch (e.keyCode) { - case 38: - this.adjustValue(this.spinCfg.step); - break; - // Up - - case 40: - this.adjustValue(-this.spinCfg.step); - break; - // Down - - case 33: - this.adjustValue(this.spinCfg.page); - break; - // PageUp - - case 34: - this.adjustValue(-this.spinCfg.page); - break; - // PageDown - } // we always ignore the first keypress event (use the keydown instead) - - } else { - this.repeating = true; - } - }) // clear the 'repeating' flag - .keyup(function (e) { - this.repeating = false; - - switch (e.keyCode) { - case 38: // Up - - case 40: // Down - - case 33: // PageUp - - case 34: // PageDown - - case 13: - this.adjustValue(0); - break; - // Enter/Return - } - }).bind('mousewheel', function (e) { - // Respond to mouse wheel in IE. (It returns up/dn motion in multiples of 120) - if (e.wheelDelta >= 120) { - this.adjustValue(this.spinCfg.step); - } else if (e.wheelDelta <= -120) { - this.adjustValue(-this.spinCfg.step); - } - - e.preventDefault(); - }).change(function (e) { - this.adjustValue(0); - }); - - if (this.addEventListener) { - // Respond to mouse wheel in Firefox - this.addEventListener('DOMMouseScroll', function (e) { - if (e.detail > 0) { - this.adjustValue(-this.spinCfg.step); - } else if (e.detail < 0) { - this.adjustValue(this.spinCfg.step); - } - - e.preventDefault(); - }); - } - }); - }; - - return $; -} - -/** -* @callback module:jQueryContextMenu.jQueryContextMenuListener -* @param {string} href The `href` value after the first character (for bypassing an initial `#`) -* @param {external:jQuery} srcElement The wrapped jQuery srcElement -* @param {{x: Float, y: Float, docX: Float, docY: Float}} coords -* @returns {void} -*/ - -/** -* @typedef {PlainObject} module:jQueryContextMenu.jQueryContextMenuConfig -* @property {string} menu -* @property {Float} inSpeed -* @property {Float} outSpeed -* @property {boolean} allowLeft -*/ - -/** -* Adds {@link external:jQuery.fn.contextMenu}, -* {@link external:jQuery.fn.disableContextMenuItems}, -* {@link external:jQuery.fn.enableContextMenuItems}, -* {@link external:jQuery.fn.disableContextMenu}, -* {@link external:jQuery.fn.enableContextMenu}, -* {@link external:jQuery.fn.destroyContextMenu}. -* @function module:jQueryContextMenu.jQueryContextMenu -* @param {external:jQuery} $ The jQuery object to wrap (with `contextMenu`, `disableContextMenuItems`, `enableContextMenuItems`, `disableContextMenu`, `enableContextMenu`, `destroyContextMenu`) -* @returns {external:jQuery} -*/ - -function jQueryContextMenu($) { - var win = $(window); - var doc = $(document); - $.extend($.fn, { - /** - * @memberof external:jQuery.fn - * @param {module:jQueryContextMenu.jQueryContextMenuConfig} o - * @param {module:jQueryContextMenu.jQueryContextMenuListener} listener - * @returns {external:jQuery} - */ - contextMenu: function contextMenu(o, listener) { - // Defaults - if (o.menu === undefined) return false; - if (o.inSpeed === undefined) o.inSpeed = 150; - if (o.outSpeed === undefined) o.outSpeed = 75; // 0 needs to be -1 for expected results (no fade) - - if (o.inSpeed === 0) o.inSpeed = -1; - if (o.outSpeed === 0) o.outSpeed = -1; // Loop each context menu - - $(this).each(function () { - var el = $(this); - var offset = $(el).offset(); - var menu = $('#' + o.menu); // Add contextMenu class - - menu.addClass('contextMenu'); // Simulate a true right click - - $(this).bind('mousedown', function (evt) { - $(this).mouseup(function (e) { - var srcElement = $(this); - srcElement.unbind('mouseup'); - - if (!(evt.button === 2 || o.allowLeft || evt.ctrlKey && isMac())) { - return undefined; - } - - e.stopPropagation(); // Hide context menus that may be showing - - $('.contextMenu').hide(); // Get this context menu - - if (el.hasClass('disabled')) return false; // Detect mouse position - - var x = e.pageX, - y = e.pageY; - var xOff = win.width() - menu.width(), - yOff = win.height() - menu.height(); - if (x > xOff - 15) x = xOff - 15; - if (y > yOff - 30) y = yOff - 30; // 30 is needed to prevent scrollbars in FF - // Show the menu - - doc.unbind('click'); - menu.css({ - top: y, - left: x - }).fadeIn(o.inSpeed); // Hover events - - menu.find('A').mouseover(function () { - menu.find('LI.hover').removeClass('hover'); - $(this).parent().addClass('hover'); - }).mouseout(function () { - menu.find('LI.hover').removeClass('hover'); - }); // Keyboard - - doc.keypress(function (ev) { - switch (ev.keyCode) { - case 38: - // up - if (!menu.find('LI.hover').length) { - menu.find('LI:last').addClass('hover'); - } else { - menu.find('LI.hover').removeClass('hover').prevAll('LI:not(.disabled)').eq(0).addClass('hover'); - if (!menu.find('LI.hover').length) menu.find('LI:last').addClass('hover'); - } - - break; - - case 40: - // down - if (!menu.find('LI.hover').length) { - menu.find('LI:first').addClass('hover'); - } else { - menu.find('LI.hover').removeClass('hover').nextAll('LI:not(.disabled)').eq(0).addClass('hover'); - if (!menu.find('LI.hover').length) menu.find('LI:first').addClass('hover'); - } - - break; - - case 13: - // enter - menu.find('LI.hover A').trigger('click'); - break; - - case 27: - // esc - doc.trigger('click'); - break; - } - }); // When items are selected - - menu.find('A').unbind('mouseup'); - menu.find('LI:not(.disabled) A').mouseup(function () { - doc.unbind('click').unbind('keypress'); - $('.contextMenu').hide(); - - if (listener) { - listener($(this).attr('href').substr(1), $(srcElement), { - x: x - offset.left, - y: y - offset.top, - docX: x, - docY: y - }); - } - - return false; - }); // Hide bindings - - setTimeout(function () { - // Delay for Mozilla - doc.click(function () { - doc.unbind('click').unbind('keypress'); - menu.fadeOut(o.outSpeed); - return false; - }); - }, 0); - return undefined; - }); - }); // Disable text selection - - if ($.browser.mozilla) { - $('#' + o.menu).each(function () { - $(this).css({ - MozUserSelect: 'none' - }); - }); - } else if ($.browser.msie) { - $('#' + o.menu).each(function () { - $(this).bind('selectstart.disableTextSelect', function () { - return false; - }); - }); - } else { - $('#' + o.menu).each(function () { - $(this).bind('mousedown.disableTextSelect', function () { - return false; - }); - }); - } // Disable browser context menu (requires both selectors to work in IE/Safari + FF/Chrome) - - - $(el).add($('UL.contextMenu')).bind('contextmenu', function () { - return false; - }); - }); - return $(this); - }, - - /** - * Disable context menu items on the fly. - * @memberof external:jQuery.fn - * @param {void|string} o Comma-separated - * @returns {external:jQuery} - */ - disableContextMenuItems: function disableContextMenuItems(o) { - if (o === undefined) { - // Disable all - $(this).find('LI').addClass('disabled'); - return $(this); - } - - $(this).each(function () { - if (o !== undefined) { - var d = o.split(','); - - var _iterator = _createForOfIteratorHelper(d), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var href = _step.value; - $(this).find('A[href="' + href + '"]').parent().addClass('disabled'); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - }); - return $(this); - }, - - /** - * Enable context menu items on the fly. - * @memberof external:jQuery.fn - * @param {void|string} o Comma-separated - * @returns {external:jQuery} - */ - enableContextMenuItems: function enableContextMenuItems(o) { - if (o === undefined) { - // Enable all - $(this).find('LI.disabled').removeClass('disabled'); - return $(this); - } - - $(this).each(function () { - if (o !== undefined) { - var d = o.split(','); - - var _iterator2 = _createForOfIteratorHelper(d), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var href = _step2.value; - $(this).find('A[href="' + href + '"]').parent().removeClass('disabled'); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - }); - return $(this); - }, - - /** - * Disable context menu(s). - * @memberof external:jQuery.fn - * @returns {external:jQuery} - */ - disableContextMenu: function disableContextMenu() { - $(this).each(function () { - $(this).addClass('disabled'); - }); - return $(this); - }, - - /** - * Enable context menu(s). - * @memberof external:jQuery.fn - * @returns {external:jQuery} - */ - enableContextMenu: function enableContextMenu() { - $(this).each(function () { - $(this).removeClass('disabled'); - }); - return $(this); - }, - - /** - * Destroy context menu(s). - * @memberof external:jQuery.fn - * @returns {external:jQuery} - */ - destroyContextMenu: function destroyContextMenu() { - // Destroy specified context menus - $(this).each(function () { - // Disable action - $(this).unbind('mousedown').unbind('mouseup'); - }); - return $(this); - } - }); - return $; -} - -/* eslint-disable no-bitwise, max-len */ - -/** - * @file jPicker (Adapted from version 1.1.6) - * - * jQuery Plugin for Photoshop style color picker - * - * @module jPicker - * @copyright (c) 2010 Christopher T. Tillman - * Digital Magic Productions, Inc. ({@link http://www.digitalmagicpro.com/}) - * FREE to use, alter, copy, sell, and especially ENHANCE - * @license MIT - * - * Painstakingly ported from John Dyers' excellent work on his own color picker based on the Prototype framework. - * - * John Dyers' website: {@link http://johndyer.name} - * Color Picker page: {@link http://johndyer.name/photoshop-like-javascript-color-picker/} - */ - -/** -* @external Math -*/ - -/** -* @memberof external:Math -* @param {Float} value -* @param {Float} precision -* @returns {Float} -*/ -function toFixedNumeric(value, precision) { - if (precision === undefined) precision = 0; - return Math.round(value * Math.pow(10, precision)) / Math.pow(10, precision); -} -/** - * Whether a value is `null` or `undefined`. - * @param {any} val - * @returns {boolean} - */ - - -var isNullish$1 = function isNullish(val) { - return val === null || val === undefined; -}; -/** -* @function module:jPicker.jPicker -* @param {external:jQuery} $ The jQuery object to wrap (with {@link external:jQuery.loadingStylesheets}, {@link external:jQuery.fn.$.fn.jPicker}, {@link external:jQuery.fn.$.fn.jPicker.defaults}) -* @returns {external:jQuery} -*/ - - -var jPicker = function jPicker($) { - if (!$.loadingStylesheets) { - /** - * @name loadingStylesheets - * @type {string[]} - * @memberof external:jQuery - */ - $.loadingStylesheets = []; - } - - var stylesheet = 'jgraduate/css/jPicker.css'; - - if (!$.loadingStylesheets.includes(stylesheet)) { - $.loadingStylesheets.push(stylesheet); - } - /** - * @typedef {PlainObject} module:jPicker.SliderOptions - * @property {external:jQuery|PlainObject} arrow - * @property {string} arrow.image Not in use? - * @property {Float} arrow.width - * @property {Float} arrow.height - * @property {PlainObject} map - * @property {Float} map.width - * @property {Float} map.height - */ - - /** - * Encapsulate slider functionality for the ColorMap and ColorBar - - * could be useful to use a jQuery UI draggable for this with certain extensions. - * @memberof module:jPicker - */ - - - var Slider = - /** - * @param {external:jQuery} bar - * @param {module:jPicker.SliderOptions} options - */ - function Slider(bar, options) { - _classCallCheck(this, Slider); - - var that = this; - /** - * Fire events on the supplied `context` - * @param {module:jPicker.JPickerInit} context - * @returns {void} - */ - - function fireChangeEvents(context) { - changeEvents.forEach(function (changeEvent) { - changeEvent.call(that, that, context); - }); - } - /** - * Bind the mousedown to the bar not the arrow for quick snapping to the clicked location. - * @param {external:jQuery.Event} e - * @returns {void} - */ - - - function mouseDown(e) { - var off = bar.offset(); - offset = { - l: off.left | 0, - t: off.top | 0 - }; - clearTimeout(timeout); // using setTimeout for visual updates - once the style is updated the browser will re-render internally allowing the next Javascript to run - - timeout = setTimeout(function () { - setValuesFromMousePosition.call(that, e); - }, 0); // Bind mousemove and mouseup event to the document so it responds when dragged of of the bar - we will unbind these when on mouseup to save processing - - $(document).bind('mousemove', mouseMove).bind('mouseup', mouseUp); - e.preventDefault(); // don't try to select anything or drag the image to the desktop - } - /** - * Set the values as the mouse moves. - * @param {external:jQuery.Event} e - * @returns {false} - */ - - - function mouseMove(e) { - clearTimeout(timeout); - timeout = setTimeout(function () { - setValuesFromMousePosition.call(that, e); - }, 0); - e.stopPropagation(); - e.preventDefault(); - return false; - } - /** - * Unbind the document events - they aren't needed when not dragging. - * @param {external:jQuery.Event} e - * @returns {false} - */ - - - function mouseUp(e) { - $(document).unbind('mouseup', mouseUp).unbind('mousemove', mouseMove); - e.stopPropagation(); - e.preventDefault(); - return false; - } - /** - * Calculate mouse position and set value within the current range. - * @param {Event} e - * @returns {void} - */ - - - function setValuesFromMousePosition(e) { - var barW = bar.w, - // local copies for YUI compressor - barH = bar.h; - var locX = e.pageX - offset.l, - locY = e.pageY - offset.t; // keep the arrow within the bounds of the bar - - if (locX < 0) locX = 0;else if (locX > barW) locX = barW; - if (locY < 0) locY = 0;else if (locY > barH) locY = barH; - val.call(that, 'xy', { - x: locX / barW * rangeX + minX, - y: locY / barH * rangeY + minY - }); - } - /** - * - * @returns {void} - */ - - - function draw() { - var barW = bar.w, - barH = bar.h, - arrowW = arrow.w, - arrowH = arrow.h; - var arrowOffsetX = 0, - arrowOffsetY = 0; - setTimeout(function () { - if (rangeX > 0) { - // range is greater than zero - // constrain to bounds - if (x === maxX) arrowOffsetX = barW;else arrowOffsetX = x / rangeX * barW | 0; - } - - if (rangeY > 0) { - // range is greater than zero - // constrain to bounds - if (y === maxY) arrowOffsetY = barH;else arrowOffsetY = y / rangeY * barH | 0; - } // if arrow width is greater than bar width, center arrow and prevent horizontal dragging - - - if (arrowW >= barW) arrowOffsetX = (barW >> 1) - (arrowW >> 1); // number >> 1 - superfast bitwise divide by two and truncate (move bits over one bit discarding lowest) - else arrowOffsetX -= arrowW >> 1; // if arrow height is greater than bar height, center arrow and prevent vertical dragging - - if (arrowH >= barH) arrowOffsetY = (barH >> 1) - (arrowH >> 1);else arrowOffsetY -= arrowH >> 1; // set the arrow position based on these offsets - - arrow.css({ - left: arrowOffsetX + 'px', - top: arrowOffsetY + 'px' - }); - }); - } - /** - * Get or set a value. - * @param {?("xy"|"x"|"y")} name - * @param {module:math.XYObject} value - * @param {module:jPicker.Slider} context - * @returns {module:math.XYObject|Float|void} - */ - - - function val(name, value, context) { - var set = value !== undefined; - - if (!set) { - if (isNullish$1(name)) name = 'xy'; - - switch (name.toLowerCase()) { - case 'x': - return x; - - case 'y': - return y; - - case 'xy': - default: - return { - x: x, - y: y - }; - } - } - - if (!isNullish$1(context) && context === that) return undefined; - var changed = false; - var newX, newY; - if (isNullish$1(name)) name = 'xy'; - - switch (name.toLowerCase()) { - case 'x': - newX = value && (value.x && value.x | 0 || value | 0) || 0; - break; - - case 'y': - newY = value && (value.y && value.y | 0 || value | 0) || 0; - break; - - case 'xy': - default: - newX = value && value.x && value.x | 0 || 0; - newY = value && value.y && value.y | 0 || 0; - break; - } - - if (!isNullish$1(newX)) { - if (newX < minX) newX = minX;else if (newX > maxX) newX = maxX; - - if (x !== newX) { - x = newX; - changed = true; - } - } - - if (!isNullish$1(newY)) { - if (newY < minY) newY = minY;else if (newY > maxY) newY = maxY; - - if (y !== newY) { - y = newY; - changed = true; - } - } - - changed && fireChangeEvents.call(that, context || that); - return undefined; - } - /** - * @typedef {PlainObject} module:jPicker.MinMaxRangeX - * @property {Float} minX - * @property {Float} maxX - * @property {Float} rangeX - */ - - /** - * @typedef {PlainObject} module:jPicker.MinMaxRangeY - * @property {Float} minY - * @property {Float} maxY - * @property {Float} rangeY - */ - - /** - * @typedef {module:jPicker.MinMaxRangeY|module:jPicker.MinMaxRangeX} module:jPicker.MinMaxRangeXY - */ - - /** - * - * @param {"minx"|"maxx"|"rangex"|"miny"|"maxy"|"rangey"|"all"} name - * @param {module:jPicker.MinMaxRangeXY} value - * @returns {module:jPicker.MinMaxRangeXY|module:jPicker.MinMaxRangeX|module:jPicker.MinMaxRangeY|void} - */ - - - function range(name, value) { - var set = value !== undefined; - - if (!set) { - if (isNullish$1(name)) name = 'all'; - - switch (name.toLowerCase()) { - case 'minx': - return minX; - - case 'maxx': - return maxX; - - case 'rangex': - return { - minX: minX, - maxX: maxX, - rangeX: rangeX - }; - - case 'miny': - return minY; - - case 'maxy': - return maxY; - - case 'rangey': - return { - minY: minY, - maxY: maxY, - rangeY: rangeY - }; - - case 'all': - default: - return { - minX: minX, - maxX: maxX, - rangeX: rangeX, - minY: minY, - maxY: maxY, - rangeY: rangeY - }; - } - } - - var // changed = false, - newMinX, newMaxX, newMinY, newMaxY; - if (isNullish$1(name)) name = 'all'; - - switch (name.toLowerCase()) { - case 'minx': - newMinX = value && (value.minX && value.minX | 0 || value | 0) || 0; - break; - - case 'maxx': - newMaxX = value && (value.maxX && value.maxX | 0 || value | 0) || 0; - break; - - case 'rangex': - newMinX = value && value.minX && value.minX | 0 || 0; - newMaxX = value && value.maxX && value.maxX | 0 || 0; - break; - - case 'miny': - newMinY = value && (value.minY && value.minY | 0 || value | 0) || 0; - break; - - case 'maxy': - newMaxY = value && (value.maxY && value.maxY | 0 || value | 0) || 0; - break; - - case 'rangey': - newMinY = value && value.minY && value.minY | 0 || 0; - newMaxY = value && value.maxY && value.maxY | 0 || 0; - break; - - case 'all': - default: - newMinX = value && value.minX && value.minX | 0 || 0; - newMaxX = value && value.maxX && value.maxX | 0 || 0; - newMinY = value && value.minY && value.minY | 0 || 0; - newMaxY = value && value.maxY && value.maxY | 0 || 0; - break; - } - - if (!isNullish$1(newMinX) && minX !== newMinX) { - minX = newMinX; - rangeX = maxX - minX; - } - - if (!isNullish$1(newMaxX) && maxX !== newMaxX) { - maxX = newMaxX; - rangeX = maxX - minX; - } - - if (!isNullish$1(newMinY) && minY !== newMinY) { - minY = newMinY; - rangeY = maxY - minY; - } - - if (!isNullish$1(newMaxY) && maxY !== newMaxY) { - maxY = newMaxY; - rangeY = maxY - minY; - } - - return undefined; - } - /** - * @param {GenericCallback} callback - * @returns {void} - */ - - - function bind(callback) { - // eslint-disable-line promise/prefer-await-to-callbacks - if (typeof callback === 'function') changeEvents.push(callback); - } - /** - * @param {GenericCallback} callback - * @returns {void} - */ - - - function unbind(callback) { - // eslint-disable-line promise/prefer-await-to-callbacks - if (typeof callback !== 'function') return; - var i; - - while (i = changeEvents.includes(callback)) { - changeEvents.splice(i, 1); - } - } - /** - * - * @returns {void} - */ - - - function destroy() { - // unbind all possible events and null objects - $(document).unbind('mouseup', mouseUp).unbind('mousemove', mouseMove); - bar.unbind('mousedown', mouseDown); - bar = null; - arrow = null; - changeEvents = null; - } - - var offset, - timeout, - x = 0, - y = 0, - minX = 0, - maxX = 100, - rangeX = 100, - minY = 0, - maxY = 100, - rangeY = 100, - arrow = bar.find('img:first'), - // the arrow image to drag - changeEvents = []; - $.extend(true, // public properties, methods, and event bindings - these we need - // to access from other controls - that, { - val: val, - range: range, - bind: bind, - unbind: unbind, - destroy: destroy - }); // initialize this control - - arrow.src = options.arrow && options.arrow.image; - arrow.w = options.arrow && options.arrow.width || arrow.width(); - arrow.h = options.arrow && options.arrow.height || arrow.height(); - bar.w = options.map && options.map.width || bar.width(); - bar.h = options.map && options.map.height || bar.height(); // bind mousedown event - - bar.bind('mousedown', mouseDown); - bind.call(that, draw); - }; - /** - * Controls for all the input elements for the typing in color values. - */ - - - var ColorValuePicker = - /** - * @param {external:jQuery} picker - * @param {external:jQuery.jPicker.Color} color - * @param {external:jQuery.fn.$.fn.jPicker} bindedHex - * @param {Float} alphaPrecision - */ - function ColorValuePicker(picker, color, bindedHex, alphaPrecision) { - _classCallCheck(this, ColorValuePicker); - - var that = this; // private properties and methods - - var inputs = picker.find('td.Text input'); // input box key down - use arrows to alter color - - /** - * - * @param {Event} e - * @returns {Event|false|void} - */ - - function keyDown(e) { - if (e.target.value === '' && e.target !== hex.get(0) && (!isNullish$1(bindedHex) && e.target !== bindedHex.get(0) || isNullish$1(bindedHex))) return undefined; - if (!validateKey(e)) return e; - - switch (e.target) { - case red.get(0): - switch (e.keyCode) { - case 38: - red.val(setValueInRange.call(that, (red.val() << 0) + 1, 0, 255)); - color.val('r', red.val(), e.target); - return false; - - case 40: - red.val(setValueInRange.call(that, (red.val() << 0) - 1, 0, 255)); - color.val('r', red.val(), e.target); - return false; - } - - break; - - case green.get(0): - switch (e.keyCode) { - case 38: - green.val(setValueInRange.call(that, (green.val() << 0) + 1, 0, 255)); - color.val('g', green.val(), e.target); - return false; - - case 40: - green.val(setValueInRange.call(that, (green.val() << 0) - 1, 0, 255)); - color.val('g', green.val(), e.target); - return false; - } - - break; - - case blue.get(0): - switch (e.keyCode) { - case 38: - blue.val(setValueInRange.call(that, (blue.val() << 0) + 1, 0, 255)); - color.val('b', blue.val(), e.target); - return false; - - case 40: - blue.val(setValueInRange.call(that, (blue.val() << 0) - 1, 0, 255)); - color.val('b', blue.val(), e.target); - return false; - } - - break; - - case alpha && alpha.get(0): - switch (e.keyCode) { - case 38: - alpha.val(setValueInRange.call(that, Number.parseFloat(alpha.val()) + 1, 0, 100)); - color.val('a', toFixedNumeric(alpha.val() * 255 / 100, alphaPrecision), e.target); - return false; - - case 40: - alpha.val(setValueInRange.call(that, Number.parseFloat(alpha.val()) - 1, 0, 100)); - color.val('a', toFixedNumeric(alpha.val() * 255 / 100, alphaPrecision), e.target); - return false; - } - - break; - - case hue.get(0): - switch (e.keyCode) { - case 38: - hue.val(setValueInRange.call(that, (hue.val() << 0) + 1, 0, 360)); - color.val('h', hue.val(), e.target); - return false; - - case 40: - hue.val(setValueInRange.call(that, (hue.val() << 0) - 1, 0, 360)); - color.val('h', hue.val(), e.target); - return false; - } - - break; - - case saturation.get(0): - switch (e.keyCode) { - case 38: - saturation.val(setValueInRange.call(that, (saturation.val() << 0) + 1, 0, 100)); - color.val('s', saturation.val(), e.target); - return false; - - case 40: - saturation.val(setValueInRange.call(that, (saturation.val() << 0) - 1, 0, 100)); - color.val('s', saturation.val(), e.target); - return false; - } - - break; - - case value.get(0): - switch (e.keyCode) { - case 38: - value.val(setValueInRange.call(that, (value.val() << 0) + 1, 0, 100)); - color.val('v', value.val(), e.target); - return false; - - case 40: - value.val(setValueInRange.call(that, (value.val() << 0) - 1, 0, 100)); - color.val('v', value.val(), e.target); - return false; - } - - break; - } - - return undefined; - } // input box key up - validate value and set color - - /** - * @param {Event} e - * @returns {Event|void} - * @todo Why is this returning an event? - */ - - - function keyUp(e) { - if (e.target.value === '' && e.target !== hex.get(0) && (!isNullish$1(bindedHex) && e.target !== bindedHex.get(0) || isNullish$1(bindedHex))) return undefined; - if (!validateKey(e)) return e; - - switch (e.target) { - case red.get(0): - red.val(setValueInRange.call(that, red.val(), 0, 255)); - color.val('r', red.val(), e.target); - break; - - case green.get(0): - green.val(setValueInRange.call(that, green.val(), 0, 255)); - color.val('g', green.val(), e.target); - break; - - case blue.get(0): - blue.val(setValueInRange.call(that, blue.val(), 0, 255)); - color.val('b', blue.val(), e.target); - break; - - case alpha && alpha.get(0): - alpha.val(setValueInRange.call(that, alpha.val(), 0, 100)); - color.val('a', toFixedNumeric(alpha.val() * 255 / 100, alphaPrecision), e.target); - break; - - case hue.get(0): - hue.val(setValueInRange.call(that, hue.val(), 0, 360)); - color.val('h', hue.val(), e.target); - break; - - case saturation.get(0): - saturation.val(setValueInRange.call(that, saturation.val(), 0, 100)); - color.val('s', saturation.val(), e.target); - break; - - case value.get(0): - value.val(setValueInRange.call(that, value.val(), 0, 100)); - color.val('v', value.val(), e.target); - break; - - case hex.get(0): - hex.val(hex.val().replace(/[^a-fA-F\d]/g, '').toLowerCase().substring(0, 6)); - bindedHex && bindedHex.val(hex.val()); - color.val('hex', hex.val() !== '' ? hex.val() : null, e.target); - break; - - case bindedHex && bindedHex.get(0): - bindedHex.val(bindedHex.val().replace(/[^a-fA-F\d]/g, '').toLowerCase().substring(0, 6)); - hex.val(bindedHex.val()); - color.val('hex', bindedHex.val() !== '' ? bindedHex.val() : null, e.target); - break; - - case ahex && ahex.get(0): - ahex.val(ahex.val().replace(/[^a-fA-F\d]/g, '').toLowerCase().substring(0, 2)); - color.val('a', !isNullish$1(ahex.val()) ? Number.parseInt(ahex.val(), 16) : null, e.target); - break; - } - - return undefined; - } // input box blur - reset to original if value empty - - /** - * @param {Event} e - * @returns {void} - */ - - - function blur(e) { - if (!isNullish$1(color.val())) { - switch (e.target) { - case red.get(0): - red.val(color.val('r')); - break; - - case green.get(0): - green.val(color.val('g')); - break; - - case blue.get(0): - blue.val(color.val('b')); - break; - - case alpha && alpha.get(0): - alpha.val(toFixedNumeric(color.val('a') * 100 / 255, alphaPrecision)); - break; - - case hue.get(0): - hue.val(color.val('h')); - break; - - case saturation.get(0): - saturation.val(color.val('s')); - break; - - case value.get(0): - value.val(color.val('v')); - break; - - case hex.get(0): - case bindedHex && bindedHex.get(0): - hex.val(color.val('hex')); - bindedHex && bindedHex.val(color.val('hex')); - break; - - case ahex && ahex.get(0): - ahex.val(color.val('ahex').substring(6)); - break; - } - } - } - /** - * @param {Event} e - * @returns {boolean} - */ - - - function validateKey(e) { - switch (e.keyCode) { - case 9: - case 16: - case 29: - case 37: - case 39: - return false; - - case 'c'.charCodeAt(): - case 'v'.charCodeAt(): - if (e.ctrlKey) return false; - } - - return true; - } - /** - * Constrain value within range. - * @param {Float|string} value - * @param {Float} min - * @param {Float} max - * @returns {Float|string} Returns a number or numeric string - */ - - - function setValueInRange(value, min, max) { - if (value === '' || isNaN(value)) return min; - if (value > max) return max; - if (value < min) return min; - return value; - } - /** - * @param {external:jQuery} ui - * @param {Element} context - * @returns {void} - */ - - - function colorChanged(ui, context) { - var all = ui.val('all'); - if (context !== red.get(0)) red.val(!isNullish$1(all) ? all.r : ''); - if (context !== green.get(0)) green.val(!isNullish$1(all) ? all.g : ''); - if (context !== blue.get(0)) blue.val(!isNullish$1(all) ? all.b : ''); - if (alpha && context !== alpha.get(0)) alpha.val(!isNullish$1(all) ? toFixedNumeric(all.a * 100 / 255, alphaPrecision) : ''); - if (context !== hue.get(0)) hue.val(!isNullish$1(all) ? all.h : ''); - if (context !== saturation.get(0)) saturation.val(!isNullish$1(all) ? all.s : ''); - if (context !== value.get(0)) value.val(!isNullish$1(all) ? all.v : ''); - if (context !== hex.get(0) && (bindedHex && context !== bindedHex.get(0) || !bindedHex)) hex.val(!isNullish$1(all) ? all.hex : ''); - if (bindedHex && context !== bindedHex.get(0) && context !== hex.get(0)) bindedHex.val(!isNullish$1(all) ? all.hex : ''); - if (ahex && context !== ahex.get(0)) ahex.val(!isNullish$1(all) ? all.ahex.substring(6) : ''); - } - /** - * Unbind all events and null objects. - * @returns {void} - */ - - - function destroy() { - red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).add(hex).add(bindedHex).add(ahex).unbind('keyup', keyUp).unbind('blur', blur); - red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).unbind('keydown', keyDown); - color.unbind(colorChanged); - red = null; - green = null; - blue = null; - alpha = null; - hue = null; - saturation = null; - value = null; - hex = null; - ahex = null; - } - - var red = inputs.eq(3), - green = inputs.eq(4), - blue = inputs.eq(5), - alpha = inputs.length > 7 ? inputs.eq(6) : null, - hue = inputs.eq(0), - saturation = inputs.eq(1), - value = inputs.eq(2), - hex = inputs.eq(inputs.length > 7 ? 7 : 6), - ahex = inputs.length > 7 ? inputs.eq(8) : null; - $.extend(true, that, { - // public properties and methods - destroy: destroy - }); - red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).add(hex).add(bindedHex).add(ahex).bind('keyup', keyUp).bind('blur', blur); - red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).bind('keydown', keyDown); - color.bind(colorChanged); - }; - /** - * @typedef {PlainObject} module:jPicker.JPickerInit - * @property {Integer} [a] - * @property {Integer} [b] - * @property {Integer} [g] - * @property {Integer} [h] - * @property {Integer} [r] - * @property {Integer} [s] - * @property {Integer} [v] - * @property {string} [hex] - * @property {string} [ahex] - */ - - /* eslint-disable jsdoc/require-property */ - - /** - * @namespace {PlainObject} jPicker - * @memberof external:jQuery - */ - - - $.jPicker = - /** @lends external:jQuery.jPicker */ - { - /* eslint-enable jsdoc/require-property */ - - /** - * Array holding references to each active instance of the jPicker control. - * @type {external:jQuery.fn.$.fn.jPicker[]} - */ - List: [], - - /** - * Color object - we will be able to assign by any color space type or - * retrieve any color space info. - * We want this public so we can optionally assign new color objects to - * initial values using inputs other than a string hex value (also supported) - * Note: JSDoc didn't document when expressed here as an ES6 Class. - * @namespace - * @class - * @memberof external:jQuery.jPicker - * @param {module:jPicker.JPickerInit} init - * @returns {external:jQuery.jPicker.Color} - */ - Color: function Color(init) { - // eslint-disable-line object-shorthand - var that = this; - /** - * - * @param {module:jPicker.Slider} context - * @returns {void} - */ - - function fireChangeEvents(context) { - for (var i = 0; i < changeEvents.length; i++) { - changeEvents[i].call(that, that, context); - } - } - /** - * @param {string|"ahex"|"hex"|"all"|""|null|void} name String composed of letters "r", "g", "b", "a", "h", "s", and/or "v" - * @param {module:jPicker.RGBA|module:jPicker.JPickerInit|string} [value] - * @param {external:jQuery.jPicker.Color} context - * @returns {module:jPicker.JPickerInit|string|null|void} - */ - - - function val(name, value, context) { - // Kind of ugly - var set = Boolean(value); - if (set && value.ahex === '') value.ahex = '00000000'; - - if (!set) { - var ret; - if (isNullish$1(name) || name === '') name = 'all'; - if (isNullish$1(r)) return null; - - switch (name.toLowerCase()) { - case 'ahex': - return ColorMethods.rgbaToHex({ - r: r, - g: g, - b: b, - a: a - }); - - case 'hex': - return val('ahex').substring(0, 6); - - case 'all': - return { - r: r, - g: g, - b: b, - a: a, - h: h, - s: s, - v: v, - hex: val.call(that, 'hex'), - ahex: val.call(that, 'ahex') - }; - - default: - { - ret = {}; - var nameLength = name.length; - - _toConsumableArray(name).forEach(function (ch) { - switch (ch) { - case 'r': - if (nameLength === 1) ret = r;else ret.r = r; - break; - - case 'g': - if (nameLength === 1) ret = g;else ret.g = g; - break; - - case 'b': - if (nameLength === 1) ret = b;else ret.b = b; - break; - - case 'a': - if (nameLength === 1) ret = a;else ret.a = a; - break; - - case 'h': - if (nameLength === 1) ret = h;else ret.h = h; - break; - - case 's': - if (nameLength === 1) ret = s;else ret.s = s; - break; - - case 'v': - if (nameLength === 1) ret = v;else ret.v = v; - break; - } - }); - } - } - - return _typeof(ret) === 'object' && !Object.keys(ret).length ? val.call(that, 'all') : ret; - } - - if (!isNullish$1(context) && context === that) return undefined; - if (isNullish$1(name)) name = ''; - var changed = false; - - if (isNullish$1(value)) { - if (!isNullish$1(r)) { - r = null; - changed = true; - } - - if (!isNullish$1(g)) { - g = null; - changed = true; - } - - if (!isNullish$1(b)) { - b = null; - changed = true; - } - - if (!isNullish$1(a)) { - a = null; - changed = true; - } - - if (!isNullish$1(h)) { - h = null; - changed = true; - } - - if (!isNullish$1(s)) { - s = null; - changed = true; - } - - if (!isNullish$1(v)) { - v = null; - changed = true; - } - - changed && fireChangeEvents.call(that, context || that); - return undefined; - } - - switch (name.toLowerCase()) { - case 'ahex': - case 'hex': - { - var _ret = ColorMethods.hexToRgba(value && (value.ahex || value.hex) || value || 'none'); - - val.call(that, 'rgba', { - r: _ret.r, - g: _ret.g, - b: _ret.b, - a: name === 'ahex' ? _ret.a : !isNullish$1(a) ? a : 255 - }, context); - break; - } - - default: - { - if (value && (!isNullish$1(value.ahex) || !isNullish$1(value.hex))) { - val.call(that, 'ahex', value.ahex || value.hex || '00000000', context); - return undefined; - } - - var newV = {}; - var rgb = false, - hsv = false; - if (value.r !== undefined && !name.includes('r')) name += 'r'; - if (value.g !== undefined && !name.includes('g')) name += 'g'; - if (value.b !== undefined && !name.includes('b')) name += 'b'; - if (value.a !== undefined && !name.includes('a')) name += 'a'; - if (value.h !== undefined && !name.includes('h')) name += 'h'; - if (value.s !== undefined && !name.includes('s')) name += 's'; - if (value.v !== undefined && !name.includes('v')) name += 'v'; - - _toConsumableArray(name).forEach(function (ch) { - switch (ch) { - case 'r': - if (hsv) return; - rgb = true; - newV.r = value.r && value.r | 0 || value | 0 || 0; - if (newV.r < 0) newV.r = 0;else if (newV.r > 255) newV.r = 255; - - if (r !== newV.r) { - r = newV.r; - changed = true; - } - - break; - - case 'g': - if (hsv) return; - rgb = true; - newV.g = value && value.g && value.g | 0 || value && value | 0 || 0; - if (newV.g < 0) newV.g = 0;else if (newV.g > 255) newV.g = 255; - - if (g !== newV.g) { - g = newV.g; - changed = true; - } - - break; - - case 'b': - if (hsv) return; - rgb = true; - newV.b = value && value.b && value.b | 0 || value && value | 0 || 0; - if (newV.b < 0) newV.b = 0;else if (newV.b > 255) newV.b = 255; - - if (b !== newV.b) { - b = newV.b; - changed = true; - } - - break; - - case 'a': - newV.a = value && !isNullish$1(value.a) ? value.a | 0 : value | 0; - if (newV.a < 0) newV.a = 0;else if (newV.a > 255) newV.a = 255; - - if (a !== newV.a) { - a = newV.a; - changed = true; - } - - break; - - case 'h': - if (rgb) return; - hsv = true; - newV.h = value && value.h && value.h | 0 || value && value | 0 || 0; - if (newV.h < 0) newV.h = 0;else if (newV.h > 360) newV.h = 360; - - if (h !== newV.h) { - h = newV.h; - changed = true; - } - - break; - - case 's': - if (rgb) return; - hsv = true; - newV.s = !isNullish$1(value.s) ? value.s | 0 : value | 0; - if (newV.s < 0) newV.s = 0;else if (newV.s > 100) newV.s = 100; - - if (s !== newV.s) { - s = newV.s; - changed = true; - } - - break; - - case 'v': - if (rgb) return; - hsv = true; - newV.v = !isNullish$1(value.v) ? value.v | 0 : value | 0; - if (newV.v < 0) newV.v = 0;else if (newV.v > 100) newV.v = 100; - - if (v !== newV.v) { - v = newV.v; - changed = true; - } - - break; - } - }); - - if (changed) { - if (rgb) { - r = r || 0; - g = g || 0; - b = b || 0; - - var _ret2 = ColorMethods.rgbToHsv({ - r: r, - g: g, - b: b - }); - - h = _ret2.h; - s = _ret2.s; - v = _ret2.v; - } else if (hsv) { - h = h || 0; - s = !isNullish$1(s) ? s : 100; - v = !isNullish$1(v) ? v : 100; - - var _ret3 = ColorMethods.hsvToRgb({ - h: h, - s: s, - v: v - }); - - r = _ret3.r; - g = _ret3.g; - b = _ret3.b; - } - - a = !isNullish$1(a) ? a : 255; - fireChangeEvents.call(that, context || that); - } - - break; - } - } - - return undefined; - } - /** - * @param {GenericCallback} callback - * @returns {void} - */ - - - function bind(callback) { - // eslint-disable-line promise/prefer-await-to-callbacks - if (typeof callback === 'function') changeEvents.push(callback); - } - /** - * @param {GenericCallback} callback - * @returns {void} - */ - - - function unbind(callback) { - // eslint-disable-line promise/prefer-await-to-callbacks - if (typeof callback !== 'function') return; - var i; - - while (i = changeEvents.includes(callback)) { - changeEvents.splice(i, 1); - } - } - /** - * Unset `changeEvents` - * @returns {void} - */ - - - function destroy() { - changeEvents = null; - } - - var r, - g, - b, - a, - h, - s, - v, - changeEvents = []; - $.extend(true, that, { - // public properties and methods - val: val, - bind: bind, - unbind: unbind, - destroy: destroy - }); - - if (init) { - if (!isNullish$1(init.ahex)) { - val('ahex', init); - } else if (!isNullish$1(init.hex)) { - val((!isNullish$1(init.a) ? 'a' : '') + 'hex', !isNullish$1(init.a) ? { - ahex: init.hex + ColorMethods.intToHex(init.a) - } : init); - } else if (!isNullish$1(init.r) && !isNullish$1(init.g) && !isNullish$1(init.b)) { - val('rgb' + (!isNullish$1(init.a) ? 'a' : ''), init); - } else if (!isNullish$1(init.h) && !isNullish$1(init.s) && !isNullish$1(init.v)) { - val('hsv' + (!isNullish$1(init.a) ? 'a' : ''), init); - } - } - }, - - /** - * Color conversion methods - make public to give use to external scripts. - * @namespace - */ - ColorMethods: { - /** - * @typedef {PlainObject} module:jPicker.RGBA - * @property {Integer} r - * @property {Integer} g - * @property {Integer} b - * @property {Integer} a - */ - - /** - * @typedef {PlainObject} module:jPicker.RGB - * @property {Integer} r - * @property {Integer} g - * @property {Integer} b - */ - - /** - * @param {string} hex - * @returns {module:jPicker.RGBA} - */ - hexToRgba: function hexToRgba(hex) { - if (hex === '' || hex === 'none') return { - r: null, - g: null, - b: null, - a: null - }; - hex = this.validateHex(hex); - var r = '00', - g = '00', - b = '00', - a = '255'; - if (hex.length === 6) hex += 'ff'; - - if (hex.length > 6) { - r = hex.substring(0, 2); - g = hex.substring(2, 4); - b = hex.substring(4, 6); - a = hex.substring(6, hex.length); - } else { - if (hex.length > 4) { - r = hex.substring(4, hex.length); - hex = hex.substring(0, 4); - } - - if (hex.length > 2) { - g = hex.substring(2, hex.length); - hex = hex.substring(0, 2); - } - - if (hex.length > 0) b = hex.substring(0, hex.length); - } - - return { - r: this.hexToInt(r), - g: this.hexToInt(g), - b: this.hexToInt(b), - a: this.hexToInt(a) - }; - }, - - /** - * @param {string} hex - * @returns {string} - */ - validateHex: function validateHex(hex) { - // if (typeof hex === 'object') return ''; - hex = hex.toLowerCase().replace(/[^a-f\d]/g, ''); - if (hex.length > 8) hex = hex.substring(0, 8); - return hex; - }, - - /** - * @param {module:jPicker.RGBA} rgba - * @returns {string} - */ - rgbaToHex: function rgbaToHex(rgba) { - return this.intToHex(rgba.r) + this.intToHex(rgba.g) + this.intToHex(rgba.b) + this.intToHex(rgba.a); - }, - - /** - * @param {Integer} dec - * @returns {string} - */ - intToHex: function intToHex(dec) { - var result = (dec | 0).toString(16); - if (result.length === 1) result = '0' + result; - return result.toLowerCase(); - }, - - /** - * @param {string} hex - * @returns {Integer} - */ - hexToInt: function hexToInt(hex) { - return Number.parseInt(hex, 16); - }, - - /** - * @typedef {PlainObject} module:jPicker.HSV - * @property {Integer} h - * @property {Integer} s - * @property {Integer} v - */ - - /** - * @param {module:jPicker.RGB} rgb - * @returns {module:jPicker.HSV} - */ - rgbToHsv: function rgbToHsv(rgb) { - var r = rgb.r / 255, - g = rgb.g / 255, - b = rgb.b / 255, - hsv = { - h: 0, - s: 0, - v: 0 - }; - var min = 0, - max = 0; - - if (r >= g && r >= b) { - max = r; - min = g > b ? b : g; - } else if (g >= b && g >= r) { - max = g; - min = r > b ? b : r; - } else { - max = b; - min = g > r ? r : g; - } - - hsv.v = max; - hsv.s = max ? (max - min) / max : 0; - var delta; - if (!hsv.s) hsv.h = 0;else { - delta = max - min; - if (r === max) hsv.h = (g - b) / delta;else if (g === max) hsv.h = 2 + (b - r) / delta;else hsv.h = 4 + (r - g) / delta; - hsv.h = Number.parseInt(hsv.h * 60); - if (hsv.h < 0) hsv.h += 360; - } - hsv.s = hsv.s * 100 | 0; - hsv.v = hsv.v * 100 | 0; - return hsv; - }, - - /** - * @param {module:jPicker.HSV} hsv - * @returns {module:jPicker.RGB} - */ - hsvToRgb: function hsvToRgb(hsv) { - var rgb = { - r: 0, - g: 0, - b: 0, - a: 100 - }; - var h = hsv.h, - s = hsv.s, - v = hsv.v; - - if (s === 0) { - if (v === 0) rgb.r = rgb.g = rgb.b = 0;else rgb.r = rgb.g = rgb.b = v * 255 / 100 | 0; - } else { - if (h === 360) h = 0; - h /= 60; - s /= 100; - v /= 100; - var i = h | 0, - f = h - i, - p = v * (1 - s), - q = v * (1 - s * f), - t = v * (1 - s * (1 - f)); - - switch (i) { - case 0: - rgb.r = v; - rgb.g = t; - rgb.b = p; - break; - - case 1: - rgb.r = q; - rgb.g = v; - rgb.b = p; - break; - - case 2: - rgb.r = p; - rgb.g = v; - rgb.b = t; - break; - - case 3: - rgb.r = p; - rgb.g = q; - rgb.b = v; - break; - - case 4: - rgb.r = t; - rgb.g = p; - rgb.b = v; - break; - - case 5: - rgb.r = v; - rgb.g = p; - rgb.b = q; - break; - } - - rgb.r = rgb.r * 255 | 0; - rgb.g = rgb.g * 255 | 0; - rgb.b = rgb.b * 255 | 0; - } - - return rgb; - } - } - }; - var _$$jPicker = $.jPicker, - Color = _$$jPicker.Color, - List = _$$jPicker.List, - ColorMethods = _$$jPicker.ColorMethods; // local copies for YUI compressor - - /* eslint-disable jsdoc/require-returns */ - - /** - * @function external:jQuery.fn.jPicker - * @see {@link external:jQuery.fn.$.fn.jPicker} - */ - - /* eslint-enable jsdoc/require-returns */ - - /** - * Will be bound to active {@link jQuery.jPicker.Color}. - * @callback module:jPicker.LiveCallback - * @param {external:jQuery} ui - * @param {Element} context - * @returns {void} - */ - - /** - * @callback module:jPicker.CommitCallback - * @param {external:jQuery.jPicker.Color} activeColor - * @param {external:jQuery} okButton - * @returns {void} Return value not used. - */ - - /** - * @callback module:jPicker.CancelCallback - * @param {external:jQuery.jPicker.Color} activeColor - * @param {external:jQuery} cancelButton - * @returns {void} Return value not used. - */ - - /** - * While it would seem this should specify the name `jPicker` for JSDoc, that doesn't - * get us treated as a function as well as a namespace (even with `@function name`), - * so we use an approach to add a redundant `$.fn.` in the name. - * @namespace - * @memberof external:jQuery.fn - * @param {external:jQuery.fn.jPickerOptions} options - * @param {module:jPicker.CommitCallback} [commitCallback] - * @param {module:jPicker.LiveCallback} [liveCallback] - * @param {module:jPicker.CancelCallback} [cancelCallback] - * @returns {external:jQuery} - */ - - $.fn.jPicker = function (options, commitCallback, liveCallback, cancelCallback) { - return this.each(function () { - var that = this, - settings = $.extend(true, {}, $.fn.jPicker.defaults, options); // local copies for YUI compressor - - if ($(that).get(0).nodeName.toLowerCase() === 'input') { - // Add color picker icon if binding to an input element and bind the events to the input - $.extend(true, settings, { - window: { - bindToInput: true, - expandable: true, - input: $(that) - } - }); - - if ($(that).val() === '') { - settings.color.active = new Color({ - hex: null - }); - settings.color.current = new Color({ - hex: null - }); - } else if (ColorMethods.validateHex($(that).val())) { - settings.color.active = new Color({ - hex: $(that).val(), - a: settings.color.active.val('a') - }); - settings.color.current = new Color({ - hex: $(that).val(), - a: settings.color.active.val('a') - }); - } - } - - if (settings.window.expandable) { - $(that).after('<span class="jPicker"><span class="Icon"><span class="Color"> </span><span class="Alpha"> </span><span class="Image" title="Click To Open Color Picker"> </span><span class="Container"> </span></span></span>'); - } else { - settings.window.liveUpdate = false; // Basic control binding for inline use - You will need to override the liveCallback or commitCallback function to retrieve results - } - - var isLessThanIE7 = Number.parseFloat(navigator.appVersion.split('MSIE')[1]) < 7 && document.body.filters; // needed to run the AlphaImageLoader function for IE6 - // set color mode and update visuals for the new color mode - - /** - * - * @param {"h"|"s"|"v"|"r"|"g"|"b"|"a"} colorMode - * @throws {Error} Invalid mode - * @returns {void} - */ - - function setColorMode(colorMode) { - var active = color.active, - hex = active.val('hex'); - var rgbMap, rgbBar; - settings.color.mode = colorMode; - - switch (colorMode) { - case 'h': - setTimeout(function () { - setBG.call(that, colorMapDiv, 'transparent'); - setImgLoc.call(that, colorMapL1, 0); - setAlpha.call(that, colorMapL1, 100); - setImgLoc.call(that, colorMapL2, 260); - setAlpha.call(that, colorMapL2, 100); - setBG.call(that, colorBarDiv, 'transparent'); - setImgLoc.call(that, colorBarL1, 0); - setAlpha.call(that, colorBarL1, 100); - setImgLoc.call(that, colorBarL2, 260); - setAlpha.call(that, colorBarL2, 100); - setImgLoc.call(that, colorBarL3, 260); - setAlpha.call(that, colorBarL3, 100); - setImgLoc.call(that, colorBarL4, 260); - setAlpha.call(that, colorBarL4, 100); - setImgLoc.call(that, colorBarL6, 260); - setAlpha.call(that, colorBarL6, 100); - }, 0); - colorMap.range('all', { - minX: 0, - maxX: 100, - minY: 0, - maxY: 100 - }); - colorBar.range('rangeY', { - minY: 0, - maxY: 360 - }); - if (isNullish$1(active.val('ahex'))) break; - colorMap.val('xy', { - x: active.val('s'), - y: 100 - active.val('v') - }, colorMap); - colorBar.val('y', 360 - active.val('h'), colorBar); - break; - - case 's': - setTimeout(function () { - setBG.call(that, colorMapDiv, 'transparent'); - setImgLoc.call(that, colorMapL1, -260); - setImgLoc.call(that, colorMapL2, -520); - setImgLoc.call(that, colorBarL1, -260); - setImgLoc.call(that, colorBarL2, -520); - setImgLoc.call(that, colorBarL6, 260); - setAlpha.call(that, colorBarL6, 100); - }, 0); - colorMap.range('all', { - minX: 0, - maxX: 360, - minY: 0, - maxY: 100 - }); - colorBar.range('rangeY', { - minY: 0, - maxY: 100 - }); - if (isNullish$1(active.val('ahex'))) break; - colorMap.val('xy', { - x: active.val('h'), - y: 100 - active.val('v') - }, colorMap); - colorBar.val('y', 100 - active.val('s'), colorBar); - break; - - case 'v': - setTimeout(function () { - setBG.call(that, colorMapDiv, '000000'); - setImgLoc.call(that, colorMapL1, -780); - setImgLoc.call(that, colorMapL2, 260); - setBG.call(that, colorBarDiv, hex); - setImgLoc.call(that, colorBarL1, -520); - setImgLoc.call(that, colorBarL2, 260); - setAlpha.call(that, colorBarL2, 100); - setImgLoc.call(that, colorBarL6, 260); - setAlpha.call(that, colorBarL6, 100); - }, 0); - colorMap.range('all', { - minX: 0, - maxX: 360, - minY: 0, - maxY: 100 - }); - colorBar.range('rangeY', { - minY: 0, - maxY: 100 - }); - if (isNullish$1(active.val('ahex'))) break; - colorMap.val('xy', { - x: active.val('h'), - y: 100 - active.val('s') - }, colorMap); - colorBar.val('y', 100 - active.val('v'), colorBar); - break; - - case 'r': - rgbMap = -1040; - rgbBar = -780; - colorMap.range('all', { - minX: 0, - maxX: 255, - minY: 0, - maxY: 255 - }); - colorBar.range('rangeY', { - minY: 0, - maxY: 255 - }); - if (isNullish$1(active.val('ahex'))) break; - colorMap.val('xy', { - x: active.val('b'), - y: 255 - active.val('g') - }, colorMap); - colorBar.val('y', 255 - active.val('r'), colorBar); - break; - - case 'g': - rgbMap = -1560; - rgbBar = -1820; - colorMap.range('all', { - minX: 0, - maxX: 255, - minY: 0, - maxY: 255 - }); - colorBar.range('rangeY', { - minY: 0, - maxY: 255 - }); - if (isNullish$1(active.val('ahex'))) break; - colorMap.val('xy', { - x: active.val('b'), - y: 255 - active.val('r') - }, colorMap); - colorBar.val('y', 255 - active.val('g'), colorBar); - break; - - case 'b': - rgbMap = -2080; - rgbBar = -2860; - colorMap.range('all', { - minX: 0, - maxX: 255, - minY: 0, - maxY: 255 - }); - colorBar.range('rangeY', { - minY: 0, - maxY: 255 - }); - if (isNullish$1(active.val('ahex'))) break; - colorMap.val('xy', { - x: active.val('r'), - y: 255 - active.val('g') - }, colorMap); - colorBar.val('y', 255 - active.val('b'), colorBar); - break; - - case 'a': - setTimeout(function () { - setBG.call(that, colorMapDiv, 'transparent'); - setImgLoc.call(that, colorMapL1, -260); - setImgLoc.call(that, colorMapL2, -520); - setImgLoc.call(that, colorBarL1, 260); - setImgLoc.call(that, colorBarL2, 260); - setAlpha.call(that, colorBarL2, 100); - setImgLoc.call(that, colorBarL6, 0); - setAlpha.call(that, colorBarL6, 100); - }, 0); - colorMap.range('all', { - minX: 0, - maxX: 360, - minY: 0, - maxY: 100 - }); - colorBar.range('rangeY', { - minY: 0, - maxY: 255 - }); - if (isNullish$1(active.val('ahex'))) break; - colorMap.val('xy', { - x: active.val('h'), - y: 100 - active.val('v') - }, colorMap); - colorBar.val('y', 255 - active.val('a'), colorBar); - break; - - default: - throw new Error('Invalid Mode'); - } - - switch (colorMode) { - case 'h': - break; - - case 's': - case 'v': - case 'a': - setTimeout(function () { - setAlpha.call(that, colorMapL1, 100); - setAlpha.call(that, colorBarL1, 100); - setImgLoc.call(that, colorBarL3, 260); - setAlpha.call(that, colorBarL3, 100); - setImgLoc.call(that, colorBarL4, 260); - setAlpha.call(that, colorBarL4, 100); - }, 0); - break; - - case 'r': - case 'g': - case 'b': - setTimeout(function () { - setBG.call(that, colorMapDiv, 'transparent'); - setBG.call(that, colorBarDiv, 'transparent'); - setAlpha.call(that, colorBarL1, 100); - setAlpha.call(that, colorMapL1, 100); - setImgLoc.call(that, colorMapL1, rgbMap); - setImgLoc.call(that, colorMapL2, rgbMap - 260); - setImgLoc.call(that, colorBarL1, rgbBar - 780); - setImgLoc.call(that, colorBarL2, rgbBar - 520); - setImgLoc.call(that, colorBarL3, rgbBar); - setImgLoc.call(that, colorBarL4, rgbBar - 260); - setImgLoc.call(that, colorBarL6, 260); - setAlpha.call(that, colorBarL6, 100); - }, 0); - break; - } - - if (isNullish$1(active.val('ahex'))) return; - activeColorChanged.call(that, active); - } - /** - * Update color when user changes text values. - * @param {external:jQuery} ui - * @param {?module:jPicker.Slider} context - * @returns {void} - */ - - - function activeColorChanged(ui, context) { - if (isNullish$1(context) || context !== colorBar && context !== colorMap) positionMapAndBarArrows.call(that, ui, context); - setTimeout(function () { - updatePreview.call(that, ui); - updateMapVisuals.call(that, ui); - updateBarVisuals.call(that, ui); - }, 0); - } - /** - * User has dragged the ColorMap pointer. - * @param {external:jQuery} ui - * @param {?module:jPicker.Slider} context - * @returns {void} - */ - - - function mapValueChanged(ui, context) { - var active = color.active; - if (context !== colorMap && isNullish$1(active.val())) return; - var xy = ui.val('all'); - - switch (settings.color.mode) { - case 'h': - active.val('sv', { - s: xy.x, - v: 100 - xy.y - }, context); - break; - - case 's': - case 'a': - active.val('hv', { - h: xy.x, - v: 100 - xy.y - }, context); - break; - - case 'v': - active.val('hs', { - h: xy.x, - s: 100 - xy.y - }, context); - break; - - case 'r': - active.val('gb', { - g: 255 - xy.y, - b: xy.x - }, context); - break; - - case 'g': - active.val('rb', { - r: 255 - xy.y, - b: xy.x - }, context); - break; - - case 'b': - active.val('rg', { - r: xy.x, - g: 255 - xy.y - }, context); - break; - } - } - /** - * User has dragged the ColorBar slider. - * @param {external:jQuery} ui - * @param {?module:jPicker.Slider} context - * @returns {void} - */ - - - function colorBarValueChanged(ui, context) { - var active = color.active; - if (context !== colorBar && isNullish$1(active.val())) return; - - switch (settings.color.mode) { - case 'h': - active.val('h', { - h: 360 - ui.val('y') - }, context); - break; - - case 's': - active.val('s', { - s: 100 - ui.val('y') - }, context); - break; - - case 'v': - active.val('v', { - v: 100 - ui.val('y') - }, context); - break; - - case 'r': - active.val('r', { - r: 255 - ui.val('y') - }, context); - break; - - case 'g': - active.val('g', { - g: 255 - ui.val('y') - }, context); - break; - - case 'b': - active.val('b', { - b: 255 - ui.val('y') - }, context); - break; - - case 'a': - active.val('a', 255 - ui.val('y'), context); - break; - } - } - /** - * Position map and bar arrows to match current color. - * @param {external:jQuery} ui - * @param {?module:jPicker.Slider} context - * @returns {void} - */ - - - function positionMapAndBarArrows(ui, context) { - if (context !== colorMap) { - switch (settings.color.mode) { - case 'h': - { - var sv = ui.val('sv'); - colorMap.val('xy', { - x: !isNullish$1(sv) ? sv.s : 100, - y: 100 - (!isNullish$1(sv) ? sv.v : 100) - }, context); - break; - } - - case 's': // Fall through - - case 'a': - { - var hv = ui.val('hv'); - colorMap.val('xy', { - x: hv && hv.h || 0, - y: 100 - (!isNullish$1(hv) ? hv.v : 100) - }, context); - break; - } - - case 'v': - { - var hs = ui.val('hs'); - colorMap.val('xy', { - x: hs && hs.h || 0, - y: 100 - (!isNullish$1(hs) ? hs.s : 100) - }, context); - break; - } - - case 'r': - { - var bg = ui.val('bg'); - colorMap.val('xy', { - x: bg && bg.b || 0, - y: 255 - (bg && bg.g || 0) - }, context); - break; - } - - case 'g': - { - var br = ui.val('br'); - colorMap.val('xy', { - x: br && br.b || 0, - y: 255 - (br && br.r || 0) - }, context); - break; - } - - case 'b': - { - var rg = ui.val('rg'); - colorMap.val('xy', { - x: rg && rg.r || 0, - y: 255 - (rg && rg.g || 0) - }, context); - break; - } - } - } - - if (context !== colorBar) { - switch (settings.color.mode) { - case 'h': - colorBar.val('y', 360 - (ui.val('h') || 0), context); - break; - - case 's': - { - var s = ui.val('s'); - colorBar.val('y', 100 - (!isNullish$1(s) ? s : 100), context); - break; - } - - case 'v': - { - var v = ui.val('v'); - colorBar.val('y', 100 - (!isNullish$1(v) ? v : 100), context); - break; - } - - case 'r': - colorBar.val('y', 255 - (ui.val('r') || 0), context); - break; - - case 'g': - colorBar.val('y', 255 - (ui.val('g') || 0), context); - break; - - case 'b': - colorBar.val('y', 255 - (ui.val('b') || 0), context); - break; - - case 'a': - { - var a = ui.val('a'); - colorBar.val('y', 255 - (!isNullish$1(a) ? a : 255), context); - break; - } - } - } - } - /** - * @param {external:jQuery} ui - * @returns {void} - */ - - - function updatePreview(ui) { - try { - var all = ui.val('all'); - activePreview.css({ - backgroundColor: all && '#' + all.hex || 'transparent' - }); - setAlpha.call(that, activePreview, all && toFixedNumeric(all.a * 100 / 255, 4) || 0); - } catch (e) {} - } - /** - * @param {external:jQuery} ui - * @returns {void} - */ - - - function updateMapVisuals(ui) { - switch (settings.color.mode) { - case 'h': - setBG.call(that, colorMapDiv, new Color({ - h: ui.val('h') || 0, - s: 100, - v: 100 - }).val('hex')); - break; - - case 's': - case 'a': - { - var s = ui.val('s'); - setAlpha.call(that, colorMapL2, 100 - (!isNullish$1(s) ? s : 100)); - break; - } - - case 'v': - { - var v = ui.val('v'); - setAlpha.call(that, colorMapL1, !isNullish$1(v) ? v : 100); - break; - } - - case 'r': - setAlpha.call(that, colorMapL2, toFixedNumeric((ui.val('r') || 0) / 255 * 100, 4)); - break; - - case 'g': - setAlpha.call(that, colorMapL2, toFixedNumeric((ui.val('g') || 0) / 255 * 100, 4)); - break; - - case 'b': - setAlpha.call(that, colorMapL2, toFixedNumeric((ui.val('b') || 0) / 255 * 100)); - break; - } - - var a = ui.val('a'); - setAlpha.call(that, colorMapL3, toFixedNumeric((255 - (a || 0)) * 100 / 255, 4)); - } - /** - * @param {external:jQuery} ui - * @returns {void} - */ - - - function updateBarVisuals(ui) { - switch (settings.color.mode) { - case 'h': - { - var a = ui.val('a'); - setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (a || 0)) * 100 / 255, 4)); - break; - } - - case 's': - { - var hva = ui.val('hva'), - saturatedColor = new Color({ - h: hva && hva.h || 0, - s: 100, - v: !isNullish$1(hva) ? hva.v : 100 - }); - setBG.call(that, colorBarDiv, saturatedColor.val('hex')); - setAlpha.call(that, colorBarL2, 100 - (!isNullish$1(hva) ? hva.v : 100)); - setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (hva && hva.a || 0)) * 100 / 255, 4)); - break; - } - - case 'v': - { - var hsa = ui.val('hsa'), - valueColor = new Color({ - h: hsa && hsa.h || 0, - s: !isNullish$1(hsa) ? hsa.s : 100, - v: 100 - }); - setBG.call(that, colorBarDiv, valueColor.val('hex')); - setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (hsa && hsa.a || 0)) * 100 / 255, 4)); - break; - } - - case 'r': - case 'g': - case 'b': - { - var rgba = ui.val('rgba'); - var hValue = 0, - vValue = 0; - - if (settings.color.mode === 'r') { - hValue = rgba && rgba.b || 0; - vValue = rgba && rgba.g || 0; - } else if (settings.color.mode === 'g') { - hValue = rgba && rgba.b || 0; - vValue = rgba && rgba.r || 0; - } else if (settings.color.mode === 'b') { - hValue = rgba && rgba.r || 0; - vValue = rgba && rgba.g || 0; - } - - var middle = vValue > hValue ? hValue : vValue; - setAlpha.call(that, colorBarL2, hValue > vValue ? toFixedNumeric((hValue - vValue) / (255 - vValue) * 100, 4) : 0); - setAlpha.call(that, colorBarL3, vValue > hValue ? toFixedNumeric((vValue - hValue) / (255 - hValue) * 100, 4) : 0); - setAlpha.call(that, colorBarL4, toFixedNumeric(middle / 255 * 100, 4)); - setAlpha.call(that, colorBarL5, toFixedNumeric((255 - (rgba && rgba.a || 0)) * 100 / 255, 4)); - break; - } - - case 'a': - { - var _a = ui.val('a'); - - setBG.call(that, colorBarDiv, ui.val('hex') || '000000'); - setAlpha.call(that, colorBarL5, !isNullish$1(_a) ? 0 : 100); - setAlpha.call(that, colorBarL6, !isNullish$1(_a) ? 100 : 0); - break; - } - } - } - /** - * @param {external:jQuery} el - * @param {string} [c="transparent"] - * @returns {void} - */ - - - function setBG(el, c) { - el.css({ - backgroundColor: c && c.length === 6 && '#' + c || 'transparent' - }); - } - /** - * @param {external:jQuery} img - * @param {string} src The image source - * @returns {void} - */ - - - function setImg(img, src) { - if (isLessThanIE7 && (src.includes('AlphaBar.png') || src.includes('Bars.png') || src.includes('Maps.png'))) { - img.attr('pngSrc', src); - img.css({ - backgroundImage: 'none', - filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=\'scale\')' - }); - } else img.css({ - backgroundImage: 'url(\'' + src + '\')' - }); - } - /** - * @param {external:jQuery} img - * @param {Float} y - * @returns {void} - */ - - - function setImgLoc(img, y) { - img.css({ - top: y + 'px' - }); - } - /** - * @param {external:jQuery} obj - * @param {Float} alpha - * @returns {void} - */ - - - function setAlpha(obj, alpha) { - obj.css({ - visibility: alpha > 0 ? 'visible' : 'hidden' - }); - - if (alpha > 0 && alpha < 100) { - if (isLessThanIE7) { - var src = obj.attr('pngSrc'); - - if (!isNullish$1(src) && (src.includes('AlphaBar.png') || src.includes('Bars.png') || src.includes('Maps.png'))) { - obj.css({ - filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=\'scale\') progid:DXImageTransform.Microsoft.Alpha(opacity=' + alpha + ')' - }); - } else obj.css({ - opacity: toFixedNumeric(alpha / 100, 4) - }); - } else obj.css({ - opacity: toFixedNumeric(alpha / 100, 4) - }); - } else if (alpha === 0 || alpha === 100) { - if (isLessThanIE7) { - var _src = obj.attr('pngSrc'); - - if (!isNullish$1(_src) && (_src.includes('AlphaBar.png') || _src.includes('Bars.png') || _src.includes('Maps.png'))) { - obj.css({ - filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + _src + '\', sizingMethod=\'scale\')' - }); - } else obj.css({ - opacity: '' - }); - } else obj.css({ - opacity: '' - }); - } - } - /** - * Revert color to original color when opened. - * @returns {void} - */ - - - function revertColor() { - color.active.val('ahex', color.current.val('ahex')); - } - /** - * Commit the color changes. - * @returns {void} - */ - - - function commitColor() { - color.current.val('ahex', color.active.val('ahex')); - } - /** - * @param {Event} e - * @returns {void} - */ - - - function radioClicked(e) { - $(this).parents('tbody:first').find('input:radio[value!="' + e.target.value + '"]').removeAttr('checked'); - setColorMode.call(that, e.target.value); - } - /** - * - * @returns {void} - */ - - - function currentClicked() { - revertColor.call(that); - } - /** - * - * @returns {void} - */ - - - function cancelClicked() { - revertColor.call(that); - settings.window.expandable && hide.call(that); - typeof cancelCallback === 'function' && cancelCallback.call(that, color.active, cancelButton); - } - /** - * - * @returns {void} - */ - - - function okClicked() { - commitColor.call(that); - settings.window.expandable && hide.call(that); - typeof commitCallback === 'function' && commitCallback.call(that, color.active, okButton); - } - /** - * - * @returns {void} - */ - - - function iconImageClicked() { - show.call(that); - } - /** - * @param {external:jQuery} ui - * @returns {void} - */ - - - function currentColorChanged(ui) { - var hex = ui.val('hex'); - currentPreview.css({ - backgroundColor: hex && '#' + hex || 'transparent' - }); - setAlpha.call(that, currentPreview, toFixedNumeric((ui.val('a') || 0) * 100 / 255, 4)); - } - /** - * @param {external:jQuery} ui - * @returns {void} - */ - - - function expandableColorChanged(ui) { - var hex = ui.val('hex'); - var va = ui.val('va'); - iconColor.css({ - backgroundColor: hex && '#' + hex || 'transparent' - }); - setAlpha.call(that, iconAlpha, toFixedNumeric((255 - (va && va.a || 0)) * 100 / 255, 4)); - - if (settings.window.bindToInput && settings.window.updateInputColor) { - settings.window.input.css({ - backgroundColor: hex && '#' + hex || 'transparent', - color: isNullish$1(va) || va.v > 75 ? '#000000' : '#ffffff' - }); - } - } - /** - * @param {Event} e - * @returns {void} - */ - - - function moveBarMouseDown(e) { - // const {element} = settings.window, // local copies for YUI compressor - // {page} = settings.window; - elementStartX = Number.parseInt(container.css('left')); - elementStartY = Number.parseInt(container.css('top')); - pageStartX = e.pageX; - pageStartY = e.pageY; // bind events to document to move window - we will unbind these on mouseup - - $(document).bind('mousemove', documentMouseMove).bind('mouseup', documentMouseUp); - e.preventDefault(); // prevent attempted dragging of the column - } - /** - * @param {Event} e - * @returns {false} - */ - - - function documentMouseMove(e) { - container.css({ - left: elementStartX - (pageStartX - e.pageX) + 'px', - top: elementStartY - (pageStartY - e.pageY) + 'px' - }); - - if (settings.window.expandable && !$.support.boxModel) { - container.prev().css({ - left: container.css('left'), - top: container.css('top') - }); - } - - e.stopPropagation(); - e.preventDefault(); - return false; - } - /** - * @param {Event} e - * @returns {false} - */ - - - function documentMouseUp(e) { - $(document).unbind('mousemove', documentMouseMove).unbind('mouseup', documentMouseUp); - e.stopPropagation(); - e.preventDefault(); - return false; - } - /** - * @param {Event} e - * @returns {false} - */ - - - function quickPickClicked(e) { - e.preventDefault(); - e.stopPropagation(); - color.active.val('ahex', $(this).attr('title') || null, e.target); - return false; - } - /** - * - * @returns {void} - */ - - - function show() { - color.current.val('ahex', color.active.val('ahex')); - /** - * - * @returns {void} - */ - - function attachIFrame() { - if (!settings.window.expandable || $.support.boxModel) return; - var table = container.find('table:first'); - container.before('<iframe/>'); - container.prev().css({ - width: table.width(), - height: container.height(), - opacity: 0, - position: 'absolute', - left: container.css('left'), - top: container.css('top') - }); - } - - if (settings.window.expandable) { - $(document.body).children('div.jPicker.Container').css({ - zIndex: 10 - }); - container.css({ - zIndex: 20 - }); - } - - switch (settings.window.effects.type) { - case 'fade': - container.fadeIn(settings.window.effects.speed.show, attachIFrame); - break; - - case 'slide': - container.slideDown(settings.window.effects.speed.show, attachIFrame); - break; - - case 'show': - default: - container.show(settings.window.effects.speed.show, attachIFrame); - break; - } - } - /** - * - * @returns {void} - */ - - - function hide() { - /** - * - * @returns {void} - */ - function removeIFrame() { - if (settings.window.expandable) container.css({ - zIndex: 10 - }); - if (!settings.window.expandable || $.support.boxModel) return; - container.prev().remove(); - } - - switch (settings.window.effects.type) { - case 'fade': - container.fadeOut(settings.window.effects.speed.hide, removeIFrame); - break; - - case 'slide': - container.slideUp(settings.window.effects.speed.hide, removeIFrame); - break; - - case 'show': - default: - container.hide(settings.window.effects.speed.hide, removeIFrame); - break; - } - } - /** - * - * @returns {void} - */ - - - function initialize() { - var win = settings.window, - popup = win.expandable ? $(that).next().find('.Container:first') : null; - container = win.expandable ? $('<div/>') : $(that); - container.addClass('jPicker Container'); - if (win.expandable) container.hide(); - - container.get(0).onselectstart = function (e) { - if (e.target.nodeName.toLowerCase() !== 'input') return false; - return true; - }; // inject html source code - we are using a single table for this control - I know tables are considered bad, but it takes care of equal height columns and - // this control really is tabular data, so I believe it is the right move - - - var all = color.active.val('all'); - if (win.alphaPrecision < 0) win.alphaPrecision = 0;else if (win.alphaPrecision > 2) win.alphaPrecision = 2; - var controlHtml = "<table class=\"jPicker\" cellpadding=\"0\" cellspacing=\"0\">\n <tbody>\n ".concat(win.expandable ? '<tr><td class="Move" colspan="5"> </td></tr>' : '', "\n <tr>\n <td rowspan=\"9\"><h2 class=\"Title\">").concat(win.title || localization.text.title, "</h2><div class=\"Map\"><span class=\"Map1\"> </span><span class=\"Map2\"> </span><span class=\"Map3\"> </span><img src=\"").concat(images.clientPath + images.colorMap.arrow.file, "\" class=\"Arrow\"/></div></td>\n <td rowspan=\"9\"><div class=\"Bar\"><span class=\"Map1\"> </span><span class=\"Map2\"> </span><span class=\"Map3\"> </span><span class=\"Map4\"> </span><span class=\"Map5\"> </span><span class=\"Map6\"> </span><img src=\"").concat(images.clientPath + images.colorBar.arrow.file, "\" class=\"Arrow\"/></div></td>\n <td colspan=\"2\" class=\"Preview\">").concat(localization.text.newColor, "<div><span class=\"Active\" title=\"").concat(localization.tooltips.colors.newColor, "\"> </span><span class=\"Current\" title=\"").concat(localization.tooltips.colors.currentColor, "\"> </span></div>").concat(localization.text.currentColor, "</td>\n <td rowspan=\"9\" class=\"Button\"><input type=\"button\" class=\"Ok\" value=\"").concat(localization.text.ok, "\" title=\"").concat(localization.tooltips.buttons.ok, "\"/><input type=\"button\" class=\"Cancel\" value=\"").concat(localization.text.cancel, "\" title=\"").concat(localization.tooltips.buttons.cancel, "\"/><hr/><div class=\"Grid\"> </div></td>\n </tr>\n <tr class=\"Hue\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.hue.radio, "\"><input type=\"radio\" value=\"h\"").concat(settings.color.mode === 'h' ? ' checked="checked"' : '', "/>H:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$1(all) ? all.h : '', "\" title=\"").concat(localization.tooltips.hue.textbox, "\"/> °</td>\n </tr>\n <tr class=\"Saturation\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.saturation.radio, "\"><input type=\"radio\" value=\"s\"").concat(settings.color.mode === 's' ? ' checked="checked"' : '', "/>S:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$1(all) ? all.s : '', "\" title=\"").concat(localization.tooltips.saturation.textbox, "\"/> %</td>\n </tr>\n <tr class=\"Value\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.value.radio, "\"><input type=\"radio\" value=\"v\"").concat(settings.color.mode === 'v' ? ' checked="checked"' : '', "/>V:</label><br/><br/></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$1(all) ? all.v : '', "\" title=\"").concat(localization.tooltips.value.textbox, "\"/> %<br/><br/></td>\n </tr>\n <tr class=\"Red\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.red.radio, "\"><input type=\"radio\" value=\"r\"").concat(settings.color.mode === 'r' ? ' checked="checked"' : '', "/>R:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$1(all) ? all.r : '', "\" title=\"").concat(localization.tooltips.red.textbox, "\"/></td>\n </tr>\n <tr class=\"Green\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.green.radio, "\"><input type=\"radio\" value=\"g\"").concat(settings.color.mode === 'g' ? ' checked="checked"' : '', "/>G:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$1(all) ? all.g : '', "\" title=\"").concat(localization.tooltips.green.textbox, "\"/></td>\n </tr>\n <tr class=\"Blue\">\n <td class=\"Radio\"><label title=\"").concat(localization.tooltips.blue.radio, "\"><input type=\"radio\" value=\"b\"").concat(settings.color.mode === 'b' ? ' checked="checked"' : '', "/>B:</label></td>\n <td class=\"Text\"><input type=\"text\" maxlength=\"3\" value=\"").concat(!isNullish$1(all) ? all.b : '', "\" title=\"").concat(localization.tooltips.blue.textbox, "\"/></td>\n </tr>\n <tr class=\"Alpha\">\n <td class=\"Radio\">").concat(win.alphaSupport ? "<label title=\"".concat(localization.tooltips.alpha.radio, "\"><input type=\"radio\" value=\"a\"").concat(settings.color.mode === 'a' ? ' checked="checked"' : '', "/>A:</label>") : ' ', "</td>\n <td class=\"Text\">").concat(win.alphaSupport ? "<input type=\"text\" maxlength=\"".concat(3 + win.alphaPrecision, "\" value=\"").concat(!isNullish$1(all) ? toFixedNumeric(all.a * 100 / 255, win.alphaPrecision) : '', "\" title=\"").concat(localization.tooltips.alpha.textbox, "\"/> %") : ' ', "</td>\n </tr>\n <tr class=\"Hex\">\n <td colspan=\"2\" class=\"Text\"><label title=\"").concat(localization.tooltips.hex.textbox, "\">#:<input type=\"text\" maxlength=\"6\" class=\"Hex\" value=\"").concat(!isNullish$1(all) ? all.hex : '', "\"/></label>").concat(win.alphaSupport ? "<input type=\"text\" maxlength=\"2\" class=\"AHex\" value=\"".concat(!isNullish$1(all) ? all.ahex.substring(6) : '', "\" title=\"").concat(localization.tooltips.hex.alpha, "\"/></td>") : ' ', "\n </tr>\n </tbody></table>"); - - if (win.expandable) { - container.html(controlHtml); - - if (!$(document.body).children('div.jPicker.Container').length) { - $(document.body).prepend(container); - } else { - $(document.body).children('div.jPicker.Container:last').after(container); - } - - container.mousedown(function () { - $(document.body).children('div.jPicker.Container').css({ - zIndex: 10 - }); - container.css({ - zIndex: 20 - }); - }); - container.css( // positions must be set and display set to absolute before source code injection or IE will size the container to fit the window - { - left: win.position.x === 'left' ? popup.offset().left - 530 - (win.position.y === 'center' ? 25 : 0) + 'px' : win.position.x === 'center' ? popup.offset().left - 260 + 'px' : win.position.x === 'right' ? popup.offset().left - 10 + (win.position.y === 'center' ? 25 : 0) + 'px' : win.position.x === 'screenCenter' ? ($(document).width() >> 1) - 260 + 'px' : popup.offset().left + Number.parseInt(win.position.x) + 'px', - position: 'absolute', - top: win.position.y === 'top' ? popup.offset().top - 312 + 'px' : win.position.y === 'center' ? popup.offset().top - 156 + 'px' : win.position.y === 'bottom' ? popup.offset().top + 25 + 'px' : popup.offset().top + Number.parseInt(win.position.y) + 'px' - }); - } else { - container = $(that); - container.html(controlHtml); - } // initialize the objects to the source code just injected - - - var tbody = container.find('tbody:first'); - colorMapDiv = tbody.find('div.Map:first'); - colorBarDiv = tbody.find('div.Bar:first'); - var MapMaps = colorMapDiv.find('span'); - var BarMaps = colorBarDiv.find('span'); - colorMapL1 = MapMaps.filter('.Map1:first'); - colorMapL2 = MapMaps.filter('.Map2:first'); - colorMapL3 = MapMaps.filter('.Map3:first'); - colorBarL1 = BarMaps.filter('.Map1:first'); - colorBarL2 = BarMaps.filter('.Map2:first'); - colorBarL3 = BarMaps.filter('.Map3:first'); - colorBarL4 = BarMaps.filter('.Map4:first'); - colorBarL5 = BarMaps.filter('.Map5:first'); - colorBarL6 = BarMaps.filter('.Map6:first'); // create color pickers and maps - - colorMap = new Slider(colorMapDiv, { - map: { - width: images.colorMap.width, - height: images.colorMap.height - }, - arrow: { - image: images.clientPath + images.colorMap.arrow.file, - width: images.colorMap.arrow.width, - height: images.colorMap.arrow.height - } - }); - colorMap.bind(mapValueChanged); - colorBar = new Slider(colorBarDiv, { - map: { - width: images.colorBar.width, - height: images.colorBar.height - }, - arrow: { - image: images.clientPath + images.colorBar.arrow.file, - width: images.colorBar.arrow.width, - height: images.colorBar.arrow.height - } - }); - colorBar.bind(colorBarValueChanged); - colorPicker = new ColorValuePicker(tbody, color.active, win.expandable && win.bindToInput ? win.input : null, win.alphaPrecision); - var hex = !isNullish$1(all) ? all.hex : null, - preview = tbody.find('.Preview'), - button = tbody.find('.Button'); - activePreview = preview.find('.Active:first').css({ - backgroundColor: hex && '#' + hex || 'transparent' - }); - currentPreview = preview.find('.Current:first').css({ - backgroundColor: hex && '#' + hex || 'transparent' - }).bind('click', currentClicked); - setAlpha.call(that, currentPreview, toFixedNumeric(color.current.val('a') * 100 / 255, 4)); - okButton = button.find('.Ok:first').bind('click', okClicked); - cancelButton = button.find('.Cancel:first').bind('click', cancelClicked); - grid = button.find('.Grid:first'); - setTimeout(function () { - setImg.call(that, colorMapL1, images.clientPath + 'Maps.png'); - setImg.call(that, colorMapL2, images.clientPath + 'Maps.png'); - setImg.call(that, colorMapL3, images.clientPath + 'map-opacity.png'); - setImg.call(that, colorBarL1, images.clientPath + 'Bars.png'); - setImg.call(that, colorBarL2, images.clientPath + 'Bars.png'); - setImg.call(that, colorBarL3, images.clientPath + 'Bars.png'); - setImg.call(that, colorBarL4, images.clientPath + 'Bars.png'); - setImg.call(that, colorBarL5, images.clientPath + 'bar-opacity.png'); - setImg.call(that, colorBarL6, images.clientPath + 'AlphaBar.png'); - setImg.call(that, preview.find('div:first'), images.clientPath + 'preview-opacity.png'); - }, 0); - tbody.find('td.Radio input').bind('click', radioClicked); // initialize quick list - - if (color.quickList && color.quickList.length > 0) { - var html = ''; - - for (var i = 0; i < color.quickList.length; i++) { - /* if default colors are hex strings, change them to color objects */ - if (_typeof(color.quickList[i]).toString().toLowerCase() === 'string') { - color.quickList[i] = new Color({ - hex: color.quickList[i] - }); - } - - var _alpha = color.quickList[i].val('a'); - - var _ahex = color.quickList[i].val('ahex'); - - if (!win.alphaSupport && _ahex) _ahex = _ahex.substring(0, 6) + 'ff'; - var quickHex = color.quickList[i].val('hex'); - if (!_ahex) _ahex = '00000000'; - html += '<span class="QuickColor"' + (' title="#' + _ahex + '"') + ' style="background-color:' + (quickHex && '#' + quickHex || '') + ';' + (quickHex ? '' : 'background-image:url(' + images.clientPath + 'NoColor.png)') + (win.alphaSupport && _alpha && _alpha < 255 ? ';opacity:' + toFixedNumeric(_alpha / 255, 4) + ';filter:Alpha(opacity=' + toFixedNumeric(_alpha / 2.55, 4) + ')' : '') + '"> </span>'; - } - - setImg.call(that, grid, images.clientPath + 'bar-opacity.png'); - grid.html(html); - grid.find('.QuickColor').click(quickPickClicked); - } - - setColorMode.call(that, settings.color.mode); - color.active.bind(activeColorChanged); - typeof liveCallback === 'function' && color.active.bind(liveCallback); - color.current.bind(currentColorChanged); // bind to input - - if (win.expandable) { - that.icon = popup.parents('.Icon:first'); - iconColor = that.icon.find('.Color:first').css({ - backgroundColor: hex && '#' + hex || 'transparent' - }); - iconAlpha = that.icon.find('.Alpha:first'); - setImg.call(that, iconAlpha, images.clientPath + 'bar-opacity.png'); - setAlpha.call(that, iconAlpha, toFixedNumeric((255 - (!isNullish$1(all) ? all.a : 0)) * 100 / 255, 4)); - iconImage = that.icon.find('.Image:first').css({ - backgroundImage: 'url(\'' + images.clientPath + images.picker.file + '\')' - }).bind('click', iconImageClicked); - - if (win.bindToInput && win.updateInputColor) { - win.input.css({ - backgroundColor: hex && '#' + hex || 'transparent', - color: isNullish$1(all) || all.v > 75 ? '#000000' : '#ffffff' - }); - } - - moveBar = tbody.find('.Move:first').bind('mousedown', moveBarMouseDown); - color.active.bind(expandableColorChanged); - } else show.call(that); - } - /** - * - * @returns {void} - */ - - - function destroy() { - container.find('td.Radio input').unbind('click', radioClicked); - currentPreview.unbind('click', currentClicked); - cancelButton.unbind('click', cancelClicked); - okButton.unbind('click', okClicked); - - if (settings.window.expandable) { - iconImage.unbind('click', iconImageClicked); - moveBar.unbind('mousedown', moveBarMouseDown); - that.icon = null; - } - - container.find('.QuickColor').unbind('click', quickPickClicked); - colorMapDiv = null; - colorBarDiv = null; - colorMapL1 = null; - colorMapL2 = null; - colorMapL3 = null; - colorBarL1 = null; - colorBarL2 = null; - colorBarL3 = null; - colorBarL4 = null; - colorBarL5 = null; - colorBarL6 = null; - colorMap.destroy(); - colorMap = null; - colorBar.destroy(); - colorBar = null; - colorPicker.destroy(); - colorPicker = null; - activePreview = null; - currentPreview = null; - okButton = null; - cancelButton = null; - grid = null; - commitCallback = null; - cancelCallback = null; - liveCallback = null; - container.html(''); - - for (var i = 0; i < List.length; i++) { - if (List[i] === that) { - List.splice(i, 1); - i--; // Decrement to ensure we don't miss next item (lgtm warning) - } - } - } - - var images = settings.images, - localization = settings.localization; // local copies for YUI compressor - - var color = { - active: _typeof(settings.color.active).toString().toLowerCase() === 'string' ? new Color({ - ahex: !settings.window.alphaSupport && settings.color.active ? settings.color.active.substring(0, 6) + 'ff' : settings.color.active - }) : new Color({ - ahex: !settings.window.alphaSupport && settings.color.active.val('ahex') ? settings.color.active.val('ahex').substring(0, 6) + 'ff' : settings.color.active.val('ahex') - }), - current: _typeof(settings.color.active).toString().toLowerCase() === 'string' ? new Color({ - ahex: !settings.window.alphaSupport && settings.color.active ? settings.color.active.substring(0, 6) + 'ff' : settings.color.active - }) : new Color({ - ahex: !settings.window.alphaSupport && settings.color.active.val('ahex') ? settings.color.active.val('ahex').substring(0, 6) + 'ff' : settings.color.active.val('ahex') - }), - quickList: settings.color.quickList - }; - - if (typeof commitCallback !== 'function') { - commitCallback = null; - } - - if (typeof liveCallback !== 'function') { - liveCallback = null; - } - - if (typeof cancelCallback !== 'function') { - cancelCallback = null; - } - - var elementStartX = null, - // Used to record the starting css positions for dragging the control - elementStartY = null, - pageStartX = null, - // Used to record the mousedown coordinates for dragging the control - pageStartY = null, - container = null, - colorMapDiv = null, - colorBarDiv = null, - colorMapL1 = null, - // different layers of colorMap and colorBar - colorMapL2 = null, - colorMapL3 = null, - colorBarL1 = null, - colorBarL2 = null, - colorBarL3 = null, - colorBarL4 = null, - colorBarL5 = null, - colorBarL6 = null, - colorMap = null, - // color maps - colorBar = null, - colorPicker = null, - activePreview = null, - // color boxes above the radio buttons - currentPreview = null, - okButton = null, - cancelButton = null, - grid = null, - // preset colors grid - iconColor = null, - // iconColor for popup icon - iconAlpha = null, - // iconAlpha for popup icon - iconImage = null, - // iconImage popup icon - moveBar = null; // drag bar - - $.extend(true, that, { - // public properties, methods, and callbacks - commitCallback: commitCallback, - // commitCallback function can be overridden to return the selected color to a method you specify when the user clicks "OK" - liveCallback: liveCallback, - // liveCallback function can be overridden to return the selected color to a method you specify in live mode (continuous update) - cancelCallback: cancelCallback, - // cancelCallback function can be overridden to a method you specify when the user clicks "Cancel" - color: color, - show: show, - hide: hide, - destroy: destroy // destroys this control entirely, removing all events and objects, and removing itself from the List - - }); - List.push(that); - setTimeout(function () { - initialize.call(that); - }, 0); - }); - }; - /** - * @typedef {PlainObject} external:jQuery.fn.jPickerOptionsIconInfo - * @property {string} file Color Map/Color Bar/Color Picker arrow icon - * @property {Float} width - * @property {Float} height - */ - - /** - * @typedef {PlainObject} external:jQuery.fn.jPickerOptionsImagesDimensionsArrow - * @property {Float} width - * @property {Float} height - * @property {external:jQuery.fn.jPickerOptionsIconInfo} arrow - */ - - /** - * @typedef {PlainObject} external:jQuery.fn.jPickerOptionsRadioTextboxLocale - * @property {string} radio - * @property {string} textbox - */ - - /** - * @typedef {PlainObject} external:jQuery.fn.jPickerOptions - * @property {PlainObject} window - * @property {string|null} window.title Any title for the jPicker window itself - displays - * "Drag Markers To Pick A Color" if left null - * @property {PlainObject} window.effects - * @property {"slide"|"show"|"fade"} window.effects.type Effect used to show/hide an expandable picker - * @property {PlainObject} window.effects.speed - * @property {"fast"|"slow"|Float} window.effects.speed.show Duration of "show" effect. Time in milliseconds. - * @property {"fast"|"slow"|Float} window.effects.speed.hide Duration of "hide" effect. Time in milliseconds - * @property {PlainObject} window.position - * @property {"left"|"center"|"right"|"screenCenter"|Float} window.position.x Relative px value - * @property {"top"|"bottom"|"center"|Float} window.position.y Relative px value - * @property {boolean} window.expandable Defaults to large static picker - set to `true` to make an expandable - * picker (small icon with popup) - set automatically when binded to input element; added by `$.fn.jPicker` - * @property {boolean} window.liveUpdate Set `false` if you want the user to have to click "OK" before the - * binded input box updates values (always `true` for expandable picker) - * @property {boolean} window.alphaSupport Set to `true` to enable alpha picking - * @property {Float} window.alphaPrecision Set decimal precision for alpha percentage display - hex codes do - * not map directly to percentage integers - range 0-2 - * @property {boolean} window.updateInputColor Set to `false` to prevent binded input colors from changing - * @property {boolean} [window.bindToInput] Added by `$.fn.jPicker` - * @property {external:jQuery} [window.input] Added by `$.fn.jPicker` - * @property {PlainObject} color - * @property {"h"|"s"|"v"|"r"|"g"|"b"|"a"} color.mode Symbols stand for "h" (hue), "s" (saturation), "v" (value), "r" (red), "g" (green), "b" (blue), "a" (alpha) - * @property {Color|string} color.active Strings are HEX values (e.g. #ffc000) WITH OR WITHOUT the "#" prefix - * @property {Color[]|string[]} color.quickList The quick pick color list - * Strings are HEX values (e.g. #ffc000) WITH OR WITHOUT the "#" prefix - * @property {PlainObject} images - * @property {string} images.clientPath Path to image files - * @property {external:jQuery.fn.jPickerOptionsImagesDimensionsArrow} images.colorMap - * @property {external:jQuery.fn.jPickerOptionsImagesDimensionsArrow} images.colorBar - * @property {external:jQuery.fn.jPickerOptionsIconInfo} images.picker - * @property {PlainObject} localization alter these to change the text presented by the picker (e.g. different language) - * @property {PlainObject} localization.text - * @property {string} localization.text.title - * @property {string} localization.text.newColor - * @property {string} localization.text.currentColor - * @property {string} localization.text.ok - * @property {string} localization.text.cancel - * @property {PlainObject} localization.tooltips - * @property {PlainObject} localization.tooltips.colors - * @property {string} localization.tooltips.colors.newColor - * @property {string} localization.tooltips.colors.currentColor - * @property {PlainObject} localization.tooltips.buttons - * @property {string} localization.tooltips.buttons.ok - * @property {string} localization.tooltips.buttons.cancel - * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.hue - * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.saturation - * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.value - * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.red - * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.green - * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.blue - * @property {external:jQuery.fn.jPickerOptionsRadioTextboxLocale} localization.tooltips.alpha - * @property {PlainObject} localization.tooltips.hex - * @property {string} localization.tooltips.hex.textbox - * @property {string} localization.tooltips.hex.alpha - */ - - /** - * The jPicker defaults - you can change anything in this section (such as the - * clientPath to your images) without fear of breaking the program. - * @namespace {external:jQuery.fn.jPickerOptions} defaults - * @memberof external:jQuery.fn.$.fn.jPicker - * @borrows external:jQuery.fn.jPickerOptions as external:jQuery.fn.jPicker.defaults - * @see Source for all of the values - */ - - - $.fn.jPicker.defaults = { - window: { - title: null, - effects: { - type: 'slide', - speed: { - show: 'slow', - hide: 'fast' - } - }, - position: { - x: 'screenCenter', - y: 'top' - }, - expandable: false, - liveUpdate: true, - alphaSupport: false, - alphaPrecision: 0, - updateInputColor: true - }, - color: { - mode: 'h', - active: new Color({ - ahex: '#ffcc00ff' - }), - quickList: [new Color({ - h: 360, - s: 33, - v: 100 - }), new Color({ - h: 360, - s: 66, - v: 100 - }), new Color({ - h: 360, - s: 100, - v: 100 - }), new Color({ - h: 360, - s: 100, - v: 75 - }), new Color({ - h: 360, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 100 - }), new Color({ - h: 30, - s: 33, - v: 100 - }), new Color({ - h: 30, - s: 66, - v: 100 - }), new Color({ - h: 30, - s: 100, - v: 100 - }), new Color({ - h: 30, - s: 100, - v: 75 - }), new Color({ - h: 30, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 90 - }), new Color({ - h: 60, - s: 33, - v: 100 - }), new Color({ - h: 60, - s: 66, - v: 100 - }), new Color({ - h: 60, - s: 100, - v: 100 - }), new Color({ - h: 60, - s: 100, - v: 75 - }), new Color({ - h: 60, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 80 - }), new Color({ - h: 90, - s: 33, - v: 100 - }), new Color({ - h: 90, - s: 66, - v: 100 - }), new Color({ - h: 90, - s: 100, - v: 100 - }), new Color({ - h: 90, - s: 100, - v: 75 - }), new Color({ - h: 90, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 70 - }), new Color({ - h: 120, - s: 33, - v: 100 - }), new Color({ - h: 120, - s: 66, - v: 100 - }), new Color({ - h: 120, - s: 100, - v: 100 - }), new Color({ - h: 120, - s: 100, - v: 75 - }), new Color({ - h: 120, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 60 - }), new Color({ - h: 150, - s: 33, - v: 100 - }), new Color({ - h: 150, - s: 66, - v: 100 - }), new Color({ - h: 150, - s: 100, - v: 100 - }), new Color({ - h: 150, - s: 100, - v: 75 - }), new Color({ - h: 150, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 50 - }), new Color({ - h: 180, - s: 33, - v: 100 - }), new Color({ - h: 180, - s: 66, - v: 100 - }), new Color({ - h: 180, - s: 100, - v: 100 - }), new Color({ - h: 180, - s: 100, - v: 75 - }), new Color({ - h: 180, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 40 - }), new Color({ - h: 210, - s: 33, - v: 100 - }), new Color({ - h: 210, - s: 66, - v: 100 - }), new Color({ - h: 210, - s: 100, - v: 100 - }), new Color({ - h: 210, - s: 100, - v: 75 - }), new Color({ - h: 210, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 30 - }), new Color({ - h: 240, - s: 33, - v: 100 - }), new Color({ - h: 240, - s: 66, - v: 100 - }), new Color({ - h: 240, - s: 100, - v: 100 - }), new Color({ - h: 240, - s: 100, - v: 75 - }), new Color({ - h: 240, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 20 - }), new Color({ - h: 270, - s: 33, - v: 100 - }), new Color({ - h: 270, - s: 66, - v: 100 - }), new Color({ - h: 270, - s: 100, - v: 100 - }), new Color({ - h: 270, - s: 100, - v: 75 - }), new Color({ - h: 270, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 10 - }), new Color({ - h: 300, - s: 33, - v: 100 - }), new Color({ - h: 300, - s: 66, - v: 100 - }), new Color({ - h: 300, - s: 100, - v: 100 - }), new Color({ - h: 300, - s: 100, - v: 75 - }), new Color({ - h: 300, - s: 100, - v: 50 - }), new Color({ - h: 180, - s: 0, - v: 0 - }), new Color({ - h: 330, - s: 33, - v: 100 - }), new Color({ - h: 330, - s: 66, - v: 100 - }), new Color({ - h: 330, - s: 100, - v: 100 - }), new Color({ - h: 330, - s: 100, - v: 75 - }), new Color({ - h: 330, - s: 100, - v: 50 - }), new Color()] - }, - images: { - clientPath: '/jPicker/images/', - colorMap: { - width: 256, - height: 256, - arrow: { - file: 'mappoint.gif', - width: 15, - height: 15 - } - }, - colorBar: { - width: 20, - height: 256, - arrow: { - file: 'rangearrows.gif', - width: 20, - height: 7 - } - }, - picker: { - file: 'picker.gif', - width: 25, - height: 24 - } - }, - localization: { - text: { - title: 'Drag Markers To Pick A Color', - newColor: 'new', - currentColor: 'current', - ok: 'OK', - cancel: 'Cancel' - }, - tooltips: { - colors: { - newColor: 'New Color - Press “OK” To Commit', - currentColor: 'Click To Revert To Original Color' - }, - buttons: { - ok: 'Commit To This Color Selection', - cancel: 'Cancel And Revert To Original Color' - }, - hue: { - radio: 'Set To “Hue” Color Mode', - textbox: 'Enter A “Hue” Value (0-360°)' - }, - saturation: { - radio: 'Set To “Saturation” Color Mode', - textbox: 'Enter A “Saturation” Value (0-100%)' - }, - value: { - radio: 'Set To “Value” Color Mode', - textbox: 'Enter A “Value” Value (0-100%)' - }, - red: { - radio: 'Set To “Red” Color Mode', - textbox: 'Enter A “Red” Value (0-255)' - }, - green: { - radio: 'Set To “Green” Color Mode', - textbox: 'Enter A “Green” Value (0-255)' - }, - blue: { - radio: 'Set To “Blue” Color Mode', - textbox: 'Enter A “Blue” Value (0-255)' - }, - alpha: { - radio: 'Set To “Alpha” Color Mode', - textbox: 'Enter A “Alpha” Value (0-100)' - }, - hex: { - textbox: 'Enter A “Hex” Color Value (#000000-#ffffff)', - alpha: 'Enter A “Alpha” Value (#00-#ff)' - } - } - } - }; - return $; -}; - -var $$b = jQuery; -var langParam; -/** - * Looks for elements to localize using the supplied `obj` to indicate - * on which selectors (or IDs if `ids` is set to `true`) to set its - * strings (with selectors relative to the editor root element). All - * keys will be translated, but for each selector, only the first item - * found matching will be modified. - * If the type is `content`, the selector-identified element's children - * will be checked, and the first (non-empty) text (placeholder) node - * found will have its text replaced. - * If the type is `title`, the element's `title` - * property will be set. - * If the type is `aria-label`, the element's `aria-label` attribute - * will be set (i.e., instructions for screen readers when there is - * otherwise no visible text to be read for the function of the form - * control). - * @param {"content"|"title"} type - * @param {module:locale.LocaleSelectorValue} obj Selectors or IDs keyed to strings - * @param {boolean} ids - * @returns {void} -*/ - -var setStrings = function setStrings(type, obj, ids) { - // Root element to look for element from - var parent = $$b('#svg_editor').parent(); - Object.entries(obj).forEach(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - sel = _ref2[0], - val = _ref2[1]; - - if (!val) { - console.log(sel); // eslint-disable-line no-console - - return; // keep old text when has no translation - } - - if (ids) { - sel = '#' + sel; - } - - var $elem = parent.find(sel); - - if ($elem.length) { - var elem = $elem[0]; - - switch (type) { - case 'aria-label': - elem.setAttribute('aria-label', val); - break; - - case 'content': - _toConsumableArray(elem.childNodes).some(function (node) { - if (node.nodeType === 3 - /* Node.TEXT_NODE */ - && node.textContent.trim()) { - node.textContent = val; - return true; - } - - return false; - }); - - break; - - case 'title': - elem.title = val; - break; - } - } else { - console.log('Missing element for localization: ' + sel); // eslint-disable-line no-console - } - }); -}; -/** -* The "data" property is generally set to an an array of objects with -* "id" and "title" or "textContent" properties. -* @typedef {PlainObject} module:locale.AddLangExtensionLocaleData -* @property {module:locale.LocaleStrings[]} data See {@tutorial LocaleDocs} -*/ - -/** -* @interface module:locale.LocaleEditorInit -*/ - -/** - * @function module:locale.LocaleEditorInit#addLangData - * @param {string} langParam - * @returns {module:locale.AddLangExtensionLocaleData} -*/ - -var editor_; -/** - * Sets the current editor instance (on which `addLangData`) exists. - * @function init - * @memberof module:locale - * @param {module:locale.LocaleEditorInit} editor - * @returns {void} -*/ - -var init$7 = function init(editor) { - editor_ = editor; -}; -/** -* @typedef {PlainObject} module:locale.LangAndData -* @property {string} langParam -* @property {module:locale.LocaleStrings} langData -*/ - -/** -* @function module:locale.readLang -* @param {module:locale.LocaleStrings} langData See {@tutorial LocaleDocs} -* @fires module:svgcanvas.SvgCanvas#event:ext_addLangData -* @returns {Promise<module:locale.LangAndData>} Resolves to [`LangAndData`]{@link module:locale.LangAndData} -*/ - -var readLang = /*#__PURE__*/function () { - var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(langData) { - var more, _langData, tools, properties, config, layers, common, ui, opts, ariaLabels; - - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return editor_.addLangData(langParam); - - case 2: - more = _context.sent; - $$b.each(more, function (i, m) { - if (m.data) { - langData = $$b.merge(langData, m.data); - } - }); // Old locale file, do nothing for now. - - if (langData.tools) { - _context.next = 6; - break; - } - - return _context.abrupt("return", undefined); - - case 6: - _langData = langData, tools = _langData.tools, properties = _langData.properties, config = _langData.config, layers = _langData.layers, common = _langData.common, ui = _langData.ui; - setStrings('content', { - // Todo: Add this powered by (probably by default) but with config to remove - // copyrightLabel: misc.powered_by, // Currently commented out in svg-editor.html - curve_segments: properties.curve_segments, - fitToContent: tools.fitToContent, - fit_to_all: tools.fit_to_all, - fit_to_canvas: tools.fit_to_canvas, - fit_to_layer_content: tools.fit_to_layer_content, - fit_to_sel: tools.fit_to_sel, - icon_large: config.icon_large, - icon_medium: config.icon_medium, - icon_small: config.icon_small, - icon_xlarge: config.icon_xlarge, - image_opt_embed: config.image_opt_embed, - image_opt_ref: config.image_opt_ref, - includedImages: config.included_images, - largest_object: tools.largest_object, - layersLabel: layers.layers, - page: tools.page, - relativeToLabel: tools.relativeTo, - selLayerLabel: layers.move_elems_to, - selectedPredefined: config.select_predefined, - selected_objects: tools.selected_objects, - smallest_object: tools.smallest_object, - straight_segments: properties.straight_segments, - svginfo_bg_url: config.editor_img_url + ':', - svginfo_bg_note: config.editor_bg_note, - svginfo_change_background: config.background, - svginfo_dim: config.doc_dims, - svginfo_editor_prefs: config.editor_prefs, - svginfo_height: common.height, - svginfo_icons: config.icon_size, - svginfo_image_props: config.image_props, - svginfo_lang: config.language, - svginfo_title: config.doc_title, - svginfo_width: common.width, - tool_docprops_cancel: common.cancel, - tool_docprops_save: common.ok, - tool_source_cancel: common.cancel, - tool_source_save: common.ok, - tool_prefs_cancel: common.cancel, - tool_prefs_save: common.ok, - sidepanel_handle: layers.layers.split('').join(' '), - tool_clear: tools.new_doc, - tool_docprops: tools.docprops, - tool_export: tools.export_img, - tool_import: tools.import_doc, - tool_open: tools.open_doc, - tool_save: tools.save_doc, - tool_editor_prefs: config.editor_prefs, - tool_editor_homepage: tools.editor_homepage, - svginfo_units_rulers: config.units_and_rulers, - svginfo_rulers_onoff: config.show_rulers, - svginfo_unit: config.base_unit, - svginfo_grid_settings: config.grid, - svginfo_snap_onoff: config.snapping_onoff, - svginfo_snap_step: config.snapping_stepsize, - svginfo_grid_color: config.grid_color - }, true); // Context menus - - opts = {}; - ['cut', 'copy', 'paste', 'paste_in_place', 'delete', 'group', 'ungroup', 'move_front', 'move_up', 'move_down', 'move_back'].forEach(function (item) { - opts['#cmenu_canvas a[href="#' + item + '"]'] = tools[item]; - }); - ['dupe', 'merge_down', 'merge_all'].forEach(function (item) { - opts['#cmenu_layers a[href="#' + item + '"]'] = layers[item]; - }); - opts['#cmenu_layers a[href="#delete"]'] = layers.del; - setStrings('content', opts); - ariaLabels = {}; - Object.entries({ - tool_blur: properties.blur, - tool_position: tools.align_to_page, - tool_font_family: properties.font_family, - zoom_panel: ui.zoom_level, - stroke_linejoin: properties.linejoin_miter, - stroke_linecap: properties.linecap_butt, - tool_opacity: properties.opacity - }).forEach(function (_ref4) { - var _ref5 = _slicedToArray(_ref4, 2), - id = _ref5[0], - value = _ref5[1]; - - ariaLabels['#' + id + ' button'] = value; - }); - Object.entries({ - group_opacity: properties.opacity, - zoom: ui.zoom_level - }).forEach(function (_ref6) { - var _ref7 = _slicedToArray(_ref6, 2), - id = _ref7[0], - value = _ref7[1]; - - ariaLabels['#' + id] = value; - }); - setStrings('aria-label', ariaLabels); - setStrings('title', { - align_relative_to: tools.align_relative_to, - circle_cx: properties.circle_cx, - circle_cy: properties.circle_cy, - circle_r: properties.circle_r, - cornerRadiusLabel: properties.corner_radius, - ellipse_cx: properties.ellipse_cx, - ellipse_cy: properties.ellipse_cy, - ellipse_rx: properties.ellipse_rx, - ellipse_ry: properties.ellipse_ry, - fill_color: properties.fill_color, - font_family: properties.font_family, - idLabel: properties.id, - image_height: properties.image_height, - image_url: properties.image_url, - image_width: properties.image_width, - layer_delete: layers.del, - layer_down: layers.move_down, - layer_new: layers["new"], - layer_rename: layers.rename, - layer_moreopts: common.more_opts, - layer_up: layers.move_up, - line_x1: properties.line_x1, - line_x2: properties.line_x2, - line_y1: properties.line_y1, - line_y2: properties.line_y2, - linecap_butt: properties.linecap_butt, - linecap_round: properties.linecap_round, - linecap_square: properties.linecap_square, - linejoin_bevel: properties.linejoin_bevel, - linejoin_miter: properties.linejoin_miter, - linejoin_round: properties.linejoin_round, - main_icon: tools.main_menu, - palette: ui.palette_info, - zoom_panel: ui.zoom_level, - path_node_x: properties.node_x, - path_node_y: properties.node_y, - rect_height_tool: properties.rect_height, - rect_width_tool: properties.rect_width, - seg_type: properties.seg_type, - selLayerNames: layers.move_selected, - selected_x: properties.pos_x, - selected_y: properties.pos_y, - stroke_color: properties.stroke_color, - stroke_style: properties.stroke_style, - stroke_width: properties.stroke_width, - svginfo_title: config.doc_title, - text: properties.text_contents, - toggle_stroke_tools: ui.toggle_stroke_tools, - tool_add_subpath: tools.add_subpath, - tool_alignbottom: tools.align_bottom, - tool_aligncenter: tools.align_center, - tool_alignleft: tools.align_left, - tool_alignmiddle: tools.align_middle, - tool_alignright: tools.align_right, - tool_aligntop: tools.align_top, - tool_angle: properties.angle, - tool_blur: properties.blur, - tool_bold: properties.bold, - tool_circle: tools.mode_circle, - tool_clone: tools.clone, - tool_clone_multi: tools.clone, - tool_delete: tools.del, - tool_delete_multi: tools.del, - tool_ellipse: tools.mode_ellipse, - tool_fhellipse: tools.mode_fhellipse, - tool_fhpath: tools.mode_fhpath, - tool_fhrect: tools.mode_fhrect, - tool_font_size: properties.font_size, - tool_group_elements: tools.group_elements, - tool_make_link: tools.make_link, - tool_link_url: tools.set_link_url, - tool_image: tools.mode_image, - tool_italic: properties.italic, - tool_line: tools.mode_line, - tool_move_bottom: tools.move_bottom, - tool_move_top: tools.move_top, - tool_node_clone: tools.node_clone, - tool_node_delete: tools.node_delete, - tool_node_link: tools.node_link, - tool_opacity: properties.opacity, - tool_openclose_path: tools.openclose_path, - tool_path: tools.mode_path, - tool_position: tools.align_to_page, - tool_rect: tools.mode_rect, - tool_redo: tools.redo, - tool_reorient: tools.reorient_path, - tool_select: tools.mode_select, - tool_source: tools.source_save, - tool_square: tools.mode_square, - tool_text: tools.mode_text, - tool_topath: tools.to_path, - tool_undo: tools.undo, - tool_ungroup: tools.ungroup, - tool_wireframe: tools.wireframe_mode, - tool_zoom: tools.mode_zoom, - url_notice: tools.no_embed - }, true); - return _context.abrupt("return", { - langParam: langParam, - langData: langData - }); - - case 19: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function readLang(_x) { - return _ref3.apply(this, arguments); - }; -}(); -/** - * - * @function module:locale.putLocale - * @param {string} givenParam - * @param {string[]} goodLangs - * @param {{langPath: string}} conf - * @fires module:svgcanvas.SvgCanvas#event:ext_addLangData - * @fires module:svgcanvas.SvgCanvas#event:ext_langReady - * @fires module:svgcanvas.SvgCanvas#event:ext_langChanged - * @returns {Promise<module:locale.LangAndData>} Resolves to result of {@link module:locale.readLang} -*/ - -var putLocale = /*#__PURE__*/function () { - var _ref8 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(givenParam, goodLangs, conf) { - var url; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (givenParam) { - langParam = givenParam; - } else if (navigator.userLanguage) { - // Explorer - langParam = navigator.userLanguage; - } else if (navigator.language) { - // FF, Opera, ... - langParam = navigator.language; - } - - console.log('Lang: ' + langParam); // eslint-disable-line no-console - // Set to English if language is not in list of good langs - - if (!goodLangs.includes(langParam) && langParam !== 'test') { - langParam = 'en'; - } - - url = conf.langPath + 'lang.' + langParam + '.js'; - _context2.t0 = readLang; - _context2.next = 7; - return importSetGlobalDefault(url, { - global: 'svgEditorLang_' + langParam.replace(/-/g, '_') - }); - - case 7: - _context2.t1 = _context2.sent; - return _context2.abrupt("return", (0, _context2.t0)(_context2.t1)); - - case 9: - case "end": - return _context2.stop(); - } - } - }, _callee2); - })); - - return function putLocale(_x2, _x3, _x4) { - return _ref8.apply(this, arguments); - }; -}(); - -function _slicedToArray$1(arr, i) { - return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _nonIterableRest$1(); -} - -function _arrayWithHoles$1(arr) { - if (Array.isArray(arr)) return arr; -} - -function _iterableToArrayLimit$1(arr, i) { - if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { - return; - } - - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; -} - -function _nonIterableRest$1() { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); -} - -function loadStylesheets(stylesheets) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - beforeDefault = _ref.before, - afterDefault = _ref.after, - faviconDefault = _ref.favicon, - canvasDefault = _ref.canvas, - _ref$image = _ref.image, - imageDefault = _ref$image === void 0 ? true : _ref$image, - acceptErrors = _ref.acceptErrors; - - stylesheets = Array.isArray(stylesheets) ? stylesheets : [stylesheets]; - - function setupLink(stylesheetURL) { - var options = {}; - - if (Array.isArray(stylesheetURL)) { - var _stylesheetURL = stylesheetURL; - - var _stylesheetURL2 = _slicedToArray$1(_stylesheetURL, 2); - - stylesheetURL = _stylesheetURL2[0]; - var _stylesheetURL2$ = _stylesheetURL2[1]; - options = _stylesheetURL2$ === void 0 ? {} : _stylesheetURL2$; - } - - var _options = options, - _options$favicon = _options.favicon, - favicon = _options$favicon === void 0 ? faviconDefault : _options$favicon; - var _options2 = options, - _options2$before = _options2.before, - before = _options2$before === void 0 ? beforeDefault : _options2$before, - _options2$after = _options2.after, - after = _options2$after === void 0 ? afterDefault : _options2$after, - _options2$canvas = _options2.canvas, - canvas = _options2$canvas === void 0 ? canvasDefault : _options2$canvas, - _options2$image = _options2.image, - image = _options2$image === void 0 ? imageDefault : _options2$image; - - function addLink() { - if (before) { - before.before(link); - } else if (after) { - after.after(link); - } else { - // eslint-disable-next-line unicorn/prefer-node-append - document.head.appendChild(link); - } - } - - var link = document.createElement('link'); // eslint-disable-next-line promise/avoid-new - - return new Promise(function (resolve, reject) { - var rej = reject; - - if (acceptErrors) { - rej = typeof acceptErrors === 'function' ? function (error) { - acceptErrors({ - error: error, - stylesheetURL: stylesheetURL, - options: options, - resolve: resolve, - reject: reject - }); - } : resolve; - } - - if (stylesheetURL.endsWith('.css')) { - favicon = false; - } else if (stylesheetURL.endsWith('.ico')) { - favicon = true; - } - - if (favicon) { - link.rel = 'shortcut icon'; - link.type = 'image/x-icon'; - - if (image === false) { - link.href = stylesheetURL; - addLink(); - resolve(link); - return; - } - - var cnv = document.createElement('canvas'); - cnv.width = 16; - cnv.height = 16; - var context = cnv.getContext('2d'); - var img = document.createElement('img'); - img.addEventListener('error', function (error) { - reject(error); - }); - img.addEventListener('load', function () { - context.drawImage(img, 0, 0); - link.href = canvas ? cnv.toDataURL('image/x-icon') : stylesheetURL; - addLink(); - resolve(link); - }); - img.src = stylesheetURL; - return; - } - - link.rel = 'stylesheet'; - link.type = 'text/css'; - link.href = stylesheetURL; - addLink(); - link.addEventListener('error', function (error) { - rej(error); - }); - link.addEventListener('load', function () { - resolve(link); - }); - }); - } - - return Promise.all(stylesheets.map(function (stylesheetURL) { - return setupLink(stylesheetURL); - })); -} - -var $q$1 = $q; -var editor = {}; -var $$c = [jQueryPluginJSHotkeys, jQueryPluginSVGIcons, jQueryPluginJGraduate, jQueryPluginSpinButton, jQueryPluginSVG, jQueryContextMenu, jPicker].reduce(function (jq, func) { - return func(jq); -}, jQuery); -/* -if (!$.loadingStylesheets) { - $.loadingStylesheets = []; -} -*/ - -var homePage = 'https://github.com/SVG-Edit/svgedit'; -var stylesheet = 'svg-editor.css'; - -if (!$$c.loadingStylesheets.includes(stylesheet)) { - $$c.loadingStylesheets.push(stylesheet); -} - -var favicon = 'images/logo.png'; - -if ($$c.loadingStylesheets.some(function (item) { - return !Array.isArray(item) || item[0] !== favicon; -})) { - $$c.loadingStylesheets.push([favicon, { - favicon: true - }]); -} // EDITOR PROPERTIES: (defined below) -// curPrefs, curConfig, canvas, storage, uiStrings -// -// STATE MAINTENANCE PROPERTIES - -/** -* @type {Float} -*/ - - -editor.tool_scale = 1; // Dependent on icon size, so any use to making configurable instead? Used by `jQuery.SpinButton.js` - -/** -* @type {Integer} -*/ - -editor.exportWindowCt = 0; -/** -* @type {boolean} -*/ - -editor.langChanged = false; -/** -* @type {boolean} -*/ - -editor.showSaveWarning = false; -/** - * Will be set to a boolean by `ext-storage.js` - * @type {"ignore"|"waiting"|"closed"} -*/ - -editor.storagePromptState = 'ignore'; -var callbacks = [], - -/** -* @typedef {"s"|"m"|"l"|"xl"|Float} module:SVGEditor.IconSize -*/ - -/** -* Preferences. -* @interface module:SVGEditor.Prefs -* @property {string} [lang="en"] Two-letter language code. The language must exist in the Editor Preferences language list. Defaults to "en" if `locale.js` detection does not detect another language. -* @property {module:SVGEditor.IconSize} [iconsize="s"|"m"] Size of the toolbar icons. Will default to 's' if the window height is smaller than the minimum height and 'm' otherwise. -* @property {string} [bkgd_color="#FFF"] Color hex for canvas background color. Defaults to white. -* @property {string} [bkgd_url=""] Background raster image URL. This image will fill the background of the document; useful for tracing purposes. -* @property {"embed"|"ref"} [img_save="embed"] Defines whether included raster images should be saved as Data URIs when possible, or as URL references. Settable in the Document Properties dialog. -* @property {boolean} [save_notice_done=false] Used to track alert status -* @property {boolean} [export_notice_done=false] Used to track alert status -* @todo `save_notice_done` and `export_notice_done` should be changed to flags rather than preferences -*/ - -/** -* @namespace {module:SVGEditor.Prefs} defaultPrefs -* @memberof module:SVGEditor~ -* @implements {module:SVGEditor.Prefs} -*/ -// The iteration algorithm for defaultPrefs does not currently support array/objects -defaultPrefs = -/** @lends module:SVGEditor~defaultPrefs */ -{ - // EDITOR OPTIONS (DIALOG) - - /** - * Default to "en" if locale.js detection does not detect another language. - */ - lang: '', - - /** - * Will default to 's' if the window height is smaller than the minimum - * height and 'm' otherwise. - */ - iconsize: '', - bkgd_color: '#FFF', - bkgd_url: '', - // DOCUMENT PROPERTIES (DIALOG) - img_save: 'embed', - // ALERT NOTICES - // Only shows in UI as far as alert notices, but useful to remember, so keeping as pref - save_notice_done: false, - export_notice_done: false -}, - -/** -* @name module:SVGEditor~defaultExtensions -* @type {string[]} -*/ -defaultExtensions = ['ext-connector.js', 'ext-eyedropper.js', 'ext-grid.js', 'ext-imagelib.js', 'ext-markers.js', 'ext-overview_window.js', 'ext-panning.js', 'ext-polygon.js', 'ext-shapes.js', 'ext-star.js', 'ext-storage.js'], - -/** -* @typedef {"@default"|string} module:SVGEditor.Stylesheet `@default` will automatically load all of the default CSS paths for SVGEditor -*/ - -/** -* @typedef {GenericArray} module:SVGEditor.XYDimensions -* @property {Integer} length 2 -* @property {Float} 0 -* @property {Float} 1 -*/ - -/** -* @tutorial ConfigOptions -* @interface module:SVGEditor.Config -* @property {string} [canvasName="default"] Used to namespace storage provided via `ext-storage.js`; you can use this if you wish to have multiple independent instances of SVG Edit on the same domain -* @property {boolean} [no_save_warning=false] If `true`, prevents the warning dialog box from appearing when closing/reloading the page. Mostly useful for testing. -* @property {string} [imgPath="images/"] The path where the SVG icons are located, with trailing slash. Note that as of version 2.7, this is not configurable by URL for security reasons. -* @property {string} [langPath="locale/"] The path where the language files are located, with trailing slash. Default will be changed to `../dist/locale/` if this is a modular load. Note that as of version 2.7, this is not configurable by URL for security reasons. -* @property {string} [extPath="extensions/"] The path used for extension files, with trailing slash. Default will be changed to `../dist/extensions/` if this is a modular load. Note that as of version 2.7, this is not configurable by URL for security reasons. -* @property {string} [canvgPath="canvg/"] The path used for `canvg` files, with trailing slash. Default will be changed to `../dist/` if this is a modular load. -* @property {string} [jspdfPath="jspdf/"] The path used for `jsPDF` files, with trailing slash. Default will be changed to `../dist/` if this is a modular load. -* @property {string} [extIconsPath="extensions/"] The path used for extension icons, with trailing slash. -* @property {string} [jGraduatePath="jgraduate/images/"] The path where jGraduate images are located. Note that as of version 2.7, this is not configurable by URL for security reasons. -* @property {boolean} [preventAllURLConfig=false] Set to `true` to override the ability for URLs to set non-content configuration (including extension config). Must be set early, i.e., in `svgedit-config-iife.js`; extension loading is too late! -* @property {boolean} [preventURLContentLoading=false] Set to `true` to override the ability for URLs to set URL-based SVG content. Must be set early, i.e., in `svgedit-config-iife.js`; extension loading is too late! -* @property {boolean} [lockExtensions=false] Set to `true` to override the ability for URLs to set their own extensions; disallowed in URL setting. There is no need for this when `preventAllURLConfig` is used. Must be set early, i.e., in `svgedit-config-iife.js`; extension loading is too late! -* @property {boolean} [noDefaultExtensions=false] If set to `true`, prohibits automatic inclusion of default extensions (though "extensions" can still be used to add back any desired default extensions along with any other extensions). This can only be meaningfully used in `svgedit-config-iife.js` or in the URL -* @property {boolean} [noStorageOnLoad=false] Some interaction with `ext-storage.js`; prevent even the loading of previously saved local storage. -* @property {boolean} [forceStorage=false] Some interaction with `ext-storage.js`; strongly discouraged from modification as it bypasses user privacy by preventing them from choosing whether to keep local storage or not (and may be required by law in some regions) -* @property {boolean} [emptyStorageOnDecline=false] Used by `ext-storage.js`; empty any prior storage if the user declines to store -* @property {boolean} [avoidClientSide=false] DEPRECATED (use `avoidClientSideDownload` instead); Used by `ext-server_opensave.js`; set to `true` if you wish to always save to server and not only as fallback when client support is lacking -* @property {boolean} [avoidClientSideDownload=false] Used by `ext-server_opensave.js`; set to `true` if you wish to always save to server and not only as fallback when client support is lacking -* @property {boolean} [avoidClientSideOpen=false] Used by `ext-server_opensave.js`; set to `true` if you wish to always open from the server and not only as fallback when FileReader client support is lacking -* @property {string[]} [extensions=module:SVGEditor~defaultExtensions] Extensions to load on startup. Use an array in `setConfig` and comma separated file names in the URL. Extension names must begin with "ext-". Note that as of version 2.7, paths containing "/", "\", or ":", are disallowed for security reasons. Although previous versions of this list would entirely override the default list, as of version 2.7, the defaults will always be added to this explicit list unless the configuration `noDefaultExtensions` is included. -* @property {module:SVGEditor.Stylesheet[]} [stylesheets=["@default"]] An array of required stylesheets to load in parallel; include the value `"@default"` within this array to ensure all default stylesheets are loaded. -* @property {string[]} [allowedOrigins=[]] Used by `ext-xdomain-messaging.js` to indicate which origins are permitted for cross-domain messaging (e.g., between the embedded editor and main editor code). Besides explicit domains, one might add '*' to allow all domains (not recommended for privacy/data integrity of your user's content!), `window.location.origin` for allowing the same origin (should be safe if you trust all apps on your domain), 'null' to allow `file:///` URL usage -* @property {null|PlainObject} [colorPickerCSS=null] Object of CSS properties mapped to values (for jQuery) to apply to the color picker. See {@link http://api.jquery.com/css/#css-properties}. A `null` value (the default) will cause the CSS to default to `left` with a position equal to that of the `fill_color` or `stroke_color` element minus 140, and a `bottom` equal to 40 -* @property {string} [paramurl] This was available via URL only. Allowed an un-encoded URL within the query string (use "url" or "source" with a data: URI instead) -* @property {Float} [canvas_expansion=3] The minimum area visible outside the canvas, as a multiple of the image dimensions. The larger the number, the more one can scroll outside the canvas. -* @property {PlainObject} [initFill] Init fill properties -* @property {string} [initFill.color="FF0000"] The initial fill color. Must be a hex code string. Defaults to solid red. -* @property {Float} [initFill.opacity=1] The initial fill opacity. Must be a number between 0 and 1 -* @property {PlainObject} [initStroke] Init stroke properties -* @property {Float} [initStroke.width=5] The initial stroke width. Must be a positive number. -* @property {string} [initStroke.color="000000"] The initial stroke color. Must be a hex code. Defaults to solid black. -* @property {Float} [initStroke.opacity=1] The initial stroke opacity. Must be a number between 0 and 1. -* @property {PlainObject} text Text style properties -* @property {Float} [text.stroke_width=0] Text stroke width -* @property {Float} [text.font_size=24] Text font size -* @property {string} [text.font_family="serif"] Text font family -* @property {Float} [initOpacity=1] Initial opacity (multiplied by 100) -* @property {module:SVGEditor.XYDimensions} [dimensions=[640, 480]] The default width/height of a new document. Use an array in `setConfig` (e.g., `[800, 600]`) and comma separated numbers in the URL. -* @property {boolean} [gridSnapping=false] Enable snap to grid by default. Set in Editor Options. -* @property {string} [gridColor="#000"] Accepts hex, e.g., '#000'. Set in Editor Options. Defaults to black. -* @property {string} [baseUnit="px"] Set in Editor Options. -* @property {Float} [snappingStep=10] Set the default grid snapping value. Set in Editor Options. -* @property {boolean} [showRulers=true] Initial state of ruler display (v2.6). Set in Editor Options. -* @property {string} [initTool="select"] The initially selected tool. Must be either the ID of the button for the tool, or the ID without `tool_` prefix (e.g., "select"). -* @property {boolean} [wireframe=false] Start in wireframe mode -* @property {boolean} [showlayers=false] Open the layers side-panel by default. -* @property {"new"|"same"} [exportWindowType="new"] Can be "new" or "same" to indicate whether new windows will be generated for each export; the `window.name` of the export window is namespaced based on the `canvasName` (and incremented if "new" is selected as the type). Introduced 2.8. -* @property {boolean} [showGrid=false] Set by `ext-grid.js`; determines whether or not to show the grid by default -* @property {boolean} [show_outside_canvas=true] Defines whether or not elements outside the canvas should be visible. Set and used in `svgcanvas.js`. -* @property {boolean} [selectNew=true] If true, will replace the selection with the current element and automatically select element objects (when not in "path" mode) after they are created, showing their grips (v2.6). Set and used in `svgcanvas.js` (`mouseUp`). -* @todo Some others could be preferences as well (e.g., preventing URL changing of extensions, defaultExtensions, stylesheets, colorPickerCSS); Change the following to preferences and add pref controls where missing to the UI (e.g., `canvas_expansion`, `initFill`, `initStroke`, `text`, `initOpacity`, `dimensions`, `initTool`, `wireframe`, `showlayers`, `gridSnapping`, `gridColor`, `baseUnit`, `snappingStep`, `showRulers`, `exportWindowType`, `showGrid`, `show_outside_canvas`, `selectNew`)? -*/ - -/** -* @namespace {module:SVGEditor.Config} defaultConfig -* @memberof module:SVGEditor~ -* @implements {module:SVGEditor.Config} -*/ -defaultConfig = { - canvasName: 'default', - canvas_expansion: 3, - initFill: { - color: 'FF0000', - // solid red - opacity: 1 - }, - initStroke: { - width: 5, - color: '000000', - // solid black - opacity: 1 - }, - text: { - stroke_width: 0, - font_size: 24, - font_family: 'serif' - }, - initOpacity: 1, - colorPickerCSS: null, - // Defaults to 'left' with a position equal to that of the fill_color or stroke_color element minus 140, and a 'bottom' equal to 40 - initTool: 'select', - exportWindowType: 'new', - // 'same' (todo: also support 'download') - wireframe: false, - showlayers: false, - no_save_warning: false, - // PATH CONFIGURATION - // The following path configuration items are disallowed in the URL (as should any future path configurations) - langPath: 'locale/', - // Default will be changed if this is a non-modular load - extPath: 'extensions/', - // Default will be changed if this is a non-modular load - canvgPath: 'canvg/', - // Default will be changed if this is a non-modular load - jspdfPath: 'jspdf/', - // Default will be changed if this is a non-modular load - imgPath: 'images/', - jGraduatePath: 'jgraduate/images/', - extIconsPath: 'extensions/', - // DOCUMENT PROPERTIES - // Change the following to a preference (already in the Document Properties dialog)? - dimensions: [640, 480], - // EDITOR OPTIONS - // Change the following to preferences (already in the Editor Options dialog)? - gridSnapping: false, - gridColor: '#000', - baseUnit: 'px', - snappingStep: 10, - showRulers: true, - // URL BEHAVIOR CONFIGURATION - preventAllURLConfig: false, - preventURLContentLoading: false, - // EXTENSION CONFIGURATION (see also preventAllURLConfig) - lockExtensions: false, - // Disallowed in URL setting - noDefaultExtensions: false, - // noDefaultExtensions can only be meaningfully used in `svgedit-config-iife.js` or in the URL - // EXTENSION-RELATED (GRID) - showGrid: false, - // Set by ext-grid.js - // EXTENSION-RELATED (STORAGE) - noStorageOnLoad: false, - // Some interaction with ext-storage.js; prevent even the loading of previously saved local storage - forceStorage: false, - // Some interaction with ext-storage.js; strongly discouraged from modification as it bypasses user privacy by preventing them from choosing whether to keep local storage or not - emptyStorageOnDecline: false, - // Used by ext-storage.js; empty any prior storage if the user declines to store - // EXTENSION (CLIENT VS. SERVER SAVING/OPENING) - avoidClientSide: false, - // Deprecated in favor of `avoidClientSideDownload` - avoidClientSideDownload: false, - avoidClientSideOpen: false -}, - -/** -* LOCALE. -* @name module:SVGEditor.uiStrings -* @type {PlainObject} -*/ -uiStrings$1 = editor.uiStrings = {}; -var svgCanvas, - urldata = {}, - isReady = false, - customExportImage = false, - customExportPDF = false, - curPrefs = {}, - // Note: The difference between Prefs and Config is that Prefs -// can be changed in the UI and are stored in the browser, -// while config cannot -curConfig = { - // We do not put on defaultConfig to simplify object copying - // procedures (we obtain instead from defaultExtensions) - extensions: [], - stylesheets: [], - - /** - * Can use `location.origin` to indicate the current - * origin. Can contain a '*' to allow all domains or 'null' (as - * a string) to support all `file:///` URLs. Cannot be set by - * URL for security reasons (not safe, at least for - * privacy or data integrity of SVG content). - * Might have been fairly safe to allow - * `new URL(location.href).origin` by default but - * avoiding it ensures some more security that even third - * party apps on the same domain also cannot communicate - * with this app by default. - * For use with `ext-xdomain-messaging.js` - * @todo We might instead make as a user-facing preference. - */ - allowedOrigins: [] -}; -/** - * - * @param {string} str SVG string - * @param {PlainObject} [opts={}] - * @param {boolean} [opts.noAlert] - * @throws {Error} Upon failure to load SVG - * @returns {Promise<void>} Resolves to undefined upon success (or if `noAlert` is - * falsey, though only until after the `alert` is closed); rejects if SVG - * loading fails and `noAlert` is truthy. - */ - -function loadSvgString(_x) { - return _loadSvgString.apply(this, arguments); -} -/** - * @function module:SVGEditor~getImportLocale - * @param {PlainObject} defaults - * @param {string} defaults.defaultLang - * @param {string} defaults.defaultName - * @returns {module:SVGEditor~ImportLocale} - */ - - -function _loadSvgString() { - _loadSvgString = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee23(str) { - var _ref42, - noAlert, - success, - _args23 = arguments; - - return regeneratorRuntime.wrap(function _callee23$(_context23) { - while (1) { - switch (_context23.prev = _context23.next) { - case 0: - _ref42 = _args23.length > 1 && _args23[1] !== undefined ? _args23[1] : {}, noAlert = _ref42.noAlert; - success = svgCanvas.setSvgString(str) !== false; - - if (!success) { - _context23.next = 4; - break; - } - - return _context23.abrupt("return"); - - case 4: - if (noAlert) { - _context23.next = 8; - break; - } - - _context23.next = 7; - return $$c.alert(uiStrings$1.notification.errorLoadingSVG); - - case 7: - return _context23.abrupt("return"); - - case 8: - throw new Error('Error loading SVG'); - - case 9: - case "end": - return _context23.stop(); - } - } - }, _callee23); - })); - return _loadSvgString.apply(this, arguments); -} - -function getImportLocale(_ref) { - var defaultLang = _ref.defaultLang, - defaultName = _ref.defaultName; - - /** - * @function module:SVGEditor~ImportLocale - * @param {PlainObject} localeInfo - * @param {string} [localeInfo.name] Defaults to `defaultName` of {@link module:SVGEditor~getImportLocale} - * @param {string} [localeInfo.lang=defaultLang] Defaults to `defaultLang` of {@link module:SVGEditor~getImportLocale} - * @returns {Promise<module:locale.LocaleStrings>} Resolves to {@link module:locale.LocaleStrings} - */ - return /*#__PURE__*/function () { - var _importLocaleDefaulting = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var _ref2, - _ref2$name, - name, - _ref2$lang, - lang, - importLocale, - _args = arguments; - - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - importLocale = function _importLocale(language) { - var url = "".concat(curConfig.extPath, "ext-locale/").concat(name, "/").concat(language, ".js"); - return importSetGlobalDefault(url, { - global: "svgEditorExtensionLocale_".concat(name, "_").concat(language.replace(/-/g, '_')) - }); - }; - - _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, _ref2$name = _ref2.name, name = _ref2$name === void 0 ? defaultName : _ref2$name, _ref2$lang = _ref2.lang, lang = _ref2$lang === void 0 ? defaultLang : _ref2$lang; - _context.prev = 2; - _context.next = 5; - return importLocale(lang); - - case 5: - return _context.abrupt("return", _context.sent); - - case 8: - _context.prev = 8; - _context.t0 = _context["catch"](2); - return _context.abrupt("return", importLocale('en')); - - case 11: - case "end": - return _context.stop(); - } - } - }, _callee, null, [[2, 8]]); - })); - - function importLocaleDefaulting() { - return _importLocaleDefaulting.apply(this, arguments); - } - - return importLocaleDefaulting; - }(); -} -/** -* EXPORTS. -*/ - -/** -* Store and retrieve preferences. -* @function module:SVGEditor.pref -* @param {string} key The preference name to be retrieved or set -* @param {string} [val] The value. If the value supplied is missing or falsey, no change to the preference will -* be made unless `mayBeEmpty` is set. -* @param {boolean} [mayBeEmpty] If value may be falsey. -* @returns {string|void} If val is missing or falsey and `mayBeEmpty` is not set, the -* value of the previously stored preference will be returned. -* @todo Review whether any remaining existing direct references to -* getting `curPrefs` can be changed to use `svgEditor.pref()` getting to ensure -* `defaultPrefs` fallback (also for sake of `allowInitialUserOverride`); -* specifically, `bkgd_color` could be changed so that the pref dialog has a -* button to auto-calculate background, but otherwise uses `svgEditor.pref()` to -* be able to get default prefs or overridable settings -*/ - - -editor.pref = function (key, val, mayBeEmpty) { - if (mayBeEmpty || val) { - curPrefs[key] = val; - /** - * @name curPrefs - * @memberof module:SVGEditor - * @implements {module:SVGEditor.Prefs} - */ - - editor.curPrefs = curPrefs; // Update exported value - - return undefined; - } - - return key in curPrefs ? curPrefs[key] : defaultPrefs[key]; -}; -/* -* EDITOR PUBLIC METHODS -// Todo: Sort these methods per invocation order, ideally with init at the end -// Todo: Prevent execution until init executes if dependent on it? -*/ - - -editor.putLocale = putLocale; -editor.readLang = readLang; -editor.setStrings = setStrings; -/** -* Where permitted, sets canvas and/or `defaultPrefs` based on previous -* storage. This will override URL settings (for security reasons) but -* not `svgedit-config-iife.js` configuration (unless initial user -* overriding is explicitly permitted there via `allowInitialUserOverride`). -* @function module:SVGEditor.loadContentAndPrefs -* @todo Split `allowInitialUserOverride` into `allowOverrideByURL` and -* `allowOverrideByUserStorage` so `svgedit-config-iife.js` can disallow some -* individual items for URL setting but allow for user storage AND/OR -* change URL setting so that it always uses a different namespace, -* so it won't affect pre-existing user storage (but then if users saves -* that, it will then be subject to tampering -* @returns {void} -*/ - -editor.loadContentAndPrefs = function () { - if (!curConfig.forceStorage && (curConfig.noStorageOnLoad || !document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/))) { - return; - } // LOAD CONTENT - - - if (editor.storage && ( // Cookies do not have enough available memory to hold large documents - curConfig.forceStorage || !curConfig.noStorageOnLoad && document.cookie.match(/(?:^|;\s*)svgeditstore=prefsAndContent/))) { - var _name = 'svgedit-' + curConfig.canvasName; - - var cached = editor.storage.getItem(_name); - - if (cached) { - editor.loadFromString(cached); - } - } // LOAD PREFS - - - Object.keys(defaultPrefs).forEach(function (key) { - var storeKey = 'svg-edit-' + key; - - if (editor.storage) { - var val = editor.storage.getItem(storeKey); - - if (val) { - defaultPrefs[key] = String(val); // Convert to string for FF (.value fails in Webkit) - } - } else if (window.widget) { - defaultPrefs[key] = window.widget.preferenceForKey(storeKey); - } else { - var result = document.cookie.match(new RegExp('(?:^|;\\s*)' + regexEscape(encodeURIComponent(storeKey)) + '=([^;]+)')); - defaultPrefs[key] = result ? decodeURIComponent(result[1]) : ''; - } - }); -}; -/** -* Allows setting of preferences or configuration (including extensions). -* @function module:SVGEditor.setConfig -* @param {module:SVGEditor.Config|module:SVGEditor.Prefs} opts The preferences or configuration (including extensions). See the tutorial on {@tutorial ConfigOptions} for info on config and preferences. -* @param {PlainObject} [cfgCfg] Describes configuration which applies to the -* particular batch of supplied options -* @param {boolean} [cfgCfg.allowInitialUserOverride=false] Set to true if you wish -* to allow initial overriding of settings by the user via the URL -* (if permitted) or previously stored preferences (if permitted); -* note that it will be too late if you make such calls in extension -* code because the URL or preference storage settings will -* have already taken place. -* @param {boolean} [cfgCfg.overwrite=true] Set to false if you wish to -* prevent the overwriting of prior-set preferences or configuration -* (URL settings will always follow this requirement for security -* reasons, so `svgedit-config-iife.js` settings cannot be overridden unless it -* explicitly permits via `allowInitialUserOverride` but extension config -* can be overridden as they will run after URL settings). Should -* not be needed in `svgedit-config-iife.js`. -* @returns {void} -*/ - - -editor.setConfig = function (opts, cfgCfg) { - cfgCfg = cfgCfg || {}; - /** - * - * @param {module:SVGEditor.Config|module:SVGEditor.Prefs} cfgObj - * @param {string} key - * @param {any} val See {@link module:SVGEditor.Config} or {@link module:SVGEditor.Prefs} - * @returns {void} - */ - - function extendOrAdd(cfgObj, key, val) { - if (cfgObj[key] && _typeof(cfgObj[key]) === 'object') { - $$c.extend(true, cfgObj[key], val); - } else { - cfgObj[key] = val; - } - } - - Object.entries(opts).forEach(function (_ref3) { - var _ref4 = _slicedToArray(_ref3, 2), - key = _ref4[0], - val = _ref4[1]; - - // Only allow prefs defined in defaultPrefs or... - if ({}.hasOwnProperty.call(defaultPrefs, key)) { - if (cfgCfg.overwrite === false && (curConfig.preventAllURLConfig || {}.hasOwnProperty.call(curPrefs, key))) { - return; - } - - if (cfgCfg.allowInitialUserOverride === true) { - defaultPrefs[key] = val; - } else { - editor.pref(key, val); - } - } else if (['extensions', 'stylesheets', 'allowedOrigins'].includes(key)) { - if (cfgCfg.overwrite === false && (curConfig.preventAllURLConfig || ['allowedOrigins', 'stylesheets'].includes(key) || key === 'extensions' && curConfig.lockExtensions)) { - return; - } - - curConfig[key] = curConfig[key].concat(val); // We will handle any dupes later - // Only allow other curConfig if defined in defaultConfig - } else if ({}.hasOwnProperty.call(defaultConfig, key)) { - if (cfgCfg.overwrite === false && (curConfig.preventAllURLConfig || {}.hasOwnProperty.call(curConfig, key))) { - return; - } // Potentially overwriting of previously set config - - - if ({}.hasOwnProperty.call(curConfig, key)) { - if (cfgCfg.overwrite === false) { - return; - } - - extendOrAdd(curConfig, key, val); - } else if (cfgCfg.allowInitialUserOverride === true) { - extendOrAdd(defaultConfig, key, val); - } else if (defaultConfig[key] && _typeof(defaultConfig[key]) === 'object') { - curConfig[key] = Array.isArray(defaultConfig[key]) ? [] : {}; - $$c.extend(true, curConfig[key], val); // Merge properties recursively, e.g., on initFill, initStroke objects - } else { - curConfig[key] = val; - } - } - }); - /** - * @name curConfig - * @memberof module:SVGEditor - * @implements {module:SVGEditor.Config} - */ - - editor.curConfig = curConfig; // Update exported value -}; -/** -* All methods are optional. -* @interface module:SVGEditor.CustomHandler -* @type {PlainObject} -*/ - -/** -* Its responsibilities are: -* - invoke a file chooser dialog in 'open' mode -* - let user pick a SVG file -* - calls [svgCanvas.setSvgString()]{@link module:svgcanvas.SvgCanvas#setSvgString} with the string contents of that file. -* Not passed any parameters. -* @function module:SVGEditor.CustomHandler#open -* @returns {void} -*/ - -/** -* Its responsibilities are: -* - accept the string contents of the current document -* - invoke a file chooser dialog in 'save' mode -* - save the file to location chosen by the user. -* @function module:SVGEditor.CustomHandler#save -* @param {external:Window} win -* @param {module:svgcanvas.SvgCanvas#event:saved} svgStr A string of the SVG -* @listens module:svgcanvas.SvgCanvas#event:saved -* @returns {void} -*/ - -/** -* Its responsibilities (with regard to the object it is supplied in its 2nd argument) are: -* - inform user of any issues supplied via the "issues" property -* - convert the "svg" property SVG string into an image for export; -* utilize the properties "type" (currently 'PNG', 'JPEG', 'BMP', -* 'WEBP', 'PDF'), "mimeType", and "quality" (for 'JPEG' and 'WEBP' -* types) to determine the proper output. -* @function module:SVGEditor.CustomHandler#exportImage -* @param {external:Window} win -* @param {module:svgcanvas.SvgCanvas#event:exported} data -* @listens module:svgcanvas.SvgCanvas#event:exported -* @returns {void} -*/ - -/** -* @function module:SVGEditor.CustomHandler#exportPDF -* @param {external:Window} win -* @param {module:svgcanvas.SvgCanvas#event:exportedPDF} data -* @listens module:svgcanvas.SvgCanvas#event:exportedPDF -* @returns {void} -*/ - -/** -* Allows one to override default SVGEdit `open`, `save`, and -* `export` editor behaviors. -* @function module:SVGEditor.setCustomHandlers -* @param {module:SVGEditor.CustomHandler} opts Extension mechanisms may call `setCustomHandlers` with three functions: `opts.open`, `opts.save`, and `opts.exportImage` -* @returns {Promise<void>} -*/ - - -editor.setCustomHandlers = function (opts) { - return editor.ready(function () { - if (opts.open) { - $$c('#tool_open > input[type="file"]').remove(); - $$c('#tool_open').show(); - svgCanvas.open = opts.open; - } - - if (opts.save) { - editor.showSaveWarning = false; - svgCanvas.bind('saved', opts.save); - } - - if (opts.exportImage) { - customExportImage = opts.exportImage; - svgCanvas.bind('exported', customExportImage); // canvg and our RGBColor will be available to the method - } - - if (opts.exportPDF) { - customExportPDF = opts.exportPDF; - svgCanvas.bind('exportedPDF', customExportPDF); // jsPDF and our RGBColor will be available to the method - } - }); -}; -/** - * @function module:SVGEditor.randomizeIds - * @param {boolean} arg - * @returns {void} - */ - - -editor.randomizeIds = function (arg) { - svgCanvas.randomizeIds(arg); -}; -/** -* Auto-run after a Promise microtask. -* @function module:SVGEditor.init -* @returns {void} -*/ - - -editor.init = function () { - var modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false; - - if (!modularVersion) { - Object.assign(defaultConfig, { - langPath: '../../dist/locale/', - extPath: '../../dist/extensions/', - canvgPath: '../../dist/', - jspdfPath: '../../dist/' - }); - } // const host = location.hostname, - // onWeb = host && host.includes('.'); - // Some FF versions throw security errors here when directly accessing - - - try { - if ('localStorage' in window) { - // && onWeb removed so Webkit works locally - - /** - * The built-in interface implemented by `localStorage` - * @external Storage - */ - - /** - * @name storage - * @memberof module:SVGEditor - * @type {external:Storage} - */ - editor.storage = localStorage; - } - } catch (err) {} // Todo: Avoid const-defined functions and group functions together, etc. where possible - - - var goodLangs = []; - $$c('#lang_select option').each(function () { - goodLangs.push(this.value); - }); - /** - * Sets up current preferences based on defaults. - * @returns {void} - */ - - function setupCurPrefs() { - curPrefs = $$c.extend(true, {}, defaultPrefs, curPrefs); // Now safe to merge with priority for curPrefs in the event any are already set - // Export updated prefs - - editor.curPrefs = curPrefs; - } - /** - * Sets up current config based on defaults. - * @returns {void} - */ - - - function setupCurConfig() { - curConfig = $$c.extend(true, {}, defaultConfig, curConfig); // Now safe to merge with priority for curConfig in the event any are already set - // Now deal with extensions and other array config - - if (!curConfig.noDefaultExtensions) { - curConfig.extensions = curConfig.extensions.concat(defaultExtensions); - } // ...and remove any dupes - - - ['extensions', 'stylesheets', 'allowedOrigins'].forEach(function (cfg) { - curConfig[cfg] = $$c.grep(curConfig[cfg], function (n, i) { - // Supposedly faster than filter per http://amandeep1986.blogspot.hk/2015/02/jquery-grep-vs-js-filter.html - return i === curConfig[cfg].indexOf(n); - }); - }); // Export updated config - - editor.curConfig = curConfig; - } - - (function () { - // Load config/data from URL if given - var _URL = new URL(location), - search = _URL.search, - searchParams = _URL.searchParams; - - if (search) { - urldata = deparam(searchParams.toString(), true); - ['initStroke', 'initFill'].forEach(function (prop) { - if (searchParams.has("".concat(prop, "[color]"))) { - // Restore back to original non-deparamed value to avoid color - // strings being converted to numbers - urldata[prop].color = searchParams.get("".concat(prop, "[color]")); - } - }); - - if (searchParams.has('bkgd_color')) { - urldata.bkgd_color = '#' + searchParams.get('bkgd_color'); - } - - if (urldata.dimensions) { - urldata.dimensions = urldata.dimensions.split(','); - } - - if (urldata.extensions) { - // For security reasons, disallow cross-domain or cross-folder - // extensions via URL - urldata.extensions = urldata.extensions.match(/[:/\\]/) ? '' : urldata.extensions.split(','); - } // Disallowing extension paths via URL for - // security reasons, even for same-domain - // ones given potential to interact in undesirable - // ways with other script resources - - - ['langPath', 'extPath', 'canvgPath', 'jspdfPath', 'imgPath', 'jGraduatePath', 'extIconsPath'].forEach(function (pathConfig) { - if (urldata[pathConfig]) { - delete urldata[pathConfig]; - } - }); // Note: `source` and `url` (as with `storagePrompt` later) are not - // set on config but are used below - - editor.setConfig(urldata, { - overwrite: false - }); - setupCurConfig(); - - if (!curConfig.preventURLContentLoading) { - var _urldata = urldata, - source = _urldata.source; - - if (!source) { - // urldata.source may have been null if it ended with '=' - var src = searchParams.get('source'); - - if (src && src.startsWith('data:')) { - source = src; - } - } - - if (source) { - if (source.startsWith('data:')) { - editor.loadFromDataURI(source); - } else { - editor.loadFromString(source); - } - - return; - } - - if (urldata.url) { - editor.loadFromURL(urldata.url); - return; - } - } - - if (!urldata.noStorageOnLoad || curConfig.forceStorage) { - editor.loadContentAndPrefs(); - } - } else { - setupCurConfig(); - editor.loadContentAndPrefs(); - } - })(); - - setupCurPrefs(); - /** - * Called internally. - * @function module:SVGEditor.setIcon - * @param {string|Element|external:jQuery} elem - * @param {string|external:jQuery} iconId - * @param {Float} forcedSize Not in use - * @returns {void} - */ - - var setIcon = editor.setIcon = function (elem, iconId, forcedSize) { - var icon = typeof iconId === 'string' ? $$c.getSvgIcon(iconId, true) : iconId.clone(); - - if (!icon) { - // Todo: Investigate why this still occurs in some cases - console.log('NOTE: Icon image missing: ' + iconId); // eslint-disable-line no-console - - return; - } - - $$c(elem).empty().append(icon); - }; - /** - * @fires module:svgcanvas.SvgCanvas#event:ext_addLangData - * @fires module:svgcanvas.SvgCanvas#event:ext_langReady - * @fires module:svgcanvas.SvgCanvas#event:ext_langChanged - * @fires module:svgcanvas.SvgCanvas#event:extensions_added - * @returns {Promise<module:locale.LangAndData>} Resolves to result of {@link module:locale.readLang} - */ - - - var extAndLocaleFunc = /*#__PURE__*/function () { - var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var _yield$editor$putLoca, langParam, langData, _uiStrings$common, ok, cancel; - - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return editor.putLocale(editor.pref('lang'), goodLangs, curConfig); - - case 2: - _yield$editor$putLoca = _context3.sent; - langParam = _yield$editor$putLoca.langParam; - langData = _yield$editor$putLoca.langData; - _context3.next = 7; - return setLang(langParam, langData); - - case 7: - _uiStrings$common = uiStrings$1.common, ok = _uiStrings$common.ok, cancel = _uiStrings$common.cancel; - jQueryPluginDBox($$c, { - ok: ok, - cancel: cancel - }); - setIcons(); // Wait for dbox as needed for i18n - - _context3.prev = 10; - _context3.next = 13; - return Promise.all(curConfig.extensions.map( /*#__PURE__*/function () { - var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(extname) { - var extName, url, imported, _imported$name, _name2, init, importLocale; - - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - extName = extname.match(/^ext-(.+)\.js/); // const {extName} = extname.match(/^ext-(?<extName>.+)\.js/).groups; - - if (extName) { - _context2.next = 3; - break; - } - - return _context2.abrupt("return", undefined); - - case 3: - url = curConfig.extPath + extname; // Todo: Replace this with `return import(url);` when - // `import()` widely supported - - /** - * @tutorial ExtensionDocs - * @typedef {PlainObject} module:SVGEditor.ExtensionObject - * @property {string} [name] Name of the extension. Used internally; no need for i18n. Defaults to extension name without beginning "ext-" or ending ".js". - * @property {module:svgcanvas.ExtensionInitCallback} [init] - */ - - _context2.prev = 4; - _context2.next = 7; - return importSetGlobalDefault(url, { - global: 'svgEditorExtension_' + extName[1].replace(/-/g, '_') // global: 'svgEditorExtension_' + extName.replace(/-/g, '_') - - }); - - case 7: - imported = _context2.sent; - _imported$name = imported.name, _name2 = _imported$name === void 0 ? extName[1] : _imported$name, init = imported.init; // const {name = extName, init} = imported; - - importLocale = getImportLocale({ - defaultLang: langParam, - defaultName: _name2 - }); - return _context2.abrupt("return", editor.addExtension(_name2, init && init.bind(editor), { - $: $$c, - importLocale: importLocale - })); - - case 13: - _context2.prev = 13; - _context2.t0 = _context2["catch"](4); - // Todo: Add config to alert any errors - console.log(_context2.t0); // eslint-disable-line no-console - - console.error('Extension failed to load: ' + extname + '; ' + _context2.t0); // eslint-disable-line no-console - - return _context2.abrupt("return", undefined); - - case 18: - case "end": - return _context2.stop(); - } - } - }, _callee2, null, [[4, 13]]); - })); - - return function (_x2) { - return _ref6.apply(this, arguments); - }; - }())); - - case 13: - svgCanvas.bind('extensions_added', - /** - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:extensions_added} data - * @listens module:svgcanvas.SvgCanvas#event:extensions_added - * @returns {void} - */ - function (win, data) { - extensionsAdded = true; - Actions.setAll(); - $$c('.flyout_arrow_horiz:empty').each(function () { - $$c(this).append($$c.getSvgIcon('arrow_right', true).width(5).height(5)); - }); - - if (editor.storagePromptState === 'ignore') { - updateCanvas(true); - } - - messageQueue.forEach( - /** - * @param {module:svgcanvas.SvgCanvas#event:message} messageObj - * @fires module:svgcanvas.SvgCanvas#event:message - * @returns {void} - */ - function (messageObj) { - svgCanvas.call('message', messageObj); - }); - }); - svgCanvas.call('extensions_added'); - _context3.next = 20; - break; - - case 17: - _context3.prev = 17; - _context3.t0 = _context3["catch"](10); - // Todo: Report errors through the UI - console.log(_context3.t0); // eslint-disable-line no-console - - case 20: - case "end": - return _context3.stop(); - } - } - }, _callee3, null, [[10, 17]]); - })); - - return function extAndLocaleFunc() { - return _ref5.apply(this, arguments); - }; - }(); - - var stateObj = { - tool_scale: editor.tool_scale - }; - /** - * - * @returns {void} - */ - - var setFlyoutPositions = function setFlyoutPositions() { - $$c('.tools_flyout').each(function () { - var shower = $$c('#' + this.id + '_show'); - - var _shower$offset = shower.offset(), - left = _shower$offset.left, - top = _shower$offset.top; - - var w = shower.outerWidth(); - $$c(this).css({ - left: (left + w) * editor.tool_scale, - top: top - }); - }); - }; - /** - * @type {string} - */ - - - var uaPrefix = function () { - var regex = /^(?:Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/; - var someScript = document.getElementsByTagName('script')[0]; - - for (var prop in someScript.style) { - if (regex.test(prop)) { - // test is faster than match, so it's better to perform - // that on the lot and match only when necessary - return prop.match(regex)[0]; - } - } // Nothing found so far? - - - if ('WebkitOpacity' in someScript.style) { - return 'Webkit'; - } - - if ('KhtmlOpacity' in someScript.style) { - return 'Khtml'; - } - - return ''; - }(); - /** - * @param {external:jQuery} elems - * @param {Float} scale - * @returns {void} - */ - - - var scaleElements = function scaleElements(elems, scale) { - // const prefix = '-' + uaPrefix.toLowerCase() + '-'; // Currently unused - var sides = ['top', 'left', 'bottom', 'right']; - elems.each(function () { - // Handled in CSS - // this.style[uaPrefix + 'Transform'] = 'scale(' + scale + ')'; - var el = $$c(this); - var w = el.outerWidth() * (scale - 1); - var h = el.outerHeight() * (scale - 1); // const margins = {}; // Currently unused - - for (var i = 0; i < 4; i++) { - var s = sides[i]; - var cur = el.data('orig_margin-' + s); - - if (isNullish(cur)) { - cur = Number.parseInt(el.css('margin-' + s)); // Cache the original margin - - el.data('orig_margin-' + s, cur); - } - - var val = cur * scale; - - if (s === 'right') { - val += w; - } else if (s === 'bottom') { - val += h; - } - - el.css('margin-' + s, val); // el.css('outline', '1px solid red'); - } - }); - }; - /** - * Called internally. - * @function module:SVGEditor.setIconSize - * @param {module:SVGEditor.IconSize} size - * @returns {void} - */ - - - var setIconSize = editor.setIconSize = function (size) { - // const elems = $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open'); - var selToscale = '#tools_top .toolset, #editor_panel > *, #history_panel > *,' + ' #main_button, #tools_left > *, #path_node_panel > *, #multiselected_panel > *,' + ' #g_panel > *, #tool_font_size > *, .tools_flyout'; - var elems = $$c(selToscale); - var scale = 1; - - if (typeof size === 'number') { - scale = size; - } else { - var iconSizes = { - s: 0.75, - m: 1, - l: 1.25, - xl: 1.5 - }; - scale = iconSizes[size]; - } - - stateObj.tool_scale = editor.tool_scale = scale; - setFlyoutPositions(); // $('.tools_flyout').each(function () { - // const pos = $(this).position(); - // console.log($(this), pos.left+(34 * scale)); - // $(this).css({left: pos.left+(34 * scale), top: pos.top+(77 * scale)}); - // console.log('l', $(this).css('left')); - // }); - // - // const scale = .75; - - var hiddenPs = elems.parents(':hidden'); - hiddenPs.css('visibility', 'hidden').show(); - scaleElements(elems, scale); - hiddenPs.css('visibility', 'visible').hide(); // return; - - editor.pref('iconsize', size); - $$c('#iconsize').val(size); // Change icon size - // $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open') - // .find('> svg, > img').each(function () { - // this.setAttribute('width',size_num); - // this.setAttribute('height',size_num); - // }); - // - // $.resizeSvgIcons({ - // '.flyout_arrow_horiz > svg, .flyout_arrow_horiz > img': size_num / 5, - // '#logo > svg, #logo > img': size_num * 1.3, - // '#tools_bottom .icon_label > *': (size_num === 16 ? 18 : size_num * .75) - // }); - // if (size != 's') { - // $.resizeSvgIcons({'#layerbuttons svg, #layerbuttons img': size_num * .6}); - // } - // Note that all rules will be prefixed with '#svg_editor' when parsed - - var cssResizeRules = { - // '.tool_button,\ - // .push_button,\ - // .tool_button_current,\ - // .push_button_pressed,\ - // .disabled,\ - // .icon_label,\ - // .tools_flyout .tool_button': { - // width: {s: '16px', l: '32px', xl: '48px'}, - // height: {s: '16px', l: '32px', xl: '48px'}, - // padding: {s: '1px', l: '2px', xl: '3px'} - // }, - // '.tool_sep': { - // height: {s: '16px', l: '32px', xl: '48px'}, - // margin: {s: '2px 2px', l: '2px 5px', xl: '2px 8px'} - // }, - // '#main_icon': { - // width: {s: '31px', l: '53px', xl: '75px'}, - // height: {s: '22px', l: '42px', xl: '64px'} - // }, - '#tools_top': { - left: 50 + $$c('#main_button').width(), - height: 72 - }, - '#tools_left': { - width: 31, - top: 74 - }, - 'div#workarea': { - left: 38, - top: 74 - } // '#tools_bottom': { - // left: {s: '27px', l: '46px', xl: '65px'}, - // height: {s: '58px', l: '98px', xl: '145px'} - // }, - // '#color_tools': { - // 'border-spacing': {s: '0 1px'}, - // 'margin-top': {s: '-1px'} - // }, - // '#color_tools .icon_label': { - // width: {l:'43px', xl: '60px'} - // }, - // '.color_tool': { - // height: {s: '20px'} - // }, - // '#tool_opacity': { - // top: {s: '1px'}, - // height: {s: 'auto', l:'auto', xl:'auto'} - // }, - // '#tools_top input, #tools_bottom input': { - // 'margin-top': {s: '2px', l: '4px', xl: '5px'}, - // height: {s: 'auto', l: 'auto', xl: 'auto'}, - // border: {s: '1px solid #555', l: 'auto', xl: 'auto'}, - // 'font-size': {s: '.9em', l: '1.2em', xl: '1.4em'} - // }, - // '#zoom_panel': { - // 'margin-top': {s: '3px', l: '4px', xl: '5px'} - // }, - // '#copyright, #tools_bottom .label': { - // 'font-size': {l: '1.5em', xl: '2em'}, - // 'line-height': {s: '15px'} - // }, - // '#tools_bottom_2': { - // width: {l: '295px', xl: '355px'}, - // top: {s: '4px'} - // }, - // '#tools_top > div, #tools_top': { - // 'line-height': {s: '17px', l: '34px', xl: '50px'} - // }, - // '.dropdown button': { - // height: {s: '18px', l: '34px', xl: '40px'}, - // 'line-height': {s: '18px', l: '34px', xl: '40px'}, - // 'margin-top': {s: '3px'} - // }, - // '#tools_top label, #tools_bottom label': { - // 'font-size': {s: '1em', l: '1.5em', xl: '2em'}, - // height: {s: '25px', l: '42px', xl: '64px'} - // }, - // 'div.toolset': { - // height: {s: '25px', l: '42px', xl: '64px'} - // }, - // '#tool_bold, #tool_italic': { - // 'font-size': {s: '1.5em', l: '3em', xl: '4.5em'} - // }, - // '#sidepanels': { - // top: {s: '50px', l: '88px', xl: '125px'}, - // bottom: {s: '51px', l: '68px', xl: '65px'} - // }, - // '#layerbuttons': { - // width: {l: '130px', xl: '175px'}, - // height: {l: '24px', xl: '30px'} - // }, - // '#layerlist': { - // width: {l: '128px', xl: '150px'} - // }, - // '.layer_button': { - // width: {l: '19px', xl: '28px'}, - // height: {l: '19px', xl: '28px'} - // }, - // 'input.spin-button': { - // 'background-image': {l: 'url('images/spinbtn_updn_big.png')', xl: 'url('images/spinbtn_updn_big.png')'}, - // 'background-position': {l: '100% -5px', xl: '100% -2px'}, - // 'padding-right': {l: '24px', xl: '24px' } - // }, - // 'input.spin-button.up': { - // 'background-position': {l: '100% -45px', xl: '100% -42px'} - // }, - // 'input.spin-button.down': { - // 'background-position': {l: '100% -85px', xl: '100% -82px'} - // }, - // '#position_opts': { - // width: {all: (size_num*4) +'px'} - // } - - }; - var ruleElem = $$c('#tool_size_rules'); - - if (!ruleElem.length) { - ruleElem = $$c('<style id="tool_size_rules"></style>').appendTo('head'); - } else { - ruleElem.empty(); - } - - if (size !== 'm') { - var styleStr = ''; - $$c.each(cssResizeRules, function (selector, rules) { - selector = '#svg_editor ' + selector.replace(/,/g, ', #svg_editor'); - styleStr += selector + '{'; - $$c.each(rules, function (prop, values) { - var val; - - if (typeof values === 'number') { - val = values * scale + 'px'; - } else if (values[size] || values.all) { - val = values[size] || values.all; - } - - styleStr += prop + ':' + val + ';'; - }); - styleStr += '}'; - }); // this.style[uaPrefix + 'Transform'] = 'scale(' + scale + ')'; - - var prefix = '-' + uaPrefix.toLowerCase() + '-'; - styleStr += selToscale + '{' + prefix + 'transform: scale(' + scale + ');}' + ' #svg_editor div.toolset .toolset {' + prefix + 'transform: scale(1); margin: 1px !important;}' + // Hack for markers - ' #svg_editor .ui-slider {' + prefix + 'transform: scale(' + 1 / scale + ');}' // Hack for sliders - ; - ruleElem.text(styleStr); - } - - setFlyoutPositions(); - }; - /** - * Setup SVG icons. - * @returns {void} - */ - - - function setIcons() { - $$c.svgIcons(curConfig.imgPath + 'svg_edit_icons.svg', { - w: 24, - h: 24, - id_match: false, - no_img: !isWebkit(), - // Opera & Firefox 4 gives odd behavior w/images - fallback_path: curConfig.imgPath, - // Todo: Set `alts: {}` with keys as the IDs in fallback set to - // `uiStrings` (localized) values - 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', - config: 'config.png' - }, - placement: { - '#logo': 'logo', - '#tool_clear div,#layer_new': 'new_image', - '#tool_save div': 'save', - '#tool_export div': 'export', - '#tool_open div': 'open', - '#tool_import div': 'import', - '#tool_source': 'source', - '#tool_docprops > div': 'docprops', - '#tool_editor_prefs > div': 'config', - '#tool_editor_homepage > div': 'globe_link', - '#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 callback(icons) { - return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() { - var tleft, minHeight, size, getStylesheetPriority, stylesheets, idx, _stylesheets; - - return regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - getStylesheetPriority = function _getStylesheetPriorit(stylesheetFile) { - switch (stylesheetFile) { - 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 Infinity; - } - }; - - $$c('.toolbar_button button > svg, .toolbar_button button > img').each(function () { - $$c(this).parent().prepend(this); - }); - tleft = $$c('#tools_left'); - - if (tleft.length) { - minHeight = tleft.offset().top + tleft.outerHeight(); - } - - size = editor.pref('iconsize'); - editor.setIconSize(size || ($$c(window).height() < minHeight ? 's' : 'm')); // Look for any missing flyout icons from plugins - - $$c('.tools_flyout').each(function () { - var shower = $$c('#' + this.id + '_show'); - var sel = shower.attr('data-curopt'); // Check if there's an icon here - - if (!shower.children('svg, img').length) { - var clone = $$c(sel).children().clone(); - - if (clone.length) { - clone[0].removeAttribute('style'); // Needed for Opera - - shower.append(clone); - } - } - }); - /** - * Since stylesheets may be added out of order, we indicate the desired order - * for defaults and others after them (in an indeterminate order). - * @param {string} stylesheetFile - * @returns {Integer|PositiveInfinity} - */ - - stylesheets = $$c.loadingStylesheets.sort(function (a, b) { - var priorityA = getStylesheetPriority(a); - var priorityB = getStylesheetPriority(b); - - if (priorityA === priorityB) { - return 0; - } - - return priorityA > priorityB; - }); - - if (curConfig.stylesheets.length) { - // Ensure a copy with unique items - stylesheets = _toConsumableArray(new Set(curConfig.stylesheets)); - idx = stylesheets.indexOf('@default'); - - if (idx > -1) { - (_stylesheets = stylesheets).splice.apply(_stylesheets, [idx, 1].concat(_toConsumableArray($$c.loadingStylesheets))); - } - } - - _context4.next = 11; - return loadStylesheets(stylesheets, { - acceptErrors: function acceptErrors(_ref7) { - var stylesheetURL = _ref7.stylesheetURL, - reject = _ref7.reject, - resolve = _ref7.resolve; - - if ($$c.loadingStylesheets.includes(stylesheetURL)) { - reject(new Error("Missing expected stylesheet: ".concat(stylesheetURL))); - return; - } - - resolve(); - } - }); - - case 11: - $$c('#svg_container')[0].style.visibility = 'visible'; - _context4.next = 14; - return editor.runCallbacks(); - - case 14: - case "end": - return _context4.stop(); - } - } - }, _callee4); - }))(); - } - }); - } - /** - * @name module:SVGEditor.canvas - * @type {module:svgcanvas.SvgCanvas} - */ - - - editor.canvas = svgCanvas = new SvgCanvas(document.getElementById('svgcanvas'), curConfig); - var palette = [// Todo: Make into configuration item? - '#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'], - modKey = isMac() ? 'meta+' : 'ctrl+', - path = svgCanvas.pathActions, - _svgCanvas = svgCanvas, - undoMgr = _svgCanvas.undoMgr, - workarea = $$c('#workarea'), - canvMenu = $$c('#cmenu_canvas'), - paintBox = { - fill: null, - stroke: null - }; - var resizeTimer, curScrollPos; - var exportWindow = null, - defaultImageURL = curConfig.imgPath + 'logo.png', - zoomInIcon = 'crosshair', - zoomOutIcon = 'crosshair', - uiContext = 'toolbars'; // For external openers - - (function () { - // let the opener know SVG Edit is ready (now that config is set up) - var w = window.opener || window.parent; - - if (w) { - try { - /** - * Triggered on a containing `document` (of `window.opener` - * or `window.parent`) when the editor is loaded. - * @event module:SVGEditor#event:svgEditorReadyEvent - * @type {Event} - * @property {true} bubbles - * @property {true} cancelable - */ - - /** - * @name module:SVGEditor.svgEditorReadyEvent - * @type {module:SVGEditor#event:svgEditorReadyEvent} - */ - var svgEditorReadyEvent = new w.CustomEvent('svgEditorReady', { - bubbles: true, - cancelable: true - }); - w.document.documentElement.dispatchEvent(svgEditorReadyEvent); - } catch (e) {} - } - })(); - /** - * - * @returns {void} - */ - - - var setSelectMode = function setSelectMode() { - var curr = $$c('.tool_button_current'); - - if (curr.length && curr[0].id !== 'tool_select') { - curr.removeClass('tool_button_current').addClass('tool_button'); - $$c('#tool_select').addClass('tool_button_current').removeClass('tool_button'); - $$c('#styleoverrides').text("\n #svgcanvas svg * {\n cursor: move;\n pointer-events: all;\n }\n #svgcanvas svg {\n cursor: default;\n }\n "); - } - - svgCanvas.setMode('select'); - workarea.css('cursor', 'auto'); - }; // used to make the flyouts stay on the screen longer the very first time - // const flyoutspeed = 1250; // Currently unused - // let textBeingEntered = false; // Currently unused - - - var origTitle = $$c('title:first').text(); // Make [1,2,5] array - - var rIntervals = []; - - for (var i = 0.1; i < 1e5; i *= 10) { - rIntervals.push(i); - rIntervals.push(2 * i); - rIntervals.push(5 * i); - } - /** - * This function highlights the layer passed in (by fading out the other layers). - * If no layer is passed in, this function restores the other layers. - * @param {string} [layerNameToHighlight] - * @returns {void} - */ - - - var toggleHighlightLayer = function toggleHighlightLayer(layerNameToHighlight) { - var i; - var curNames = [], - numLayers = svgCanvas.getCurrentDrawing().getNumLayers(); - - for (i = 0; i < numLayers; i++) { - curNames[i] = svgCanvas.getCurrentDrawing().getLayerName(i); - } - - if (layerNameToHighlight) { - curNames.forEach(function (curName) { - if (curName !== layerNameToHighlight) { - svgCanvas.getCurrentDrawing().setLayerOpacity(curName, 0.5); - } - }); - } else { - curNames.forEach(function (curName) { - svgCanvas.getCurrentDrawing().setLayerOpacity(curName, 1.0); - }); - } - }; - /** - * - * @returns {void} - */ - - - var populateLayers = function populateLayers() { - svgCanvas.clearSelection(); - var layerlist = $$c('#layerlist tbody').empty(); - var selLayerNames = $$c('#selLayerNames').empty(); - var drawing = svgCanvas.getCurrentDrawing(); - var currentLayerName = drawing.getCurrentLayerName(); - var icon = $$c.getSvgIcon('eye'); - var layer = svgCanvas.getCurrentDrawing().getNumLayers(); // we get the layers in the reverse z-order (the layer rendered on top is listed first) - - while (layer--) { - var _name3 = drawing.getLayerName(layer); - - var layerTr = $$c('<tr class="layer">').toggleClass('layersel', _name3 === currentLayerName); - var layerVis = $$c('<td class="layervis">').toggleClass('layerinvis', !drawing.getLayerVisibility(_name3)); - var layerName = $$c('<td class="layername">' + _name3 + '</td>'); - layerlist.append(layerTr.append(layerVis, layerName)); - selLayerNames.append('<option value="' + _name3 + '">' + _name3 + '</option>'); - } - - if (icon !== undefined) { - var copy = icon.clone(); - $$c('td.layervis', layerlist).append(copy); - $$c.resizeSvgIcons({ - 'td.layervis .svg_icon': 14 - }); - } // handle selection of layer - - - $$c('#layerlist td.layername').mouseup(function (evt) { - $$c('#layerlist tr.layer').removeClass('layersel'); - $$c(this.parentNode).addClass('layersel'); - svgCanvas.setCurrentLayer(this.textContent); - evt.preventDefault(); - }).mouseover(function () { - toggleHighlightLayer(this.textContent); - }).mouseout(function () { - toggleHighlightLayer(); - }); - $$c('#layerlist td.layervis').click(function () { - var row = $$c(this.parentNode).prevAll().length; - var name = $$c('#layerlist tr.layer:eq(' + row + ') td.layername').text(); - var vis = $$c(this).hasClass('layerinvis'); - svgCanvas.setLayerVisibility(name, vis); - $$c(this).toggleClass('layerinvis'); - }); // if there were too few rows, let's add a few to make it not so lonely - - var num = 5 - $$c('#layerlist tr.layer').size(); - - while (num-- > 0) { - // TODO: there must a better way to do this - layerlist.append('<tr><td style="color:white">_</td><td/></tr>'); - } - }; - - var editingsource = false; - var origSource = ''; - /** - * @param {Event} [e] Not used. - * @param {boolean} forSaving - * @returns {void} - */ - - var showSourceEditor = function showSourceEditor(e, forSaving) { - if (editingsource) { - return; - } - - editingsource = true; - origSource = svgCanvas.getSvgString(); - $$c('#save_output_btns').toggle(Boolean(forSaving)); - $$c('#tool_source_back').toggle(!forSaving); - $$c('#svg_source_textarea').val(origSource); - $$c('#svg_source_editor').fadeIn(); - $$c('#svg_source_textarea').focus(); - }; - - var selectedElement = null; - var multiselected = false; - /** - * @param {boolean} editmode - * @param {module:svgcanvas.SvgCanvas#event:selected} elems - * @returns {void} - */ - - var togglePathEditMode = function togglePathEditMode(editmode, elems) { - $$c('#path_node_panel').toggle(editmode); - $$c('#tools_bottom_2,#tools_bottom_3').toggle(!editmode); - - if (editmode) { - // Change select icon - $$c('.tool_button_current').removeClass('tool_button_current').addClass('tool_button'); - $$c('#tool_select').addClass('tool_button_current').removeClass('tool_button'); - setIcon('#tool_select', 'select_node'); - multiselected = false; - - if (elems.length) { - selectedElement = elems[0]; - } - } else { - setTimeout(function () { - setIcon('#tool_select', 'select'); - }, 1000); - } - }; - /** - * @type {module:svgcanvas.EventHandler} - * @param {external:Window} wind - * @param {module:svgcanvas.SvgCanvas#event:saved} svg The SVG source - * @listens module:svgcanvas.SvgCanvas#event:saved - * @returns {void} - */ - - - var saveHandler = function saveHandler(wind, svg) { - editor.showSaveWarning = false; // by default, we add the XML prolog back, systems integrating SVG-edit (wikis, CMSs) - // can just provide their own custom save handler and might not want the XML prolog - - svg = '<?xml version="1.0"?>\n' + svg; // IE9 doesn't allow standalone Data URLs - // https://connect.microsoft.com/IE/feedback/details/542600/data-uri-images-fail-when-loaded-by-themselves - - if (isIE()) { - showSourceEditor(0, true); - return; - } // Since saving SVGs by opening a new window was removed in Chrome use artificial link-click - // https://stackoverflow.com/questions/45603201/window-is-not-allowed-to-navigate-top-frame-navigations-to-data-urls - - - var a = document.createElement('a'); - a.href = 'data:image/svg+xml;base64,' + encode64(svg); - a.download = 'icon.svg'; - a.style.display = 'none'; - document.body.append(a); // Need to append for Firefox - - a.click(); // Alert will only appear the first time saved OR the - // first time the bug is encountered - - var done = editor.pref('save_notice_done'); - - if (done !== 'all') { - var note = uiStrings$1.notification.saveFromBrowser.replace('%s', 'SVG'); // Check if FF and has <defs/> - - if (isGecko()) { - if (svg.includes('<defs')) { - // warning about Mozilla bug #308590 when applicable (seems to be fixed now in Feb 2013) - note += '\n\n' + uiStrings$1.notification.defsFailOnSave; - editor.pref('save_notice_done', 'all'); - done = 'all'; - } else { - editor.pref('save_notice_done', 'part'); - } - } else { - editor.pref('save_notice_done', 'all'); - } - - if (done !== 'part') { - $$c.alert(note); - } - } - }; - /** - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:exported} data - * @listens module:svgcanvas.SvgCanvas#event:exported - * @returns {void} - */ - - - var exportHandler = function exportHandler(win, data) { - var issues = data.issues, - exportWindowName = data.exportWindowName; - exportWindow = window.open(blankPageObjectURL || '', exportWindowName); // A hack to get the window via JSON-able name without opening a new one - - if (!exportWindow || exportWindow.closed) { - /* await */ - $$c.alert(uiStrings$1.notification.popupWindowBlocked); - return; - } - - exportWindow.location.href = data.bloburl || data.datauri; - var done = editor.pref('export_notice_done'); - - if (done !== 'all') { - var note = uiStrings$1.notification.saveFromBrowser.replace('%s', data.type); // Check if there are issues - - if (issues.length) { - var pre = "\n \u2022 "; - note += '\n\n' + uiStrings$1.notification.noteTheseIssues + pre + issues.join(pre); - } // Note that this will also prevent the notice even though new issues may appear later. - // May want to find a way to deal with that without annoying the user - - - editor.pref('export_notice_done', 'all'); - exportWindow.alert(note); - } - }; - /** - * - * @returns {void} - */ - - - var operaRepaint = function operaRepaint() { - // Repaints canvas in Opera. Needed for stroke-dasharray change as well as fill change - if (!window.opera) { - return; - } - - $$c('<p/>').hide().appendTo('body').remove(); - }; - /** - * - * @param {Element} opt - * @param {boolean} changeElem - * @returns {void} - */ - - - function setStrokeOpt(opt, changeElem) { - var id = opt.id; - var bits = id.split('_'); - - var _bits = _slicedToArray(bits, 2), - pre = _bits[0], - val = _bits[1]; - - if (changeElem) { - svgCanvas.setStrokeAttr('stroke-' + pre, val); - } - - operaRepaint(); - setIcon('#cur_' + pre, id, 20); - $$c(opt).addClass('current').siblings().removeClass('current'); - } - /** - * This is a common function used when a tool has been clicked (chosen). - * It does several common things: - * - Removes the `tool_button_current` class from whatever tool currently has it. - * - Hides any flyouts. - * - Adds the `tool_button_current` class to the button passed in. - * @function module:SVGEditor.toolButtonClick - * @param {string|Element} button The DOM element or string selector representing the toolbar button - * @param {boolean} noHiding Whether not to hide any flyouts - * @returns {boolean} Whether the button was disabled or not - */ - - - var toolButtonClick = editor.toolButtonClick = function (button, noHiding) { - if ($$c(button).hasClass('disabled')) { - return false; - } - - if ($$c(button).parent().hasClass('tools_flyout')) { - return true; - } - - var fadeFlyouts = 'normal'; - - if (!noHiding) { - $$c('.tools_flyout').fadeOut(fadeFlyouts); - } - - $$c('#styleoverrides').text(''); - workarea.css('cursor', 'auto'); - $$c('.tool_button_current').removeClass('tool_button_current').addClass('tool_button'); - $$c(button).addClass('tool_button_current').removeClass('tool_button'); - return true; - }; - /** - * Unless the select toolbar button is disabled, sets the button - * and sets the select mode and cursor styles. - * @function module:SVGEditor.clickSelect - * @returns {void} - */ - - - var clickSelect = editor.clickSelect = function () { - if (toolButtonClick('#tool_select')) { - svgCanvas.setMode('select'); - $$c('#styleoverrides').text("\n #svgcanvas svg * {\n cursor: move;\n pointer-events: all;\n }\n #svgcanvas svg {\n cursor: default;\n }\n "); - } - }; - /** - * Set a selected image's URL. - * @function module:SVGEditor.setImageURL - * @param {string} url - * @returns {void} - */ - - - var setImageURL = editor.setImageURL = function (url) { - if (!url) { - url = defaultImageURL; - } - - svgCanvas.setImageURL(url); - $$c('#image_url').val(url); - - if (url.startsWith('data:')) { - // data URI found - $$c('#image_url').hide(); - $$c('#change_image_url').show(); - } else { - // regular URL - svgCanvas.embedImage(url, function (dataURI) { - // Couldn't embed, so show warning - $$c('#url_notice').toggle(!dataURI); - defaultImageURL = url; - }); - $$c('#image_url').show(); - $$c('#change_image_url').hide(); - } - }; - /** - * - * @param {string} color - * @param {string} url - * @returns {void} - */ - - - function setBackground(color, url) { - // if (color == editor.pref('bkgd_color') && url == editor.pref('bkgd_url')) { return; } - editor.pref('bkgd_color', color); - editor.pref('bkgd_url', url, true); // This should be done in svgcanvas.js for the borderRect fill - - svgCanvas.setBackground(color, url); - } - /** - * @param {PlainObject} [opts={}] - * @param {boolean} [opts.cancelDeletes=false}] - * @returns {Promise<void>} Resolves to `undefined` - */ - - - function promptImgURL() { - return _promptImgURL.apply(this, arguments); - } - /** - * @param {Element} elem - * @returns {void} - */ - - - function _promptImgURL() { - _promptImgURL = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee18() { - var _ref28, - _ref28$cancelDeletes, - cancelDeletes, - curhref, - url, - _args18 = arguments; - - return regeneratorRuntime.wrap(function _callee18$(_context18) { - while (1) { - switch (_context18.prev = _context18.next) { - case 0: - _ref28 = _args18.length > 0 && _args18[0] !== undefined ? _args18[0] : {}, _ref28$cancelDeletes = _ref28.cancelDeletes, cancelDeletes = _ref28$cancelDeletes === void 0 ? false : _ref28$cancelDeletes; - curhref = svgCanvas.getHref(selectedElement); - curhref = curhref.startsWith('data:') ? '' : curhref; - _context18.next = 5; - return $$c.prompt(uiStrings$1.notification.enterNewImgURL, curhref); - - case 5: - url = _context18.sent; - - if (url) { - setImageURL(url); - } else if (cancelDeletes) { - svgCanvas.deleteSelectedElements(); - } - - case 7: - case "end": - return _context18.stop(); - } - } - }, _callee18); - })); - return _promptImgURL.apply(this, arguments); - } - - var setInputWidth = function setInputWidth(elem) { - var w = Math.min(Math.max(12 + elem.value.length * 6, 50), 300); - $$c(elem).width(w); - }; - /** - * - * @param {HTMLDivElement} [scanvas] - * @param {Float} [zoom] - * @returns {void} - */ - - - function updateRulers(scanvas, zoom) { - if (!zoom) { - zoom = svgCanvas.getZoom(); - } - - if (!scanvas) { - scanvas = $$c('#svgcanvas'); - } - - var d, i; - var limit = 30000; - var contentElem = svgCanvas.getContentElem(); - var units = getTypeMap(); - var unit = units[curConfig.baseUnit]; // 1 = 1px - // draw x ruler then y ruler - - for (d = 0; d < 2; d++) { - var isX = d === 0; - var dim = isX ? 'x' : 'y'; - var lentype = isX ? 'width' : 'height'; - var contentDim = Number(contentElem.getAttribute(dim)); - var $hcanvOrig = $$c('#ruler_' + dim + ' canvas:first'); // Bit of a hack to fully clear the canvas in Safari & IE9 - - var $hcanv = $hcanvOrig.clone(); - $hcanvOrig.replaceWith($hcanv); - var hcanv = $hcanv[0]; // Set the canvas size to the width of the container - - var rulerLen = scanvas[lentype](); - var totalLen = rulerLen; - hcanv.parentNode.style[lentype] = totalLen + 'px'; - var ctx = hcanv.getContext('2d'); - var ctxArr = void 0, - num = void 0, - ctxArrNum = void 0; - ctx.fillStyle = 'rgb(200,0,0)'; - ctx.fillRect(0, 0, hcanv.width, hcanv.height); // Remove any existing canvasses - - $hcanv.siblings().remove(); // Create multiple canvases when necessary (due to browser limits) - - if (rulerLen >= limit) { - ctxArrNum = Number.parseInt(rulerLen / limit) + 1; - ctxArr = []; - ctxArr[0] = ctx; - var copy = void 0; - - for (i = 1; i < ctxArrNum; i++) { - hcanv[lentype] = limit; - copy = hcanv.cloneNode(true); - hcanv.parentNode.append(copy); - ctxArr[i] = copy.getContext('2d'); - } - - copy[lentype] = rulerLen % limit; // set copy width to last - - rulerLen = limit; - } - - hcanv[lentype] = rulerLen; - var uMulti = unit * zoom; // Calculate the main number interval - - var rawM = 50 / uMulti; - var multi = 1; - - for (i = 0; i < rIntervals.length; i++) { - num = rIntervals[i]; - multi = num; - - if (rawM <= num) { - break; - } - } - - var bigInt = multi * uMulti; - ctx.font = '9px sans-serif'; - var rulerD = contentDim / uMulti % multi * uMulti; - var labelPos = rulerD - bigInt; // draw big intervals - - var ctxNum = 0; - - while (rulerD < totalLen) { - labelPos += bigInt; // const realD = rulerD - contentDim; // Currently unused - - var curD = Math.round(rulerD) + 0.5; - - if (isX) { - ctx.moveTo(curD, 15); - ctx.lineTo(curD, 0); - } else { - ctx.moveTo(15, curD); - ctx.lineTo(0, curD); - } - - num = (labelPos - contentDim) / uMulti; - var label = void 0; - - if (multi >= 1) { - label = Math.round(num); - } else { - var decs = String(multi).split('.')[1].length; - label = num.toFixed(decs); - } // Change 1000s to Ks - - - if (label !== 0 && label !== 1000 && label % 1000 === 0) { - label = label / 1000 + 'K'; - } - - if (isX) { - ctx.fillText(label, rulerD + 2, 8); - } else { - // draw label vertically - var _str = String(label).split(''); - - for (i = 0; i < _str.length; i++) { - ctx.fillText(_str[i], 1, rulerD + 9 + i * 9); - } - } - - var part = bigInt / 10; // draw the small intervals - - for (i = 1; i < 10; i++) { - var subD = Math.round(rulerD + part * i) + 0.5; - - if (ctxArr && subD > rulerLen) { - ctxNum++; - ctx.stroke(); - - if (ctxNum >= ctxArrNum) { - i = 10; - rulerD = totalLen; - continue; - } - - ctx = ctxArr[ctxNum]; - rulerD -= limit; - subD = Math.round(rulerD + part * i) + 0.5; - } // odd lines are slighly longer - - - var lineNum = i % 2 ? 12 : 10; - - if (isX) { - ctx.moveTo(subD, 15); - ctx.lineTo(subD, lineNum); - } else { - ctx.moveTo(15, subD); - ctx.lineTo(lineNum, subD); - } - } - - rulerD += bigInt; - } - - ctx.strokeStyle = '#000'; - ctx.stroke(); - } - } - /** - * @function module:SVGEditor.updateCanvas - * @param {boolean} center - * @param {module:math.XYObject} newCtr - * @returns {void} - */ - - - var updateCanvas = editor.updateCanvas = function (center, newCtr) { - var zoom = svgCanvas.getZoom(); - var wArea = workarea; - var cnvs = $$c('#svgcanvas'); - var w = workarea.width(), - h = workarea.height(); - var wOrig = w, - hOrig = h; - var oldCtr = { - x: wArea[0].scrollLeft + wOrig / 2, - y: wArea[0].scrollTop + hOrig / 2 - }; - var multi = curConfig.canvas_expansion; - w = Math.max(wOrig, svgCanvas.contentW * zoom * multi); - h = Math.max(hOrig, svgCanvas.contentH * zoom * multi); - - if (w === wOrig && h === hOrig) { - workarea.css('overflow', 'hidden'); - } else { - workarea.css('overflow', 'scroll'); - } - - var oldCanY = cnvs.height() / 2; - var oldCanX = cnvs.width() / 2; - cnvs.width(w).height(h); - var newCanY = h / 2; - var newCanX = w / 2; - var offset = svgCanvas.updateCanvas(w, h); - var ratio = newCanX / oldCanX; - var scrollX = w / 2 - wOrig / 2; // eslint-disable-line no-shadow - - var scrollY = h / 2 - hOrig / 2; // eslint-disable-line no-shadow - - if (!newCtr) { - var oldDistX = oldCtr.x - oldCanX; - var newX = newCanX + oldDistX * ratio; - var oldDistY = oldCtr.y - oldCanY; - var newY = newCanY + oldDistY * ratio; - newCtr = { - x: newX, - y: newY - }; - } else { - newCtr.x += offset.x; - newCtr.y += offset.y; - } - - if (center) { - // Go to top-left for larger documents - if (svgCanvas.contentW > wArea.width()) { - // Top-left - workarea[0].scrollLeft = offset.x - 10; - workarea[0].scrollTop = offset.y - 10; - } else { - // Center - wArea[0].scrollLeft = scrollX; - wArea[0].scrollTop = scrollY; - } - } else { - wArea[0].scrollLeft = newCtr.x - wOrig / 2; - wArea[0].scrollTop = newCtr.y - hOrig / 2; - } - - if (curConfig.showRulers) { - updateRulers(cnvs, zoom); - workarea.scroll(); - } - - if (urldata.storagePrompt !== true && editor.storagePromptState === 'ignore') { - $$c('#dialog_box').hide(); - } - }; - /** - * @fires module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate - * @returns {void} - */ - - - var updateToolButtonState = function updateToolButtonState() { - var bNoFill = svgCanvas.getColor('fill') === 'none'; - var bNoStroke = svgCanvas.getColor('stroke') === 'none'; - var buttonsNeedingStroke = ['#tool_fhpath', '#tool_line']; - var buttonsNeedingFillAndStroke = ['#tools_rect .tool_button', '#tools_ellipse .tool_button', '#tool_text', '#tool_path']; - - if (bNoStroke) { - buttonsNeedingStroke.forEach(function (btn) { - if ($$c(btn).hasClass('tool_button_current')) { - clickSelect(); - } - - $$c(btn).addClass('disabled'); - }); - } else { - buttonsNeedingStroke.forEach(function (btn) { - $$c(btn).removeClass('disabled'); - }); - } - - if (bNoStroke && bNoFill) { - buttonsNeedingFillAndStroke.forEach(function (btn) { - if ($$c(btn).hasClass('tool_button_current')) { - clickSelect(); - } - - $$c(btn).addClass('disabled'); - }); - } else { - buttonsNeedingFillAndStroke.forEach(function (btn) { - $$c(btn).removeClass('disabled'); - }); - } - - svgCanvas.runExtensions('toolButtonStateUpdate', - /** @type {module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate} */ - { - nofill: bNoFill, - nostroke: bNoStroke - }); // Disable flyouts if all inside are disabled - - $$c('.tools_flyout').each(function () { - var shower = $$c('#' + this.id + '_show'); - var hasEnabled = false; - $$c(this).children().each(function () { - if (!$$c(this).hasClass('disabled')) { - hasEnabled = true; - } - }); - shower.toggleClass('disabled', !hasEnabled); - }); - operaRepaint(); - }; - /** - * Updates the toolbar (colors, opacity, etc) based on the selected element. - * This function also updates the opacity and id elements that are in the - * context panel. - * @returns {void} - */ - - - var updateToolbar = function updateToolbar() { - var i, len; - - if (!isNullish(selectedElement)) { - switch (selectedElement.tagName) { - case 'use': - case 'image': - case 'foreignObject': - break; - - case 'g': - case 'a': - { - // Look for common styles - var childs = selectedElement.getElementsByTagName('*'); - var gWidth = null; - - for (i = 0, len = childs.length; i < len; i++) { - var swidth = childs[i].getAttribute('stroke-width'); - - if (i === 0) { - gWidth = swidth; - } else if (gWidth !== swidth) { - gWidth = null; - } - } - - $$c('#stroke_width').val(gWidth === null ? '' : gWidth); - paintBox.fill.update(true); - paintBox.stroke.update(true); - break; - } - - default: - { - paintBox.fill.update(true); - paintBox.stroke.update(true); - $$c('#stroke_width').val(selectedElement.getAttribute('stroke-width') || 1); - $$c('#stroke_style').val(selectedElement.getAttribute('stroke-dasharray') || 'none'); - var attr = selectedElement.getAttribute('stroke-linejoin') || 'miter'; - - if ($$c('#linejoin_' + attr).length) { - setStrokeOpt($$c('#linejoin_' + attr)[0]); - } - - attr = selectedElement.getAttribute('stroke-linecap') || 'butt'; - - if ($$c('#linecap_' + attr).length) { - setStrokeOpt($$c('#linecap_' + attr)[0]); - } - } - } - } // All elements including image and group have opacity - - - if (!isNullish(selectedElement)) { - var opacPerc = (selectedElement.getAttribute('opacity') || 1.0) * 100; - $$c('#group_opacity').val(opacPerc); - $$c('#opac_slider').slider('option', 'value', opacPerc); - $$c('#elem_id').val(selectedElement.id); - $$c('#elem_class').val(selectedElement.getAttribute('class')); - } - - updateToolButtonState(); - }; - /** - * Updates the context panel tools based on the selected element. - * @returns {void} - */ - - - var updateContextPanel = function updateContextPanel() { - var elem = selectedElement; // If element has just been deleted, consider it null - - if (!isNullish(elem) && !elem.parentNode) { - elem = null; - } - - var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName(); - var currentMode = svgCanvas.getMode(); - var unit = curConfig.baseUnit !== 'px' ? curConfig.baseUnit : null; - var isNode = currentMode === 'pathedit'; // elem ? (elem.id && elem.id.startsWith('pathpointgrip')) : false; - - var menuItems = $$c('#cmenu_canvas li'); - $$c('#selected_panel, #multiselected_panel, #g_panel, #rect_panel, #circle_panel,' + '#ellipse_panel, #line_panel, #text_panel, #image_panel, #container_panel,' + ' #use_panel, #a_panel').hide(); - - if (!isNullish(elem)) { - var elname = elem.nodeName; // If this is a link with no transform and one child, pretend - // its child is selected - // if (elname === 'a') { // && !$(elem).attr('transform')) { - // elem = elem.firstChild; - // } - - var angle = svgCanvas.getRotationAngle(elem); - $$c('#angle').val(angle); - var blurval = svgCanvas.getBlur(elem); - $$c('#blur').val(blurval); - $$c('#blur_slider').slider('option', 'value', blurval); - - if (svgCanvas.addedNew) { - if (elname === 'image' && svgCanvas.getMode() === 'image') { - // Prompt for URL if not a data URL - if (!svgCanvas.getHref(elem).startsWith('data:')) { - /* await */ - promptImgURL({ - cancelDeletes: true - }); - } - } - /* else if (elname == 'text') { - // TODO: Do something here for new text - } */ - - } - - if (!isNode && currentMode !== 'pathedit') { - $$c('#selected_panel').show(); // Elements in this array already have coord fields - - if (['line', 'circle', 'ellipse'].includes(elname)) { - $$c('#xy_panel').hide(); - } else { - var x, y; // Get BBox vals for g, polyline and path - - if (['g', 'polyline', 'path'].includes(elname)) { - var bb = svgCanvas.getStrokedBBox([elem]); - - if (bb) { - x = bb.x; - y = bb.y; - } - } else { - x = elem.getAttribute('x'); - y = elem.getAttribute('y'); - } - - if (unit) { - x = convertUnit(x); - y = convertUnit(y); - } - - $$c('#selected_x').val(x || 0); - $$c('#selected_y').val(y || 0); - $$c('#xy_panel').show(); - } // Elements in this array cannot be converted to a path - - - var noPath = !['image', 'text', 'path', 'g', 'use'].includes(elname); - $$c('#tool_topath').toggle(noPath); - $$c('#tool_reorient').toggle(elname === 'path'); - $$c('#tool_reorient').toggleClass('disabled', angle === 0); - } else { - var point = path.getNodePoint(); - $$c('#tool_add_subpath').removeClass('push_button_pressed').addClass('tool_button'); - $$c('#tool_node_delete').toggleClass('disabled', !path.canDeleteNodes); // Show open/close button based on selected point - - setIcon('#tool_openclose_path', path.closed_subpath ? 'open_path' : 'close_path'); - - if (point) { - var segType = $$c('#seg_type'); - - if (unit) { - point.x = convertUnit(point.x); - point.y = convertUnit(point.y); - } - - $$c('#path_node_x').val(point.x); - $$c('#path_node_y').val(point.y); - - if (point.type) { - segType.val(point.type).removeAttr('disabled'); - } else { - segType.val(4).attr('disabled', 'disabled'); - } - } - - return; - } // update contextual tools here - - - var panels = { - g: [], - a: [], - rect: ['rx', 'width', 'height'], - image: ['width', 'height'], - circle: ['cx', 'cy', 'r'], - ellipse: ['cx', 'cy', 'rx', 'ry'], - line: ['x1', 'y1', 'x2', 'y2'], - text: [], - use: [] - }; - var _elem = elem, - tagName = _elem.tagName; // if ($(elem).data('gsvg')) { - // $('#g_panel').show(); - // } - - var linkHref = null; - - if (tagName === 'a') { - linkHref = svgCanvas.getHref(elem); - $$c('#g_panel').show(); - } - - if (elem.parentNode.tagName === 'a') { - if (!$$c(elem).siblings().length) { - $$c('#a_panel').show(); - linkHref = svgCanvas.getHref(elem.parentNode); - } - } // Hide/show the make_link buttons - - - $$c('#tool_make_link, #tool_make_link').toggle(!linkHref); - - if (linkHref) { - $$c('#link_url').val(linkHref); - } - - if (panels[tagName]) { - var curPanel = panels[tagName]; - $$c('#' + tagName + '_panel').show(); - $$c.each(curPanel, function (i, item) { - var attrVal = elem.getAttribute(item); - - if (curConfig.baseUnit !== 'px' && elem[item]) { - var bv = elem[item].baseVal.value; - attrVal = convertUnit(bv); - } - - $$c('#' + tagName + '_' + item).val(attrVal || 0); - }); - - if (tagName === 'text') { - $$c('#text_panel').css('display', 'inline'); - $$c('#tool_font_size').css('display', 'inline'); - - if (svgCanvas.getItalic()) { - $$c('#tool_italic').addClass('push_button_pressed').removeClass('tool_button'); - } else { - $$c('#tool_italic').removeClass('push_button_pressed').addClass('tool_button'); - } - - if (svgCanvas.getBold()) { - $$c('#tool_bold').addClass('push_button_pressed').removeClass('tool_button'); - } else { - $$c('#tool_bold').removeClass('push_button_pressed').addClass('tool_button'); - } - - $$c('#font_family').val(elem.getAttribute('font-family')); - $$c('#font_size').val(elem.getAttribute('font-size')); - $$c('#text').val(elem.textContent); - - if (svgCanvas.addedNew) { - // Timeout needed for IE9 - setTimeout(function () { - $$c('#text').focus().select(); - }, 100); - } // text - - } else if (tagName === 'image' && svgCanvas.getMode() === 'image') { - setImageURL(svgCanvas.getHref(elem)); // image - } else if (tagName === 'g' || tagName === 'use') { - $$c('#container_panel').show(); - var title = svgCanvas.getTitle(); - var label = $$c('#g_title')[0]; - label.value = title; - setInputWidth(label); - $$c('#g_title').prop('disabled', tagName === 'use'); - } - } - - menuItems[(tagName === 'g' ? 'en' : 'dis') + 'ableContextMenuItems']('#ungroup'); - menuItems[(tagName === 'g' || !multiselected ? 'dis' : 'en') + 'ableContextMenuItems']('#group'); // if (!Utils.isNullish(elem)) - } else if (multiselected) { - $$c('#multiselected_panel').show(); - menuItems.enableContextMenuItems('#group').disableContextMenuItems('#ungroup'); - } else { - menuItems.disableContextMenuItems('#delete,#cut,#copy,#group,#ungroup,#move_front,#move_up,#move_down,#move_back'); - } // update history buttons - - - $$c('#tool_undo').toggleClass('disabled', undoMgr.getUndoStackSize() === 0); - $$c('#tool_redo').toggleClass('disabled', undoMgr.getRedoStackSize() === 0); - svgCanvas.addedNew = false; - - if (elem && !isNode || multiselected) { - // update the selected elements' layer - $$c('#selLayerNames').removeAttr('disabled').val(currentLayerName); // Enable regular menu options - - canvMenu.enableContextMenuItems('#delete,#cut,#copy,#move_front,#move_up,#move_down,#move_back'); - } else { - $$c('#selLayerNames').attr('disabled', 'disabled'); - } - }; - /** - * - * @returns {void} - */ - - - var updateWireFrame = function updateWireFrame() { - // Test support - if (supportsNonSS) { - return; - } - - var rule = "\n #workarea.wireframe #svgcontent * {\n stroke-width: ".concat(1 / svgCanvas.getZoom(), "px;\n }\n "); - $$c('#wireframe_rules').text(workarea.hasClass('wireframe') ? rule : ''); - }; - - var curContext = ''; - /** - * @param {string} [title=svgCanvas.getDocumentTitle()] - * @returns {void} - */ - - var updateTitle = function updateTitle(title) { - title = title || svgCanvas.getDocumentTitle(); - var newTitle = origTitle + (title ? ': ' + title : ''); // Remove title update with current context info, isn't really necessary - // if (curContext) { - // new_title = new_title + curContext; - // } - - $$c('title:first').text(newTitle); - }; // called when we've selected a different element - - /** - * - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:selected} elems Array of elements that were selected - * @listens module:svgcanvas.SvgCanvas#event:selected - * @fires module:svgcanvas.SvgCanvas#event:ext_selectedChanged - * @returns {void} - */ - - - var selectedChanged = function selectedChanged(win, elems) { - var mode = svgCanvas.getMode(); - - if (mode === 'select') { - setSelectMode(); - } - - var isNode = mode === 'pathedit'; // if elems[1] is present, then we have more than one element - - selectedElement = elems.length === 1 || isNullish(elems[1]) ? elems[0] : null; - multiselected = elems.length >= 2 && !isNullish(elems[1]); - - if (!isNullish(selectedElement)) { - // unless we're already in always set the mode of the editor to select because - // upon creation of a text element the editor is switched into - // select mode and this event fires - we need our UI to be in sync - if (!isNode) { - updateToolbar(); - } - } // if (!Utils.isNullish(elem)) - // Deal with pathedit mode - - - togglePathEditMode(isNode, elems); - updateContextPanel(); - svgCanvas.runExtensions('selectedChanged', - /** @type {module:svgcanvas.SvgCanvas#event:ext_selectedChanged} */ - { - elems: elems, - selectedElement: selectedElement, - multiselected: multiselected - }); - }; // Call when part of element is in process of changing, generally - // on mousemove actions like rotate, move, etc. - - /** - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:transition} elems - * @listens module:svgcanvas.SvgCanvas#event:transition - * @fires module:svgcanvas.SvgCanvas#event:ext_elementTransition - * @returns {void} - */ - - - var elementTransition = function elementTransition(win, elems) { - var mode = svgCanvas.getMode(); - var elem = elems[0]; - - if (!elem) { - return; - } - - multiselected = elems.length >= 2 && !isNullish(elems[1]); // Only updating fields for single elements for now - - if (!multiselected) { - switch (mode) { - case 'rotate': - { - var ang = svgCanvas.getRotationAngle(elem); - $$c('#angle').val(ang); - $$c('#tool_reorient').toggleClass('disabled', ang === 0); - break; // TODO: Update values that change on move/resize, etc - // } case 'select': { - // } case 'resize': { - // break; - // } - } - } - } - - svgCanvas.runExtensions('elementTransition', - /** @type {module:svgcanvas.SvgCanvas#event:ext_elementTransition} */ - { - elems: elems - }); - }; - /** - * Test whether an element is a layer or not. - * @param {SVGGElement} elem - The SVGGElement to test. - * @returns {boolean} True if the element is a layer - */ - - - function isLayer(elem) { - return elem && elem.tagName === 'g' && Layer.CLASS_REGEX.test(elem.getAttribute('class')); - } // called when any element has changed - - /** - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:changed} elems - * @listens module:svgcanvas.SvgCanvas#event:changed - * @fires module:svgcanvas.SvgCanvas#event:ext_elementChanged - * @returns {void} - */ - - - var elementChanged = function elementChanged(win, elems) { - var mode = svgCanvas.getMode(); - - if (mode === 'select') { - setSelectMode(); - } - - elems.forEach(function (elem) { - var isSvgElem = elem && elem.tagName === 'svg'; - - if (isSvgElem || isLayer(elem)) { - populateLayers(); // if the element changed was the svg, then it could be a resolution change - - if (isSvgElem) { - updateCanvas(); - } // Update selectedElement if element is no longer part of the image. - // This occurs for the text elements in Firefox - - } else if (elem && selectedElement && isNullish(selectedElement.parentNode)) { - // || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why - selectedElement = elem; - } - }); - editor.showSaveWarning = true; // we update the contextual panel with potentially new - // positional/sizing information (we DON'T want to update the - // toolbar here as that creates an infinite loop) - // also this updates the history buttons - // we tell it to skip focusing the text control if the - // text element was previously in focus - - updateContextPanel(); // In the event a gradient was flipped: - - if (selectedElement && mode === 'select') { - paintBox.fill.update(); - paintBox.stroke.update(); - } - - svgCanvas.runExtensions('elementChanged', - /** @type {module:svgcanvas.SvgCanvas#event:ext_elementChanged} */ - { - elems: elems - }); - }; - /** - * @returns {void} - */ - - - var zoomDone = function zoomDone() { - updateWireFrame(); // updateCanvas(); // necessary? - }; - /** - * @typedef {PlainObject} module:SVGEditor.BBoxObjectWithFactor (like `DOMRect`) - * @property {Float} x - * @property {Float} y - * @property {Float} width - * @property {Float} height - * @property {Float} [factor] Needed if width or height are 0 - * @property {Float} [zoom] - * @see module:svgcanvas.SvgCanvas#event:zoomed - */ - - /** - * @function module:svgcanvas.SvgCanvas#zoomChanged - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:zoomed} bbox - * @param {boolean} autoCenter - * @listens module:svgcanvas.SvgCanvas#event:zoomed - * @returns {void} - */ - - - var zoomChanged = svgCanvas.zoomChanged = function (win, bbox, autoCenter) { - var scrbar = 15, - // res = svgCanvas.getResolution(), // Currently unused - wArea = workarea; // const canvasPos = $('#svgcanvas').position(); // Currently unused - - var zInfo = svgCanvas.setBBoxZoom(bbox, wArea.width() - scrbar, wArea.height() - scrbar); - - if (!zInfo) { - return; - } - - var zoomlevel = zInfo.zoom, - bb = zInfo.bbox; - - if (zoomlevel < 0.001) { - changeZoom({ - value: 0.1 - }); - return; - } - - $$c('#zoom').val((zoomlevel * 100).toFixed(1)); - - if (autoCenter) { - updateCanvas(); - } else { - updateCanvas(false, { - x: bb.x * zoomlevel + bb.width * zoomlevel / 2, - y: bb.y * zoomlevel + bb.height * zoomlevel / 2 - }); - } - - if (svgCanvas.getMode() === 'zoom' && bb.width) { - // Go to select if a zoom box was drawn - setSelectMode(); - } - - zoomDone(); - }; - /** - * @type {module:jQuerySpinButton.ValueCallback} - */ - - - var changeZoom = function changeZoom(ctl) { - var zoomlevel = ctl.value / 100; - - if (zoomlevel < 0.001) { - ctl.value = 0.1; - return; - } - - var zoom = svgCanvas.getZoom(); - var wArea = workarea; - zoomChanged(window, { - width: 0, - height: 0, - // center pt of scroll position - x: (wArea[0].scrollLeft + wArea.width() / 2) / zoom, - y: (wArea[0].scrollTop + wArea.height() / 2) / zoom, - zoom: zoomlevel - }, true); - }; - - $$c('#cur_context_panel').delegate('a', 'click', function () { - var link = $$c(this); - - if (link.attr('data-root')) { - svgCanvas.leaveContext(); - } else { - svgCanvas.setContext(link.text()); - } - - svgCanvas.clearSelection(); - return false; - }); - /** - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:contextset} context - * @listens module:svgcanvas.SvgCanvas#event:contextset - * @returns {void} - */ - - var contextChanged = function contextChanged(win, context) { - var linkStr = ''; - - if (context) { - var _str2 = ''; - linkStr = '<a href="#" data-root="y">' + svgCanvas.getCurrentDrawing().getCurrentLayerName() + '</a>'; - $$c(context).parentsUntil('#svgcontent > g').andSelf().each(function () { - if (this.id) { - _str2 += ' > ' + this.id; - - if (this !== context) { - linkStr += ' > <a href="#">' + this.id + '</a>'; - } else { - linkStr += ' > ' + this.id; - } - } - }); - curContext = _str2; - } else { - curContext = null; - } - - $$c('#cur_context_panel').toggle(Boolean(context)).html(linkStr); - updateTitle(); - }; - /** - * Makes sure the current selected paint is available to work with. - * @returns {void} - */ - - - var prepPaints = function prepPaints() { - paintBox.fill.prep(); - paintBox.stroke.prep(); - }; - - var flyoutFuncs = {}; - /** - * - * @returns {void} - */ - - var setFlyoutTitles = function setFlyoutTitles() { - $$c('.tools_flyout').each(function () { - var shower = $$c('#' + this.id + '_show'); - - if (shower.data('isLibrary')) { - return; - } - - var tooltips = $$c(this).children().map(function () { - return this.title; - }).get(); - shower[0].title = tooltips.join(' / '); - }); - }; - - var allHolders = {}; - /** - * @param {PlainObject<string, module:SVGEditor.ToolButton>} holders Key is a selector - * @returns {void} - */ - - var setupFlyouts = function setupFlyouts(holders) { - $$c.each(holders, function (holdSel, btnOpts) { - var _allHolders$holdSel; - - if (!allHolders[holdSel]) { - allHolders[holdSel] = []; - } - - (_allHolders$holdSel = allHolders[holdSel]).push.apply(_allHolders$holdSel, _toConsumableArray(btnOpts)); - - var buttons = $$c(holdSel).children().not('.tool_button_evt_handled'); - var showSel = holdSel + '_show'; - var shower = $$c(showSel); - var def = false; - buttons.addClass('tool_button tool_button_evt_handled').unbind('click mousedown mouseup') // may not be necessary - .each(function () { - // Get this button's options - var idSel = '#' + this.getAttribute('id'); - - var _Object$entries$find = Object.entries(btnOpts).find(function (_ref8) { - var _ref9 = _slicedToArray(_ref8, 2), - _ = _ref9[0], - sel = _ref9[1].sel; - - return sel === idSel; - }), - _Object$entries$find2 = _slicedToArray(_Object$entries$find, 2), - i = _Object$entries$find2[0], - opts = _Object$entries$find2[1]; // Remember the function that goes with this ID - - - flyoutFuncs[opts.sel] = opts.fn; - - if (opts.isDefault) { - def = i; - } - /** - * Clicking the icon in flyout should set this set's icon. - * @param {Event} ev - * @returns {boolean} - */ - - - var flyoutAction = function flyoutAction(ev) { - var options = opts; // Find the currently selected tool if comes from keystroke - - if (ev.type === 'keydown') { - var flyoutIsSelected = $$c(options.parent + '_show').hasClass('tool_button_current'); - var currentOperation = $$c(options.parent + '_show').attr('data-curopt'); - Object.entries(holders[opts.parent]).some(function (_ref10) { - var _ref11 = _slicedToArray(_ref10, 2), - j = _ref11[0], - tool = _ref11[1]; - - if (tool.sel !== currentOperation) { - return false; - } - - if (!ev.shiftKey || !flyoutIsSelected) { - options = tool; - } else { - // If flyout is selected, allow shift key to iterate through subitems - j = Number.parseInt(j); // Use `allHolders` to include both extension `includeWith` and toolbarButtons - - options = allHolders[opts.parent][j + 1] || holders[opts.parent][0]; - } - - return true; - }); - } - - if ($$c(this).hasClass('disabled')) { - return false; - } - - if (toolButtonClick(showSel)) { - options.fn(); - } - - var icon; - - if (options.icon) { - icon = $$c.getSvgIcon(options.icon, true); - } else { - icon = $$c(options.sel).children().eq(0).clone(); - } - - icon[0].setAttribute('width', shower.width()); - icon[0].setAttribute('height', shower.height()); - shower.children(':not(.flyout_arrow_horiz)').remove(); - shower.append(icon).attr('data-curopt', options.sel); // This sets the current mode - - return true; - }; - - $$c(this).mouseup(flyoutAction); - - if (opts.key) { - $$c(document).bind('keydown', opts.key[0] + ' shift+' + opts.key[0], flyoutAction); - } - - return true; - }); - - if (def) { - shower.attr('data-curopt', btnOpts[def].sel); - } else if (!shower.attr('data-curopt')) { - // Set first as default - shower.attr('data-curopt', btnOpts[0].sel); - } - - var timer; // Clicking the "show" icon should set the current mode - - shower.mousedown(function (evt) { - if (shower.hasClass('disabled')) { - return false; - } - - var holder = $$c(holdSel); - var pos = $$c(showSel).position(); - var l = pos.left + 34; - var w = holder.width() * -1; - var time = holder.data('shown_popop') ? 200 : 0; - timer = setTimeout(function () { - // Show corresponding menu - if (!shower.data('isLibrary')) { - holder.css('left', w).show().animate({ - left: l - }, 150); - } else { - holder.css('left', l).show(); - } - - holder.data('shown_popop', true); - }, time); - evt.preventDefault(); - return true; - }).mouseup(function (evt) { - clearTimeout(timer); - var opt = $$c(this).attr('data-curopt'); // Is library and popped up, so do nothing - - if (shower.data('isLibrary') && $$c(showSel.replace('_show', '')).is(':visible')) { - toolButtonClick(showSel, true); - return; - } - - if (toolButtonClick(showSel) && flyoutFuncs[opt]) { - flyoutFuncs[opt](); - } - }); // $('#tools_rect').mouseleave(function () { $('#tools_rect').fadeOut(); }); - }); - setFlyoutTitles(); - setFlyoutPositions(); - }; - /** - * @param {string} id - * @param {external:jQuery} child - * @returns {external:jQuery} - */ - - - var makeFlyoutHolder = function makeFlyoutHolder(id, child) { - var div = $$c('<div>', { - "class": 'tools_flyout', - id: id - }).appendTo('#svg_editor').append(child); - return div; - }; - /** - * @param {string} elemSel - * @param {string} listSel - * @param {external:jQuery.Function} callback - * @param {PlainObject} opts - * @param {boolean} opts.dropUp - * @param {boolean} opts.seticon - * @param {boolean} opts.multiclick - * @todo Combine this with `addDropDown` or find other way to optimize. - * @returns {void} - */ - - - var addAltDropDown = function addAltDropDown(elemSel, listSel, callback, opts) { - var button = $$c(elemSel); - var dropUp = opts.dropUp; - var list = $$c(listSel); - - if (dropUp) { - $$c(elemSel).addClass('dropup'); - } - - list.find('li').bind('mouseup', function () { - if (opts.seticon) { - setIcon('#cur_' + button[0].id, $$c(this).children()); - $$c(this).addClass('current').siblings().removeClass('current'); - } - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply.apply(callback, [this].concat(args)); - }); - var onButton = false; - $$c(window).mouseup(function (evt) { - if (!onButton) { - button.removeClass('down'); - list.hide(); - list.css({ - top: 0, - left: 0 - }); - } - - onButton = false; - }); // const height = list.height(); // Currently unused - - button.bind('mousedown', function () { - var off = button.offset(); - - if (dropUp) { - off.top -= list.height(); - off.left += 8; - } else { - off.top += button.height(); - } - - list.offset(off); - - if (!button.hasClass('down')) { - list.show(); - onButton = true; - } else { - // CSS position must be reset for Webkit - list.hide(); - list.css({ - top: 0, - left: 0 - }); - } - - button.toggleClass('down'); - }).hover(function () { - onButton = true; - }).mouseout(function () { - onButton = false; - }); - - if (opts.multiclick) { - list.mousedown(function () { - onButton = true; - }); - } - }; - - var extsPreLang = []; - /** - * @param {external:Window} win - * @param {module:svgcanvas.SvgCanvas#event:extension_added} ext - * @listens module:svgcanvas.SvgCanvas#event:extension_added - * @returns {Promise<void>|void} Resolves to `undefined` - */ - - var extAdded = /*#__PURE__*/function () { - var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(win, ext) { - var cbCalled, resizeDone, lang, prepResize, runCallback, btnSelects, svgicons, fallbackObj, altsObj, placementObj, holders; - return regeneratorRuntime.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - prepResize = function _prepResize() { - if (resizeTimer) { - clearTimeout(resizeTimer); - resizeTimer = null; - } - - if (!resizeDone) { - resizeTimer = setTimeout(function () { - resizeDone = true; - setIconSize(editor.pref('iconsize')); - }, 50); - } - }; - - if (ext) { - _context5.next = 3; - break; - } - - return _context5.abrupt("return", undefined); - - case 3: - cbCalled = false; - resizeDone = false; - - if (!ext.langReady) { - _context5.next = 14; - break; - } - - if (!editor.langChanged) { - _context5.next = 13; - break; - } - - // We check for this since the "lang" pref could have been set by storage - lang = editor.pref('lang'); - _context5.next = 10; - return ext.langReady({ - lang: lang, - uiStrings: uiStrings$1, - importLocale: getImportLocale({ - defaultLang: lang, - defaultName: ext.name - }) - }); - - case 10: - loadedExtensionNames.push(ext.name); - _context5.next = 14; - break; - - case 13: - extsPreLang.push(ext); - - case 14: - /** - * - * @returns {void} - */ - runCallback = function runCallback() { - if (ext.callback && !cbCalled) { - cbCalled = true; - ext.callback.call(editor); - } - }; - - btnSelects = []; - /** - * @typedef {PlainObject} module:SVGEditor.ContextTool - * @property {string} panel The ID of the existing panel to which the tool is being added. Required. - * @property {string} id The ID of the actual tool element. Required. - * @property {PlainObject<string, external:jQuery.Function>|PlainObject<"change", external:jQuery.Function>} events DOM event names keyed to associated functions. Example: `{change () { alert('Option was changed') } }`. "change" event is one specifically handled for the "button-select" type. Required. - * @property {string} title The tooltip text that will appear when the user hovers over the tool. Required. - * @property {"tool_button"|"select"|"button-select"|"input"|string} type The type of tool being added. Expected. - * @property {PlainObject<string, string>} [options] List of options and their labels for select tools. Example: `{1: 'One', 2: 'Two', all: 'All' }`. Required by "select" tools. - * @property {string} [container_id] The ID to be given to the tool's container element. - * @property {string} [defval] Default value - * @property {string|Integer} [colnum] Added as part of the option list class. - * @property {string} [label] Label associated with the tool, visible in the UI - * @property {Integer} [size] Value of the "size" attribute of the tool input - * @property {module:jQuerySpinButton.SpinButtonConfig} [spindata] When added to a tool of type "input", this tool becomes a "spinner" which allows the number to be in/decreased. - */ - - if (ext.context_tools) { - $$c.each(ext.context_tools, function (i, tool) { - // Add select tool - var contId = tool.container_id ? ' id="' + tool.container_id + '"' : ''; - var panel = $$c('#' + tool.panel); // create the panel if it doesn't exist - - if (!panel.length) { - panel = $$c('<div>', { - id: tool.panel - }).appendTo('#tools_top'); - } - - var html; // TODO: Allow support for other types, or adding to existing tool - - switch (tool.type) { - case 'tool_button': - { - html = '<div class="tool_button">' + tool.id + '</div>'; - var div = $$c(html).appendTo(panel); - - if (tool.events) { - $$c.each(tool.events, function (evt, func) { - $$c(div).bind(evt, func); - }); - } - - break; - } - - case 'select': - { - html = '<label' + contId + '>' + '<select id="' + tool.id + '">'; - $$c.each(tool.options, function (val, text) { - var sel = val === tool.defval ? ' selected' : ''; - html += '<option value="' + val + '"' + sel + '>' + text + '</option>'; - }); - html += '</select></label>'; // Creates the tool, hides & adds it, returns the select element - - var sel = $$c(html).appendTo(panel).find('select'); - $$c.each(tool.events, function (evt, func) { - $$c(sel).bind(evt, func); - }); - break; - } - - case 'button-select': - { - html = '<div id="' + tool.id + '" class="dropdown toolset" title="' + tool.title + '">' + '<div id="cur_' + tool.id + '" class="icon_label"></div><button></button></div>'; - var list = $$c('<ul id="' + tool.id + '_opts"></ul>').appendTo('#option_lists'); - - if (tool.colnum) { - list.addClass('optcols' + tool.colnum); - } // Creates the tool, hides & adds it, returns the select element - - /* const dropdown = */ - - - $$c(html).appendTo(panel).children(); - btnSelects.push({ - elem: '#' + tool.id, - list: '#' + tool.id + '_opts', - title: tool.title, - callback: tool.events.change, - cur: '#cur_' + tool.id - }); - break; - } - - case 'input': - { - html = '<label' + contId + '>' + '<span id="' + tool.id + '_label">' + tool.label + ':</span>' + '<input id="' + tool.id + '" title="' + tool.title + '" size="' + (tool.size || '4') + '" value="' + (tool.defval || '') + '" type="text"/></label>'; // Creates the tool, hides & adds it, returns the select element - // Add to given tool.panel - - var inp = $$c(html).appendTo(panel).find('input'); - - if (tool.spindata) { - inp.SpinButton(tool.spindata); - } - - if (tool.events) { - $$c.each(tool.events, function (evt, func) { - inp.bind(evt, func); - }); - } - - break; - } - } - }); - } - - svgicons = ext.svgicons; - - if (!ext.buttons) { - _context5.next = 24; - break; - } - - fallbackObj = {}, altsObj = {}, placementObj = {}, holders = {}; - /** - * @typedef {GenericArray} module:SVGEditor.KeyArray - * @property {string} 0 The key to bind (on `keydown`) - * @property {boolean} 1 Whether to `preventDefault` on the `keydown` event - * @property {boolean} 2 Not apparently in use (NoDisableInInput) - */ - - /** - * @typedef {string|module:SVGEditor.KeyArray} module:SVGEditor.Key - */ - - /** - * @typedef {PlainObject} module:SVGEditor.Button - * @property {string} id A unique identifier for this button. If SVG icons are used, this must match the ID used in the icon file. Required. - * @property {"mode_flyout"|"mode"|"context"|"app_menu"} type Type of button. Required. - * @property {string} title The tooltip text that will appear when the user hovers over the icon. Required. - * @property {PlainObject<string, external:jQuery.Function>|PlainObject<"click", external:jQuery.Function>} events DOM event names with associated functions. Example: `{click () { alert('Button was clicked') } }`. Click is used with `includeWith` and `type` of "mode_flyout" (and "mode"); any events may be added if `list` is not present. Expected. - * @property {string} panel The ID of the context panel to be included, if type is "context". Required only if type is "context". - * @property {string} icon The file path to the raster version of the icon image source. Required only if no `svgicons` is supplied from [ExtensionInitResponse]{@link module:svgcanvas.ExtensionInitResponse}. - * @property {string} [svgicon] If absent, will utilize the button "id"; used to set "placement" on the `svgIcons` call - * @property {string} [list] Points to the "id" of a `context_tools` item of type "button-select" into which the button will be added as a panel list item - * @property {Integer} [position] The numeric index for placement; defaults to last position (as of the time of extension addition) if not present. For use with {@link http://api.jquery.com/eq/}. - * @property {boolean} [isDefault] Whether or not the button is the default. Used with `list`. - * @property {PlainObject} [includeWith] Object with flyout menu data - * @property {boolean} [includeWith.isDefault] Indicates whether button is default in flyout list or not. - * @property {string} includeWith.button jQuery selector of the existing button to be joined. Example: '#tool_line'. Required if `includeWith` is used. - * @property {"last"|Integer} [includeWith.position] Position of icon in flyout list; will be added to end if not indicated. Integer is for use with {@link http://api.jquery.com/eq/}. - * @property {module:SVGEditor.Key} [key] The key to bind to the button - */ - // Add buttons given by extension - - $$c.each(ext.buttons, function (i, - /** @type {module:SVGEditor.Button} */ - btn) { - var id = btn.id; - var num = i; // Give button a unique ID - - while ($$c('#' + id).length) { - id = btn.id + '_' + ++num; - } - - var icon; - - if (!svgicons) { - icon = $$c('<img src="' + btn.icon + (btn.title ? '" alt="' + btn.title : '') + '">'); - } else { - fallbackObj[id] = btn.icon; - altsObj[id] = btn.title; - var svgicon = btn.svgicon || btn.id; - - if (btn.type === 'app_menu') { - placementObj['#' + id + ' > div'] = svgicon; - } else { - placementObj['#' + id] = svgicon; - } - } - - var cls, parent; // Set button up according to its type - - switch (btn.type) { - case 'mode_flyout': - case 'mode': - cls = 'tool_button'; - parent = '#tools_left'; - break; - - case 'context': - cls = 'tool_button'; - parent = '#' + btn.panel; // create the panel if it doesn't exist - - if (!$$c(parent).length) { - $$c('<div>', { - id: btn.panel - }).appendTo('#tools_top'); - } - - break; - - case 'app_menu': - cls = ''; - parent = '#main_menu ul'; - break; - } - - var flyoutHolder, showBtn, refData, refBtn; - var button = $$c(btn.list || btn.type === 'app_menu' ? '<li/>' : '<div/>').attr('id', id).attr('title', btn.title).addClass(cls); - - if (!btn.includeWith && !btn.list) { - if ('position' in btn) { - if ($$c(parent).children().eq(btn.position).length) { - $$c(parent).children().eq(btn.position).before(button); - } else { - $$c(parent).children().last().after(button); - } - } else { - button.appendTo(parent); - } - - if (btn.type === 'mode_flyout') { - // Add to flyout menu / make flyout menu - // const opts = btn.includeWith; - // // opts.button, default, position - refBtn = $$c(button); - flyoutHolder = refBtn.parent(); // Create a flyout menu if there isn't one already - - var tlsId; - - if (!refBtn.parent().hasClass('tools_flyout')) { - // Create flyout placeholder - tlsId = refBtn[0].id.replace('tool_', 'tools_'); - showBtn = refBtn.clone().attr('id', tlsId + '_show').append($$c('<div>', { - "class": 'flyout_arrow_horiz' - })); - refBtn.before(showBtn); // Create a flyout div - - flyoutHolder = makeFlyoutHolder(tlsId, refBtn); - flyoutHolder.data('isLibrary', true); - showBtn.data('isLibrary', true); - } // refData = Actions.getButtonData(opts.button); - - - placementObj['#' + tlsId + '_show'] = btn.id; // TODO: Find way to set the current icon using the iconloader if this is not default - // Include data for extension button as well as ref button - - /* curH = */ - - holders['#' + flyoutHolder[0].id] = [{ - sel: '#' + id, - fn: btn.events.click, - icon: btn.id, - // key: btn.key, - isDefault: true - }]; // , refData - // - // // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'} - // - // const pos = ('position' in opts)?opts.position:'last'; - // const len = flyoutHolder.children().length; - // - // // Add at given position or end - // if (!isNaN(pos) && pos >= 0 && pos < len) { - // flyoutHolder.children().eq(pos).before(button); - // } else { - // flyoutHolder.append(button); - // curH.reverse(); - // } - } else if (btn.type === 'app_menu') { - button.append('<div>').append(btn.title); - } - } else if (btn.list) { - // Add button to list - button.addClass('push_button'); - $$c('#' + btn.list + '_opts').append(button); - - if (btn.isDefault) { - $$c('#cur_' + btn.list).append(button.children().clone()); - - var _svgicon = btn.svgicon || btn.id; - - placementObj['#cur_' + btn.list] = _svgicon; - } - } else if (btn.includeWith) { - // Add to flyout menu / make flyout menu - var opts = btn.includeWith; // opts.button, default, position - - refBtn = $$c(opts.button); - flyoutHolder = refBtn.parent(); // Create a flyout menu if there isn't one already - - var _tlsId; - - if (!refBtn.parent().hasClass('tools_flyout')) { - // Create flyout placeholder - _tlsId = refBtn[0].id.replace('tool_', 'tools_'); - showBtn = refBtn.clone().attr('id', _tlsId + '_show').append($$c('<div>', { - "class": 'flyout_arrow_horiz' - })); - refBtn.before(showBtn); // Create a flyout div - - flyoutHolder = makeFlyoutHolder(_tlsId, refBtn); - } - - refData = Actions.getButtonData(opts.button); - - if (opts.isDefault) { - placementObj['#' + _tlsId + '_show'] = btn.id; - } // TODO: Find way to set the current icon using the iconloader if this is not default - // Include data for extension button as well as ref button - - - var curH = holders['#' + flyoutHolder[0].id] = [{ - sel: '#' + id, - fn: btn.events.click, - icon: btn.id, - key: btn.key, - isDefault: Boolean(btn.includeWith && btn.includeWith.isDefault) - }, refData]; // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'} - - var pos = 'position' in opts ? opts.position : 'last'; - var len = flyoutHolder.children().length; // Add at given position or end - - if (!isNaN(pos) && pos >= 0 && pos < len) { - flyoutHolder.children().eq(pos).before(button); - } else { - flyoutHolder.append(button); - curH.reverse(); - } - } - - if (!svgicons) { - button.append(icon); - } - - if (!btn.list) { - // Add given events to button - $$c.each(btn.events, function (name, func) { - if (name === 'click' && btn.type === 'mode') { - // `touch.js` changes `touchstart` to `mousedown`, - // so we must map extension click events as well - if (isTouch() && name === 'click') { - name = 'mousedown'; - } - - if (btn.includeWith) { - button.bind(name, func); - } else { - button.bind(name, function () { - if (toolButtonClick(button)) { - func(); - } - }); - } - - if (btn.key) { - $$c(document).bind('keydown', btn.key, func); - - if (btn.title) { - button.attr('title', btn.title + ' [' + btn.key + ']'); - } - } - } else { - button.bind(name, func); - } - }); - } - - setupFlyouts(holders); - }); - $$c.each(btnSelects, function () { - addAltDropDown(this.elem, this.list, this.callback, { - seticon: true - }); - }); - - if (!svgicons) { - _context5.next = 24; - break; - } - - return _context5.abrupt("return", new Promise(function (resolve, reject) { - // eslint-disable-line promise/avoid-new - $$c.svgIcons(svgicons, { - w: 24, - h: 24, - id_match: false, - no_img: !isWebkit(), - fallback: fallbackObj, - placement: placementObj, - callback: function callback(icons) { - // Non-ideal hack to make the icon match the current size - // if (curPrefs.iconsize && curPrefs.iconsize !== 'm') { - if (editor.pref('iconsize') !== 'm') { - prepResize(); - } - - runCallback(); - resolve(); - } - }); - })); - - case 24: - return _context5.abrupt("return", runCallback()); - - case 25: - case "end": - return _context5.stop(); - } - } - }, _callee5); - })); - - return function extAdded(_x3, _x4) { - return _ref12.apply(this, arguments); - }; - }(); - /** - * @param {string} color - * @param {Float} opac - * @param {string} type - * @returns {module:jGraduate~Paint} - */ - - - var getPaint = function getPaint(color, opac, type) { - // update the editor's fill paint - var opts = { - alpha: opac - }; - - if (color.startsWith('url(#')) { - var refElem = svgCanvas.getRefElem(color); - - if (refElem) { - refElem = refElem.cloneNode(true); - } else { - refElem = $$c('#' + type + '_color defs *')[0]; - } - - opts[refElem.tagName] = refElem; - } else if (color.startsWith('#')) { - opts.solidColor = color.substr(1); - } else { - opts.solidColor = 'none'; - } - - return new $$c.jGraduate.Paint(opts); - }; // $('#text').focus(function () { textBeingEntered = true; }); - // $('#text').blur(function () { textBeingEntered = false; }); - // bind the selected event to our function that handles updates to the UI - - - svgCanvas.bind('selected', selectedChanged); - svgCanvas.bind('transition', elementTransition); - svgCanvas.bind('changed', elementChanged); - svgCanvas.bind('saved', saveHandler); - svgCanvas.bind('exported', exportHandler); - svgCanvas.bind('exportedPDF', function (win, data) { - if (!data.output) { - // Ignore Chrome - return; - } - - var exportWindowName = data.exportWindowName; - - if (exportWindowName) { - exportWindow = window.open('', exportWindowName); // A hack to get the window via JSON-able name without opening a new one - } - - if (!exportWindow || exportWindow.closed) { - /* await */ - $$c.alert(uiStrings$1.notification.popupWindowBlocked); - return; - } - - exportWindow.location.href = data.output; - }); - svgCanvas.bind('zoomed', zoomChanged); - svgCanvas.bind('zoomDone', zoomDone); - svgCanvas.bind('updateCanvas', - /** - * @param {external:Window} win - * @param {PlainObject} centerInfo - * @param {false} centerInfo.center - * @param {module:math.XYObject} centerInfo.newCtr - * @listens module:svgcanvas.SvgCanvas#event:updateCanvas - * @returns {void} - */ - function (win, _ref13) { - var center = _ref13.center, - newCtr = _ref13.newCtr; - updateCanvas(center, newCtr); - }); - svgCanvas.bind('contextset', contextChanged); - svgCanvas.bind('extension_added', extAdded); - svgCanvas.textActions.setInputElem($$c('#text')[0]); - var str = '<div class="palette_item" data-rgb="none"></div>'; - $$c.each(palette, function (i, item) { - str += '<div class="palette_item" style="background-color: ' + item + ';" data-rgb="' + item + '"></div>'; - }); - $$c('#palette').append(str); // Set up editor background functionality - - var colorBlocks = ['#FFF', '#888', '#000', 'chessboard']; - str = ''; - $$c.each(colorBlocks, function (i, e) { - if (e === 'chessboard') { - str += '<div class="color_block" data-bgcolor="' + e + '" style="background-image:url(data:image/gif;base64,' + 'R0lGODlhEAAQAIAAAP///9bW1iH5BAAAAAAALAAAAAAQABAAAAIfjG+' + 'gq4jM3IFLJgpswNly/XkcBpIiVaInlLJr9FZWAQA7);"></div>'; - } else { - str += '<div class="color_block" data-bgcolor="' + e + '" style="background-color:' + e + ';"></div>'; - } - }); - $$c('#bg_blocks').append(str); - var blocks = $$c('#bg_blocks div'); - var curBg = 'cur_background'; - blocks.each(function () { - var blk = $$c(this); - blk.click(function () { - blocks.removeClass(curBg); - $$c(this).addClass(curBg); - }); - }); - setBackground(editor.pref('bkgd_color'), editor.pref('bkgd_url')); - $$c('#image_save_opts input').val([editor.pref('img_save')]); - /** - * @type {module:jQuerySpinButton.ValueCallback} - */ - - var changeRectRadius = function changeRectRadius(ctl) { - svgCanvas.setRectRadius(ctl.value); - }; - /** - * @type {module:jQuerySpinButton.ValueCallback} - */ - - - var changeFontSize = function changeFontSize(ctl) { - svgCanvas.setFontSize(ctl.value); - }; - /** - * @type {module:jQuerySpinButton.ValueCallback} - */ - - - var changeStrokeWidth = function changeStrokeWidth(ctl) { - var val = ctl.value; - - if (val === 0 && selectedElement && ['line', 'polyline'].includes(selectedElement.nodeName)) { - val = ctl.value = 1; - } - - svgCanvas.setStrokeWidth(val); - }; - /** - * @type {module:jQuerySpinButton.ValueCallback} - */ - - - var changeRotationAngle = function changeRotationAngle(ctl) { - svgCanvas.setRotationAngle(ctl.value); - $$c('#tool_reorient').toggleClass('disabled', Number.parseInt(ctl.value) === 0); - }; - /** - * @param {external:jQuery.fn.SpinButton} ctl Spin Button - * @param {string} [val=ctl.value] - * @returns {void} - */ - - - var changeOpacity = function changeOpacity(ctl, val) { - if (isNullish(val)) { - val = ctl.value; - } - - $$c('#group_opacity').val(val); - - if (!ctl || !ctl.handle) { - $$c('#opac_slider').slider('option', 'value', val); - } - - svgCanvas.setOpacity(val / 100); - }; - /** - * @param {external:jQuery.fn.SpinButton} ctl Spin Button - * @param {string} [val=ctl.value] - * @param {boolean} noUndo - * @returns {void} - */ - - - var changeBlur = function changeBlur(ctl, val, noUndo) { - if (isNullish(val)) { - val = ctl.value; - } - - $$c('#blur').val(val); - var complete = false; - - if (!ctl || !ctl.handle) { - $$c('#blur_slider').slider('option', 'value', val); - complete = true; - } - - if (noUndo) { - svgCanvas.setBlurNoUndo(val); - } else { - svgCanvas.setBlur(val, complete); - } - }; - - $$c('#stroke_style').change(function () { - svgCanvas.setStrokeAttr('stroke-dasharray', $$c(this).val()); - operaRepaint(); - }); - $$c('#stroke_linejoin').change(function () { - svgCanvas.setStrokeAttr('stroke-linejoin', $$c(this).val()); - operaRepaint(); - }); // Lose focus for select elements when changed (Allows keyboard shortcuts to work better) - - $$c('select').change(function () { - $$c(this).blur(); - }); // fired when user wants to move elements to another layer - - var promptMoveLayerOnce = false; - $$c('#selLayerNames').change( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() { - var destLayer, confirmStr, moveToLayer, ok; - return regeneratorRuntime.wrap(function _callee6$(_context6) { - while (1) { - switch (_context6.prev = _context6.next) { - case 0: - destLayer = this.options[this.selectedIndex].value; - confirmStr = uiStrings$1.notification.QmoveElemsToLayer.replace('%s', destLayer); - /** - * @param {boolean} ok - * @returns {void} - */ - - moveToLayer = function moveToLayer(ok) { - if (!ok) { - return; - } - - promptMoveLayerOnce = true; - svgCanvas.moveSelectedToLayer(destLayer); - svgCanvas.clearSelection(); - populateLayers(); - }; - - if (!destLayer) { - _context6.next = 14; - break; - } - - if (!promptMoveLayerOnce) { - _context6.next = 8; - break; - } - - moveToLayer(true); - _context6.next = 14; - break; - - case 8: - _context6.next = 10; - return $$c.confirm(confirmStr); - - case 10: - ok = _context6.sent; - - if (ok) { - _context6.next = 13; - break; - } - - return _context6.abrupt("return"); - - case 13: - moveToLayer(true); - - case 14: - case "end": - return _context6.stop(); - } - } - }, _callee6, this); - }))); - $$c('#font_family').change(function () { - svgCanvas.setFontFamily(this.value); - }); - $$c('#seg_type').change(function () { - svgCanvas.setSegType($$c(this).val()); - }); - $$c('#text').bind('keyup input', function () { - svgCanvas.setTextContent(this.value); - }); - $$c('#image_url').change(function () { - setImageURL(this.value); - }); - $$c('#link_url').change(function () { - if (this.value.length) { - svgCanvas.setLinkURL(this.value); - } else { - svgCanvas.removeHyperlink(); - } - }); - $$c('#g_title').change(function () { - svgCanvas.setGroupTitle(this.value); - }); - $$c('.attr_changer').change(function () { - var attr = this.getAttribute('data-attr'); - var val = this.value; - var valid = isValidUnit(attr, val, selectedElement); - - if (!valid) { - this.value = selectedElement.getAttribute(attr); - /* await */ - - $$c.alert(uiStrings$1.notification.invalidAttrValGiven); - return false; - } - - if (attr !== 'id' && attr !== 'class') { - if (isNaN(val)) { - val = svgCanvas.convertToNum(attr, val); - } else if (curConfig.baseUnit !== 'px') { - // Convert unitless value to one with given unit - var unitData = getTypeMap(); - - if (selectedElement[attr] || svgCanvas.getMode() === 'pathedit' || attr === 'x' || attr === 'y') { - val *= unitData[curConfig.baseUnit]; - } - } - } // if the user is changing the id, then de-select the element first - // change the ID, then re-select it with the new ID - - - if (attr === 'id') { - var elem = selectedElement; - svgCanvas.clearSelection(); - elem.id = val; - svgCanvas.addToSelection([elem], true); - } else { - svgCanvas.changeSelectedAttribute(attr, val); - } - - this.blur(); - return true; - }); // Prevent selection of elements when shift-clicking - - $$c('#palette').mouseover(function () { - var inp = $$c('<input type="hidden">'); - $$c(this).append(inp); - inp.focus().remove(); - }); - $$c('.palette_item').mousedown(function (evt) { - // shift key or right click for stroke - var picker = evt.shiftKey || evt.button === 2 ? 'stroke' : 'fill'; - var color = $$c(this).data('rgb'); - var paint; // Webkit-based browsers returned 'initial' here for no stroke - - if (color === 'none' || color === 'transparent' || color === 'initial') { - color = 'none'; - paint = new $$c.jGraduate.Paint(); - } else { - paint = new $$c.jGraduate.Paint({ - alpha: 100, - solidColor: color.substr(1) - }); - } - - paintBox[picker].setPaint(paint); - svgCanvas.setColor(picker, color); - - if (color !== 'none' && svgCanvas.getPaintOpacity(picker) !== 1) { - svgCanvas.setPaintOpacity(picker, 1.0); - } - - updateToolButtonState(); - }).bind('contextmenu', function (e) { - e.preventDefault(); - }); - $$c('#toggle_stroke_tools').on('click', function () { - $$c('#tools_bottom').toggleClass('expanded'); - }); - - (function () { - var wArea = workarea[0]; - var lastX = null, - lastY = null, - panning = false, - keypan = false; - $$c('#svgcanvas').bind('mousemove mouseup', function (evt) { - if (panning === false) { - return true; - } - - wArea.scrollLeft -= evt.clientX - lastX; - wArea.scrollTop -= evt.clientY - lastY; - lastX = evt.clientX; - lastY = evt.clientY; - - if (evt.type === 'mouseup') { - panning = false; - } - - return false; - }).mousedown(function (evt) { - if (evt.button === 1 || keypan === true) { - panning = true; - lastX = evt.clientX; - lastY = evt.clientY; - return false; - } - - return true; - }); - $$c(window).mouseup(function () { - panning = false; - }); - $$c(document).bind('keydown', 'space', function (evt) { - svgCanvas.spaceKey = keypan = true; - evt.preventDefault(); - }).bind('keyup', 'space', function (evt) { - evt.preventDefault(); - svgCanvas.spaceKey = keypan = false; - }).bind('keydown', 'shift', function (evt) { - if (svgCanvas.getMode() === 'zoom') { - workarea.css('cursor', zoomOutIcon); - } - }).bind('keyup', 'shift', function (evt) { - if (svgCanvas.getMode() === 'zoom') { - workarea.css('cursor', zoomInIcon); - } - }); - /** - * @function module:SVGEditor.setPanning - * @param {boolean} active - * @returns {void} - */ - - editor.setPanning = function (active) { - svgCanvas.spaceKey = keypan = active; - }; - })(); - - (function () { - var button = $$c('#main_icon'); - var overlay = $$c('#main_icon span'); - var list = $$c('#main_menu'); - var onButton = false; - var height = 0; - var jsHover = true; - var setClick = false; - /* - // Currently unused - const hideMenu = function () { - list.fadeOut(200); - }; - */ - - $$c(window).mouseup(function (evt) { - if (!onButton) { - button.removeClass('buttondown'); // do not hide if it was the file input as that input needs to be visible - // for its change event to fire - - if (evt.target.tagName !== 'INPUT') { - list.fadeOut(200); - } else if (!setClick) { - setClick = true; - $$c(evt.target).click(function () { - list.css('margin-left', '-9999px').show(); - }); - } - } - - onButton = false; - }).mousedown(function (evt) { - // $('.contextMenu').hide(); - var islib = $$c(evt.target).closest('div.tools_flyout, .contextMenu').length; - - if (!islib) { - $$c('.tools_flyout:visible,.contextMenu').fadeOut(250); - } - }); - overlay.bind('mousedown', function () { - if (!button.hasClass('buttondown')) { - // Margin must be reset in case it was changed before; - list.css('margin-left', 0).show(); - - if (!height) { - height = list.height(); - } // Using custom animation as slideDown has annoying 'bounce effect' - - - list.css('height', 0).animate({ - height: height - }, 200); - onButton = true; - } else { - list.fadeOut(200); - } - - button.toggleClass('buttondown buttonup'); - }).hover(function () { - onButton = true; - }).mouseout(function () { - onButton = false; - }); - var listItems = $$c('#main_menu li'); // Check if JS method of hovering needs to be used (Webkit bug) - - listItems.mouseover(function () { - jsHover = $$c(this).css('background-color') === 'rgba(0, 0, 0, 0)'; - listItems.unbind('mouseover'); - - if (jsHover) { - listItems.mouseover(function () { - this.style.backgroundColor = '#FFC'; - }).mouseout(function () { - this.style.backgroundColor = 'transparent'; - return true; - }); - } - }); - })(); // Made public for UI customization. - // TODO: Group UI functions into a public editor.ui interface. - - /** - * See {@link http://api.jquery.com/bind/#bind-eventType-eventData-handler}. - * @callback module:SVGEditor.DropDownCallback - * @param {external:jQuery.Event} ev See {@link http://api.jquery.com/Types/#Event} - * @listens external:jQuery.Event - * @returns {void|boolean} Calls `preventDefault()` and `stopPropagation()` - */ - - /** - * @function module:SVGEditor.addDropDown - * @param {Element|string} elem DOM Element or selector - * @param {module:SVGEditor.DropDownCallback} callback Mouseup callback - * @param {boolean} dropUp - * @returns {void} - */ - - - editor.addDropDown = function (elem, callback, dropUp) { - if (!$$c(elem).length) { - return; - } // Quit if called on non-existent element - - - var button = $$c(elem).find('button'); - var list = $$c(elem).find('ul').attr('id', $$c(elem)[0].id + '-list'); - - if (dropUp) { - $$c(elem).addClass('dropup'); - } else { - // Move list to place where it can overflow container - $$c('#option_lists').append(list); - } - - list.find('li').bind('mouseup', callback); - var onButton = false; - $$c(window).mouseup(function (evt) { - if (!onButton) { - button.removeClass('down'); - list.hide(); - } - - onButton = false; - }); - button.bind('mousedown', function () { - if (!button.hasClass('down')) { - if (!dropUp) { - var pos = $$c(elem).position(); - list.css({ - top: pos.top + 24, - left: pos.left - 10 - }); - } - - list.show(); - onButton = true; - } else { - list.hide(); - } - - button.toggleClass('down'); - }).hover(function () { - onButton = true; - }).mouseout(function () { - onButton = false; - }); - }; - - editor.addDropDown('#font_family_dropdown', function () { - $$c('#font_family').val($$c(this).text()).change(); - }); - editor.addDropDown('#opacity_dropdown', function () { - if ($$c(this).find('div').length) { - return; - } - - var perc = Number.parseInt($$c(this).text().split('%')[0]); - changeOpacity(false, perc); - }, true); // For slider usage, see: http://jqueryui.com/demos/slider/ - - $$c('#opac_slider').slider({ - start: function start() { - $$c('#opacity_dropdown li:not(.special)').hide(); - }, - stop: function stop() { - $$c('#opacity_dropdown li').show(); - $$c(window).mouseup(); - }, - slide: function slide(evt, ui) { - changeOpacity(ui); - } - }); - editor.addDropDown('#blur_dropdown', $$c.noop); - var slideStart = false; - $$c('#blur_slider').slider({ - max: 10, - step: 0.1, - stop: function stop(evt, ui) { - slideStart = false; - changeBlur(ui); - $$c('#blur_dropdown li').show(); - $$c(window).mouseup(); - }, - start: function start() { - slideStart = true; - }, - slide: function slide(evt, ui) { - changeBlur(ui, null, slideStart); - } - }); - editor.addDropDown('#zoom_dropdown', function () { - var item = $$c(this); - var val = item.data('val'); - - if (val) { - zoomChanged(window, val); - } else { - changeZoom({ - value: Number.parseFloat(item.text()) - }); - } - }, true); - addAltDropDown('#stroke_linecap', '#linecap_opts', function () { - setStrokeOpt(this, true); - }, { - dropUp: true - }); - addAltDropDown('#stroke_linejoin', '#linejoin_opts', function () { - setStrokeOpt(this, true); - }, { - dropUp: true - }); - addAltDropDown('#tool_position', '#position_opts', function () { - var letter = this.id.replace('tool_pos', '').charAt(0); - svgCanvas.alignSelectedElements(letter, 'page'); - }, { - multiclick: true - }); - /* - When a flyout icon is selected - (if flyout) { - - Change the icon - - Make pressing the button run its stuff - } - - Run its stuff - When its shortcut key is pressed - - If not current in list, do as above - , else: - - Just run its stuff - */ - // Unfocus text input when workarea is mousedowned. - - (function () { - var inp; - /** - * - * @returns {void} - */ - - var unfocus = function unfocus() { - $$c(inp).blur(); - }; - - $$c('#svg_editor').find('button, select, input:not(#text)').focus(function () { - inp = this; - uiContext = 'toolbars'; - workarea.mousedown(unfocus); - }).blur(function () { - uiContext = 'canvas'; - workarea.unbind('mousedown', unfocus); // Go back to selecting text if in textedit mode - - if (svgCanvas.getMode() === 'textedit') { - $$c('#text').focus(); - } - }); - })(); - /** - * - * @returns {void} - */ - - - var clickFHPath = function clickFHPath() { - if (toolButtonClick('#tool_fhpath')) { - svgCanvas.setMode('fhpath'); - } - }; - /** - * - * @returns {void} - */ - - - var clickLine = function clickLine() { - if (toolButtonClick('#tool_line')) { - svgCanvas.setMode('line'); - } - }; - /** - * - * @returns {void} - */ - - - var clickSquare = function clickSquare() { - if (toolButtonClick('#tool_square')) { - svgCanvas.setMode('square'); - } - }; - /** - * - * @returns {void} - */ - - - var clickRect = function clickRect() { - if (toolButtonClick('#tool_rect')) { - svgCanvas.setMode('rect'); - } - }; - /** - * - * @returns {void} - */ - - - var clickFHRect = function clickFHRect() { - if (toolButtonClick('#tool_fhrect')) { - svgCanvas.setMode('fhrect'); - } - }; - /** - * - * @returns {void} - */ - - - var clickCircle = function clickCircle() { - if (toolButtonClick('#tool_circle')) { - svgCanvas.setMode('circle'); - } - }; - /** - * - * @returns {void} - */ - - - var clickEllipse = function clickEllipse() { - if (toolButtonClick('#tool_ellipse')) { - svgCanvas.setMode('ellipse'); - } - }; - /** - * - * @returns {void} - */ - - - var clickFHEllipse = function clickFHEllipse() { - if (toolButtonClick('#tool_fhellipse')) { - svgCanvas.setMode('fhellipse'); - } - }; - /** - * - * @returns {void} - */ - - - var clickImage = function clickImage() { - if (toolButtonClick('#tool_image')) { - svgCanvas.setMode('image'); - } - }; - /** - * - * @returns {void} - */ - - - var clickZoom = function clickZoom() { - if (toolButtonClick('#tool_zoom')) { - svgCanvas.setMode('zoom'); - workarea.css('cursor', zoomInIcon); - } - }; - /** - * @param {Float} multiplier - * @returns {void} - */ - - - var zoomImage = function zoomImage(multiplier) { - var res = svgCanvas.getResolution(); - multiplier = multiplier ? res.zoom * multiplier : 1; // setResolution(res.w * multiplier, res.h * multiplier, true); - - $$c('#zoom').val(multiplier * 100); - svgCanvas.setZoom(multiplier); - zoomDone(); - updateCanvas(true); - }; - /** - * - * @returns {void} - */ - - - var dblclickZoom = function dblclickZoom() { - if (toolButtonClick('#tool_zoom')) { - zoomImage(); - setSelectMode(); - } - }; - /** - * - * @returns {void} - */ - - - var clickText = function clickText() { - if (toolButtonClick('#tool_text')) { - svgCanvas.setMode('text'); - } - }; - /** - * - * @returns {void} - */ - - - var clickPath = function clickPath() { - if (toolButtonClick('#tool_path')) { - svgCanvas.setMode('path'); - } - }; - /** - * Delete is a contextual tool that only appears in the ribbon if - * an element has been selected. - * @returns {void} - */ - - - var deleteSelected = function deleteSelected() { - if (!isNullish(selectedElement) || multiselected) { - svgCanvas.deleteSelectedElements(); - } - }; - /** - * - * @returns {void} - */ - - - var cutSelected = function cutSelected() { - if (!isNullish(selectedElement) || multiselected) { - svgCanvas.cutSelectedElements(); - } - }; - /** - * - * @returns {void} - */ - - - var copySelected = function copySelected() { - if (!isNullish(selectedElement) || multiselected) { - svgCanvas.copySelectedElements(); - } - }; - /** - * - * @returns {void} - */ - - - var pasteInCenter = function pasteInCenter() { - var zoom = svgCanvas.getZoom(); - var x = (workarea[0].scrollLeft + workarea.width() / 2) / zoom - svgCanvas.contentW; - var y = (workarea[0].scrollTop + workarea.height() / 2) / zoom - svgCanvas.contentH; - svgCanvas.pasteElements('point', x, y); - }; - /** - * - * @returns {void} - */ - - - var moveToTopSelected = function moveToTopSelected() { - if (!isNullish(selectedElement)) { - svgCanvas.moveToTopSelectedElement(); - } - }; - /** - * - * @returns {void} - */ - - - var moveToBottomSelected = function moveToBottomSelected() { - if (!isNullish(selectedElement)) { - svgCanvas.moveToBottomSelectedElement(); - } - }; - /** - * @param {"Up"|"Down"} dir - * @returns {void} - */ - - - var moveUpDownSelected = function moveUpDownSelected(dir) { - if (!isNullish(selectedElement)) { - svgCanvas.moveUpDownSelected(dir); - } - }; - /** - * - * @returns {void} - */ - - - var convertToPath = function convertToPath() { - if (!isNullish(selectedElement)) { - svgCanvas.convertToPath(); - } - }; - /** - * - * @returns {void} - */ - - - var reorientPath = function reorientPath() { - if (!isNullish(selectedElement)) { - path.reorient(); - } - }; - /** - * - * @returns {Promise<void>} Resolves to `undefined` - */ - - - var makeHyperlink = /*#__PURE__*/function () { - var _ref15 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7() { - var url; - return regeneratorRuntime.wrap(function _callee7$(_context7) { - while (1) { - switch (_context7.prev = _context7.next) { - case 0: - if (!(!isNullish(selectedElement) || multiselected)) { - _context7.next = 5; - break; - } - - _context7.next = 3; - return $$c.prompt(uiStrings$1.notification.enterNewLinkURL, 'http://'); - - case 3: - url = _context7.sent; - - if (url) { - svgCanvas.makeHyperlink(url); - } - - case 5: - case "end": - return _context7.stop(); - } - } - }, _callee7); - })); - - return function makeHyperlink() { - return _ref15.apply(this, arguments); - }; - }(); - /** - * @param {Float} dx - * @param {Float} dy - * @returns {void} - */ - - - var moveSelected = function moveSelected(dx, dy) { - if (!isNullish(selectedElement) || multiselected) { - if (curConfig.gridSnapping) { - // Use grid snap value regardless of zoom level - var multi = svgCanvas.getZoom() * curConfig.snappingStep; - dx *= multi; - dy *= multi; - } - - svgCanvas.moveSelectedElements(dx, dy); - } - }; - /** - * - * @returns {void} - */ - - - var linkControlPoints = function linkControlPoints() { - $$c('#tool_node_link').toggleClass('push_button_pressed tool_button'); - var linked = $$c('#tool_node_link').hasClass('push_button_pressed'); - path.linkControlPoints(linked); - }; - /** - * - * @returns {void} - */ - - - var clonePathNode = function clonePathNode() { - if (path.getNodePoint()) { - path.clonePathNode(); - } - }; - /** - * - * @returns {void} - */ - - - var deletePathNode = function deletePathNode() { - if (path.getNodePoint()) { - path.deletePathNode(); - } - }; - /** - * - * @returns {void} - */ - - - var addSubPath = function addSubPath() { - var button = $$c('#tool_add_subpath'); - var sp = !button.hasClass('push_button_pressed'); - button.toggleClass('push_button_pressed tool_button'); - path.addSubPath(sp); - }; - /** - * - * @returns {void} - */ - - - var opencloseSubPath = function opencloseSubPath() { - path.opencloseSubPath(); - }; - /** - * - * @returns {void} - */ - - - var selectNext = function selectNext() { - svgCanvas.cycleElement(1); - }; - /** - * - * @returns {void} - */ - - - var selectPrev = function selectPrev() { - svgCanvas.cycleElement(0); - }; - /** - * @param {0|1} cw - * @param {Integer} step - * @returns {void} - */ - - - var rotateSelected = function rotateSelected(cw, step) { - if (isNullish(selectedElement) || multiselected) { - return; - } - - if (!cw) { - step *= -1; - } - - var angle = Number.parseFloat($$c('#angle').val()) + step; - svgCanvas.setRotationAngle(angle); - updateContextPanel(); - }; - /** - * @fires module:svgcanvas.SvgCanvas#event:ext_onNewDocument - * @returns {Promise<void>} Resolves to `undefined` - */ - - - var clickClear = /*#__PURE__*/function () { - var _ref16 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8() { - var _curConfig$dimensions, x, y, ok; - - return regeneratorRuntime.wrap(function _callee8$(_context8) { - while (1) { - switch (_context8.prev = _context8.next) { - case 0: - _curConfig$dimensions = _slicedToArray(curConfig.dimensions, 2), x = _curConfig$dimensions[0], y = _curConfig$dimensions[1]; - _context8.next = 3; - return $$c.confirm(uiStrings$1.notification.QwantToClear); - - case 3: - ok = _context8.sent; - - if (ok) { - _context8.next = 6; - break; - } - - return _context8.abrupt("return"); - - case 6: - setSelectMode(); - svgCanvas.clear(); - svgCanvas.setResolution(x, y); - updateCanvas(true); - zoomImage(); - populateLayers(); - updateContextPanel(); - prepPaints(); - svgCanvas.runExtensions('onNewDocument'); - - case 15: - case "end": - return _context8.stop(); - } - } - }, _callee8); - })); - - return function clickClear() { - return _ref16.apply(this, arguments); - }; - }(); - /** - * - * @returns {false} - */ - - - var clickBold = function clickBold() { - svgCanvas.setBold(!svgCanvas.getBold()); - updateContextPanel(); - return false; - }; - /** - * - * @returns {false} - */ - - - var clickItalic = function clickItalic() { - svgCanvas.setItalic(!svgCanvas.getItalic()); - updateContextPanel(); - return false; - }; - /** - * - * @returns {void} - */ - - - var clickSave = function clickSave() { - // In the future, more options can be provided here - var saveOpts = { - images: editor.pref('img_save'), - round_digits: 6 - }; - svgCanvas.save(saveOpts); - }; - - var loadingURL; - /** - * - * @returns {Promise<void>} Resolves to `undefined` - */ - - var clickExport = /*#__PURE__*/function () { - var _ref17 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9() { - var imgType, exportWindowName, openExportWindow, chrome, quality; - return regeneratorRuntime.wrap(function _callee9$(_context9) { - while (1) { - switch (_context9.prev = _context9.next) { - case 0: - openExportWindow = function _openExportWindow() { - var loadingImage = uiStrings$1.notification.loadingImage; - - if (curConfig.exportWindowType === 'new') { - editor.exportWindowCt++; - } - - exportWindowName = curConfig.canvasName + editor.exportWindowCt; - var popHTML, popURL; - - if (loadingURL) { - popURL = loadingURL; - } else { - popHTML = "<!DOCTYPE html><html>\n <head>\n <meta charset=\"utf-8\">\n <title>".concat(loadingImage, "\n \n

").concat(loadingImage, "

\n "); - - if (typeof URL !== 'undefined' && URL.createObjectURL) { - var blob = new Blob([popHTML], { - type: 'text/html' - }); - popURL = URL.createObjectURL(blob); - } else { - popURL = 'data:text/html;base64;charset=utf-8,' + encode64(popHTML); - } - - loadingURL = popURL; - } - - exportWindow = window.open(popURL, exportWindowName); - }; - - _context9.next = 3; - return $$c.select('Select an image type for export: ', [// See http://kangax.github.io/jstests/toDataUrl_mime_type_test/ for a useful list of MIME types and browser support - // 'ICO', // Todo: Find a way to preserve transparency in SVG-Edit if not working presently and do full packaging for x-icon; then switch back to position after 'PNG' - 'PNG', 'JPEG', 'BMP', 'WEBP', 'PDF'], function () { - var sel = $$c(this); - - if (sel.val() === 'JPEG' || sel.val() === 'WEBP') { - if (!$$c('#image-slider').length) { - $$c("
")).appendTo(sel.parent()); - } - } else { - $$c('#image-slider').parent().remove(); - } - }); - - case 3: - imgType = _context9.sent; - - if (imgType) { - _context9.next = 6; - break; - } - - return _context9.abrupt("return"); - - case 6: - chrome = isChrome(); - - if (!(imgType === 'PDF')) { - _context9.next = 12; - break; - } - - if (!customExportPDF && !chrome) { - openExportWindow(); - } - - svgCanvas.exportPDF(exportWindowName); - _context9.next = 16; - break; - - case 12: - if (!customExportImage) { - openExportWindow(); - } - - quality = Number.parseInt($$c('#image-slider').val()) / 100; - /* const results = */ - - _context9.next = 16; - return svgCanvas.rasterExport(imgType, quality, exportWindowName); - - case 16: - case "end": - return _context9.stop(); - } - } - }, _callee9); - })); - - return function clickExport() { - return _ref17.apply(this, arguments); - }; - }(); - /** - * By default, svgCanvas.open() is a no-op. It is up to an extension - * mechanism (opera widget, etc.) to call `setCustomHandlers()` which - * will make it do something. - * @returns {void} - */ - - - var clickOpen = function clickOpen() { - svgCanvas.open(); - }; - /** - * - * @returns {void} - */ - - - var clickImport = function clickImport() { - /* */ - }; - /** - * - * @returns {void} - */ - - - var clickUndo = function clickUndo() { - if (undoMgr.getUndoStackSize() > 0) { - undoMgr.undo(); - populateLayers(); - } - }; - /** - * - * @returns {void} - */ - - - var clickRedo = function clickRedo() { - if (undoMgr.getRedoStackSize() > 0) { - undoMgr.redo(); - populateLayers(); - } - }; - /** - * - * @returns {void} - */ - - - var clickGroup = function clickGroup() { - // group - if (multiselected) { - svgCanvas.groupSelectedElements(); // ungroup - } else if (selectedElement) { - svgCanvas.ungroupSelectedElement(); - } - }; - /** - * - * @returns {void} - */ - - - var clickClone = function clickClone() { - svgCanvas.cloneSelectedElements(20, 20); - }; - /** - * - * @returns {void} - */ - - - var clickAlign = function clickAlign() { - var letter = this.id.replace('tool_align', '').charAt(0); - svgCanvas.alignSelectedElements(letter, $$c('#align_relative_to').val()); - }; - /** - * - * @returns {void} - */ - - - var clickWireframe = function clickWireframe() { - $$c('#tool_wireframe').toggleClass('push_button_pressed tool_button'); - workarea.toggleClass('wireframe'); - - if (supportsNonSS) { - return; - } - - var wfRules = $$c('#wireframe_rules'); - - if (!wfRules.length) { - /* wfRules = */ - $$c('').appendTo('head'); - } else { - wfRules.empty(); - } - - updateWireFrame(); - }; - - $$c('#svg_docprops_container, #svg_prefs_container').draggable({ - cancel: 'button,fieldset', - containment: 'window' - }).css('position', 'absolute'); - var docprops = false; - var preferences = false; - /** - * - * @returns {void} - */ - - var showDocProperties = function showDocProperties() { - if (docprops) { - return; - } - - docprops = true; // This selects the correct radio button by using the array notation - - $$c('#image_save_opts input').val([editor.pref('img_save')]); // update resolution option with actual resolution - - var res = svgCanvas.getResolution(); - - if (curConfig.baseUnit !== 'px') { - res.w = convertUnit(res.w) + curConfig.baseUnit; - res.h = convertUnit(res.h) + curConfig.baseUnit; - } - - $$c('#canvas_width').val(res.w); - $$c('#canvas_height').val(res.h); - $$c('#canvas_title').val(svgCanvas.getDocumentTitle()); - $$c('#svg_docprops').show(); - }; - /** - * - * @returns {void} - */ - - - var showPreferences = function showPreferences() { - if (preferences) { - return; - } - - preferences = true; - $$c('#main_menu').hide(); // Update background color with current one - - var canvasBg = curPrefs.bkgd_color; - var url = editor.pref('bkgd_url'); - blocks.each(function () { - var blk = $$c(this); - var isBg = blk.data('bgcolor') === canvasBg; - blk.toggleClass(curBg, isBg); - }); - - if (!canvasBg) { - blocks.eq(0).addClass(curBg); - } - - if (url) { - $$c('#canvas_bg_url').val(url); - } - - $$c('#grid_snapping_on').prop('checked', curConfig.gridSnapping); - $$c('#grid_snapping_step').attr('value', curConfig.snappingStep); - $$c('#grid_color').attr('value', curConfig.gridColor); - $$c('#svg_prefs').show(); - }; - /** - * - * @returns {void} - */ - - - var openHomePage = function openHomePage() { - window.open(homePage, '_blank'); - }; - /** - * - * @returns {void} - */ - - - var hideSourceEditor = function hideSourceEditor() { - $$c('#svg_source_editor').hide(); - editingsource = false; - $$c('#svg_source_textarea').blur(); - }; - /** - * - * @returns {Promise} Resolves to `undefined` - */ - - - var saveSourceEditor = /*#__PURE__*/function () { - var _ref18 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10() { - var saveChanges, ok; - return regeneratorRuntime.wrap(function _callee10$(_context10) { - while (1) { - switch (_context10.prev = _context10.next) { - case 0: - if (editingsource) { - _context10.next = 2; - break; - } - - return _context10.abrupt("return"); - - case 2: - saveChanges = function saveChanges() { - svgCanvas.clearSelection(); - hideSourceEditor(); - zoomImage(); - populateLayers(); - updateTitle(); - prepPaints(); - }; - - if (svgCanvas.setSvgString($$c('#svg_source_textarea').val())) { - _context10.next = 11; - break; - } - - _context10.next = 6; - return $$c.confirm(uiStrings$1.notification.QerrorsRevertToSource); - - case 6: - ok = _context10.sent; - - if (ok) { - _context10.next = 9; - break; - } - - return _context10.abrupt("return"); - - case 9: - saveChanges(); - return _context10.abrupt("return"); - - case 11: - saveChanges(); - setSelectMode(); - - case 13: - case "end": - return _context10.stop(); - } - } - }, _callee10); - })); - - return function saveSourceEditor() { - return _ref18.apply(this, arguments); - }; - }(); - /** - * - * @returns {void} - */ - - - var hideDocProperties = function hideDocProperties() { - $$c('#svg_docprops').hide(); - $$c('#canvas_width,#canvas_height').removeAttr('disabled'); - $$c('#resolution')[0].selectedIndex = 0; - $$c('#image_save_opts input').val([editor.pref('img_save')]); - docprops = false; - }; - /** - * - * @returns {void} - */ - - - var hidePreferences = function hidePreferences() { - $$c('#svg_prefs').hide(); - preferences = false; - }; - /** - * - * @returns {boolean} Whether there were problems saving the document properties - */ - - - var saveDocProperties = function saveDocProperties() { - // set title - var newTitle = $$c('#canvas_title').val(); - updateTitle(newTitle); - svgCanvas.setDocumentTitle(newTitle); // update resolution - - var width = $$c('#canvas_width'), - w = width.val(); - var height = $$c('#canvas_height'), - h = height.val(); - - if (w !== 'fit' && !isValidUnit('width', w)) { - width.parent().addClass('error'); - /* await */ - - $$c.alert(uiStrings$1.notification.invalidAttrValGiven); - return false; - } - - width.parent().removeClass('error'); - - if (h !== 'fit' && !isValidUnit('height', h)) { - height.parent().addClass('error'); - /* await */ - - $$c.alert(uiStrings$1.notification.invalidAttrValGiven); - return false; - } - - height.parent().removeClass('error'); - - if (!svgCanvas.setResolution(w, h)) { - /* await */ - $$c.alert(uiStrings$1.notification.noContentToFitTo); - return false; - } // Set image save option - - - editor.pref('img_save', $$c('#image_save_opts :checked').val()); - updateCanvas(); - hideDocProperties(); - return true; - }; - /** - * Save user preferences based on current values in the UI. - * @function module:SVGEditor.savePreferences - * @returns {Promise} - */ - - - var savePreferences = editor.savePreferences = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11() { - var color, lang, _yield$editor$putLoca2, langParam, langData; - - return regeneratorRuntime.wrap(function _callee11$(_context11) { - while (1) { - switch (_context11.prev = _context11.next) { - case 0: - // Set background - color = $$c('#bg_blocks div.cur_background').data('bgcolor') || '#FFF'; - setBackground(color, $$c('#canvas_bg_url').val()); // set language - - lang = $$c('#lang_select').val(); - - if (!(lang && lang !== editor.pref('lang'))) { - _context11.next = 11; - break; - } - - _context11.next = 6; - return editor.putLocale(lang, goodLangs, curConfig); - - case 6: - _yield$editor$putLoca2 = _context11.sent; - langParam = _yield$editor$putLoca2.langParam; - langData = _yield$editor$putLoca2.langData; - _context11.next = 11; - return setLang(langParam, langData); - - case 11: - // set icon size - setIconSize($$c('#iconsize').val()); // set grid setting - - curConfig.gridSnapping = $$c('#grid_snapping_on')[0].checked; - curConfig.snappingStep = $$c('#grid_snapping_step').val(); - curConfig.gridColor = $$c('#grid_color').val(); - curConfig.showRulers = $$c('#show_rulers')[0].checked; - $$c('#rulers').toggle(curConfig.showRulers); - - if (curConfig.showRulers) { - updateRulers(); - } - - curConfig.baseUnit = $$c('#base_unit').val(); - svgCanvas.setConfig(curConfig); - updateCanvas(); - hidePreferences(); - - case 22: - case "end": - return _context11.stop(); - } - } - }, _callee11); - })); - - var resetScrollPos = $$c.noop; - /** - * - * @returns {Promise} Resolves to `undefined` - */ - - var cancelOverlays = /*#__PURE__*/function () { - var _ref20 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12() { - var ok; - return regeneratorRuntime.wrap(function _callee12$(_context12) { - while (1) { - switch (_context12.prev = _context12.next) { - case 0: - $$c('#dialog_box').hide(); - - if (!(!editingsource && !docprops && !preferences)) { - _context12.next = 4; - break; - } - - if (curContext) { - svgCanvas.leaveContext(); - } - - return _context12.abrupt("return"); - - case 4: - if (!editingsource) { - _context12.next = 15; - break; - } - - if (!(origSource !== $$c('#svg_source_textarea').val())) { - _context12.next = 12; - break; - } - - _context12.next = 8; - return $$c.confirm(uiStrings$1.notification.QignoreSourceChanges); - - case 8: - ok = _context12.sent; - - if (ok) { - hideSourceEditor(); - } - - _context12.next = 13; - break; - - case 12: - hideSourceEditor(); - - case 13: - _context12.next = 16; - break; - - case 15: - if (docprops) { - hideDocProperties(); - } else if (preferences) { - hidePreferences(); - } - - case 16: - resetScrollPos(); - - case 17: - case "end": - return _context12.stop(); - } - } - }, _callee12); - })); - - return function cancelOverlays() { - return _ref20.apply(this, arguments); - }; - }(); - - var winWh = { - width: $$c(window).width(), - height: $$c(window).height() - }; // Fix for Issue 781: Drawing area jumps to top-left corner on window resize (IE9) - - if (isIE()) { - resetScrollPos = function resetScrollPos() { - if (workarea[0].scrollLeft === 0 && workarea[0].scrollTop === 0) { - workarea[0].scrollLeft = curScrollPos.left; - workarea[0].scrollTop = curScrollPos.top; - } - }; - - curScrollPos = { - left: workarea[0].scrollLeft, - top: workarea[0].scrollTop - }; - $$c(window).resize(resetScrollPos); - editor.ready(function () { - // TODO: Find better way to detect when to do this to minimize - // flickering effect - return new Promise(function (resolve, reject) { - // eslint-disable-line promise/avoid-new - setTimeout(function () { - resetScrollPos(); - resolve(); - }, 500); - }); - }); - workarea.scroll(function () { - curScrollPos = { - left: workarea[0].scrollLeft, - top: workarea[0].scrollTop - }; - }); - } - - $$c(window).resize(function (evt) { - $$c.each(winWh, function (type, val) { - var curval = $$c(window)[type](); - workarea[0]['scroll' + (type === 'width' ? 'Left' : 'Top')] -= (curval - val) / 2; - winWh[type] = curval; - }); - setFlyoutPositions(); - }); - workarea.scroll(function () { - // TODO: jQuery's scrollLeft/Top() wouldn't require a null check - if ($$c('#ruler_x').length) { - $$c('#ruler_x')[0].scrollLeft = workarea[0].scrollLeft; - } - - if ($$c('#ruler_y').length) { - $$c('#ruler_y')[0].scrollTop = workarea[0].scrollTop; - } - }); - $$c('#url_notice').click(function () { - /* await */ - $$c.alert(this.title); - }); - $$c('#change_image_url').click(promptImgURL); // added these event handlers for all the push buttons so they - // behave more like buttons being pressed-in and not images - - (function () { - var toolnames = ['clear', 'open', 'save', 'source', 'delete', 'delete_multi', 'paste', 'clone', 'clone_multi', 'move_top', 'move_bottom']; - var curClass = 'tool_button_current'; - var allTools = ''; - $$c.each(toolnames, function (i, item) { - allTools += (i ? ',' : '') + '#tool_' + item; - }); - $$c(allTools).mousedown(function () { - $$c(this).addClass(curClass); - }).bind('mousedown mouseout', function () { - $$c(this).removeClass(curClass); - }); - $$c('#tool_undo, #tool_redo').mousedown(function () { - if (!$$c(this).hasClass('disabled')) { - $$c(this).addClass(curClass); - } - }).bind('mousedown mouseout', function () { - $$c(this).removeClass(curClass); - }); - })(); // switch modifier key in tooltips if mac - // NOTE: This code is not used yet until I can figure out how to successfully bind ctrl/meta - // in Opera and Chrome - - - if (isMac() && !window.opera) { - var shortcutButtons = ['tool_clear', 'tool_save', 'tool_source', 'tool_undo', 'tool_redo', 'tool_clone']; - var _i = shortcutButtons.length; - - while (_i--) { - var button = document.getElementById(shortcutButtons[_i]); - - if (button) { - var title = button.title; - var index = title.indexOf('Ctrl+'); - button.title = [title.substr(0, index), 'Cmd+', title.substr(index + 5)].join(''); - } - } - } - /** - * @param {external:jQuery} elem - * @todo Go back to the color boxes having white background-color and then setting - * background-image to none.png (otherwise partially transparent gradients look weird) - * @returns {void} - */ - - - var colorPicker = function colorPicker(elem) { - var picker = elem.attr('id') === 'stroke_color' ? 'stroke' : 'fill'; // const opacity = (picker == 'stroke' ? $('#stroke_opacity') : $('#fill_opacity')); - - var title = picker === 'stroke' ? uiStrings$1.ui.pick_stroke_paint_opacity : uiStrings$1.ui.pick_fill_paint_opacity; // let wasNone = false; // Currently unused - - var pos = elem.offset(); - var paint = paintBox[picker].paint; - $$c('#color_picker').draggable({ - cancel: '.jGraduate_tabs, .jGraduate_colPick, .jGraduate_gradPick, .jPicker', - containment: 'window' - }).css(curConfig.colorPickerCSS || { - left: pos.left - 140, - bottom: 40 - }).jGraduate({ - paint: paint, - window: { - pickerTitle: title - }, - images: { - clientPath: curConfig.jGraduatePath - }, - newstop: 'inverse' - }, function (p) { - paint = new $$c.jGraduate.Paint(p); - paintBox[picker].setPaint(paint); - svgCanvas.setPaint(picker, paint); - $$c('#color_picker').hide(); - }, function () { - $$c('#color_picker').hide(); - }); - }; - /** - * Paint box class. - */ - - - var PaintBox = /*#__PURE__*/function () { - /** - * @param {string|Element|external:jQuery} container - * @param {"fill"} type - */ - function PaintBox(container, type) { - _classCallCheck(this, PaintBox); - - var cur = curConfig[type === 'fill' ? 'initFill' : 'initStroke']; // set up gradients to be used for the buttons - - var svgdocbox = new DOMParser().parseFromString("\n \n \n "), 'text/xml'); - var docElem = svgdocbox.documentElement; - docElem = $$c(container)[0].appendChild(document.importNode(docElem, true)); - docElem.setAttribute('width', 16.5); - this.rect = docElem.firstElementChild; - this.defs = docElem.getElementsByTagName('defs')[0]; - this.grad = this.defs.firstElementChild; - this.paint = new $$c.jGraduate.Paint({ - solidColor: cur.color - }); - this.type = type; - } - /** - * @param {module:jGraduate~Paint} paint - * @param {boolean} apply - * @returns {void} - */ - - - _createClass(PaintBox, [{ - key: "setPaint", - value: function setPaint(paint, apply) { - this.paint = paint; - var ptype = paint.type; - var opac = paint.alpha / 100; - var fillAttr = 'none'; - - switch (ptype) { - case 'solidColor': - fillAttr = paint[ptype] !== 'none' ? '#' + paint[ptype] : paint[ptype]; - break; - - case 'linearGradient': - case 'radialGradient': - { - this.grad.remove(); - this.grad = this.defs.appendChild(paint[ptype]); - var id = this.grad.id = 'gradbox_' + this.type; - fillAttr = 'url(#' + id + ')'; - break; - } - } - - this.rect.setAttribute('fill', fillAttr); - this.rect.setAttribute('opacity', opac); - - if (apply) { - svgCanvas.setColor(this.type, this._paintColor, true); - svgCanvas.setPaintOpacity(this.type, this._paintOpacity, true); - } - } - /** - * @param {boolean} apply - * @returns {void} - */ - - }, { - key: "update", - value: function update(apply) { - if (!selectedElement) { - return; - } - - var type = this.type; - - switch (selectedElement.tagName) { - case 'use': - case 'image': - case 'foreignObject': - // These elements don't have fill or stroke, so don't change - // the current value - return; - - case 'g': - case 'a': - { - var childs = selectedElement.getElementsByTagName('*'); - var gPaint = null; - - for (var _i2 = 0, len = childs.length; _i2 < len; _i2++) { - var elem = childs[_i2]; - var p = elem.getAttribute(type); - - if (_i2 === 0) { - gPaint = p; - } else if (gPaint !== p) { - gPaint = null; - break; - } - } - - if (gPaint === null) { - // No common color, don't update anything - this._paintColor = null; - return; - } - - this._paintColor = gPaint; - this._paintOpacity = 1; - break; - } - - default: - { - this._paintOpacity = Number.parseFloat(selectedElement.getAttribute(type + '-opacity')); - - if (Number.isNaN(this._paintOpacity)) { - this._paintOpacity = 1.0; - } - - var defColor = type === 'fill' ? 'black' : 'none'; - this._paintColor = selectedElement.getAttribute(type) || defColor; - } - } - - if (apply) { - svgCanvas.setColor(type, this._paintColor, true); - svgCanvas.setPaintOpacity(type, this._paintOpacity, true); - } - - this._paintOpacity *= 100; - var paint = getPaint(this._paintColor, this._paintOpacity, type); // update the rect inside #fill_color/#stroke_color - - this.setPaint(paint); - } - /** - * @returns {void} - */ - - }, { - key: "prep", - value: function prep() { - var ptype = this.paint.type; - - switch (ptype) { - case 'linearGradient': - case 'radialGradient': - { - var paint = new $$c.jGraduate.Paint({ - copy: this.paint - }); - svgCanvas.setPaint(this.type, paint); - break; - } - } - } - }]); - - return PaintBox; - }(); - - PaintBox.ctr = 0; - paintBox.fill = new PaintBox('#fill_color', 'fill'); - paintBox.stroke = new PaintBox('#stroke_color', 'stroke'); - $$c('#stroke_width').val(curConfig.initStroke.width); - $$c('#group_opacity').val(curConfig.initOpacity * 100); // Use this SVG elem to test vectorEffect support - - var testEl = paintBox.fill.rect.cloneNode(false); - testEl.setAttribute('style', 'vector-effect:non-scaling-stroke'); - var supportsNonSS = testEl.style.vectorEffect === 'non-scaling-stroke'; - testEl.removeAttribute('style'); - var svgdocbox = paintBox.fill.rect.ownerDocument; // Use this to test support for blur element. Seems to work to test support in Webkit - - var blurTest = svgdocbox.createElementNS(NS.SVG, 'feGaussianBlur'); - - if (blurTest.stdDeviationX === undefined) { - $$c('#tool_blur').hide(); - } - - $$c(blurTest).remove(); // Test for zoom icon support - - (function () { - var pre = '-' + uaPrefix.toLowerCase() + '-zoom-'; - var zoom = pre + 'in'; - workarea.css('cursor', zoom); - - if (workarea.css('cursor') === zoom) { - zoomInIcon = zoom; - zoomOutIcon = pre + 'out'; - } - - workarea.css('cursor', 'auto'); - })(); // Test for embedImage support (use timeout to not interfere with page load) - - - setTimeout(function () { - svgCanvas.embedImage('images/logo.png', function (datauri) { - if (!datauri) { - // Disable option - $$c('#image_save_opts [value=embed]').attr('disabled', 'disabled'); - $$c('#image_save_opts input').val(['ref']); - editor.pref('img_save', 'ref'); - $$c('#image_opt_embed').css('color', '#666').attr('title', uiStrings$1.notification.featNotSupported); - } - }); - }, 1000); - $$c('#fill_color, #tool_fill .icon_label').click(function () { - colorPicker($$c('#fill_color')); - updateToolButtonState(); - }); - $$c('#stroke_color, #tool_stroke .icon_label').click(function () { - colorPicker($$c('#stroke_color')); - updateToolButtonState(); - }); - $$c('#group_opacityLabel').click(function () { - $$c('#opacity_dropdown button').mousedown(); - $$c(window).mouseup(); - }); - $$c('#zoomLabel').click(function () { - $$c('#zoom_dropdown button').mousedown(); - $$c(window).mouseup(); - }); - $$c('#tool_move_top').mousedown(function (evt) { - $$c('#tools_stacking').show(); - evt.preventDefault(); - }); - $$c('.layer_button').mousedown(function () { - $$c(this).addClass('layer_buttonpressed'); - }).mouseout(function () { - $$c(this).removeClass('layer_buttonpressed'); - }).mouseup(function () { - $$c(this).removeClass('layer_buttonpressed'); - }); - $$c('.push_button').mousedown(function () { - if (!$$c(this).hasClass('disabled')) { - $$c(this).addClass('push_button_pressed').removeClass('push_button'); - } - }).mouseout(function () { - $$c(this).removeClass('push_button_pressed').addClass('push_button'); - }).mouseup(function () { - $$c(this).removeClass('push_button_pressed').addClass('push_button'); - }); // ask for a layer name - - $$c('#layer_new').click( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13() { - var uniqName, i, newName; - return regeneratorRuntime.wrap(function _callee13$(_context13) { - while (1) { - switch (_context13.prev = _context13.next) { - case 0: - i = svgCanvas.getCurrentDrawing().getNumLayers(); - - do { - uniqName = uiStrings$1.layers.layer + ' ' + ++i; - } while (svgCanvas.getCurrentDrawing().hasLayer(uniqName)); - - _context13.next = 4; - return $$c.prompt(uiStrings$1.notification.enterUniqueLayerName, uniqName); - - case 4: - newName = _context13.sent; - - if (newName) { - _context13.next = 7; - break; - } - - return _context13.abrupt("return"); - - case 7: - if (!svgCanvas.getCurrentDrawing().hasLayer(newName)) { - _context13.next = 10; - break; - } - - /* await */ - $$c.alert(uiStrings$1.notification.dupeLayerName); - return _context13.abrupt("return"); - - case 10: - svgCanvas.createLayer(newName); - updateContextPanel(); - populateLayers(); - - case 13: - case "end": - return _context13.stop(); - } - } - }, _callee13); - }))); - /** - * - * @returns {void} - */ - - function deleteLayer() { - if (svgCanvas.deleteCurrentLayer()) { - updateContextPanel(); - populateLayers(); // This matches what SvgCanvas does - // TODO: make this behavior less brittle (svg-editor should get which - // layer is selected from the canvas and then select that one in the UI) - - $$c('#layerlist tr.layer').removeClass('layersel'); - $$c('#layerlist tr.layer:first').addClass('layersel'); - } - } - /** - * - * @returns {Promise} - */ - - - function cloneLayer() { - return _cloneLayer.apply(this, arguments); - } - /** - * - * @returns {void} - */ - - - function _cloneLayer() { - _cloneLayer = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee19() { - var name, newName; - return regeneratorRuntime.wrap(function _callee19$(_context19) { - while (1) { - switch (_context19.prev = _context19.next) { - case 0: - name = svgCanvas.getCurrentDrawing().getCurrentLayerName() + ' copy'; - _context19.next = 3; - return $$c.prompt(uiStrings$1.notification.enterUniqueLayerName, name); - - case 3: - newName = _context19.sent; - - if (newName) { - _context19.next = 6; - break; - } - - return _context19.abrupt("return"); - - case 6: - if (!svgCanvas.getCurrentDrawing().hasLayer(newName)) { - _context19.next = 9; - break; - } - - /* await */ - $$c.alert(uiStrings$1.notification.dupeLayerName); - return _context19.abrupt("return"); - - case 9: - svgCanvas.cloneLayer(newName); - updateContextPanel(); - populateLayers(); - - case 12: - case "end": - return _context19.stop(); - } - } - }, _callee19); - })); - return _cloneLayer.apply(this, arguments); - } - - function mergeLayer() { - if ($$c('#layerlist tr.layersel').index() === svgCanvas.getCurrentDrawing().getNumLayers() - 1) { - return; - } - - svgCanvas.mergeLayer(); - updateContextPanel(); - populateLayers(); - } - /** - * @param {Integer} pos - * @returns {void} - */ - - - function moveLayer(pos) { - var total = svgCanvas.getCurrentDrawing().getNumLayers(); - var curIndex = $$c('#layerlist tr.layersel').index(); - - if (curIndex > 0 || curIndex < total - 1) { - curIndex += pos; - svgCanvas.setCurrentLayerPosition(total - curIndex - 1); - populateLayers(); - } - } - - $$c('#layer_delete').click(deleteLayer); - $$c('#layer_up').click(function () { - moveLayer(-1); - }); - $$c('#layer_down').click(function () { - moveLayer(1); - }); - $$c('#layer_rename').click( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14() { - var oldName, newName; - return regeneratorRuntime.wrap(function _callee14$(_context14) { - while (1) { - switch (_context14.prev = _context14.next) { - case 0: - // const curIndex = $('#layerlist tr.layersel').prevAll().length; // Currently unused - oldName = $$c('#layerlist tr.layersel td.layername').text(); - _context14.next = 3; - return $$c.prompt(uiStrings$1.notification.enterNewLayerName, ''); - - case 3: - newName = _context14.sent; - - if (newName) { - _context14.next = 6; - break; - } - - return _context14.abrupt("return"); - - case 6: - if (!(oldName === newName || svgCanvas.getCurrentDrawing().hasLayer(newName))) { - _context14.next = 9; - break; - } - - /* await */ - $$c.alert(uiStrings$1.notification.layerHasThatName); - return _context14.abrupt("return"); - - case 9: - svgCanvas.renameCurrentLayer(newName); - populateLayers(); - - case 11: - case "end": - return _context14.stop(); - } - } - }, _callee14); - }))); - var SIDEPANEL_MAXWIDTH = 300; - var SIDEPANEL_OPENWIDTH = 150; - var sidedrag = -1, - sidedragging = false, - allowmove = false; - /** - * @param {Float} delta - * @fires module:svgcanvas.SvgCanvas#event:ext_workareaResized - * @returns {void} - */ - - var changeSidePanelWidth = function changeSidePanelWidth(delta) { - var rulerX = $$c('#ruler_x'); - $$c('#sidepanels').width('+=' + delta); - $$c('#layerpanel').width('+=' + delta); - rulerX.css('right', Number.parseInt(rulerX.css('right')) + delta); - workarea.css('right', Number.parseInt(workarea.css('right')) + delta); - svgCanvas.runExtensions('workareaResized'); - }; - /** - * @param {Event} evt - * @returns {void} - */ - - - var resizeSidePanel = function resizeSidePanel(evt) { - if (!allowmove) { - return; - } - - if (sidedrag === -1) { - return; - } - - sidedragging = true; - var deltaX = sidedrag - evt.pageX; - var sideWidth = $$c('#sidepanels').width(); - - if (sideWidth + deltaX > SIDEPANEL_MAXWIDTH) { - deltaX = SIDEPANEL_MAXWIDTH - sideWidth; // sideWidth = SIDEPANEL_MAXWIDTH; - } else if (sideWidth + deltaX < 2) { - deltaX = 2 - sideWidth; // sideWidth = 2; - } - - if (deltaX === 0) { - return; - } - - sidedrag -= deltaX; - changeSidePanelWidth(deltaX); - }; - /** - * If width is non-zero, then fully close it; otherwise fully open it. - * @param {boolean} close Forces the side panel closed - * @returns {void} - */ - - - var toggleSidePanel = function toggleSidePanel(close) { - var dpr = window.devicePixelRatio || 1; - var w = $$c('#sidepanels').width(); - var isOpened = (dpr < 1 ? w : w / dpr) > 2; - var zoomAdjustedSidepanelWidth = (dpr < 1 ? 1 : dpr) * SIDEPANEL_OPENWIDTH; - var deltaX = (isOpened || close ? 0 : zoomAdjustedSidepanelWidth) - w; - changeSidePanelWidth(deltaX); - }; - - $$c('#sidepanel_handle').mousedown(function (evt) { - sidedrag = evt.pageX; - $$c(window).mousemove(resizeSidePanel); - allowmove = false; // Silly hack for Chrome, which always runs mousemove right after mousedown - - setTimeout(function () { - allowmove = true; - }, 20); - }).mouseup(function (evt) { - if (!sidedragging) { - toggleSidePanel(); - } - - sidedrag = -1; - sidedragging = false; - }); - $$c(window).mouseup(function () { - sidedrag = -1; - sidedragging = false; - $$c('#svg_editor').unbind('mousemove', resizeSidePanel); - }); - populateLayers(); // function changeResolution (x,y) { - // const {zoom} = svgCanvas.getResolution(); - // setResolution(x * zoom, y * zoom); - // } - - var centerCanvas = function centerCanvas() { - // this centers the canvas vertically in the workarea (horizontal handled in CSS) - workarea.css('line-height', workarea.height() + 'px'); - }; - - $$c(window).bind('load resize', centerCanvas); - /** - * @type {module:jQuerySpinButton.StepCallback} - */ - - function stepFontSize(elem, step) { - var origVal = Number(elem.value); - var sugVal = origVal + step; - var increasing = sugVal >= origVal; - - if (step === 0) { - return origVal; - } - - if (origVal >= 24) { - if (increasing) { - return Math.round(origVal * 1.1); - } - - return Math.round(origVal / 1.1); - } - - if (origVal <= 1) { - if (increasing) { - return origVal * 2; - } - - return origVal / 2; - } - - return sugVal; - } - /** - * @type {module:jQuerySpinButton.StepCallback} - */ - - - function stepZoom(elem, step) { - var origVal = Number(elem.value); - - if (origVal === 0) { - return 100; - } - - var sugVal = origVal + step; - - if (step === 0) { - return origVal; - } - - if (origVal >= 100) { - return sugVal; - } - - if (sugVal >= origVal) { - return origVal * 2; - } - - return origVal / 2; - } // function setResolution (w, h, center) { - // updateCanvas(); - // // w -= 0; h -= 0; - // // $('#svgcanvas').css({width: w, height: h}); - // // $('#canvas_width').val(w); - // // $('#canvas_height').val(h); - // // - // // if (center) { - // // const wArea = workarea; - // // const scrollY = h/2 - wArea.height()/2; - // // const scrollX = w/2 - wArea.width()/2; - // // wArea[0].scrollTop = scrollY; - // // wArea[0].scrollLeft = scrollX; - // // } - // } - - - $$c('#resolution').change(function () { - var wh = $$c('#canvas_width,#canvas_height'); - - if (!this.selectedIndex) { - if ($$c('#canvas_width').val() === 'fit') { - wh.removeAttr('disabled').val(100); - } - } else if (this.value === 'content') { - wh.val('fit').attr('disabled', 'disabled'); - } else { - var dims = this.value.split('x'); - $$c('#canvas_width').val(dims[0]); - $$c('#canvas_height').val(dims[1]); - wh.removeAttr('disabled'); - } - }); // Prevent browser from erroneously repopulating fields - - $$c('input,select').attr('autocomplete', 'off'); - var dialogSelectors = ['#tool_source_cancel', '#tool_docprops_cancel', '#tool_prefs_cancel', '.overlay']; - /* eslint-disable jsdoc/require-property */ - - /** - * Associate all button actions as well as non-button keyboard shortcuts. - * @namespace {PlainObject} module:SVGEditor~Actions - */ - - var Actions = function () { - /* eslint-enable jsdoc/require-property */ - - /** - * @typedef {PlainObject} module:SVGEditor.ToolButton - * @property {string} sel The CSS selector for the tool - * @property {external:jQuery.Function} fn A handler to be attached to the `evt` - * @property {string} evt The event for which the `fn` listener will be added - * @property {module:SVGEditor.Key} [key] [key, preventDefault, NoDisableInInput] - * @property {string} [parent] Selector - * @property {boolean} [hidekey] Whether to show key value in title - * @property {string} [icon] The button ID - * @property {boolean} isDefault For flyout holders - */ - - /** - * - * @name module:SVGEditor~ToolButtons - * @type {module:SVGEditor.ToolButton[]} - */ - var toolButtons = [{ - sel: '#tool_select', - fn: clickSelect, - evt: 'click', - key: ['V', true] - }, { - sel: '#tool_fhpath', - fn: clickFHPath, - evt: 'click', - key: ['Q', true] - }, { - sel: '#tool_line', - fn: clickLine, - evt: 'click', - key: ['L', true], - parent: '#tools_line', - prepend: true - }, { - sel: '#tool_rect', - fn: clickRect, - evt: 'mouseup', - key: ['R', true], - parent: '#tools_rect', - icon: 'rect' - }, { - sel: '#tool_square', - fn: clickSquare, - evt: 'mouseup', - parent: '#tools_rect', - icon: 'square' - }, { - sel: '#tool_fhrect', - fn: clickFHRect, - evt: 'mouseup', - parent: '#tools_rect', - icon: 'fh_rect' - }, { - sel: '#tool_ellipse', - fn: clickEllipse, - evt: 'mouseup', - key: ['E', true], - parent: '#tools_ellipse', - icon: 'ellipse' - }, { - sel: '#tool_circle', - fn: clickCircle, - evt: 'mouseup', - parent: '#tools_ellipse', - icon: 'circle' - }, { - sel: '#tool_fhellipse', - fn: clickFHEllipse, - evt: 'mouseup', - parent: '#tools_ellipse', - icon: 'fh_ellipse' - }, { - sel: '#tool_path', - fn: clickPath, - evt: 'click', - key: ['P', true] - }, { - sel: '#tool_text', - fn: clickText, - evt: 'click', - key: ['T', true] - }, { - sel: '#tool_image', - fn: clickImage, - evt: 'mouseup' - }, { - sel: '#tool_zoom', - fn: clickZoom, - evt: 'mouseup', - key: ['Z', true] - }, { - sel: '#tool_clear', - fn: clickClear, - evt: 'mouseup', - key: ['N', true] - }, { - sel: '#tool_save', - fn: function fn() { - if (editingsource) { - saveSourceEditor(); - } else { - clickSave(); - } - }, - evt: 'mouseup', - key: ['S', true] - }, { - sel: '#tool_export', - fn: clickExport, - evt: 'mouseup' - }, { - sel: '#tool_open', - fn: clickOpen, - evt: 'mouseup', - key: ['O', true] - }, { - sel: '#tool_import', - fn: clickImport, - evt: 'mouseup' - }, { - sel: '#tool_source', - fn: showSourceEditor, - evt: 'click', - key: ['U', true] - }, { - sel: '#tool_wireframe', - fn: clickWireframe, - evt: 'click', - key: ['F', true] - }, { - key: ['esc', false, false], - fn: function fn() { - if (dialogSelectors.every(function (sel) { - return $$c(sel + ':hidden').length; - })) { - svgCanvas.clearSelection(); - } - }, - hidekey: true - }, { - sel: dialogSelectors.join(','), - fn: cancelOverlays, - evt: 'click', - key: ['esc', false, false], - hidekey: true - }, { - sel: '#tool_source_save', - fn: saveSourceEditor, - evt: 'click' - }, { - sel: '#tool_docprops_save', - fn: saveDocProperties, - evt: 'click' - }, { - sel: '#tool_docprops', - fn: showDocProperties, - evt: 'click' - }, { - sel: '#tool_prefs_save', - fn: savePreferences, - evt: 'click' - }, { - sel: '#tool_editor_prefs', - fn: showPreferences, - evt: 'click' - }, { - sel: '#tool_editor_homepage', - fn: openHomePage, - evt: 'click' - }, { - sel: '#tool_open', - fn: function fn() { - window.dispatchEvent(new CustomEvent('openImage')); - }, - evt: 'click' - }, { - sel: '#tool_import', - fn: function fn() { - window.dispatchEvent(new CustomEvent('importImage')); - }, - evt: 'click' - }, { - sel: '#tool_delete,#tool_delete_multi', - fn: deleteSelected, - evt: 'click', - key: ['del/backspace', true] - }, { - sel: '#tool_reorient', - fn: reorientPath, - evt: 'click' - }, { - sel: '#tool_node_link', - fn: linkControlPoints, - evt: 'click' - }, { - sel: '#tool_node_clone', - fn: clonePathNode, - evt: 'click' - }, { - sel: '#tool_node_delete', - fn: deletePathNode, - evt: 'click' - }, { - sel: '#tool_openclose_path', - fn: opencloseSubPath, - evt: 'click' - }, { - sel: '#tool_add_subpath', - fn: addSubPath, - evt: 'click' - }, { - sel: '#tool_move_top', - fn: moveToTopSelected, - evt: 'click', - key: 'ctrl+shift+]' - }, { - sel: '#tool_move_bottom', - fn: moveToBottomSelected, - evt: 'click', - key: 'ctrl+shift+[' - }, { - sel: '#tool_topath', - fn: convertToPath, - evt: 'click' - }, { - sel: '#tool_make_link,#tool_make_link_multi', - fn: makeHyperlink, - evt: 'click' - }, { - sel: '#tool_undo', - fn: clickUndo, - evt: 'click' - }, { - sel: '#tool_redo', - fn: clickRedo, - evt: 'click' - }, { - sel: '#tool_clone,#tool_clone_multi', - fn: clickClone, - evt: 'click', - key: ['D', true] - }, { - sel: '#tool_group_elements', - fn: clickGroup, - evt: 'click', - key: ['G', true] - }, { - sel: '#tool_ungroup', - fn: clickGroup, - evt: 'click' - }, { - sel: '#tool_unlink_use', - fn: clickGroup, - evt: 'click' - }, { - sel: '[id^=tool_align]', - fn: clickAlign, - evt: 'click' - }, // these two lines are required to make Opera work properly with the flyout mechanism - // {sel: '#tools_rect_show', fn: clickRect, evt: 'click'}, - // {sel: '#tools_ellipse_show', fn: clickEllipse, evt: 'click'}, - { - sel: '#tool_bold', - fn: clickBold, - evt: 'mousedown' - }, { - sel: '#tool_italic', - fn: clickItalic, - evt: 'mousedown' - }, { - sel: '#sidepanel_handle', - fn: toggleSidePanel, - key: ['X'] - }, { - sel: '#copy_save_done', - fn: cancelOverlays, - evt: 'click' - }, // Shortcuts not associated with buttons - { - key: 'ctrl+left', - fn: function fn() { - rotateSelected(0, 1); - } - }, { - key: 'ctrl+right', - fn: function fn() { - rotateSelected(1, 1); - } - }, { - key: 'ctrl+shift+left', - fn: function fn() { - rotateSelected(0, 5); - } - }, { - key: 'ctrl+shift+right', - fn: function fn() { - rotateSelected(1, 5); - } - }, { - key: 'shift+O', - fn: selectPrev - }, { - key: 'shift+P', - fn: selectNext - }, { - key: [modKey + 'up', true], - fn: function fn() { - zoomImage(2); - } - }, { - key: [modKey + 'down', true], - fn: function fn() { - zoomImage(0.5); - } - }, { - key: [modKey + ']', true], - fn: function fn() { - moveUpDownSelected('Up'); - } - }, { - key: [modKey + '[', true], - fn: function fn() { - moveUpDownSelected('Down'); - } - }, { - key: ['up', true], - fn: function fn() { - moveSelected(0, -1); - } - }, { - key: ['down', true], - fn: function fn() { - moveSelected(0, 1); - } - }, { - key: ['left', true], - fn: function fn() { - moveSelected(-1, 0); - } - }, { - key: ['right', true], - fn: function fn() { - moveSelected(1, 0); - } - }, { - key: 'shift+up', - fn: function fn() { - moveSelected(0, -10); - } - }, { - key: 'shift+down', - fn: function fn() { - moveSelected(0, 10); - } - }, { - key: 'shift+left', - fn: function fn() { - moveSelected(-10, 0); - } - }, { - key: 'shift+right', - fn: function fn() { - moveSelected(10, 0); - } - }, { - key: ['alt+up', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(0, -1); - } - }, { - key: ['alt+down', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(0, 1); - } - }, { - key: ['alt+left', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(-1, 0); - } - }, { - key: ['alt+right', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(1, 0); - } - }, { - key: ['alt+shift+up', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(0, -10); - } - }, { - key: ['alt+shift+down', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(0, 10); - } - }, { - key: ['alt+shift+left', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(-10, 0); - } - }, { - key: ['alt+shift+right', true], - fn: function fn() { - svgCanvas.cloneSelectedElements(10, 0); - } - }, { - key: 'a', - fn: function fn() { - svgCanvas.selectAllInCurrentLayer(); - } - }, { - key: modKey + 'a', - fn: function fn() { - svgCanvas.selectAllInCurrentLayer(); - } - }, // Standard shortcuts - { - key: modKey + 'z', - fn: clickUndo - }, { - key: modKey + 'shift+z', - fn: clickRedo - }, { - key: modKey + 'y', - fn: clickRedo - }, { - key: modKey + 'x', - fn: cutSelected - }, { - key: modKey + 'c', - fn: copySelected - }, { - key: modKey + 'v', - fn: pasteInCenter - }]; // Tooltips not directly associated with a single function - - var keyAssocs = { - '4/Shift+4': '#tools_rect_show', - '5/Shift+5': '#tools_ellipse_show' - }; - return { - /** @lends module:SVGEditor~Actions */ - - /** - * @returns {void} - */ - setAll: function setAll() { - var flyouts = {}; - var keyHandler = {}; // will contain the action for each pressed key - - toolButtons.forEach(function (opts) { - // Bind function to button - var btn; - - if (opts.sel) { - btn = $q$1(opts.sel); - - if (btn === null) { - return true; - } // Skip if markup does not exist - - - if (opts.evt) { - // `touch.js` changes `touchstart` to `mousedown`, - // so we must map tool button click events as well - if (isTouch() && opts.evt === 'click') { - opts.evt = 'mousedown'; - } - - btn.addEventListener(opts.evt, opts.fn); - } // Add to parent flyout menu, if able to be displayed - - - if (opts.parent && $$c(opts.parent + '_show').length) { - var fH = $$c(opts.parent); - - if (!fH.length) { - fH = makeFlyoutHolder(opts.parent.substr(1)); - } - - if (opts.prepend) { - btn.style.margin = 'initial'; - } - - fH[opts.prepend ? 'prepend' : 'append'](btn); - - if (!Array.isArray(flyouts[opts.parent])) { - flyouts[opts.parent] = []; - } - - flyouts[opts.parent].push(opts); - } - } // Bind function to shortcut key - - - if (opts.key) { - // Set shortcut based on options - var keyval = opts.key; - var pd = false; - - if (Array.isArray(opts.key)) { - keyval = opts.key[0]; - - if (opts.key.length > 1) { - pd = opts.key[1]; - } - } - - keyval = String(keyval); - var fn = opts.fn; - keyval.split('/').forEach(function (key) { - keyHandler[key] = { - fn: fn, - pd: pd - }; - }); // Put shortcut in title - - if (opts.sel && !opts.hidekey && btn.title) { - var newTitle = "".concat(btn.title.split('[')[0], " (").concat(keyval, ")"); - keyAssocs[keyval] = opts.sel; // Disregard for menu items - - if (btn.closest('#main_menu') === null) { - btn.title = newTitle; - } - } - } - - return true; - }); // register the keydown event - - document.addEventListener('keydown', function (e) { - // only track keyboard shortcuts for the body containing the SVG-Editor - if (e.target.nodeName !== 'BODY') return; // normalize key - - var key = "".concat(e.metaKey ? 'meta+' : '').concat(e.ctrlKey ? 'ctrl+' : '').concat(e.key.toLowerCase()); // return if no shortcut defined for this key - - if (!keyHandler[key]) return; // launch associated handler and preventDefault if necessary - - keyHandler[key].fn(); - - if (keyHandler[key].pd) { - e.preventDefault(); - } - }); // Setup flyouts - - setupFlyouts(flyouts); // Misc additional actions - // Make 'return' keypress trigger the change event - - $$c('.attr_changer, #image_url').bind('keydown', 'return', function (evt) { - $$c(this).change(); - evt.preventDefault(); - }); - $$c(window).bind('keydown', 'tab', function (e) { - if (uiContext === 'canvas') { - e.preventDefault(); - selectNext(); - } - }).bind('keydown', 'shift+tab', function (e) { - if (uiContext === 'canvas') { - e.preventDefault(); - selectPrev(); - } - }); - $$c('#tool_zoom').dblclick(dblclickZoom); - }, - - /** - * @returns {void} - */ - setTitles: function setTitles() { - $$c.each(keyAssocs, function (keyval, sel) { - var menu = $$c(sel).parents('#main_menu').length; - $$c(sel).each(function () { - var t; - - if (menu) { - t = $$c(this).text().split(' [')[0]; - } else { - t = this.title.split(' [')[0]; - } - - var keyStr = ''; // Shift+Up - - $$c.each(keyval.split('/'), function (i, key) { - var modBits = key.split('+'); - var mod = ''; - - if (modBits.length > 1) { - mod = modBits[0] + '+'; - key = modBits[1]; - } - - keyStr += (i ? '/' : '') + mod + (uiStrings$1['key_' + key] || key); - }); - - if (menu) { - this.lastChild.textContent = t + ' [' + keyStr + ']'; - } else { - this.title = t + ' [' + keyStr + ']'; - } - }); - }); - }, - - /** - * @param {string} sel Selector to match - * @returns {module:SVGEditor.ToolButton} - */ - getButtonData: function getButtonData(sel) { - return Object.values(toolButtons).find(function (btn) { - return btn.sel === sel; - }); - } - }; - }(); // Select given tool - - - editor.ready(function () { - var tool; - var itool = curConfig.initTool, - container = $$c('#tools_left, #svg_editor .tools_flyout'), - preTool = container.find('#tool_' + itool), - regTool = container.find('#' + itool); - - if (preTool.length) { - tool = preTool; - } else if (regTool.length) { - tool = regTool; - } else { - tool = $$c('#tool_select'); - } - - tool.click().mouseup(); - - if (curConfig.wireframe) { - $$c('#tool_wireframe').click(); - } - - if (curConfig.showlayers) { - toggleSidePanel(); - } - - $$c('#rulers').toggle(Boolean(curConfig.showRulers)); - - if (curConfig.showRulers) { - $$c('#show_rulers')[0].checked = true; - } - - if (curConfig.baseUnit) { - $$c('#base_unit').val(curConfig.baseUnit); - } - - if (curConfig.gridSnapping) { - $$c('#grid_snapping_on')[0].checked = true; - } - - if (curConfig.snappingStep) { - $$c('#grid_snapping_step').val(curConfig.snappingStep); - } - - if (curConfig.gridColor) { - $$c('#grid_color').val(curConfig.gridColor); - } - }); // init SpinButtons - - $$c('#rect_rx').SpinButton({ - min: 0, - max: 1000, - stateObj: stateObj, - callback: changeRectRadius - }); - $$c('#stroke_width').SpinButton({ - min: 0, - max: 99, - smallStep: 0.1, - stateObj: stateObj, - callback: changeStrokeWidth - }); - $$c('#angle').SpinButton({ - min: -180, - max: 180, - step: 5, - stateObj: stateObj, - callback: changeRotationAngle - }); - $$c('#font_size').SpinButton({ - min: 0.001, - stepfunc: stepFontSize, - stateObj: stateObj, - callback: changeFontSize - }); - $$c('#group_opacity').SpinButton({ - min: 0, - max: 100, - step: 5, - stateObj: stateObj, - callback: changeOpacity - }); - $$c('#blur').SpinButton({ - min: 0, - max: 10, - step: 0.1, - stateObj: stateObj, - callback: changeBlur - }); - $$c('#zoom').SpinButton({ - min: 0.001, - max: 10000, - step: 50, - stepfunc: stepZoom, - stateObj: stateObj, - callback: changeZoom // Set default zoom - - }).val(svgCanvas.getZoom() * 100); - $$c('#workarea').contextMenu({ - menu: 'cmenu_canvas', - inSpeed: 0 - }, function (action, el, pos) { - switch (action) { - case 'delete': - deleteSelected(); - break; - - case 'cut': - cutSelected(); - break; - - case 'copy': - copySelected(); - 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': - moveToTopSelected(); - break; - - case 'move_up': - moveUpDownSelected('Up'); - break; - - case 'move_down': - moveUpDownSelected('Down'); - break; - - case 'move_back': - moveToBottomSelected(); - break; - - default: - if (hasCustomHandler(action)) { - getCustomHandler(action).call(); - } - - break; - } - }); - /** - * Implements {@see module:jQueryContextMenu.jQueryContextMenuListener}. - * @param {"dupe"|"delete"|"merge_down"|"merge_all"} action - * @param {external:jQuery} el - * @param {{x: Float, y: Float, docX: Float, docY: Float}} pos - * @returns {void} - */ - - var lmenuFunc = function lmenuFunc(action, el, pos) { - switch (action) { - case 'dupe': - /* await */ - cloneLayer(); - break; - - case 'delete': - deleteLayer(); - break; - - case 'merge_down': - mergeLayer(); - break; - - case 'merge_all': - svgCanvas.mergeAllLayers(); - updateContextPanel(); - populateLayers(); - break; - } - }; - - $$c('#layerlist').contextMenu({ - menu: 'cmenu_layers', - inSpeed: 0 - }, lmenuFunc); - $$c('#layer_moreopts').contextMenu({ - menu: 'cmenu_layers', - inSpeed: 0, - allowLeft: true - }, lmenuFunc); - $$c('.contextMenu li').mousedown(function (ev) { - ev.preventDefault(); - }); - $$c('#cmenu_canvas li').disableContextMenu(); - canvMenu.enableContextMenuItems('#delete,#cut,#copy'); - /** - * @returns {void} - */ - - function enableOrDisableClipboard() { - var svgeditClipboard; - - try { - svgeditClipboard = localStorage.getItem('svgedit_clipboard'); - } catch (err) {} - - canvMenu[(svgeditClipboard ? 'en' : 'dis') + 'ableContextMenuItems']('#paste,#paste_in_place'); - } - - enableOrDisableClipboard(); - window.addEventListener('storage', function (e) { - if (e.key !== 'svgedit_clipboard') { - return; - } - - enableOrDisableClipboard(); - }); - window.addEventListener('beforeunload', function (e) { - // Suppress warning if page is empty - if (undoMgr.getUndoStackSize() === 0) { - editor.showSaveWarning = false; - } // showSaveWarning is set to 'false' when the page is saved. - - - if (!curConfig.no_save_warning && editor.showSaveWarning) { - // Browser already asks question about closing the page - e.returnValue = uiStrings$1.notification.unsavedChanges; // Firefox needs this when beforeunload set by addEventListener (even though message is not used) - - return uiStrings$1.notification.unsavedChanges; - } - - return true; - }); - /** - * Expose the `uiStrings`. - * @function module:SVGEditor.canvas.getUIStrings - * @returns {module:SVGEditor.uiStrings} - */ - - editor.canvas.getUIStrings = function () { - return uiStrings$1; - }; - /** - * @function module:SVGEditor.openPrep - * @returns {boolean|Promise} Resolves to boolean indicating `true` if there were no changes - * and `false` after the user confirms. - */ - - - editor.openPrep = function () { - $$c('#main_menu').hide(); - - if (undoMgr.getUndoStackSize() === 0) { - return true; - } - - return $$c.confirm(uiStrings$1.notification.QwantToOpen); - }; - /** - * - * @param {Event} e - * @returns {void} - */ - - - function onDragEnter(e) { - e.stopPropagation(); - e.preventDefault(); // and indicator should be displayed here, such as "drop files here" - } - /** - * - * @param {Event} e - * @returns {void} - */ - - - function onDragOver(e) { - e.stopPropagation(); - e.preventDefault(); - } - /** - * - * @param {Event} e - * @returns {void} - */ - - - function onDragLeave(e) { - e.stopPropagation(); - e.preventDefault(); // hypothetical indicator should be removed here - } // Use HTML5 File API: http://www.w3.org/TR/FileAPI/ - // if browser has HTML5 File API support, then we will show the open menu item - // and provide a file input to click. When that change event fires, it will - // get the text contents of the file and send it to the canvas - - - if (window.FileReader) { - /** - * @param {Event} e - * @returns {void} - */ - var importImage = function importImage(e) { - $$c.process_cancel(uiStrings$1.notification.loadingImage); - e.stopPropagation(); - e.preventDefault(); - $$c('#main_menu').hide(); - var file = e.type === 'drop' ? e.dataTransfer.files[0] : this.files[0]; - - if (!file) { - $$c('#dialog_box').hide(); - return; - } - /* if (file.type === 'application/pdf') { // Todo: Handle PDF imports - } - else */ - - - if (!file.type.includes('image')) { - return; - } // Detected an image - // svg handling - - - var reader; - - if (file.type.includes('svg')) { - reader = new FileReader(); - - reader.onloadend = function (ev) { - var newElement = svgCanvas.importSvgString(ev.target.result, true); - svgCanvas.ungroupSelectedElement(); - svgCanvas.ungroupSelectedElement(); - svgCanvas.groupSelectedElements(); - svgCanvas.alignSelectedElements('m', 'page'); - svgCanvas.alignSelectedElements('c', 'page'); // highlight imported element, otherwise we get strange empty selectbox - - svgCanvas.selectOnly([newElement]); - $$c('#dialog_box').hide(); - }; - - reader.readAsText(file); - } else { - // bitmap handling - reader = new FileReader(); - - reader.onloadend = function (_ref23) { - var result = _ref23.target.result; - - /** - * Insert the new image until we know its dimensions. - * @param {Float} width - * @param {Float} height - * @returns {void} - */ - var insertNewImage = function insertNewImage(width, height) { - var newImage = svgCanvas.addSVGElementFromJson({ - element: 'image', - attr: { - x: 0, - y: 0, - width: width, - height: height, - id: svgCanvas.getNextId(), - style: 'pointer-events:inherit' - } - }); - svgCanvas.setHref(newImage, result); - svgCanvas.selectOnly([newImage]); - svgCanvas.alignSelectedElements('m', 'page'); - svgCanvas.alignSelectedElements('c', 'page'); - updateContextPanel(); - $$c('#dialog_box').hide(); - }; // create dummy img so we know the default dimensions - - - var imgWidth = 100; - var imgHeight = 100; - var img = new Image(); - img.style.opacity = 0; - img.addEventListener('load', function () { - imgWidth = img.offsetWidth || img.naturalWidth || img.width; - imgHeight = img.offsetHeight || img.naturalHeight || img.height; - insertNewImage(imgWidth, imgHeight); - }); - img.src = result; - }; - - reader.readAsDataURL(file); - } - }; - - workarea[0].addEventListener('dragenter', onDragEnter); - workarea[0].addEventListener('dragover', onDragOver); - workarea[0].addEventListener('dragleave', onDragLeave); - workarea[0].addEventListener('drop', importImage); - var open = $$c('').change( /*#__PURE__*/function () { - var _ref24 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee16(e) { - var ok, reader; - return regeneratorRuntime.wrap(function _callee16$(_context16) { - while (1) { - switch (_context16.prev = _context16.next) { - case 0: - _context16.next = 2; - return editor.openPrep(); - - case 2: - ok = _context16.sent; - - if (ok) { - _context16.next = 5; - break; - } - - return _context16.abrupt("return"); - - case 5: - svgCanvas.clear(); - - if (this.files.length === 1) { - $$c.process_cancel(uiStrings$1.notification.loadingImage); - reader = new FileReader(); - - reader.onloadend = /*#__PURE__*/function () { - var _ref26 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee15(_ref25) { - var target; - return regeneratorRuntime.wrap(function _callee15$(_context15) { - while (1) { - switch (_context15.prev = _context15.next) { - case 0: - target = _ref25.target; - _context15.next = 3; - return loadSvgString(target.result); - - case 3: - updateCanvas(); - - case 4: - case "end": - return _context15.stop(); - } - } - }, _callee15); - })); - - return function (_x6) { - return _ref26.apply(this, arguments); - }; - }(); - - reader.readAsText(this.files[0]); - } - - case 7: - case "end": - return _context16.stop(); - } - } - }, _callee16, this); - })); - - return function (_x5) { - return _ref24.apply(this, arguments); - }; - }()); - $$c('#tool_open').show(); - $$c(window).on('openImage', function () { - return open.click(); - }); - var imgImport = $$c('').change(importImage); - $$c('#tool_import').show(); - $$c(window).on('importImage', function () { - return imgImport.click(); - }); - } - - updateCanvas(true); // const revnums = 'svg-editor.js ($Rev$) '; - // revnums += svgCanvas.getVersion(); - // $('#copyright')[0].setAttribute('title', revnums); - - var loadedExtensionNames = []; - /** - * @function module:SVGEditor.setLang - * @param {string} lang The language code - * @param {module:locale.LocaleStrings} allStrings See {@tutorial LocaleDocs} - * @fires module:svgcanvas.SvgCanvas#event:ext_langReady - * @fires module:svgcanvas.SvgCanvas#event:ext_langChanged - * @returns {Promise} A Promise which resolves to `undefined` - */ - - var setLang = editor.setLang = /*#__PURE__*/function () { - var _ref27 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee17(lang, allStrings) { - var oldLayerName, renameLayer, elems; - return regeneratorRuntime.wrap(function _callee17$(_context17) { - while (1) { - switch (_context17.prev = _context17.next) { - case 0: - editor.langChanged = true; - editor.pref('lang', lang); - $$c('#lang_select').val(lang); - - if (allStrings) { - _context17.next = 5; - break; - } - - return _context17.abrupt("return"); - - case 5: - // Todo: Remove `allStrings.lang` property in locale in - // favor of just `lang`? - document.documentElement.lang = allStrings.lang; // lang; - // Todo: Add proper RTL Support! - // Todo: Use RTL detection instead and take out of locales? - // document.documentElement.dir = allStrings.dir; - - $$c.extend(uiStrings$1, allStrings); // const notif = allStrings.notification; // Currently unused - // $.extend will only replace the given strings - - oldLayerName = $$c('#layerlist tr.layersel td.layername').text(); - renameLayer = oldLayerName === uiStrings$1.common.layer + ' 1'; - svgCanvas.setUiStrings(allStrings); - Actions.setTitles(); - - if (renameLayer) { - svgCanvas.renameCurrentLayer(uiStrings$1.common.layer + ' 1'); - populateLayers(); - } // In case extensions loaded before the locale, now we execute a callback on them - - - if (!extsPreLang.length) { - _context17.next = 18; - break; - } - - _context17.next = 15; - return Promise.all(extsPreLang.map(function (ext) { - loadedExtensionNames.push(ext.name); - return ext.langReady({ - lang: lang, - uiStrings: uiStrings$1, - importLocale: getImportLocale({ - defaultLang: lang, - defaultName: ext.name - }) - }); - })); - - case 15: - extsPreLang.length = 0; - _context17.next = 19; - break; - - case 18: - loadedExtensionNames.forEach(function (loadedExtensionName) { - svgCanvas.runExtension(loadedExtensionName, 'langReady', - /** @type {module:svgcanvas.SvgCanvas#event:ext_langReady} */ - { - lang: lang, - uiStrings: uiStrings$1, - importLocale: getImportLocale({ - defaultLang: lang, - defaultName: loadedExtensionName - }) - }); - }); - - case 19: - svgCanvas.runExtensions('langChanged', - /** @type {module:svgcanvas.SvgCanvas#event:ext_langChanged} */ - lang); // Update flyout tooltips - - setFlyoutTitles(); // Copy title for certain tool elements - - elems = { - '#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' - }; - $$c.each(elems, function (source, dest) { - $$c(dest).attr('title', $$c(source)[0].title); - }); // Copy alignment titles - - $$c('#multiselected_panel div[id^=tool_align]').each(function () { - $$c('#tool_pos' + this.id.substr(10))[0].title = this.title; - }); - - case 24: - case "end": - return _context17.stop(); - } - } - }, _callee17); - })); - - return function (_x7, _x8) { - return _ref27.apply(this, arguments); - }; - }(); - - init$7( - /** - * @implements {module:locale.LocaleEditorInit} - */ - { - /** - * Gets an array of results from extensions with a `addLangData` method, - * returning an object with a `data` property set to its locales (to be - * merged with regular locales). - * @param {string} langParam - * @fires module:svgcanvas.SvgCanvas#event:ext_addLangData - * @todo Can we forego this in favor of `langReady` (or forego `langReady`)? - * @returns {module:locale.AddLangExtensionLocaleData[]} - */ - addLangData: function addLangData(langParam) { - return svgCanvas.runExtensions('addLangData', - /** - * @function - * @type {module:svgcanvas.ExtensionVarBuilder} - * @param {string} name - * @returns {module:svgcanvas.SvgCanvas#event:ext_addLangData} - */ - function (name) { - // We pass in a function as we don't know the extension name here when defining this `addLangData` method - return { - lang: langParam, - importLocale: getImportLocale({ - defaultLang: langParam, - defaultName: name - }) - }; - }, true); - }, - curConfig: curConfig - }); // Load extensions - // Bit of a hack to run extensions in local Opera/IE9 - - if (document.location.protocol === 'file:') { - setTimeout(extAndLocaleFunc, 100); - } else { - // Returns a promise (if we wanted to fire 'extensions-loaded' event, - // potentially useful to hide interface as some extension locales - // are only available after this) - extAndLocaleFunc(); - } -}; -/** -* @callback module:SVGEditor.ReadyCallback -* @returns {Promise|void} -*/ - -/** -* Queues a callback to be invoked when the editor is ready (or -* to be invoked immediately if it is already ready--i.e., -* if `runCallbacks` has been run). -* @function module:SVGEditor.ready -* @param {module:SVGEditor.ReadyCallback} cb Callback to be queued to invoke -* @returns {Promise} Resolves when all callbacks, including the supplied have resolved -*/ - - -editor.ready = function (cb) { - // eslint-disable-line promise/prefer-await-to-callbacks - return new Promise(function (resolve, reject) { - // eslint-disable-line promise/avoid-new - if (isReady) { - resolve(cb()); // eslint-disable-line node/callback-return, promise/prefer-await-to-callbacks - - return; - } - - callbacks.push([cb, resolve, reject]); - }); -}; -/** -* Invokes the callbacks previous set by `svgEditor.ready` -* @function module:SVGEditor.runCallbacks -* @returns {Promise} Resolves to `undefined` if all callbacks succeeded and rejects otherwise -*/ - - -editor.runCallbacks = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee20() { - return regeneratorRuntime.wrap(function _callee20$(_context20) { - while (1) { - switch (_context20.prev = _context20.next) { - case 0: - _context20.prev = 0; - _context20.next = 3; - return Promise.all(callbacks.map(function (_ref30) { - var _ref31 = _slicedToArray(_ref30, 1), - cb = _ref31[0]; - - return cb(); // eslint-disable-line promise/prefer-await-to-callbacks - })); - - case 3: - _context20.next = 9; - break; - - case 5: - _context20.prev = 5; - _context20.t0 = _context20["catch"](0); - callbacks.forEach(function (_ref32) { - var _ref33 = _slicedToArray(_ref32, 3), - reject = _ref33[2]; - - reject(); - }); - throw _context20.t0; - - case 9: - callbacks.forEach(function (_ref34) { - var _ref35 = _slicedToArray(_ref34, 2), - resolve = _ref35[1]; - - resolve(); - }); - isReady = true; - - case 11: - case "end": - return _context20.stop(); - } - } - }, _callee20, null, [[0, 5]]); -})); -/** - * @function module:SVGEditor.loadFromString - * @param {string} str The SVG string to load - * @param {PlainObject} [opts={}] - * @param {boolean} [opts.noAlert=false] Option to avoid alert to user and instead get rejected promise - * @returns {Promise} - */ - -editor.loadFromString = function (str) { - var _ref36 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - noAlert = _ref36.noAlert; - - return editor.ready( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee21() { - return regeneratorRuntime.wrap(function _callee21$(_context21) { - while (1) { - switch (_context21.prev = _context21.next) { - case 0: - _context21.prev = 0; - _context21.next = 3; - return loadSvgString(str, { - noAlert: noAlert - }); - - case 3: - _context21.next = 9; - break; - - case 5: - _context21.prev = 5; - _context21.t0 = _context21["catch"](0); - - if (!noAlert) { - _context21.next = 9; - break; - } - - throw _context21.t0; - - case 9: - case "end": - return _context21.stop(); - } - } - }, _callee21, null, [[0, 5]]); - }))); -}; -/** -* Not presently in use. -* @function module:SVGEditor.disableUI -* @param {PlainObject} featList -* @returns {void} -*/ - - -editor.disableUI = function (featList) {// $(function () { - // $('#tool_wireframe, #tool_image, #main_button, #tool_source, #sidepanels').remove(); - // $('#tools_top').css('left', 5); - // }); -}; -/** - * @callback module:SVGEditor.URLLoadCallback - * @param {boolean} success - * @returns {void} - */ - -/** - * @function module:SVGEditor.loadFromURL - * @param {string} url URL from which to load an SVG string via Ajax - * @param {PlainObject} [opts={}] May contain properties: `cache`, `callback` - * @param {boolean} [opts.cache] - * @param {boolean} [opts.noAlert] - * @returns {Promise} Resolves to `undefined` or rejects upon bad loading of - * the SVG (or upon failure to parse the loaded string) when `noAlert` is - * enabled - */ - - -editor.loadFromURL = function (url) { - var _ref38 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - cache = _ref38.cache, - noAlert = _ref38.noAlert; - - return editor.ready(function () { - return new Promise(function (resolve, reject) { - // eslint-disable-line promise/avoid-new - $$c.ajax({ - url: url, - dataType: 'text', - cache: Boolean(cache), - beforeSend: function beforeSend() { - $$c.process_cancel(uiStrings$1.notification.loadingImage); - }, - success: function success(str) { - resolve(loadSvgString(str, { - noAlert: noAlert - })); - }, - error: function error(xhr, stat, err) { - if (xhr.status !== 404 && xhr.responseText) { - resolve(loadSvgString(xhr.responseText, { - noAlert: noAlert - })); - return; - } - - if (noAlert) { - reject(new Error('URLLoadFail')); - return; - } - - $$c.alert(uiStrings$1.notification.URLLoadFail + ': \n' + err); - resolve(); - }, - complete: function complete() { - $$c('#dialog_box').hide(); - } - }); - }); - }); -}; -/** -* @function module:SVGEditor.loadFromDataURI -* @param {string} str The Data URI to base64-decode (if relevant) and load -* @param {PlainObject} [opts={}] -* @param {boolean} [opts.noAlert] -* @returns {Promise} Resolves to `undefined` and rejects if loading SVG string fails and `noAlert` is enabled -*/ - - -editor.loadFromDataURI = function (str) { - var _ref39 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - noAlert = _ref39.noAlert; - - return editor.ready(function () { - var base64 = false; - var pre = str.match(/^data:image\/svg\+xml;base64,/); - - if (pre) { - base64 = true; - } else { - pre = str.match(/^data:image\/svg\+xml(?:;|;utf8)?,/); - } - - if (pre) { - pre = pre[0]; - } - - var src = str.slice(pre.length); - return loadSvgString(base64 ? decode64(src) : decodeURIComponent(src), { - noAlert: noAlert - }); - }); -}; -/** - * @function module:SVGEditor.addExtension - * @param {string} name Used internally; no need for i18n. - * @param {module:svgcanvas.ExtensionInitCallback} init Config to be invoked on this module - * @param {module:svgcanvas.ExtensionInitArgs} initArgs - * @throws {Error} If called too early - * @returns {Promise} Resolves to `undefined` -*/ - - -editor.addExtension = function (name, init, initArgs) { - // Note that we don't want this on editor.ready since some extensions - // may want to run before then (like server_opensave). - // $(function () { - if (!svgCanvas) { - throw new Error('Extension added too early'); - } - - return svgCanvas.addExtension.call(this, name, init, initArgs); // }); -}; // Defer injection to wait out initial menu processing. This probably goes -// away once all context menu behavior is brought to context menu. - - -editor.ready(function () { - injectExtendedContextMenuItemsIntoDom(); -}); -var extensionsAdded = false; -var messageQueue = []; -/** - * @param {PlainObject} info - * @param {any} info.data - * @param {string} info.origin - * @fires module:svgcanvas.SvgCanvas#event:message - * @returns {void} - */ - -var messageListener = function messageListener(_ref40) { - var data = _ref40.data, - origin = _ref40.origin; - // eslint-disable-line no-shadow - // console.log('data, origin, extensionsAdded', data, origin, extensionsAdded); - var messageObj = { - data: data, - origin: origin - }; - - if (!extensionsAdded) { - messageQueue.push(messageObj); - } else { - // Extensions can handle messages at this stage with their own - // canvas `message` listeners - svgCanvas.call('message', messageObj); - } -}; - -window.addEventListener('message', messageListener); // Run init once DOM is loaded -// jQuery(editor.init); - -_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee22() { - return regeneratorRuntime.wrap(function _callee22$(_context22) { - while (1) { - switch (_context22.prev = _context22.next) { - case 0: - _context22.prev = 0; - _context22.next = 3; - return Promise.resolve(); - - case 3: - editor.init(); - _context22.next = 9; - break; - - case 6: - _context22.prev = 6; - _context22.t0 = _context22["catch"](0); - console.error(_context22.t0); // eslint-disable-line no-console - - case 9: - case "end": - return _context22.stop(); - } - } - }, _callee22, null, [[0, 6]]); -}))(); - -export default editor; diff --git a/dist/index-es.min.js b/dist/index-es.min.js deleted file mode 100644 index 7616001f..00000000 --- a/dist/index-es.min.js +++ /dev/null @@ -1,142 +0,0 @@ -function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t,n,r,a,i,o){try{var s=e[i](o),l=s.value}catch(e){return void n(e)}s.done?t(l):Promise.resolve(l).then(r,a)}function n(e){return function(){var n=this,r=arguments;return new Promise((function(a,i){var o=e.apply(n,r);function s(e){t(o,a,i,s,l,"next",e)}function l(e){t(o,a,i,s,l,"throw",e)}s(void 0)}))}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function y(e){var t=e.changedTouches,n=t[0],r="";switch(e.type){case"touchstart":r="mousedown";break;case"touchmove":r="mousemove";break;case"touchend":r="mouseup";break;default:return}var a=n.screenX,i=n.screenY,o=n.clientX,s=n.clientY,l=new MouseEvent(r,{bubbles:!0,cancelable:!0,view:window,detail:1,screenX:a,screenY:i,clientX:o,clientY:s,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,button:0,relatedTarget:null});t.length<2&&(n.target.dispatchEvent(l),e.preventDefault())}document.addEventListener("touchstart",y,!0),document.addEventListener("touchmove",y,!0),document.addEventListener("touchend",y,!0),document.addEventListener("touchcancel",y,!0); -/** - * Namespaces or tools therefor. - * @module namespaces - * @license MIT -*/ -var _={HTML:"http://www.w3.org/1999/xhtml",MATH:"http://www.w3.org/1998/Math/MathML",SE:"http://svg-edit.googlecode.com",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"},b=function(){var e={};return Object.entries(_).forEach((function(t){var n=f(t,2),r=n[0],a=n[1];e[a]=r.toLowerCase()})),e};!function(){if(!("SVGPathSeg"in window)){var e=function(){function e(t,n,a){r(this,e),this.pathSegType=t,this.pathSegTypeAsLetter=n,this._owningPathSegList=a}return i(e,[{key:"_segmentChanged",value:function(){this._owningPathSegList&&this._owningPathSegList.segmentChanged(this)}}]),e}();e.prototype.classname="SVGPathSeg",e.PATHSEG_UNKNOWN=0,e.PATHSEG_CLOSEPATH=1,e.PATHSEG_MOVETO_ABS=2,e.PATHSEG_MOVETO_REL=3,e.PATHSEG_LINETO_ABS=4,e.PATHSEG_LINETO_REL=5,e.PATHSEG_CURVETO_CUBIC_ABS=6,e.PATHSEG_CURVETO_CUBIC_REL=7,e.PATHSEG_CURVETO_QUADRATIC_ABS=8,e.PATHSEG_CURVETO_QUADRATIC_REL=9,e.PATHSEG_ARC_ABS=10,e.PATHSEG_ARC_REL=11,e.PATHSEG_LINETO_HORIZONTAL_ABS=12,e.PATHSEG_LINETO_HORIZONTAL_REL=13,e.PATHSEG_LINETO_VERTICAL_ABS=14,e.PATHSEG_LINETO_VERTICAL_REL=15,e.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS=16,e.PATHSEG_CURVETO_CUBIC_SMOOTH_REL=17,e.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS=18,e.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL=19;var t=function(t){s(a,t);var n=d(a);function a(t){return r(this,a),n.call(this,e.PATHSEG_CLOSEPATH,"z",t)}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegClosePath]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter}},{key:"clone",value:function(){return new a(void 0)}}]),a}(e),n=function(t){s(a,t);var n=d(a);function a(t,i,o){var s;return r(this,a),(s=n.call(this,e.PATHSEG_MOVETO_ABS,"M",t))._x=i,s._y=o,s}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegMovetoAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y)}}]),a}(e);Object.defineProperties(n.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0}});var a=function(t){s(a,t);var n=d(a);function a(t,i,o){var s;return r(this,a),(s=n.call(this,e.PATHSEG_MOVETO_REL,"m",t))._x=i,s._y=o,s}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegMovetoRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y)}}]),a}(e);Object.defineProperties(a.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0}});var o=function(t){s(a,t);var n=d(a);function a(t,i,o){var s;return r(this,a),(s=n.call(this,e.PATHSEG_LINETO_ABS,"L",t))._x=i,s._y=o,s}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegLinetoAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y)}}]),a}(e);Object.defineProperties(o.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0}});var l=function(t){s(a,t);var n=d(a);function a(t,i,o){var s;return r(this,a),(s=n.call(this,e.PATHSEG_LINETO_REL,"l",t))._x=i,s._y=o,s}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegLinetoRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y)}}]),a}(e);Object.defineProperties(l.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0}});var c=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l,c,u){var d;return r(this,a),(d=n.call(this,e.PATHSEG_CURVETO_CUBIC_ABS,"C",t))._x=i,d._y=o,d._x1=s,d._y1=l,d._x2=c,d._y2=u,d}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoCubicAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._x1,this._y1,this._x2,this._y2)}}]),a}(e);Object.defineProperties(c.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},x1:{get:function(){return this._x1},set:function(e){this._x1=e,this._segmentChanged()},enumerable:!0},y1:{get:function(){return this._y1},set:function(e){this._y1=e,this._segmentChanged()},enumerable:!0},x2:{get:function(){return this._x2},set:function(e){this._x2=e,this._segmentChanged()},enumerable:!0},y2:{get:function(){return this._y2},set:function(e){this._y2=e,this._segmentChanged()},enumerable:!0}});var u=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l,c,u){var d;return r(this,a),(d=n.call(this,e.PATHSEG_CURVETO_CUBIC_REL,"c",t))._x=i,d._y=o,d._x1=s,d._y1=l,d._x2=c,d._y2=u,d}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoCubicRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._x1,this._y1,this._x2,this._y2)}}]),a}(e);Object.defineProperties(u.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},x1:{get:function(){return this._x1},set:function(e){this._x1=e,this._segmentChanged()},enumerable:!0},y1:{get:function(){return this._y1},set:function(e){this._y1=e,this._segmentChanged()},enumerable:!0},x2:{get:function(){return this._x2},set:function(e){this._x2=e,this._segmentChanged()},enumerable:!0},y2:{get:function(){return this._y2},set:function(e){this._y2=e,this._segmentChanged()},enumerable:!0}});var h=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l){var c;return r(this,a),(c=n.call(this,e.PATHSEG_CURVETO_QUADRATIC_ABS,"Q",t))._x=i,c._y=o,c._x1=s,c._y1=l,c}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoQuadraticAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._x1,this._y1)}}]),a}(e);Object.defineProperties(h.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},x1:{get:function(){return this._x1},set:function(e){this._x1=e,this._segmentChanged()},enumerable:!0},y1:{get:function(){return this._y1},set:function(e){this._y1=e,this._segmentChanged()},enumerable:!0}});var f=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l){var c;return r(this,a),(c=n.call(this,e.PATHSEG_CURVETO_QUADRATIC_REL,"q",t))._x=i,c._y=o,c._x1=s,c._y1=l,c}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoQuadraticRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x1+" "+this._y1+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._x1,this._y1)}}]),a}(e);Object.defineProperties(f.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},x1:{get:function(){return this._x1},set:function(e){this._x1=e,this._segmentChanged()},enumerable:!0},y1:{get:function(){return this._y1},set:function(e){this._y1=e,this._segmentChanged()},enumerable:!0}});var p=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l,c,u,d){var h;return r(this,a),(h=n.call(this,e.PATHSEG_ARC_ABS,"A",t))._x=i,h._y=o,h._r1=s,h._r2=l,h._angle=c,h._largeArcFlag=u,h._sweepFlag=d,h}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegArcAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._r1+" "+this._r2+" "+this._angle+" "+(this._largeArcFlag?"1":"0")+" "+(this._sweepFlag?"1":"0")+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._r1,this._r2,this._angle,this._largeArcFlag,this._sweepFlag)}}]),a}(e);Object.defineProperties(p.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},r1:{get:function(){return this._r1},set:function(e){this._r1=e,this._segmentChanged()},enumerable:!0},r2:{get:function(){return this._r2},set:function(e){this._r2=e,this._segmentChanged()},enumerable:!0},angle:{get:function(){return this._angle},set:function(e){this._angle=e,this._segmentChanged()},enumerable:!0},largeArcFlag:{get:function(){return this._largeArcFlag},set:function(e){this._largeArcFlag=e,this._segmentChanged()},enumerable:!0},sweepFlag:{get:function(){return this._sweepFlag},set:function(e){this._sweepFlag=e,this._segmentChanged()},enumerable:!0}});var g=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l,c,u,d){var h;return r(this,a),(h=n.call(this,e.PATHSEG_ARC_REL,"a",t))._x=i,h._y=o,h._r1=s,h._r2=l,h._angle=c,h._largeArcFlag=u,h._sweepFlag=d,h}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegArcRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._r1+" "+this._r2+" "+this._angle+" "+(this._largeArcFlag?"1":"0")+" "+(this._sweepFlag?"1":"0")+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._r1,this._r2,this._angle,this._largeArcFlag,this._sweepFlag)}}]),a}(e);Object.defineProperties(g.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},r1:{get:function(){return this._r1},set:function(e){this._r1=e,this._segmentChanged()},enumerable:!0},r2:{get:function(){return this._r2},set:function(e){this._r2=e,this._segmentChanged()},enumerable:!0},angle:{get:function(){return this._angle},set:function(e){this._angle=e,this._segmentChanged()},enumerable:!0},largeArcFlag:{get:function(){return this._largeArcFlag},set:function(e){this._largeArcFlag=e,this._segmentChanged()},enumerable:!0},sweepFlag:{get:function(){return this._sweepFlag},set:function(e){this._sweepFlag=e,this._segmentChanged()},enumerable:!0}});var m=function(t){s(a,t);var n=d(a);function a(t,i){var o;return r(this,a),(o=n.call(this,e.PATHSEG_LINETO_HORIZONTAL_ABS,"H",t))._x=i,o}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegLinetoHorizontalAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x}},{key:"clone",value:function(){return new a(void 0,this._x)}}]),a}(e);Object.defineProperty(m.prototype,"x",{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0});var v=function(t){s(a,t);var n=d(a);function a(t,i){var o;return r(this,a),(o=n.call(this,e.PATHSEG_LINETO_HORIZONTAL_REL,"h",t))._x=i,o}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegLinetoHorizontalRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x}},{key:"clone",value:function(){return new a(void 0,this._x)}}]),a}(e);Object.defineProperty(v.prototype,"x",{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0});var y=function(t){s(a,t);var n=d(a);function a(t,i){var o;return r(this,a),(o=n.call(this,e.PATHSEG_LINETO_VERTICAL_ABS,"V",t))._y=i,o}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegLinetoVerticalAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._y)}}]),a}(e);Object.defineProperty(y.prototype,"y",{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0});var _=function(t){s(a,t);var n=d(a);function a(t,i){var o;return r(this,a),(o=n.call(this,e.PATHSEG_LINETO_VERTICAL_REL,"v",t))._y=i,o}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegLinetoVerticalRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._y)}}]),a}(e);Object.defineProperty(_.prototype,"y",{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0});var b=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l){var c;return r(this,a),(c=n.call(this,e.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS,"S",t))._x=i,c._y=o,c._x2=s,c._y2=l,c}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoCubicSmoothAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._x2,this._y2)}}]),a}(e);Object.defineProperties(b.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},x2:{get:function(){return this._x2},set:function(e){this._x2=e,this._segmentChanged()},enumerable:!0},y2:{get:function(){return this._y2},set:function(e){this._y2=e,this._segmentChanged()},enumerable:!0}});var x=function(t){s(a,t);var n=d(a);function a(t,i,o,s,l){var c;return r(this,a),(c=n.call(this,e.PATHSEG_CURVETO_CUBIC_SMOOTH_REL,"s",t))._x=i,c._y=o,c._x2=s,c._y2=l,c}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoCubicSmoothRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x2+" "+this._y2+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y,this._x2,this._y2)}}]),a}(e);Object.defineProperties(x.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0},x2:{get:function(){return this._x2},set:function(e){this._x2=e,this._segmentChanged()},enumerable:!0},y2:{get:function(){return this._y2},set:function(e){this._y2=e,this._segmentChanged()},enumerable:!0}});var w=function(t){s(a,t);var n=d(a);function a(t,i,o){var s;return r(this,a),(s=n.call(this,e.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS,"T",t))._x=i,s._y=o,s}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoQuadraticSmoothAbs]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y)}}]),a}(e);Object.defineProperties(w.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0}});var S=function(t){s(a,t);var n=d(a);function a(t,i,o){var s;return r(this,a),(s=n.call(this,e.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL,"t",t))._x=i,s._y=o,s}return i(a,[{key:"toString",value:function(){return"[object SVGPathSegCurvetoQuadraticSmoothRel]"}},{key:"_asPathString",value:function(){return this.pathSegTypeAsLetter+" "+this._x+" "+this._y}},{key:"clone",value:function(){return new a(void 0,this._x,this._y)}}]),a}(e);Object.defineProperties(S.prototype,{x:{get:function(){return this._x},set:function(e){this._x=e,this._segmentChanged()},enumerable:!0},y:{get:function(){return this._y},set:function(e){this._y=e,this._segmentChanged()},enumerable:!0}}),SVGPathElement.prototype.createSVGPathSegClosePath=function(){return new t(void 0)},SVGPathElement.prototype.createSVGPathSegMovetoAbs=function(e,t){return new n(void 0,e,t)},SVGPathElement.prototype.createSVGPathSegMovetoRel=function(e,t){return new a(void 0,e,t)},SVGPathElement.prototype.createSVGPathSegLinetoAbs=function(e,t){return new o(void 0,e,t)},SVGPathElement.prototype.createSVGPathSegLinetoRel=function(e,t){return new l(void 0,e,t)},SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs=function(e,t,n,r,a,i){return new c(void 0,e,t,n,r,a,i)},SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel=function(e,t,n,r,a,i){return new u(void 0,e,t,n,r,a,i)},SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs=function(e,t,n,r){return new h(void 0,e,t,n,r)},SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel=function(e,t,n,r){return new f(void 0,e,t,n,r)},SVGPathElement.prototype.createSVGPathSegArcAbs=function(e,t,n,r,a,i,o){return new p(void 0,e,t,n,r,a,i,o)},SVGPathElement.prototype.createSVGPathSegArcRel=function(e,t,n,r,a,i,o){return new g(void 0,e,t,n,r,a,i,o)},SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs=function(e){return new m(void 0,e)},SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel=function(e){return new v(void 0,e)},SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs=function(e){return new y(void 0,e)},SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel=function(e){return new _(void 0,e)},SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs=function(e,t,n,r){return new b(void 0,e,t,n,r)},SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel=function(e,t,n,r){return new x(void 0,e,t,n,r)},SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs=function(e,t){return new w(void 0,e,t)},SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel=function(e,t){return new S(void 0,e,t)},"getPathSegAtLength"in SVGPathElement.prototype||(SVGPathElement.prototype.getPathSegAtLength=function(e){if(void 0===e||!isFinite(e))throw new Error("Invalid arguments.");var t=document.createElementNS("http://www.w3.org/2000/svg","path");t.setAttribute("d",this.getAttribute("d"));var n=t.pathSegList.numberOfItems-1;if(n<=0)return 0;do{if(t.pathSegList.removeItem(n),e>t.getTotalLength())break;n--}while(n>0);return n}),window.SVGPathSeg=e,window.SVGPathSegClosePath=t,window.SVGPathSegMovetoAbs=n,window.SVGPathSegMovetoRel=a,window.SVGPathSegLinetoAbs=o,window.SVGPathSegLinetoRel=l,window.SVGPathSegCurvetoCubicAbs=c,window.SVGPathSegCurvetoCubicRel=u,window.SVGPathSegCurvetoQuadraticAbs=h,window.SVGPathSegCurvetoQuadraticRel=f,window.SVGPathSegArcAbs=p,window.SVGPathSegArcRel=g,window.SVGPathSegLinetoHorizontalAbs=m,window.SVGPathSegLinetoHorizontalRel=v,window.SVGPathSegLinetoVerticalAbs=y,window.SVGPathSegLinetoVerticalRel=_,window.SVGPathSegCurvetoCubicSmoothAbs=b,window.SVGPathSegCurvetoCubicSmoothRel=x,window.SVGPathSegCurvetoQuadraticSmoothAbs=w,window.SVGPathSegCurvetoQuadraticSmoothRel=S}if(!("SVGPathSegList"in window)||!("appendItem"in window.SVGPathSegList.prototype)){var k=function(){function e(t){r(this,e),this._pathElement=t,this._list=this._parsePath(this._pathElement.getAttribute("d")),this._mutationObserverConfig={attributes:!0,attributeFilter:["d"]},this._pathElementMutationObserver=new MutationObserver(this._updateListFromPathMutations.bind(this)),this._pathElementMutationObserver.observe(this._pathElement,this._mutationObserverConfig)}return i(e,[{key:"_checkPathSynchronizedToList",value:function(){this._updateListFromPathMutations(this._pathElementMutationObserver.takeRecords())}},{key:"_updateListFromPathMutations",value:function(e){if(this._pathElement){var t=!1;e.forEach((function(e){"d"===e.attributeName&&(t=!0)})),t&&(this._list=this._parsePath(this._pathElement.getAttribute("d")))}}},{key:"_writeListToPath",value:function(){this._pathElementMutationObserver.disconnect(),this._pathElement.setAttribute("d",e._pathSegArrayAsString(this._list)),this._pathElementMutationObserver.observe(this._pathElement,this._mutationObserverConfig)}},{key:"segmentChanged",value:function(e){this._writeListToPath()}},{key:"clear",value:function(){this._checkPathSynchronizedToList(),this._list.forEach((function(e){e._owningPathSegList=null})),this._list=[],this._writeListToPath()}},{key:"initialize",value:function(e){return this._checkPathSynchronizedToList(),this._list=[e],e._owningPathSegList=this,this._writeListToPath(),e}},{key:"_checkValidIndex",value:function(e){if(isNaN(e)||e<0||e>=this.numberOfItems)throw new Error("INDEX_SIZE_ERR")}},{key:"getItem",value:function(e){return this._checkPathSynchronizedToList(),this._checkValidIndex(e),this._list[e]}},{key:"insertItemBefore",value:function(e,t){return this._checkPathSynchronizedToList(),t>this.numberOfItems&&(t=this.numberOfItems),e._owningPathSegList&&(e=e.clone()),this._list.splice(t,0,e),e._owningPathSegList=this,this._writeListToPath(),e}},{key:"replaceItem",value:function(e,t){return this._checkPathSynchronizedToList(),e._owningPathSegList&&(e=e.clone()),this._checkValidIndex(t),this._list[t]=e,e._owningPathSegList=this,this._writeListToPath(),e}},{key:"removeItem",value:function(e){this._checkPathSynchronizedToList(),this._checkValidIndex(e);var t=this._list[e];return this._list.splice(e,1),this._writeListToPath(),t}},{key:"appendItem",value:function(e){return this._checkPathSynchronizedToList(),e._owningPathSegList&&(e=e.clone()),this._list.push(e),e._owningPathSegList=this,this._writeListToPath(),e}},{key:"_parsePath",value:function(e){if(!e||!e.length)return[];var t=this,n=function(){function e(){r(this,e),this.pathSegList=[]}return i(e,[{key:"appendSegment",value:function(e){this.pathSegList.push(e)}}]),e}(),a=function(){function e(t){r(this,e),this._string=t,this._currentIndex=0,this._endIndex=this._string.length,this._previousCommand=SVGPathSeg.PATHSEG_UNKNOWN,this._skipOptionalSpaces()}return i(e,[{key:"_isCurrentSpace",value:function(){var e=this._string[this._currentIndex];return e<=" "&&(" "===e||"\n"===e||"\t"===e||"\r"===e||"\f"===e)}},{key:"_skipOptionalSpaces",value:function(){for(;this._currentIndex="0"&&e<="9")&&t!==SVGPathSeg.PATHSEG_CLOSEPATH?t===SVGPathSeg.PATHSEG_MOVETO_ABS?SVGPathSeg.PATHSEG_LINETO_ABS:t===SVGPathSeg.PATHSEG_MOVETO_REL?SVGPathSeg.PATHSEG_LINETO_REL:t:SVGPathSeg.PATHSEG_UNKNOWN}},{key:"initialCommandIsMoveTo",value:function(){if(!this.hasMoreData())return!0;var e=this.peekSegmentType();return e===SVGPathSeg.PATHSEG_MOVETO_ABS||e===SVGPathSeg.PATHSEG_MOVETO_REL}},{key:"_parseNumber",value:function(){var e=0,t=0,n=1,r=0,a=1,i=1,o=this._currentIndex;if(this._skipOptionalSpaces(),this._currentIndex"9")&&"."!==this._string.charAt(this._currentIndex))){for(var s=this._currentIndex;this._currentIndex="0"&&this._string.charAt(this._currentIndex)<="9";)this._currentIndex++;if(this._currentIndex!==s)for(var l=this._currentIndex-1,c=1;l>=s;)t+=c*(this._string.charAt(l--)-"0"),c*=10;if(this._currentIndex=this._endIndex||this._string.charAt(this._currentIndex)<"0"||this._string.charAt(this._currentIndex)>"9")return;for(;this._currentIndex="0"&&this._string.charAt(this._currentIndex)<="9";)n*=10,r+=(this._string.charAt(this._currentIndex)-"0")/n,this._currentIndex+=1}if(this._currentIndex!==o&&this._currentIndex+1=this._endIndex||this._string.charAt(this._currentIndex)<"0"||this._string.charAt(this._currentIndex)>"9")return;for(;this._currentIndex="0"&&this._string.charAt(this._currentIndex)<="9";)e*=10,e+=this._string.charAt(this._currentIndex)-"0",this._currentIndex++}var u=t+r;if(u*=a,e&&(u*=Math.pow(10,i*e)),o!==this._currentIndex)return this._skipOptionalSpacesOrDelimiter(),u}}},{key:"_parseArcFlag",value:function(){if(!(this._currentIndex>=this._endIndex)){var e=!1,t=this._string.charAt(this._currentIndex++);if("0"===t)e=!1;else{if("1"!==t)return;e=!0}return this._skipOptionalSpacesOrDelimiter(),e}}},{key:"parseSegment",value:function(){var e=this._string[this._currentIndex],n=this._pathSegTypeFromChar(e);if(n===SVGPathSeg.PATHSEG_UNKNOWN){if(this._previousCommand===SVGPathSeg.PATHSEG_UNKNOWN)return null;if((n=this._nextCommandHelper(e,this._previousCommand))===SVGPathSeg.PATHSEG_UNKNOWN)return null}else this._currentIndex++;switch(this._previousCommand=n,n){case SVGPathSeg.PATHSEG_MOVETO_REL:return new SVGPathSegMovetoRel(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_MOVETO_ABS:return new SVGPathSegMovetoAbs(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_REL:return new SVGPathSegLinetoRel(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_ABS:return new SVGPathSegLinetoAbs(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:return new SVGPathSegLinetoHorizontalRel(t,this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:return new SVGPathSegLinetoHorizontalAbs(t,this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL:return new SVGPathSegLinetoVerticalRel(t,this._parseNumber());case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS:return new SVGPathSegLinetoVerticalAbs(t,this._parseNumber());case SVGPathSeg.PATHSEG_CLOSEPATH:return this._skipOptionalSpaces(),new SVGPathSegClosePath(t);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL:var r={x1:this._parseNumber(),y1:this._parseNumber(),x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicRel(t,r.x,r.y,r.x1,r.y1,r.x2,r.y2);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS:var a={x1:this._parseNumber(),y1:this._parseNumber(),x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicAbs(t,a.x,a.y,a.x1,a.y1,a.x2,a.y2);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:var i={x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicSmoothRel(t,i.x,i.y,i.x2,i.y2);case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:var o={x2:this._parseNumber(),y2:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoCubicSmoothAbs(t,o.x,o.y,o.x2,o.y2);case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:var s={x1:this._parseNumber(),y1:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoQuadraticRel(t,s.x,s.y,s.x1,s.y1);case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:var l={x1:this._parseNumber(),y1:this._parseNumber(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegCurvetoQuadraticAbs(t,l.x,l.y,l.x1,l.y1);case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:return new SVGPathSegCurvetoQuadraticSmoothRel(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:return new SVGPathSegCurvetoQuadraticSmoothAbs(t,this._parseNumber(),this._parseNumber());case SVGPathSeg.PATHSEG_ARC_REL:var c={x1:this._parseNumber(),y1:this._parseNumber(),arcAngle:this._parseNumber(),arcLarge:this._parseArcFlag(),arcSweep:this._parseArcFlag(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegArcRel(t,c.x,c.y,c.x1,c.y1,c.arcAngle,c.arcLarge,c.arcSweep);case SVGPathSeg.PATHSEG_ARC_ABS:var u={x1:this._parseNumber(),y1:this._parseNumber(),arcAngle:this._parseNumber(),arcLarge:this._parseArcFlag(),arcSweep:this._parseArcFlag(),x:this._parseNumber(),y:this._parseNumber()};return new SVGPathSegArcAbs(t,u.x,u.y,u.x1,u.y1,u.arcAngle,u.arcLarge,u.arcSweep);default:throw new Error("Unknown path seg type.")}}}]),e}(),o=new n,s=new a(e);if(!s.initialCommandIsMoveTo())return[];for(;s.hasMoreData();){var l=s.parseSegment();if(!l)return[];o.appendSegment(l)}return o.pathSegList}}],[{key:"_pathSegArrayAsString",value:function(e){var t="",n=!0;return e.forEach((function(e){n?(n=!1,t+=e._asPathString()):t+=" "+e._asPathString()})),t}}]),e}();k.prototype.classname="SVGPathSegList",Object.defineProperty(k.prototype,"numberOfItems",{get:function(){return this._checkPathSynchronizedToList(),this._list.length},enumerable:!0}),Object.defineProperties(SVGPathElement.prototype,{pathSegList:{get:function(){return this._pathSegList||(this._pathSegList=new k(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=k}}();var x,w=jQuery,S=(Boolean(document.createElementNS&&document.createElementNS(_.SVG,"svg").createSVGRect),navigator.userAgent),k=document.createElementNS(_.SVG,"svg"),C=Boolean(window.opera),A=S.includes("AppleWebKit"),E=S.includes("Gecko/"),G=S.includes("MSIE"),N=S.includes("Chrome/"),P=(S.includes("Windows"),S.includes("Macintosh")),I="ontouchstart"in window,T=Boolean(k.querySelector),L=Boolean(document.evaluate),M=function(){var e=document.createElementNS(_.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}(),O=function(){var e=document.createElementNS(_.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}(),j=function(){var e=document.createElementNS(_.SVG,"svg"),t=document.createElementNS(_.SVG,"svg");document.documentElement.append(e),t.setAttribute("x",5),e.append(t);var n=document.createElementNS(_.SVG,"text");n.textContent="a",t.append(n);try{return 0===n.getStartPositionOfChar(0).x}catch(e){return!1}finally{e.remove()}}(),V=function(){var e=document.createElementNS(_.SVG,"svg");document.documentElement.append(e);var t=document.createElementNS(_.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}(),R=function(){var e=document.createElementNS(_.SVG,"svg");document.documentElement.append(e);var t=document.createElementNS(_.SVG,"path");t.setAttribute("d","M0,0 10,0");var n=document.createElementNS(_.SVG,"path");n.setAttribute("d","M5,0 15,0");var r=document.createElementNS(_.SVG,"g");r.append(t,n),e.append(r);var a=r.getBBox();return e.remove(),15===a.width}(),B=(function(){var e=document.createElementNS(_.SVG,"rect");e.setAttribute("x",.1);var t=!e.cloneNode(!1).getAttribute("x").includes(",");t||w.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.')}(),(x=document.createElementNS(_.SVG,"rect")).setAttribute("style","vector-effect:non-scaling-stroke"),"non-scaling-stroke"===x.style.vectorEffect),D=function(){var t=document.createElementNS(_.SVG,"rect").transform.baseVal,n=k.createSVGTransform();t.appendItem(n);var r=t.getItem(0),a=function(t){return t&&"object"===e(t)&&"function"==typeof t.setMatrix&&"angle"in t};return a(r)&&a(n)&&r.type===n.type&&r.angle===n.angle&&r.matrix.a===n.matrix.a&&r.matrix.b===n.matrix.b&&r.matrix.c===n.matrix.c&&r.matrix.d===n.matrix.d&&r.matrix.e===n.matrix.e&&r.matrix.f===n.matrix.f}(),U=function(){return A},F=function(){return E},z=function(){return G},H=function(){return N},q=function(){return P},W=function(){return I},X=function(){return B}; -/** - * A jQuery module to work with SVG attributes. - * @module jQueryAttr - * @license MIT - */ -function Y(t){var n=t.fn.attr;return t.fn.attr=function(t,r){var a=this.length;if(!a)return n.call(this,t,r);for(var i=0;i=0)return this._xforms[e];var t=new Error("DOMException with code=INDEX_SIZE_ERR");throw t.code=1,t}},{key:"insertItemBefore",value:function(e,t){var n=null;if(t>=0)if(t=0&&(this._removeFromOtherLists(e),this._xforms[t]=e,n=e,this._list._update()),n}},{key:"removeItem",value:function(e){if(e=0){var t,n=this._xforms[e],r=new Array(this.numberOfItems-1);for(t=0;t(n=Number.parseInt(n))){var r=n;n=t,t=r}for(var a=he.createSVGMatrix(),i=t;i<=n;++i){var o=i>=0&&ie.x&&t.ye.y},we=Y(jQuery),Se="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",ke="a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use,clipPath".split(","),Ce=null,Ae=null,Ee=null,Ge=null,Ne=function(e){return e.replace(/()/,"$1$2")},Pe=function(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")};function Ie(e){if(e=Me(e),window.btoa)return window.btoa(e);var t=new Array(4*Math.floor((e.length+2)/3)),n=0,r=0;do{var a=e.charCodeAt(n++),i=e.charCodeAt(n++),o=e.charCodeAt(n++),s=a>>2,l=(3&a)<<4|i>>4,c=(15&i)<<2|o>>6,u=63&o;Number.isNaN(i)?(c=64,u=64):Number.isNaN(o)&&(u=64),t[r++]=Se.charAt(s),t[r++]=Se.charAt(l),t[r++]=Se.charAt(c),t[r++]=Se.charAt(u)}while(n>4,l=(15&a)<<4|i>>2,c=(3&i)<<6|o;t+=String.fromCharCode(s),64!==i&&(t+=String.fromCharCode(l)),64!==o&&(t+=String.fromCharCode(c))}while(nSVG-edit "],{type:"text/html"});return je(e)}(),Re=function(e){var t,n;e.includes("0?t=t[0]:(t=e.ownerDocument.createElementNS(_.SVG,"defs"),e.firstChild?e.insertBefore(t,e.firstChild.nextSibling):e.append(t)),t},He=function(e){for(var t=e.pathSegList,n=t.numberOfItems,r=[[],[]],a=t.getItem(0),i=[a.x,a.y],o=function(e,t,n,r){return function(a){return 1-Math.pow(a,3)*i[e]+3-Math.pow(a,2)*a*t[e]+3*(1-a)*Math.pow(a,2)*n[e]+Math.pow(a,3)*r[e]}},s=0;s0&&y<1&&r[h].push(f(y));var _=(-p-Math.sqrt(v))/(2*g);_>0&&_<1&&r[h].push(f(_))}}else{if(0===p)continue;var b=-m/p;b>0&&b<1&&r[h].push(f(b))}}i=d}else r[0].push(l.x),r[1].push(l.y)}var x=Math.min.apply(null,r[0]),w=Math.max.apply(null,r[0])-x,S=Math.min.apply(null,r[1]);return{x:x,y:S,width:w,height:Math.max.apply(null,r[1])-S}};function qe(e){if(R)try{return e.getBBox()}catch(e){}var t,n,r=we.data(e,"ref"),a=null;r?(n=we(r).children().clone().attr("visibility","hidden"),we(Ge).append(n),a=n.filter("line, path")):a=we(e).find("line, path");var i=!1;if(a.length)if(a.each((function(){var e=this.getBBox();e.width&&e.height||(i=!0)})),i){var o=r?n:we(e).children();t=Je(o)}else t=e.getBBox();else t=e.getBBox();return r&&n.remove(),t}var We=function(e){var t=e||Ce.geSelectedElements()[0];if(1!==e.nodeType)return null;var n,r=t.nodeName,a=null;switch(r){case"text":""===t.textContent?(t.textContent="a",a=t.getBBox(),t.textContent=""):t.getBBox&&(a=t.getBBox());break;case"path":V?t.getBBox&&(a=t.getBBox()):a=He(t);break;case"g":case"a":a=qe(t);break;default:if("use"===r&&(a=qe(t)),"use"===r||"foreignObject"===r&&U()){if(a||(a=t.getBBox()),!U()){var i=a,o=i.x,s=i.y;a={width:i.width,height:i.height,x:o+Number.parseFloat(t.getAttribute("x")||0),y:s+Number.parseFloat(t.getAttribute("y")||0)}}}else if(ke.includes(r))if(t)try{a=t.getBBox()}catch(e){var l=t.getExtentOfChar(0),c=t.getComputedTextLength();a={x:l.x,y:l.y,width:c,height:l.height}}else{var u=we(t).closest("foreignObject");u.length&&u[0].getBBox&&(a=u[0].getBBox())}}return a&&(a={x:(n=a).x,y:n.y,width:n.width,height:n.height}),a},Xe=function(e){var t="";return we.each(e,(function(e,n){var r=f(n,2),a=r[0],i=r[1];t+=a;for(var o=0;o-.001&&n<.001||(n<-89.99||n>89.99))}(i,o)){if(["ellipse","path","line","polyline","polygon"].includes(e.tagName))r=s=Ke(e,t,n);else if("rect"===e.tagName){var l=e.getAttribute("rx"),c=e.getAttribute("ry");(l||c)&&(r=s=Ke(e,t,n))}}if(!s){var u=ye(a).matrix;r=ve(r.x,r.y,r.width,r.height,u).aabox}}return r};function $e(e){var t=e.getAttribute("stroke-width");return isNaN(t)||"none"===e.getAttribute("stroke")?0:t/2}var Je=function(e,t,n){if(!e||!e.length)return!1;var r;if(we.each(e,(function(){r||this.parentNode&&(r=Ze(this,t,n))})),void 0===r)return null;var a=r.x+r.width,i=r.y+r.height,o=r.x,s=r.y;if(1===e.length){var l=$e(e[0]);o-=l,s-=l,a+=l,i+=l}else we.each(e,(function(e,r){var l=Ze(r,t,n);if(l){var c=$e(r);o=Math.min(o,l.x-c),s=Math.min(s,l.y-c),1===r.nodeType&&(a=Math.max(a,l.x+l.width+c),i=Math.max(i,l.y+l.height+c))}}));return r.x=o,r.y=s,r.width=a-o,r.height=i-s,r},et=function(e){e||(e=we(Ce.getSVGContent()).children());var t=[];return we(e).children().each((function(e,n){n.getBBox&&t.push(n)})),t.reverse()},tt=function(e){return e||(e=et()),Je(e,Ce.addSVGElementFromJson,Ce.pathActions)},nt=function(e,t){if(!e)return 0;for(var n=e.numberOfItems,r=0;r");var t=e.shortcut||"";dt("#cmenu_canvas").append("
  • "+e.label+""+t+"
  • ")}(e)}))}; -/** - * Adapted from {@link https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js}. - * @module importModule - * @license MIT - */ -function pt(e){var t=document.createElement("a");return t.setAttribute("href",e),t.cloneNode(!1).href}function gt(e,t){["id","class","type"].forEach((function(n){n in t&&(e[n]=t[n])}))}function mt(e,t){return vt(e,o({},t,{returnDefault:!0}))}function vt(e,t){return yt.apply(this,arguments)}function yt(){return(yt=n(regeneratorRuntime.mark((function e(t,n){var r,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.global,a=n.returnDefault,!(!("svgEditor"in window)||!window.svgEditor||!1!==window.svgEditor.modules)){e.next=4;break}return e.abrupt("return",bt(t,void 0,{returnDefault:a}));case 4:return e.next=6,_t(t);case 6:return e.abrupt("return",window[r]);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function _t(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Array.isArray(e)?Promise.all(e.map((function(e){return _t(e,t)}))):new Promise((function(n,r){var a=document.createElement("script");function i(){r(new Error("Failed to import: ".concat(e))),s()}function o(){n(),s()}var s=function(){a.removeEventListener("error",i),a.removeEventListener("load",o),a.remove(),a.src=""};a.defer="defer",gt(a,t),a.addEventListener("error",i),a.addEventListener("load",o),a.src=e,document.head.append(a)}))}function bt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.returnDefault,a=void 0!==r&&r;return Array.isArray(e)?Promise.all(e.map((function(e){return bt(e,t)}))):new Promise((function(n,r){var i="$importModule$"+Math.random().toString(32).slice(2),o=document.createElement("script");function s(){r(new Error("Failed to import: ".concat(e))),c()}function l(){n(window[i]),c()}var c=function(){delete window[i],o.removeEventListener("error",s),o.removeEventListener("load",l),o.remove(),URL.revokeObjectURL(o.src),o.src=""};gt(o,t),o.defer="defer",o.type="module",o.addEventListener("error",s),o.addEventListener("load",l);var u=pt(e),d="import * as m from '".concat(u.replace(/'/g,"\\'"),"'; window.").concat(i," = ").concat(a?"m.default || ":"","m;"),h=new Blob([d],{type:"text/javascript"});o.src=URL.createObjectURL(h),document.head.append(o)}))}var xt={true:!0,false:!1,null:null};function wt(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.ok,a=void 0===r?"Ok":r,i=n.cancel,o=void 0===i?"Cancel":i;t("#dialog_container").draggable({cancel:"#dialog_content, #dialog_buttons *",containment:"window"}).css("position","absolute");var s=t("#dialog_box"),l=t("#dialog_buttons"),c=t("#dialog_content");function u(n,r,i,u,d,h){c.html("

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

    ")+"

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