Merge pull request #3 from SVG-Edit/master

Sync from official repository
master
Igin 2019-03-12 11:32:30 +08:00 committed by GitHub
commit 05a4bc98c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
365 changed files with 110679 additions and 49001 deletions

View File

@ -1,13 +1,5 @@
{ {
"presets": [ "presets": [
[ ["@babel/preset-env"]
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
] ]
} }

View File

@ -21,7 +21,6 @@ editor/js-hotkeys
editor/jspdf/jspdf.min.js editor/jspdf/jspdf.min.js
editor/jspdf/underscore-min.js editor/jspdf/underscore-min.js
editor/extensions/imagelib/jquery.min.js
editor/extensions/mathjax editor/extensions/mathjax
editor/external/* editor/external/*

View File

@ -1,23 +0,0 @@
{
"extends": ["standard", "plugin:qunit/recommended"],
"parserOptions": {
"sourceType": "module"
},
"plugins": ["qunit"],
"env": {
"node": false,
"browser": true
},
"rules": {
"semi": [2, "always"],
"indent": ["error", 2, {"outerIIFEBody": 0}],
"no-tabs": 0,
"object-property-newline": 0,
"one-var": 0,
"no-var": 2,
"prefer-const": 2,
"no-extra-semi": 2,
"quote-props": [2, "as-needed"],
"object-curly-spacing": ["error", "never"]
}
}

152
.eslintrc.js Normal file
View File

@ -0,0 +1,152 @@
module.exports = {
extends: [
"ash-nazg/sauron-node",
"plugin:qunit/recommended", "plugin:testcafe/recommended"
],
parserOptions: {
sourceType: "module"
},
// Need to make explicit here for processing by jsdoc/check-examples
plugins: ["qunit"],
env: {
browser: true
},
settings: {
polyfills: ["url", "promises", "fetch", "queryselector", "object-values"],
jsdoc: {
additionalTagNames: {
// In case we need to extend
customTags: []
},
tagNamePreference: {
arg: "param",
return: "returns"
},
allowOverrideWithoutParam: true,
allowImplementsWithoutParam: true,
allowAugmentsExtendsWithoutParam: true,
// For `jsdoc/check-examples` in `ash-nazg`
matchingFileName: "dummy.md",
rejectExampleCodeRegex: "^`",
}
},
overrides: [
// These would otherwise currently break because of these issues:
// 1. `event:` https://github.com/eslint/doctrine/issues/221 and https://github.com/Kuniwak/jsdoctypeparser/pull/49 with https://github.com/Kuniwak/jsdoctypeparser/issues/47
// 1. `@implements`/`@augments`/`@extends`/`@override`: https://github.com/eslint/doctrine/issues/222
{
files: [
"test/utilities_test.js", "editor/svg-editor.js", "editor/svgcanvas.js",
"editor/coords.js",
"editor/extensions/ext-eyedropper.js", "editor/extensions/ext-webappfind.js"
],
rules: {
"jsdoc/valid-types": "off",
"valid-jsdoc": "off"
}
},
// Locales have no need for importing outside of SVG-Edit
{
files: [
"editor/locale/lang.*.js", "editor/extensions/ext-locale/**",
"docs/tutorials/ExtensionDocs.md"
],
rules: {
"import/no-anonymous-default-export": ["off"]
}
},
// For extensions, `this` is generally assigned to be the more
// descriptive `svgEditor`; they also have no need for importing outside
// of SVG-Edit
{
files: ["editor/extensions/**/ext-*.js"],
rules: {
"consistent-this": ["error", "svgEditor"],
"import/no-anonymous-default-export": ["off"]
}
},
// These browser files don't do importing or requiring
{
files: [
"editor/svgpathseg.js", "editor/touch.js", "editor/typedefs.js",
"editor/redirect-on-no-module-support.js",
"editor/extensions/imagelib/index.js",
"editor/external/dom-polyfill/dom-polyfill.js",
"test/all_tests.js", "screencasts/svgopen2010/script.js",
"opera-widget/handlers.js",
"firefox-extension/handlers.js",
"firefox-extension/content/svg-edit-overlay.js"
],
rules: {
"import/unambiguous": ["off"]
}
},
// Our Markdown rules (and used for JSDoc examples as well, by way of
// our use of `matchingFileName` in conjunction with
// `jsdoc/check-examples` within `ash-nazg`)
{
files: ["**/*.md"],
rules: {
"eol-last": ["off"],
"no-console": ["off"],
"no-undef": ["off"],
"no-unused-vars": ["warn"],
"padded-blocks": ["off"],
"import/unambiguous": ["off"],
"import/no-unresolved": ["off"],
"node/no-missing-import": ["off"]
}
},
// Dis-apply Node rules mistakenly giving errors with browser files
{
files: ["editor/**", "test/**"],
rules: {
"node/no-unsupported-features/node-builtins": ["off"]
}
},
// We want console in tests!
{
files: ["test/**"],
rules: {
"no-console": ["off"]
}
},
{
// Node files
files: [
"docs/jsdoc-config.js",
"build-html.js", "jsdoc-check-overly-generic-types.js",
"rollup.config.js", "rollup-config.config.js"
],
env: {
node: true,
},
rules: {
"node/no-unpublished-import": ["off"],
"node/no-unsupported-features/es-syntax": ["off"]
}
},
{
// As consumed by jsdoc, cannot be expressed as ESM
files: ["docs/jsdoc-config.js"],
parserOptions: {
sourceType: "script"
},
rules: {
"import/no-commonjs": "off"
}
}
],
rules: {
// Override these `ash-nazg/sauron` rules which are difficult for us
// to apply at this time
"default-case": ["off"],
"require-unicode-regexp": ["off"],
"max-len": ["off", {
ignoreUrls: true,
ignoreRegExpLiterals: true
}],
"unicorn/prefer-query-selector": ["off"],
"unicorn/prefer-node-append": ["off"]
}
};

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
ignore
node_modules node_modules
build/ build/

3
.htmlhintrc Normal file
View File

@ -0,0 +1,3 @@
{
"title-require": false
}

View File

@ -1,2 +1,8 @@
ignore
screencasts screencasts
test test
.github/ISSUE_TEMPLATE/bug_report.md
build
jsdoc-check-overly-generic-types.js
lgtm.yml

View File

@ -1,10 +1,5 @@
{ {
"plugins": { "plugins": {
"lint": { "lint-ordered-list-marker-value": "one"
"ordered-list-marker-value": "one",
"no-missing-blank-lines": false,
"list-item-spacing": false,
"list-item-indent": false
}
} }
} }

File diff suppressed because it is too large Load Diff

106
Makefile
View File

@ -1,106 +0,0 @@
NAME=svg-edit
VERSION=2.8.1
PACKAGE=$(NAME)-$(VERSION)
MAKEDOCS=naturaldocs/NaturalDocs
CLOSURE=build/tools/closure-compiler.jar
ZIP=zip
# All files that will be compiled by the Closure compiler.
JS_FILES=\
namespaces.js \
jQuery.attr.js \
contextmenu/jQuery.contextMenu.js \
svgpathseg.js \
browser.js \
svgtransformlist.js \
math.js \
units.js \
utilities.js \
sanitize.js \
history.js \
historyrecording.js \
coords.js \
recalculate.js \
select.js \
draw.js \
layer.js \
path.js \
svgcanvas.js \
svg-editor.js \
locale/locale.js \
contextmenu.js
JS_INPUT_FILES=$(addprefix editor/, $(JS_FILES))
JS_BUILD_FILES=$(addprefix build/$(PACKAGE)/, $(JS_FILES))
CLOSURE_JS_ARGS=$(addprefix --js , $(JS_INPUT_FILES))
COMPILED_JS=editor/svgedit.compiled.js
all: release firefox opera
# The build directory relies on the JS being compiled.
build/$(PACKAGE): $(COMPILED_JS)
rm -rf config
mkdir config
if [ -x $(MAKEDOCS) ] ; then $(MAKEDOCS) -i editor/ -o html docs/ -p config/ -oft -r ; fi
# Make build directory and copy all editor contents into it
mkdir -p build/$(PACKAGE)
cp -r editor/* build/$(PACKAGE)
# Remove all hidden .svn directories
-find build/$(PACKAGE) -name .svn -type d | xargs rm -rf {} \;
# Create the release version of the main HTML file.
build/tools/ship.py --i=editor/svg-editor.html --on=svg_edit_release > build/$(PACKAGE)/svg-editor.html
# NOTE: Some files are not ready for the Closure compiler: (jquery)
# NOTE: Our code safely compiles under SIMPLE_OPTIMIZATIONS
# NOTE: Our code is *not* ready for ADVANCED_OPTIMIZATIONS
# NOTE: WHITESPACE_ONLY and --formatting PRETTY_PRINT is helpful for debugging.
$(COMPILED_JS):
java -jar $(CLOSURE) \
--compilation_level SIMPLE_OPTIMIZATIONS \
$(CLOSURE_JS_ARGS) \
--js_output_file $(COMPILED_JS)
compile: $(COMPILED_JS)
release: build/$(PACKAGE)
cd build ; $(ZIP) $(PACKAGE).zip -r $(PACKAGE) ; cd ..
tar -z -c -f build/$(PACKAGE)-src.tar.gz \
--exclude='\.svn' \
--exclude='build/*' \
.
firefox: build/$(PACKAGE)
mkdir -p build/firefox/content/editor
cp -r firefox-extension/* build/firefox
rm -rf build/firefox/content/.svn
cp -r build/$(PACKAGE)/* build/firefox/content/editor
rm -f build/firefox/content/editor/embedapi.js
cd build/firefox ; $(ZIP) ../$(PACKAGE).xpi -r * ; cd ../..
opera: build/$(PACKAGE)
mkdir -p build/opera/editor
cp opera-widget/* build/opera
cp -r build/$(PACKAGE)/* build/opera/editor
cd build/opera ; $(ZIP) ../$(PACKAGE).wgt -r * ; cd ../..
chrome:
mkdir -p build/svgedit_app
cp -a chrome-app/* build/svgedit_app
cd build ; $(ZIP) -r $(PACKAGE)-crx.zip svgedit_app ; rm -rf svgedit_app; cd ..
jgraduate:
java -jar $(CLOSURE) --js editor/jgraduate/jquery.jGraduate.js --js_output_file editor/jgraduate/jquery.jgraduate.min.js
clean:
rm -rf config
rm -rf build/$(PACKAGE)
rm -rf build/firefox
rm -rf build/opera
rm -rf build/$(PACKAGE).zip
rm -rf build/$(PACKAGE)-src.tar.gz
rm -rf build/$(PACKAGE).xpi
rm -rf build/$(PACKAGE).wgt
rm -rf $(COMPILED_JS)

View File

@ -1,8 +1,23 @@
# ![alt text](https://svg-edit.github.io/svgedit/images/logo48x48.svg "svg-edit logo of a pencil") SVG-edit # ![alt text](https://svg-edit.github.io/svgedit/images/logo48x48.svg "svg-edit logo of a pencil") SVG-edit
[![Dependencies](https://img.shields.io/david/SVG-Edit/svgedit.svg)](https://david-dm.org/SVG-Edit/svgedit)
[![devDependencies](https://img.shields.io/david/dev/SVG-Edit/svgedit.svg)](https://david-dm.org/SVG-Edit/svgedit?type=dev)
[![npm](http://img.shields.io/npm/v/svgedit.svg)](https://www.npmjs.com/package/svgedit)
[![License](https://img.shields.io/npm/l/svgedit.svg)](LICENSE-MIT)
[![Code Quality: Javascript](https://img.shields.io/lgtm/grade/javascript/g/SVG-Edit/svgedit.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/SVG-Edit/svgedit/context:javascript)
[![Total Alerts](https://img.shields.io/lgtm/alerts/g/SVG-Edit/svgedit.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/SVG-Edit/svgedit/alerts)
SVG-edit is a fast, web-based, JavaScript-driven SVG drawing editor that SVG-edit is a fast, web-based, JavaScript-driven SVG drawing editor that
works in any modern browser. works in any modern browser.
## Help wanted
While we have made some recent releases to SVG-edit for bug fixes,
refactoring and documentation to make the codebase more maintainable, the
core developers responsible for the bulk of the drawing features are no
longer active with the project, so we would love others familiar with SVG
to join the project.
## Demo ## Demo
### [Try SVG-edit here](https://svg-edit.github.io/svgedit/releases/latest/editor/svg-editor.html) ### [Try SVG-edit here](https://svg-edit.github.io/svgedit/releases/latest/editor/svg-editor.html)
@ -10,9 +25,12 @@ works in any modern browser.
See the [latest release](https://svg-edit.github.io/svgedit/releases/latest/editor/svg-editor.html) See the [latest release](https://svg-edit.github.io/svgedit/releases/latest/editor/svg-editor.html)
(or its [ES6-Module](https://svg-edit.github.io/svgedit/releases/latest/editor/svg-editor.html) version, which requires a modern browser). (or its [ES6-Module](https://svg-edit.github.io/svgedit/releases/latest/editor/svg-editor.html) version, which requires a modern browser).
Also available as a download in [releases](https://github.com/SVG-Edit/svgedit/releases). You may also try it at <https://unpkg.com/svgedit/editor/svg-editor.html> (which
redirects to a versioned URL).
For testing the latest version in `master`, you may use <https://rawgit.com/SVG-Edit/svgedit/master/editor/svg-editor.html> or You may also obtain URLs for specific [releases](https://github.com/SVG-Edit/svgedit/releases).
For testing the latest version in `master`, you may use
<https://raw.githack.com/SVG-Edit/svgedit/master/editor/svg-editor.html>. <https://raw.githack.com/SVG-Edit/svgedit/master/editor/svg-editor.html>.
## Installation ## Installation
@ -28,6 +46,21 @@ For testing the latest version in `master`, you may use <https://rawgit.com/SVG-
<iframe src="svgedit/editor/svg-editor.html?extensions=" width="100%" height="100%"></iframe> <iframe src="svgedit/editor/svg-editor.html?extensions=" width="100%" height="100%"></iframe>
``` ```
Note that if you want support for the following browsers, you will at least
need some polyfills.
For Android Browser 4.4.3-4.4.4, you will need at least `fetch`.
For the following, you will need at least `URL`, `Promise`, and `fetch`:
- IE <= 11
- IE Mobile
- Opera Mini
- Blackberry Browser <= 10
And for still older browsers (e.g., IE 8), you will at minimum need a
`querySelector` polyfill.
### Integrating SVG-edit into your own npm package ### Integrating SVG-edit into your own npm package
These steps are only needed if you wish to set up your own npm package These steps are only needed if you wish to set up your own npm package
@ -82,6 +115,17 @@ incorporating SVGEdit.
## Recent news ## Recent news
- 2018-12-13 Published 4.2.0 (Chinese (simplified) and Russian locale updates; retaining lines with grid mode)
- 2018-11-29 Published 4.1.0 (Fix for hyphenated locales, svgcanvas distributions)
- 2018-11-16 Published 4.0.0/4.0.1 (Move to Promise-based APIs)
- 2018-11-01 Published 3.2.0 (Update qunit to resolve security vulnerability of a dependency)
- 2018-10-25 Published 3.1.1 (Fix for saving SVG on Firefox)
- 2018-10-24 Published 3.1.0 (Redirect on modular page for non-module-support;
versions document (for migrating))
- 2018-10-22 Published 3.0.1 (Revert fix affecting polygon selection)
- 2018-10-21 Published 3.0.0 (misc. improvements including centering canvas and
key locale fixes since last RC)
- 2018-09-30 Published 3.0.0-rc.3 with security and other fixes
- 2018-07-31 Published 3.0.0-rc.2 with misc. fixes - 2018-07-31 Published 3.0.0-rc.2 with misc. fixes
- 2018-07-19 Published 3.0.0-rc.1 allowing for extensions and locales to be - 2018-07-19 Published 3.0.0-rc.1 allowing for extensions and locales to be
expressed as modules expressed as modules

View File

@ -1,5 +1,5 @@
/* eslint-env node */ /* eslint-env node */
const fs = require('promise-fs'); import fs from 'promise-fs';
const filesAndReplacements = [ const filesAndReplacements = [
{ {
@ -32,6 +32,22 @@ const filesAndReplacements = [
[ [
'<script src="external/dom-polyfill/dom-polyfill.js"></script>', '<script src="external/dom-polyfill/dom-polyfill.js"></script>',
'<script src="../dist/dom-polyfill.js"></script>' '<script src="../dist/dom-polyfill.js"></script>'
],
[
'<script nomodule="" src="redirect-on-no-module-support.js"></script>',
''
]
]
},
// Now that file has copied, we can replace the DOCTYPE in xdomain
{
input: 'editor/xdomain-svg-editor-es.html',
output: 'editor/xdomain-svg-editor-es.html',
replacements: [
[
'<!DOCTYPE html>',
`<!DOCTYPE html>
<!-- AUTO-GENERATED FROM svg-editor-es.html; DO NOT EDIT; use build-html.js to build -->`
] ]
] ]
}, },
@ -55,6 +71,33 @@ const filesAndReplacements = [
[ [
'<script src="external/dom-polyfill/dom-polyfill.js"></script>', '<script src="external/dom-polyfill/dom-polyfill.js"></script>',
'<script src="../dist/dom-polyfill.js"></script>' '<script src="../dist/dom-polyfill.js"></script>'
],
[
'<script nomodule="" src="redirect-on-no-module-support.js"></script>',
''
]
]
},
{
input: 'editor/extensions/imagelib/openclipart-es.html',
output: 'editor/extensions/imagelib/openclipart.html',
replacements: [
[
'<!DOCTYPE html>',
`<!DOCTYPE html>
<!-- AUTO-GENERATED FROM imagelib/openclipart-es.html; DO NOT EDIT; use build-html.js to build -->`
],
[
'<script src="../../external/dom-polyfill/dom-polyfill.js"></script>',
'<script src="../../../dist/dom-polyfill.js"></script>'
],
[
'<script type="module" src="openclipart.js"></script>',
'<script defer="defer" src="../../../dist/extensions/imagelib/openclipart.js"></script>'
],
[
'<script nomodule="" src="redirect-on-no-module-support.js"></script>',
''
] ]
] ]
}, },
@ -70,32 +113,36 @@ const filesAndReplacements = [
[ [
'<script type="module" src="index.js"></script>', '<script type="module" src="index.js"></script>',
'<script defer="defer" src="../../../dist/extensions/imagelib/index.js"></script>' '<script defer="defer" src="../../../dist/extensions/imagelib/index.js"></script>'
],
[
'<script nomodule="" src="redirect-on-no-module-support.js"></script>',
''
] ]
] ]
} }
]; ];
filesAndReplacements.reduce((p, {input, output, replacements}) => { (async () => {
return p.then(async () => { await filesAndReplacements.reduce(async (p, {input, output, replacements}) => {
let data; await p;
try { let data;
data = await fs.readFile(input, 'utf8'); try {
} catch (err) { data = await fs.readFile(input, 'utf8');
console.log(`Error reading ${input} file`, err); } catch (err) {
} console.log(`Error reading ${input} file`, err); // eslint-disable-line no-console
}
data = replacements.reduce((s, [find, replacement]) => { data = replacements.reduce((s, [fnd, replacement]) => {
return s.replace(find, replacement); return s.replace(fnd, replacement);
}, data); }, data);
try { try {
await fs.writeFile(output, data); await fs.writeFile(output, data);
} catch (err) { } catch (err) {
console.log(`Error writing file: ${err}`, err); console.log(`Error writing file: ${err}`, err); // eslint-disable-line no-console
return; return;
} }
console.log(`Completed file ${input} rewriting!`); console.log(`Completed file ${input} rewriting!`); // eslint-disable-line no-console
}); }, Promise.resolve());
}, Promise.resolve()).then(() => { console.log('Finished!'); // eslint-disable-line no-console
console.log('Finished!'); })();
});

View File

@ -6,6 +6,7 @@
<script src="../editor/jquery.min.js"></script> <script src="../editor/jquery.min.js"></script>
<script src="../editor/jquery-ui/jquery-ui-1.8.17.custom.min.js"></script> <script src="../editor/jquery-ui/jquery-ui-1.8.17.custom.min.js"></script>
<style> #svgroot { overflow: hidden; } </style> <style> #svgroot { overflow: hidden; } </style>
<link rel="shortcut icon" type="image/x-icon" href="../editor/images/logo.png" />
</head> </head>
<body> <body>
@ -24,7 +25,7 @@
</div> </div>
<script type="module"> <script type="module">
import Canvas from '../editor/svgcanvas.js'; import SvgCanvas from '../editor/svgcanvas.js';
const container = document.querySelector('#editorContainer'); const container = document.querySelector('#editorContainer');
const {width, height} = {width: 500, height: 300}; const {width, height} = {width: 500, height: 300};
@ -41,7 +42,7 @@ const config = {
baseUnit: 'px', baseUnit: 'px',
}; };
window.canvas = new Canvas(container, config); window.canvas = new SvgCanvas(container, config);
canvas.updateCanvas(width, height); canvas.updateCanvas(width, height);
window.fill = function (colour) { window.fill = function (colour) {

3337
dist/canvg.js vendored

File diff suppressed because it is too large Load Diff

57
dist/dom-polyfill.js vendored
View File

@ -1,14 +1,39 @@
(function () { (function () {
'use strict'; 'use strict';
function _typeof(obj) {
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 // From https://github.com/inexorabletash/polyfill/blob/master/dom.js
/**
* @module DOMPolyfill
*/
/**
*
* @param {Node} o
* @param {module:DOMPolyfill~ParentNode|module:DOMPolyfill~ChildNode} ps
* @returns {undefined}
*/
function mixin(o, ps) { function mixin(o, ps) {
if (!o) return; if (!o) return;
Object.keys(ps).forEach(function (p) { Object.keys(ps).forEach(function (p) {
if (p in o || p in o.prototype) { if (p in o || p in o.prototype) {
return; return;
} }
try { try {
Object.defineProperty(o.prototype, p, Object.getOwnPropertyDescriptor(ps, p)); Object.defineProperty(o.prototype, p, Object.getOwnPropertyDescriptor(ps, p));
} catch (ex) { } catch (ex) {
@ -17,14 +42,23 @@
} }
}); });
} }
/**
*
* @param {Node[]} nodes
* @returns {Node}
*/
function convertNodesIntoANode(nodes) { function convertNodesIntoANode(nodes) {
nodes = nodes.map(function (node) { nodes = nodes.map(function (node) {
return !(node instanceof Node) ? document.createTextNode(node) : node; var isNode = node && _typeof(node) === 'object' && 'nodeType' in node;
return isNode ? node : document.createTextNode(node);
}); });
if (nodes.length === 1) { if (nodes.length === 1) {
return nodes[0]; return nodes[0];
} }
var node = document.createDocumentFragment(); var node = document.createDocumentFragment();
nodes.forEach(function (n) { nodes.forEach(function (n) {
node.appendChild(n); node.appendChild(n);
@ -34,7 +68,7 @@
var ParentNode = { var ParentNode = {
prepend: function prepend() { prepend: function prepend() {
for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) { for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) {
nodes[_key] = arguments[_key]; nodes[_key] = arguments[_key];
} }
@ -42,7 +76,7 @@
this.insertBefore(nodes, this.firstChild); this.insertBefore(nodes, this.firstChild);
}, },
append: function append() { append: function append() {
for (var _len2 = arguments.length, nodes = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { for (var _len2 = arguments.length, nodes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
nodes[_key2] = arguments[_key2]; nodes[_key2] = arguments[_key2];
} }
@ -50,12 +84,10 @@
this.appendChild(nodes); this.appendChild(nodes);
} }
}; };
mixin(Document || HTMLDocument, ParentNode); // HTMLDocument for IE8 mixin(Document || HTMLDocument, ParentNode); // HTMLDocument for IE8
mixin(DocumentFragment, ParentNode);
mixin(Element, ParentNode);
// Mixin ChildNode mixin(DocumentFragment, ParentNode);
mixin(Element, ParentNode); // Mixin ChildNode
// https://dom.spec.whatwg.org/#interface-childnode // https://dom.spec.whatwg.org/#interface-childnode
var ChildNode = { var ChildNode = {
@ -64,13 +96,14 @@
if (!parent) return; if (!parent) return;
var viablePreviousSibling = this.previousSibling; var viablePreviousSibling = this.previousSibling;
for (var _len3 = arguments.length, nodes = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { for (var _len3 = arguments.length, nodes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
nodes[_key3] = arguments[_key3]; nodes[_key3] = arguments[_key3];
} }
while (nodes.includes(viablePreviousSibling)) { while (nodes.includes(viablePreviousSibling)) {
viablePreviousSibling = viablePreviousSibling.previousSibling; viablePreviousSibling = viablePreviousSibling.previousSibling;
} }
var node = convertNodesIntoANode(nodes); var node = convertNodesIntoANode(nodes);
parent.insertBefore(node, viablePreviousSibling ? viablePreviousSibling.nextSibling : parent.firstChild); parent.insertBefore(node, viablePreviousSibling ? viablePreviousSibling.nextSibling : parent.firstChild);
}, },
@ -79,13 +112,14 @@
if (!parent) return; if (!parent) return;
var viableNextSibling = this.nextSibling; var viableNextSibling = this.nextSibling;
for (var _len4 = arguments.length, nodes = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { for (var _len4 = arguments.length, nodes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
nodes[_key4] = arguments[_key4]; nodes[_key4] = arguments[_key4];
} }
while (nodes.includes(viableNextSibling)) { while (nodes.includes(viableNextSibling)) {
viableNextSibling = viableNextSibling.nextSibling; viableNextSibling = viableNextSibling.nextSibling;
} }
var node = convertNodesIntoANode(nodes); var node = convertNodesIntoANode(nodes);
parent.insertBefore(node, viableNextSibling); parent.insertBefore(node, viableNextSibling);
}, },
@ -94,13 +128,14 @@
if (!parent) return; if (!parent) return;
var viableNextSibling = this.nextSibling; var viableNextSibling = this.nextSibling;
for (var _len5 = arguments.length, nodes = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { for (var _len5 = arguments.length, nodes = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
nodes[_key5] = arguments[_key5]; nodes[_key5] = arguments[_key5];
} }
while (nodes.includes(viableNextSibling)) { while (nodes.includes(viableNextSibling)) {
viableNextSibling = viableNextSibling.nextSibling; viableNextSibling = viableNextSibling.nextSibling;
} }
var node = convertNodesIntoANode(nodes); var node = convertNodesIntoANode(nodes);
if (this.parentNode === parent) { if (this.parentNode === parent) {
@ -113,10 +148,10 @@
if (!this.parentNode) { if (!this.parentNode) {
return; return;
} }
this.parentNode.removeChild(this); this.parentNode.removeChild(this);
} }
}; };
mixin(DocumentType, ChildNode); mixin(DocumentType, ChildNode);
mixin(Element, ChildNode); mixin(Element, ChildNode);
mixin(CharacterData, ChildNode); mixin(CharacterData, ChildNode);

View File

@ -1,36 +1,42 @@
var svgEditorExtension_arrows = (function () { var svgEditorExtension_arrows = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-arrows.js * ext-arrows.js
* *
@ -42,37 +48,41 @@ var svgEditorExtension_arrows = (function () {
var extArrows = { var extArrows = {
name: 'arrows', name: 'arrows',
init: function () { init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(S) { var _init = _asyncToGenerator(
var strings, svgEditor, svgCanvas, $, addElem, nonce, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; /*#__PURE__*/
regeneratorRuntime.mark(function _callee2(S) {
var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools;
return regeneratorRuntime.wrap(function _callee2$(_context2) { return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) { while (1) {
switch (_context2.prev = _context2.next) { switch (_context2.prev = _context2.next) {
case 0: case 0:
colorChanged = function colorChanged(elem) { colorChanged = function _ref10(elem) {
var color = elem.getAttribute('stroke'); var color = elem.getAttribute('stroke');
var mtypes = ['start', 'mid', 'end']; var mtypes = ['start', 'mid', 'end'];
var defs = svgCanvas.findDefs(); var defs = svgCanvas.findDefs();
$.each(mtypes, function (i, type) { $.each(mtypes, function (i, type) {
var marker = getLinked(elem, 'marker-' + type); var marker = getLinked(elem, 'marker-' + type);
if (!marker) { if (!marker) {
return; return;
} }
var curColor = $(marker).children().attr('fill'); var curColor = $(marker).children().attr('fill');
var curD = $(marker).children().attr('d'); var curD = $(marker).children().attr('d');
if (curColor === color) { if (curColor === color) {
return; return;
} }
var allMarkers = $(defs).find('marker'); var allMarkers = $(defs).find('marker');
var newMarker = null; var newMarker = null; // Different color, check if already made
// Different color, check if already made
allMarkers.each(function () { allMarkers.each(function () {
var attrs = $(this).children().attr(['fill', 'd']); var attrs = $(this).children().attr(['fill', 'd']);
if (attrs.fill === color && attrs.d === curD) { if (attrs.fill === color && attrs.d === curD) {
// Found another marker with this color and this path // Found another marker with this color and this path
newMarker = this; newMarker = this; // eslint-disable-line consistent-this
} }
}); });
@ -80,46 +90,49 @@ var svgEditorExtension_arrows = (function () {
// Create a new marker with this color // Create a new marker with this color
var lastId = marker.id; var lastId = marker.id;
var dir = lastId.includes('_fw') ? 'fw' : 'bk'; var dir = lastId.includes('_fw') ? 'fw' : 'bk';
newMarker = addMarker(dir, type, arrowprefix + dir + allMarkers.length); newMarker = addMarker(dir, type, arrowprefix + dir + allMarkers.length);
$(newMarker).children().attr('fill', color); $(newMarker).children().attr('fill', color);
} }
$(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')'); $(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')'); // Check if last marker can be removed
// Check if last marker can be removed
var remove = true; var remove = true;
$(S.svgcontent).find('line, polyline, path, polygon').each(function () { $(S.svgcontent).find('line, polyline, path, polygon').each(function () {
var elem = this; var element = this; // eslint-disable-line consistent-this
$.each(mtypes, function (j, mtype) { $.each(mtypes, function (j, mtype) {
if ($(elem).attr('marker-' + mtype) === 'url(#' + marker.id + ')') { if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') {
remove = false; remove = false;
return remove; return remove;
} }
return undefined;
}); });
if (!remove) { if (!remove) {
return false; return false;
} }
});
// Not found, so can safely remove return undefined;
}); // Not found, so can safely remove
if (remove) { if (remove) {
$(marker).remove(); $(marker).remove();
} }
}); });
}; };
setArrow = function setArrow() { setArrow = function _ref9() {
resetMarker(); resetMarker();
var type = this.value; var type = this.value;
if (type === 'none') { if (type === 'none') {
return; return;
} } // Set marker on element
// Set marker on element
var dir = 'fw'; var dir = 'fw';
if (type === 'mid_bk') { if (type === 'mid_bk') {
type = 'mid'; type = 'mid';
dir = 'bk'; dir = 'bk';
@ -137,10 +150,9 @@ var svgEditorExtension_arrows = (function () {
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
}; };
addMarker = function addMarker(dir, type, id) { addMarker = function _ref8(dir, type, id) {
// TODO: Make marker (or use?) per arrow type, since refX can be different // TODO: Make marker (or use?) per arrow type, since refX can be different
id = id || arrowprefix + dir; id = id || arrowprefix + dir;
var data = pathdata[dir]; var data = pathdata[dir];
if (type === 'mid') { if (type === 'mid') {
@ -148,6 +160,7 @@ var svgEditorExtension_arrows = (function () {
} }
var marker = svgCanvas.getElem(id); var marker = svgCanvas.getElem(id);
if (!marker) { if (!marker) {
marker = addElem({ marker = addElem({
element: 'marker', element: 'marker',
@ -160,6 +173,7 @@ var svgEditorExtension_arrows = (function () {
markerHeight: 5, markerHeight: 5,
orient: 'auto', orient: 'auto',
style: 'pointer-events:none' // Currently needed for Opera style: 'pointer-events:none' // Currently needed for Opera
} }
}); });
var arrow = addElem({ var arrow = addElem({
@ -174,25 +188,26 @@ var svgEditorExtension_arrows = (function () {
} }
marker.setAttribute('refX', data.refx); marker.setAttribute('refX', data.refx);
return marker; return marker;
}; };
resetMarker = function resetMarker() { resetMarker = function _ref7() {
var el = selElems[0]; var el = selElems[0];
el.removeAttribute('marker-start'); el.removeAttribute('marker-start');
el.removeAttribute('marker-mid'); el.removeAttribute('marker-mid');
el.removeAttribute('marker-end'); el.removeAttribute('marker-end');
}; };
showPanel = function showPanel(on) { showPanel = function _ref6(on) {
$('#arrow_panel').toggle(on); $('#arrow_panel').toggle(on);
if (on) { if (on) {
var el = selElems[0]; var el = selElems[0];
var end = el.getAttribute('marker-end'); var end = el.getAttribute('marker-end');
var start = el.getAttribute('marker-start'); var start = el.getAttribute('marker-start');
var mid = el.getAttribute('marker-mid'); var mid = el.getAttribute('marker-mid');
var val = void 0; var val;
if (end && start) { if (end && start) {
val = 'both'; val = 'both';
} else if (end) { } else if (end) {
@ -201,6 +216,7 @@ var svgEditorExtension_arrows = (function () {
val = 'start'; val = 'start';
} else if (mid) { } else if (mid) {
val = 'mid'; val = 'mid';
if (mid.includes('bk')) { if (mid.includes('bk')) {
val = 'mid_bk'; val = 'mid_bk';
} }
@ -214,26 +230,30 @@ var svgEditorExtension_arrows = (function () {
} }
}; };
getLinked = function getLinked(elem, attr) { getLinked = function _ref5(elem, attr) {
var str = elem.getAttribute(attr); var str = elem.getAttribute(attr);
if (!str) { if (!str) {
return null; return null;
} }
var m = str.match(/\(#(.*)\)/); var m = str.match(/\(#(.*)\)/);
if (!m || m.length !== 2) { if (!m || m.length !== 2) {
return null; return null;
} }
return svgCanvas.getElem(m[1]); return svgCanvas.getElem(m[1]);
}; };
unsetArrowNonce = function unsetArrowNonce(window) { unsetArrowNonce = function _ref4(win) {
randomizeIds = false; randomizeIds = false;
arrowprefix = prefix; arrowprefix = prefix;
pathdata.fw.id = arrowprefix + 'fw'; pathdata.fw.id = arrowprefix + 'fw';
pathdata.bk.id = arrowprefix + 'bk'; pathdata.bk.id = arrowprefix + 'bk';
}; };
setArrowNonce = function setArrowNonce(window, n) { setArrowNonce = function _ref3(win, n) {
randomizeIds = true; randomizeIds = true;
arrowprefix = prefix + n + '_'; arrowprefix = prefix + n + '_';
pathdata.fw.id = arrowprefix + 'fw'; pathdata.fw.id = arrowprefix + 'fw';
@ -247,11 +267,14 @@ var svgEditorExtension_arrows = (function () {
strings = _context2.sent; strings = _context2.sent;
svgEditor = this; svgEditor = this;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
$ = jQuery;
// {svgcontent} = S, // {svgcontent} = S,
addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, prefix = 'se_arrow_'; addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, $ = S.$, prefix = 'se_arrow_';
selElems = void 0, arrowprefix = void 0, randomizeIds = S.randomize_ids; randomizeIds = S.randomize_ids;
/**
* @param {Window} win
* @param {!(string|Integer)} n
* @returns {undefined}
*/
svgCanvas.bind('setnonce', setArrowNonce); svgCanvas.bind('setnonce', setArrowNonce);
svgCanvas.bind('unsetnonce', unsetArrowNonce); svgCanvas.bind('unsetnonce', unsetArrowNonce);
@ -263,9 +286,24 @@ var svgEditorExtension_arrows = (function () {
} }
pathdata = { pathdata = {
fw: { d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', refx: 8, id: arrowprefix + 'fw' }, fw: {
bk: { d: 'm10,0l-10,5l10,5l-5,-5l5,-5z', refx: 2, id: arrowprefix + 'bk' } d: 'm0,0l10,5l-10,5l5,-5l-5,-5z',
refx: 8,
id: arrowprefix + 'fw'
},
bk: {
d: 'm10,0l-10,5l10,5l-5,-5l5,-5z',
refx: 2,
id: arrowprefix + 'bk'
}
}; };
/**
* Gets linked element.
* @param {Element} elem
* @param {string} attr
* @returns {Element}
*/
contextTools = [{ contextTools = [{
type: 'select', type: 'select',
panel: 'arrow_panel', panel: 'arrow_panel',
@ -275,36 +313,39 @@ var svgEditorExtension_arrows = (function () {
change: setArrow change: setArrow
} }
}]; }];
return _context2.abrupt('return', { return _context2.abrupt("return", {
name: strings.name, name: strings.name,
context_tools: strings.contextTools.map(function (contextTool, i) { context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool); return Object.assign(contextTools[i], contextTool);
}), }),
callback: function callback() { callback: function callback() {
$('#arrow_panel').hide(); $('#arrow_panel').hide(); // Set ID so it can be translated in locale file
// Set ID so it can be translated in locale file
$('#arrow_list option')[0].id = 'connector_no_arrow'; $('#arrow_list option')[0].id = 'connector_no_arrow';
}, },
addLangData: function () { addLangData: function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref2) { var _addLangData = _asyncToGenerator(
var lang = _ref2.lang, /*#__PURE__*/
importLocale = _ref2.importLocale; regeneratorRuntime.mark(function _callee(_ref) {
var strings; var lang, importLocale, _ref2, langList;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
_context.next = 2; lang = _ref.lang, importLocale = _ref.importLocale;
_context.next = 3;
return importLocale(); return importLocale();
case 2: case 3:
strings = _context.sent; _ref2 = _context.sent;
return _context.abrupt('return', { langList = _ref2.langList;
data: strings.langList return _context.abrupt("return", {
data: langList
}); });
case 4: case 6:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -312,7 +353,7 @@ var svgEditorExtension_arrows = (function () {
})); }));
function addLangData(_x2) { function addLangData(_x2) {
return _ref3.apply(this, arguments); return _addLangData.apply(this, arguments);
} }
return addLangData; return addLangData;
@ -320,11 +361,12 @@ var svgEditorExtension_arrows = (function () {
selectedChanged: function selectedChanged(opts) { selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements // Use this to update the current selected elements
selElems = opts.elems; selElems = opts.elems;
var markerElems = ['line', 'path', 'polyline', 'polygon']; var markerElems = ['line', 'path', 'polyline', 'polygon'];
var i = selElems.length; var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && markerElems.includes(elem.tagName)) { if (elem && markerElems.includes(elem.tagName)) {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
showPanel(true); showPanel(true);
@ -338,6 +380,7 @@ var svgEditorExtension_arrows = (function () {
}, },
elementChanged: function elementChanged(opts) { elementChanged: function elementChanged(opts) {
var elem = opts.elems[0]; var elem = opts.elems[0];
if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) { if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
// const start = elem.getAttribute('marker-start'); // const start = elem.getAttribute('marker-start');
// const mid = elem.getAttribute('marker-mid'); // const mid = elem.getAttribute('marker-mid');
@ -348,8 +391,8 @@ var svgEditorExtension_arrows = (function () {
} }
}); });
case 22: case 21:
case 'end': case "end":
return _context2.stop(); return _context2.stop();
} }
} }
@ -357,7 +400,7 @@ var svgEditorExtension_arrows = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,42 @@
var svgEditorExtension_closepath = (function () { var svgEditorExtension_closepath = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-closepath.js * ext-closepath.js
* *
@ -39,27 +45,26 @@ var svgEditorExtension_closepath = (function () {
* @copyright 2010 Jeff Schiller * @copyright 2010 Jeff Schiller
* *
*/ */
// This extension adds a simple button to the contextual panel for paths // This extension adds a simple button to the contextual panel for paths
// The button toggles whether the path is open or closed // The button toggles whether the path is open or closed
var extClosepath = { var extClosepath = {
name: 'closepath', name: 'closepath',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var importLocale = _ref.importLocale; /*#__PURE__*/
var strings, $, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
_context.next = 2; importLocale = _ref.importLocale, $ = _ref.$;
_context.next = 3;
return importLocale(); return importLocale();
case 2: case 3:
strings = _context.sent; strings = _context.sent;
$ = jQuery;
svgEditor = this; svgEditor = this;
selElems = void 0;
updateButton = function updateButton(path) { updateButton = function updateButton(path) {
var seglist = path.pathSegList, var seglist = path.pathSegList,
@ -72,8 +77,10 @@ var svgEditorExtension_closepath = (function () {
showPanel = function showPanel(on) { showPanel = function showPanel(on) {
$('#closepath_panel').toggle(on); $('#closepath_panel').toggle(on);
if (on) { if (on) {
var path = selElems[0]; var path = selElems[0];
if (path) { if (path) {
updateButton(path); updateButton(path);
} }
@ -82,15 +89,17 @@ var svgEditorExtension_closepath = (function () {
toggleClosed = function toggleClosed() { toggleClosed = function toggleClosed() {
var path = selElems[0]; var path = selElems[0];
if (path) { if (path) {
var seglist = path.pathSegList, var seglist = path.pathSegList,
last = seglist.numberOfItems - 1; last = seglist.numberOfItems - 1; // is closed
// is closed
if (seglist.getItem(last).pathSegType === 1) { if (seglist.getItem(last).pathSegType === 1) {
seglist.removeItem(last); seglist.removeItem(last);
} else { } else {
seglist.appendItem(path.createSVGPathSegClosePath()); seglist.appendItem(path.createSVGPathSegClosePath());
} }
updateButton(path); updateButton(path);
} }
}; };
@ -116,7 +125,7 @@ var svgEditorExtension_closepath = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg', svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
@ -128,8 +137,10 @@ var svgEditorExtension_closepath = (function () {
selectedChanged: function selectedChanged(opts) { selectedChanged: function selectedChanged(opts) {
selElems = opts.elems; selElems = opts.elems;
var i = selElems.length; var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elem.tagName === 'path') { if (elem && elem.tagName === 'path') {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
showPanel(true); showPanel(true);
@ -143,8 +154,8 @@ var svgEditorExtension_closepath = (function () {
} }
}); });
case 11: case 10:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -152,7 +163,7 @@ var svgEditorExtension_closepath = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,44 @@
var svgEditorExtension_connector = (function () { var svgEditorExtension_connector = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* eslint-disable unicorn/no-fn-reference-in-iterator */
/* globals jQuery */
/** /**
* ext-connector.js * ext-connector.js
* *
@ -39,20 +47,22 @@ var svgEditorExtension_connector = (function () {
* @copyright 2010 Alexis Deveria * @copyright 2010 Alexis Deveria
* *
*/ */
var extConnector = { var extConnector = {
name: 'connector', name: 'connector',
init: function () { init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(S) { var _init = _asyncToGenerator(
var $, svgEditor, svgCanvas, getElem, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons; /*#__PURE__*/
return regeneratorRuntime.wrap(function _callee2$(_context2) { regeneratorRuntime.mark(function _callee(S) {
var svgEditor, svgCanvas, getElem, $, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context2.prev = _context2.next) { switch (_context.prev = _context.next) {
case 0: case 0:
init = function init() { init = function _ref9() {
// Make sure all connectors have data set // Make sure all connectors have data set
$(svgcontent).find('*').each(function () { $(svgcontent).find('*').each(function () {
var conn = this.getAttributeNS(seNs, 'connector'); var conn = this.getAttributeNS(seNs, 'connector');
if (conn) { if (conn) {
this.setAttribute('class', connSel.substr(1)); this.setAttribute('class', connSel.substr(1));
var connData = conn.split(' '); var connData = conn.split(' ');
@ -61,104 +71,107 @@ var svgEditorExtension_connector = (function () {
$(this).data('c_start', connData[0]).data('c_end', connData[1]).data('start_bb', sbb).data('end_bb', ebb); $(this).data('c_start', connData[0]).data('c_end', connData[1]).data('start_bb', sbb).data('end_bb', ebb);
svgCanvas.getEditorNS(true); svgCanvas.getEditorNS(true);
} }
}); }); // updateConnectors();
// updateConnectors();
}; };
updateConnectors = function updateConnectors(elems) { updateConnectors = function _ref8(elems) {
// Updates connector lines based on selected elements // Updates connector lines based on selected elements
// Is not used on mousemove, as it runs getStrokedBBox every time, // Is not used on mousemove, as it runs getStrokedBBox every time,
// which isn't necessary there. // which isn't necessary there.
findConnectors(elems); findConnectors(elems);
if (connections.length) { if (connections.length) {
// Update line with element // Update line with element
var i = connections.length; var i = connections.length;
while (i--) { while (i--) {
var conn = connections[i]; var conn = connections[i];
var line = conn.connector; var line = conn.connector;
var elem = conn.elem; var elem = conn.elem; // const sw = line.getAttribute('stroke-width') * 5;
// const sw = line.getAttribute('stroke-width') * 5; var pre = conn.is_start ? 'start' : 'end'; // Update bbox for this element
var pre = conn.is_start ? 'start' : 'end';
// Update bbox for this element
var bb = svgCanvas.getStrokedBBox([elem]); var bb = svgCanvas.getStrokedBBox([elem]);
bb.x = conn.start_x; bb.x = conn.start_x;
bb.y = conn.start_y; bb.y = conn.start_y;
elData(line, pre + '_bb', bb); elData(line, pre + '_bb', bb);
/* const addOffset = */elData(line, pre + '_off'); /* const addOffset = */
var altPre = conn.is_start ? 'end' : 'start'; elData(line, pre + '_off');
var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element
// Get center pt of connected element
var bb2 = elData(line, altPre + '_bb'); var bb2 = elData(line, altPre + '_bb');
var srcX = bb2.x + bb2.width / 2; var srcX = bb2.x + bb2.width / 2;
var srcY = bb2.y + bb2.height / 2; var srcY = bb2.y + bb2.height / 2; // Set point of element being moved
// Set point of element being moved
var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line));
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); // Update points attribute manually for webkit
// Update points attribute manually for webkit
if (navigator.userAgent.includes('AppleWebKit')) { if (navigator.userAgent.includes('AppleWebKit')) {
var pts = line.points; var pts = line.points;
var len = pts.numberOfItems; var len = pts.numberOfItems;
var ptArr = []; var ptArr = [];
for (var j = 0; j < len; j++) { for (var j = 0; j < len; j++) {
pt = pts.getItem(j); pt = pts.getItem(j);
ptArr[j] = pt.x + ',' + pt.y; ptArr[j] = pt.x + ',' + pt.y;
} }
line.setAttribute('points', ptArr.join(' ')); line.setAttribute('points', ptArr.join(' '));
} }
} }
} }
}; };
findConnectors = function findConnectors() { findConnectors = function _ref7() {
var elems = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : selElems; var elems = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : selElems;
var connectors = $(svgcontent).find(connSel); var connectors = $(svgcontent).find(connSel);
connections = []; connections = []; // Loop through connectors to see if one is connected to the element
// Loop through connectors to see if one is connected to the element
connectors.each(function () { connectors.each(function () {
var addThis = void 0; var addThis;
/**
*
* @returns {undefined}
*/
function add() { function add() {
if (elems.includes(this)) { if (elems.includes(this)) {
// Pretend this element is selected // Pretend this element is selected
addThis = true; addThis = true;
} }
} } // Grab the ends
// Grab the ends
var parts = []; var parts = [];
['start', 'end'].forEach(function (pos, i) { ['start', 'end'].forEach(function (pos, i) {
var key = 'c_' + pos; var key = 'c_' + pos;
var part = elData(this, key); var part = elData(this, key);
if (part == null) {
if (part === null || part === undefined) {
// Does this ever return nullish values?
part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]); part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]);
elData(this, 'c_' + pos, part.id); elData(this, 'c_' + pos, part.id);
elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part])); elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part]));
} else part = document.getElementById(part); } else part = document.getElementById(part);
parts.push(part); parts.push(part);
}.bind(this)); }, this);
for (var i = 0; i < 2; i++) { for (var i = 0; i < 2; i++) {
var cElem = parts[i]; var cElem = parts[i];
addThis = false; // The connected element might be part of a selected group
addThis = false;
// The connected element might be part of a selected group
$(cElem).parents().each(add); $(cElem).parents().each(add);
if (!cElem || !cElem.parentNode) { if (!cElem || !cElem.parentNode) {
$(this).remove(); $(this).remove();
continue; continue;
} }
if (elems.includes(cElem) || addThis) { if (elems.includes(cElem) || addThis) {
var bb = svgCanvas.getStrokedBBox([cElem]); var bb = svgCanvas.getStrokedBBox([cElem]);
connections.push({ connections.push({
@ -173,59 +186,59 @@ var svgEditorExtension_connector = (function () {
}); });
}; };
updateLine = function updateLine(diffX, diffY) { updateLine = function _ref6(diffX, diffY) {
// Update line with element // Update line with element
var i = connections.length; var i = connections.length;
while (i--) { while (i--) {
var conn = connections[i]; var conn = connections[i];
var line = conn.connector; var line = conn.connector; // const {elem} = conn;
// const {elem} = conn;
var pre = conn.is_start ? 'start' : 'end';
// const sw = line.getAttribute('stroke-width') * 5;
var pre = conn.is_start ? 'start' : 'end'; // const sw = line.getAttribute('stroke-width') * 5;
// Update bbox for this element // Update bbox for this element
var bb = elData(line, pre + '_bb'); var bb = elData(line, pre + '_bb');
bb.x = conn.start_x + diffX; bb.x = conn.start_x + diffX;
bb.y = conn.start_y + diffY; bb.y = conn.start_y + diffY;
elData(line, pre + '_bb', bb); elData(line, pre + '_bb', bb);
var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element
var altPre = conn.is_start ? 'end' : 'start';
// Get center pt of connected element
var bb2 = elData(line, altPre + '_bb'); var bb2 = elData(line, altPre + '_bb');
var srcX = bb2.x + bb2.width / 2; var srcX = bb2.x + bb2.width / 2;
var srcY = bb2.y + bb2.height / 2; var srcY = bb2.y + bb2.height / 2; // Set point of element being moved
// Set point of element being moved
var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0 var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);
// Set point of connected element setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);
} }
}; };
setPoint = function setPoint(elem, pos, x, y, setMid) { setPoint = function _ref5(elem, pos, x, y, setMid) {
var pts = elem.points; var pts = elem.points;
var pt = svgroot.createSVGPoint(); var pt = svgroot.createSVGPoint();
pt.x = x; pt.x = x;
pt.y = y; pt.y = y;
if (pos === 'end') { if (pos === 'end') {
pos = pts.numberOfItems - 1; pos = pts.numberOfItems - 1;
} } // TODO: Test for this on init, then use alt only if needed
// TODO: Test for this on init, then use alt only if needed
try { try {
pts.replaceItem(pt, pos); pts.replaceItem(pt, pos);
} catch (err) { } catch (err) {
// Should only occur in FF which formats points attr as "n,n n,n", so just split // Should only occur in FF which formats points attr as "n,n n,n", so just split
var ptArr = elem.getAttribute('points').split(' '); var ptArr = elem.getAttribute('points').split(' ');
for (var i = 0; i < ptArr.length; i++) { for (var i = 0; i < ptArr.length; i++) {
if (i === pos) { if (i === pos) {
ptArr[i] = x + ',' + y; ptArr[i] = x + ',' + y;
} }
} }
elem.setAttribute('points', ptArr.join(' ')); elem.setAttribute('points', ptArr.join(' '));
} }
@ -237,25 +250,26 @@ var svgEditorExtension_connector = (function () {
} }
}; };
showPanel = function showPanel(on) { showPanel = function _ref4(on) {
var connRules = $('#connector_rules'); var connRules = $('#connector_rules');
if (!connRules.length) { if (!connRules.length) {
connRules = $('<style id="connector_rules"></style>').appendTo('head'); connRules = $('<style id="connector_rules"></style>').appendTo('head');
} }
connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }'); connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }');
$('#connector_panel').toggle(on); $('#connector_panel').toggle(on);
}; };
getOffset = function getOffset(side, line) { getOffset = function _ref3(side, line) {
var giveOffset = !!line.getAttribute('marker-' + side); var giveOffset = line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off');
// const giveOffset = $(line).data(side+'_off');
// TODO: Make this number (5) be based on marker width/height // TODO: Make this number (5) be based on marker width/height
var size = line.getAttribute('stroke-width') * 5; var size = line.getAttribute('stroke-width') * 5;
return giveOffset ? size : 0; return giveOffset ? size : 0;
}; };
getBBintersect = function getBBintersect(x, y, bb, offset) { getBBintersect = function _ref2(x, y, bb, offset) {
if (offset) { if (offset) {
offset -= 0; offset -= 0;
bb = $.extend({}, bb); bb = $.extend({}, bb);
@ -269,10 +283,9 @@ var svgEditorExtension_connector = (function () {
var midY = bb.y + bb.height / 2; var midY = bb.y + bb.height / 2;
var lenX = x - midX; var lenX = x - midX;
var lenY = y - midY; var lenY = y - midY;
var slope = Math.abs(lenY / lenX); var slope = Math.abs(lenY / lenX);
var ratio;
var ratio = void 0;
if (slope < bb.height / bb.width) { if (slope < bb.height / bb.width) {
ratio = bb.width / 2 / Math.abs(lenX); ratio = bb.width / 2 / Math.abs(lenX);
} else { } else {
@ -285,22 +298,24 @@ var svgEditorExtension_connector = (function () {
}; };
}; };
$ = jQuery;
svgEditor = this; svgEditor = this;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
getElem = svgCanvas.getElem; getElem = svgCanvas.getElem;
svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data; $ = S.$, svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data;
_context2.next = 15; _context.next = 14;
return importLocale(); return importLocale();
case 15: case 14:
strings = _context2.sent; strings = _context.sent;
startX = void 0, startY = void 0, curLine = void 0, startElem = void 0, endElem = void 0, seNs = void 0, svgcontent = S.svgcontent, started = false, connections = [], selElems = []; svgcontent = S.svgcontent, started = false, connections = [], selElems = [];
/** /**
* *
* @param {Element[]} [elem=selElems] Array of elements * @param {Float} x
*/ * @param {Float} y
* @param {module:utilities.BBoxObject} bb
* @param {Float} offset
* @returns {module:math.XYObject}
*/
// Do once // Do once
(function () { (function () {
@ -308,21 +323,32 @@ var svgEditorExtension_connector = (function () {
svgCanvas.groupSelectedElements = function () { svgCanvas.groupSelectedElements = function () {
svgCanvas.removeFromSelection($(connSel).toArray()); svgCanvas.removeFromSelection($(connSel).toArray());
return gse.apply(this, arguments);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return gse.apply(this, args);
}; };
var mse = svgCanvas.moveSelectedElements; var mse = svgCanvas.moveSelectedElements;
svgCanvas.moveSelectedElements = function () { svgCanvas.moveSelectedElements = function () {
var cmd = mse.apply(this, arguments); for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var cmd = mse.apply(this, args);
updateConnectors(); updateConnectors();
return cmd; return cmd;
}; };
seNs = svgCanvas.getEditorNS(); seNs = svgCanvas.getEditorNS();
})(); })();
/**
// Do on reset * Do on reset.
* @returns {undefined}
*/
// $(svgroot).parent().mousemove(function (e) { // $(svgroot).parent().mousemove(function (e) {
@ -335,7 +361,6 @@ var svgEditorExtension_connector = (function () {
// // // //
// // } // // }
// }); // });
buttons = [{ buttons = [{
id: 'mode_connect', id: 'mode_connect',
type: 'mode', type: 'mode',
@ -351,38 +376,21 @@ var svgEditorExtension_connector = (function () {
} }
} }
}]; }];
return _context2.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.imgPath + 'conn.svg', svgicons: svgEditor.curConfig.imgPath + 'conn.svg',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button); return Object.assign(buttons[i], button);
}), }),
addLangData: function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref2) {
var lang = _ref2.lang,
importLocale = _ref2.importLocale;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', {
data: strings.langList
});
case 1: /* async */
case 'end': addLangData: function addLangData(_ref) {
return _context.stop(); var lang = _ref.lang;
} // , importLocale: importLoc
} return {
}, _callee, this); data: strings.langList
})); };
},
function addLangData(_x3) {
return _ref3.apply(this, arguments);
}
return addLangData;
}(),
mouseDown: function mouseDown(opts) { mouseDown: function mouseDown(opts) {
var e = opts.event; var e = opts.event;
startX = opts.start_x; startX = opts.start_x;
@ -390,28 +398,23 @@ var svgEditorExtension_connector = (function () {
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
var initStroke = svgEditor.curConfig.initStroke; var initStroke = svgEditor.curConfig.initStroke;
if (mode === 'connector') { if (mode === 'connector') {
if (started) { if (started) {
return; return undefined;
} }
var mouseTarget = e.target; var mouseTarget = e.target;
var parents = $(mouseTarget).parents(); var parents = $(mouseTarget).parents();
if ($.inArray(svgcontent, parents) !== -1) { if ($.inArray(svgcontent, parents) !== -1) {
// Connectable element // Connectable element
// If child of foreignObject, use parent // If child of foreignObject, use parent
var fo = $(mouseTarget).closest('foreignObject'); var fo = $(mouseTarget).closest('foreignObject');
startElem = fo.length ? fo[0] : mouseTarget; startElem = fo.length ? fo[0] : mouseTarget; // Get center of source element
// Get center of source element
var bb = svgCanvas.getStrokedBBox([startElem]); var bb = svgCanvas.getStrokedBBox([startElem]);
var x = bb.x + bb.width / 2; var x = bb.x + bb.width / 2;
var y = bb.y + bb.height / 2; var y = bb.y + bb.height / 2;
started = true; started = true;
curLine = addElem({ curLine = addElem({
element: 'polyline', element: 'polyline',
@ -427,23 +430,25 @@ var svgEditorExtension_connector = (function () {
}); });
elData(curLine, 'start_bb', bb); elData(curLine, 'start_bb', bb);
} }
return { return {
started: true started: true
}; };
} }
if (mode === 'select') { if (mode === 'select') {
findConnectors(); findConnectors();
} }
return undefined;
}, },
mouseMove: function mouseMove(opts) { mouseMove: function mouseMove(opts) {
var zoom = svgCanvas.getZoom(); var zoom = svgCanvas.getZoom(); // const e = opts.event;
// const e = opts.event;
var x = opts.mouse_x / zoom; var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom; var y = opts.mouse_y / zoom;
var diffX = x - startX, var diffX = x - startX,
diffY = y - startY; diffY = y - startY;
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
if (mode === 'connector' && started) { if (mode === 'connector' && started) {
@ -452,22 +457,22 @@ var svgEditorExtension_connector = (function () {
var pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine)); var pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine));
startX = pt.x; startX = pt.x;
startY = pt.y; startY = pt.y;
setPoint(curLine, 0, pt.x, pt.y, true); // Set end point
setPoint(curLine, 0, pt.x, pt.y, true);
// Set end point
setPoint(curLine, 'end', x, y, true); setPoint(curLine, 'end', x, y, true);
} else if (mode === 'select') { } else if (mode === 'select') {
var slen = selElems.length; var slen = selElems.length;
while (slen--) { while (slen--) {
var elem = selElems[slen]; var elem = selElems[slen]; // Look for selected connector elements
// Look for selected connector elements
if (elem && elData(elem, 'c_start')) { if (elem && elData(elem, 'c_start')) {
// Remove the "translate" transform given to move // Remove the "translate" transform given to move
svgCanvas.removeFromSelection([elem]); svgCanvas.removeFromSelection([elem]);
svgCanvas.getTransformList(elem).clear(); svgCanvas.getTransformList(elem).clear();
} }
} }
if (connections.length) { if (connections.length) {
updateLine(diffX, diffY); updateLine(diffX, diffY);
} }
@ -475,15 +480,17 @@ var svgEditorExtension_connector = (function () {
}, },
mouseUp: function mouseUp(opts) { mouseUp: function mouseUp(opts) {
// const zoom = svgCanvas.getZoom(); // const zoom = svgCanvas.getZoom();
var e = opts.event; var e = opts.event; // , x = opts.mouse_x / zoom,
// , x = opts.mouse_x / zoom,
// , y = opts.mouse_y / zoom, // , y = opts.mouse_y / zoom,
var mouseTarget = e.target; var mouseTarget = e.target;
if (svgCanvas.getMode() !== 'connector') { if (svgCanvas.getMode() !== 'connector') {
return; return undefined;
} }
var fo = $(mouseTarget).closest('foreignObject'); var fo = $(mouseTarget).closest('foreignObject');
if (fo.length) { if (fo.length) {
mouseTarget = fo[0]; mouseTarget = fo[0];
} }
@ -499,6 +506,7 @@ var svgEditorExtension_connector = (function () {
started: started started: started
}; };
} }
if ($.inArray(svgcontent, parents) === -1) { if ($.inArray(svgcontent, parents) === -1) {
// Not a valid target element, so remove line // Not a valid target element, so remove line
$(curLine).remove(); $(curLine).remove();
@ -508,21 +516,25 @@ var svgEditorExtension_connector = (function () {
element: null, element: null,
started: started started: started
}; };
} } // Valid end element
// Valid end element
endElem = mouseTarget;
endElem = mouseTarget;
var startId = startElem.id, var startId = startElem.id,
endId = endElem.id; endId = endElem.id;
var connStr = startId + ' ' + endId; var connStr = startId + ' ' + endId;
var altStr = endId + ' ' + startId; var altStr = endId + ' ' + startId; // Don't create connector if one already exists
// Don't create connector if one already exists
var dupe = $(svgcontent).find(connSel).filter(function () { var dupe = $(svgcontent).find(connSel).filter(function () {
var conn = this.getAttributeNS(seNs, 'connector'); var conn = this.getAttributeNS(seNs, 'connector');
if (conn === connStr || conn === altStr) { if (conn === connStr || conn === altStr) {
return true; return true;
} }
return false;
}); });
if (dupe.length) { if (dupe.length) {
$(curLine).remove(); $(curLine).remove();
return { return {
@ -533,7 +545,6 @@ var svgEditorExtension_connector = (function () {
} }
var bb = svgCanvas.getStrokedBBox([endElem]); var bb = svgCanvas.getStrokedBBox([endElem]);
var pt = getBBintersect(startX, startY, bb, getOffset('start', curLine)); var pt = getBBintersect(startX, startY, bb, getOffset('start', curLine));
setPoint(curLine, 'end', pt.x, pt.y, true); setPoint(curLine, 'end', pt.x, pt.y, true);
$(curLine).data('c_start', startId).data('c_end', endId).data('end_bb', bb); $(curLine).data('c_start', startId).data('c_end', endId).data('end_bb', bb);
@ -559,16 +570,18 @@ var svgEditorExtension_connector = (function () {
if (svgCanvas.getMode() === 'connector') { if (svgCanvas.getMode() === 'connector') {
svgCanvas.setMode('select'); svgCanvas.setMode('select');
} } // Use this to update the current selected elements
// Use this to update the current selected elements
selElems = opts.elems; selElems = opts.elems;
var i = selElems.length; var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elData(elem, 'c_start')) { if (elem && elData(elem, 'c_start')) {
selManager.requestSelector(elem).showGrips(false); selManager.requestSelector(elem).showGrips(false);
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
// TODO: Set up context tools and hide most regular line tools // TODO: Set up context tools and hide most regular line tools
showPanel(true); showPanel(true);
@ -579,35 +592,34 @@ var svgEditorExtension_connector = (function () {
showPanel(false); showPanel(false);
} }
} }
updateConnectors(); updateConnectors();
}, },
elementChanged: function elementChanged(opts) { elementChanged: function elementChanged(opts) {
var elem = opts.elems[0]; var elem = opts.elems[0];
if (elem && elem.tagName === 'svg' && elem.id === 'svgcontent') { if (elem && elem.tagName === 'svg' && elem.id === 'svgcontent') {
// Update svgcontent (can change on import) // Update svgcontent (can change on import)
svgcontent = elem; svgcontent = elem;
init(); init();
} } // Has marker, so change offset
// Has marker, so change offset
if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) { if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
var start = elem.getAttribute('marker-start'); var start = elem.getAttribute('marker-start');
var mid = elem.getAttribute('marker-mid'); var mid = elem.getAttribute('marker-mid');
var end = elem.getAttribute('marker-end'); var end = elem.getAttribute('marker-end');
curLine = elem; curLine = elem;
$(elem).data('start_off', !!start).data('end_off', !!end); $(elem).data('start_off', Boolean(start)).data('end_off', Boolean(end));
if (elem.tagName === 'line' && mid) { if (elem.tagName === 'line' && mid) {
// Convert to polyline to accept mid-arrow // Convert to polyline to accept mid-arrow
var x1 = Number(elem.getAttribute('x1')); var x1 = Number(elem.getAttribute('x1'));
var x2 = Number(elem.getAttribute('x2')); var x2 = Number(elem.getAttribute('x2'));
var y1 = Number(elem.getAttribute('y1')); var y1 = Number(elem.getAttribute('y1'));
var y2 = Number(elem.getAttribute('y2')); var y2 = Number(elem.getAttribute('y2'));
var _elem = elem, var _elem = elem,
id = _elem.id; id = _elem.id;
var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' '; var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' ';
var pline = addElem({ var pline = addElem({
element: 'polyline', element: 'polyline',
@ -626,10 +638,12 @@ var svgEditorExtension_connector = (function () {
svgCanvas.addToSelection([pline]); svgCanvas.addToSelection([pline]);
elem = pline; elem = pline;
} }
} } // Update line if it's a connector
// Update line if it's a connector
if (elem.getAttribute('class') === connSel.substr(1)) { if (elem.getAttribute('class') === connSel.substr(1)) {
var _start = getElem(elData(elem, 'c_start')); var _start = getElem(elData(elem, 'c_start'));
updateConnectors([_start]); updateConnectors([_start]);
} else { } else {
updateConnectors(); updateConnectors();
@ -641,16 +655,17 @@ var svgEditorExtension_connector = (function () {
if ('se:connector' in elem.attr) { if ('se:connector' in elem.attr) {
elem.attr['se:connector'] = elem.attr['se:connector'].split(' ').map(function (oldID) { elem.attr['se:connector'] = elem.attr['se:connector'].split(' ').map(function (oldID) {
return input.changes[oldID]; return input.changes[oldID];
}).join(' '); }).join(' '); // Check validity - the field would be something like 'svg_21 svg_22', but
// Check validity - the field would be something like 'svg_21 svg_22', but
// if one end is missing, it would be 'svg_21' and therefore fail this test // if one end is missing, it would be 'svg_21' and therefore fail this test
if (!/. ./.test(elem.attr['se:connector'])) { if (!/. ./.test(elem.attr['se:connector'])) {
remove.push(elem.attr.id); remove.push(elem.attr.id);
} }
} }
}); });
return { remove: remove }; return {
remove: remove
};
}, },
toolButtonStateUpdate: function toolButtonStateUpdate(opts) { toolButtonStateUpdate: function toolButtonStateUpdate(opts) {
if (opts.nostroke) { if (opts.nostroke) {
@ -658,20 +673,21 @@ var svgEditorExtension_connector = (function () {
svgEditor.clickSelect(); svgEditor.clickSelect();
} }
} }
$('#mode_connect').toggleClass('disabled', opts.nostroke); $('#mode_connect').toggleClass('disabled', opts.nostroke);
} }
}); });
case 20: case 19:
case 'end': case "end":
return _context2.stop(); return _context.stop();
} }
} }
}, _callee2, this); }, _callee, this);
})); }));
function init(_x) { function init(_x) {
return _ref.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,42 @@
var svgEditorExtension_eyedropper = (function () { var svgEditorExtension_eyedropper = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-eyedropper.js * ext-eyedropper.js
* *
@ -39,30 +45,33 @@ var svgEditorExtension_eyedropper = (function () {
* @copyright 2010 Jeff Schiller * @copyright 2010 Jeff Schiller
* *
*/ */
var extEyedropper = { var extEyedropper = {
name: 'eyedropper', name: 'eyedropper',
init: function () { init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) { var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons; var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
getStyle = function getStyle(opts) { getStyle = function _ref(opts) {
// if we are in eyedropper mode, we don't want to disable the eye-dropper tool // if we are in eyedropper mode, we don't want to disable the eye-dropper tool
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
if (mode === 'eyedropper') { if (mode === 'eyedropper') {
return; return;
} }
var tool = $('#tool_eyedropper'); var tool = $('#tool_eyedropper'); // enable-eye-dropper if one element is selected
// enable-eye-dropper if one element is selected
var elem = null; var elem = null;
if (!opts.multiselected && opts.elems[0] && !['svg', 'g', 'use'].includes(opts.elems[0].nodeName)) { if (!opts.multiselected && opts.elems[0] && !['svg', 'g', 'use'].includes(opts.elems[0].nodeName)) {
elem = opts.elems[0]; elem = opts.elems[0];
tool.removeClass('disabled'); tool.removeClass('disabled'); // grab the current style
// grab the current style
currentStyle.fillPaint = elem.getAttribute('fill') || 'black'; currentStyle.fillPaint = elem.getAttribute('fill') || 'black';
currentStyle.fillOpacity = elem.getAttribute('fill-opacity') || 1.0; currentStyle.fillOpacity = elem.getAttribute('fill-opacity') || 1.0;
currentStyle.strokePaint = elem.getAttribute('stroke'); currentStyle.strokePaint = elem.getAttribute('stroke');
@ -71,8 +80,7 @@ var svgEditorExtension_eyedropper = (function () {
currentStyle.strokeDashArray = elem.getAttribute('stroke-dasharray'); currentStyle.strokeDashArray = elem.getAttribute('stroke-dasharray');
currentStyle.strokeLinecap = elem.getAttribute('stroke-linecap'); currentStyle.strokeLinecap = elem.getAttribute('stroke-linecap');
currentStyle.strokeLinejoin = elem.getAttribute('stroke-linejoin'); currentStyle.strokeLinejoin = elem.getAttribute('stroke-linejoin');
currentStyle.opacity = elem.getAttribute('opacity') || 1.0; currentStyle.opacity = elem.getAttribute('opacity') || 1.0; // disable eye-dropper tool
// disable eye-dropper tool
} else { } else {
tool.addClass('disabled'); tool.addClass('disabled');
} }
@ -84,17 +92,25 @@ var svgEditorExtension_eyedropper = (function () {
case 3: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
$ = jQuery; $ = S.$, ChangeElementCommand = S.ChangeElementCommand, svgCanvas = svgEditor.canvas, addToHistory = function addToHistory(cmd) {
ChangeElementCommand = S.ChangeElementCommand, svgCanvas = svgEditor.canvas, addToHistory = function addToHistory(cmd) {
svgCanvas.undoMgr.addCommandToHistory(cmd); svgCanvas.undoMgr.addCommandToHistory(cmd);
}, currentStyle = { }, currentStyle = {
fillPaint: 'red', fillOpacity: 1.0, fillPaint: 'red',
strokePaint: 'black', strokeOpacity: 1.0, fillOpacity: 1.0,
strokeWidth: 5, strokeDashArray: null, strokePaint: 'black',
strokeOpacity: 1.0,
strokeWidth: 5,
strokeDashArray: null,
opacity: 1.0, opacity: 1.0,
strokeLinecap: 'butt', strokeLinecap: 'butt',
strokeLinejoin: 'miter' strokeLinejoin: 'miter'
}; };
/**
*
* @param {module:svgcanvas.SvgCanvas#event:ext-selectedChanged|module:svgcanvas.SvgCanvas#event:ext-elementChanged} opts
* @returns {undefined}
*/
buttons = [{ buttons = [{
id: 'tool_eyedropper', id: 'tool_eyedropper',
icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png', icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png',
@ -105,19 +121,18 @@ var svgEditorExtension_eyedropper = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'eyedropper-icon.xml', svgicons: svgEditor.curConfig.extIconsPath + 'eyedropper-icon.xml',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button); return Object.assign(buttons[i], button);
}), }),
// if we have selected an element, grab its paint and enable the eye dropper button // if we have selected an element, grab its paint and enable the eye dropper button
selectedChanged: getStyle, selectedChanged: getStyle,
elementChanged: getStyle, elementChanged: getStyle,
mouseDown: function mouseDown(opts) { mouseDown: function mouseDown(opts) {
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
if (mode === 'eyedropper') { if (mode === 'eyedropper') {
var e = opts.event; var e = opts.event;
var target = e.target; var target = e.target;
@ -133,27 +148,35 @@ var svgEditorExtension_eyedropper = (function () {
if (currentStyle.fillPaint) { if (currentStyle.fillPaint) {
change(target, 'fill', currentStyle.fillPaint); change(target, 'fill', currentStyle.fillPaint);
} }
if (currentStyle.fillOpacity) { if (currentStyle.fillOpacity) {
change(target, 'fill-opacity', currentStyle.fillOpacity); change(target, 'fill-opacity', currentStyle.fillOpacity);
} }
if (currentStyle.strokePaint) { if (currentStyle.strokePaint) {
change(target, 'stroke', currentStyle.strokePaint); change(target, 'stroke', currentStyle.strokePaint);
} }
if (currentStyle.strokeOpacity) { if (currentStyle.strokeOpacity) {
change(target, 'stroke-opacity', currentStyle.strokeOpacity); change(target, 'stroke-opacity', currentStyle.strokeOpacity);
} }
if (currentStyle.strokeWidth) { if (currentStyle.strokeWidth) {
change(target, 'stroke-width', currentStyle.strokeWidth); change(target, 'stroke-width', currentStyle.strokeWidth);
} }
if (currentStyle.strokeDashArray) { if (currentStyle.strokeDashArray) {
change(target, 'stroke-dasharray', currentStyle.strokeDashArray); change(target, 'stroke-dasharray', currentStyle.strokeDashArray);
} }
if (currentStyle.opacity) { if (currentStyle.opacity) {
change(target, 'opacity', currentStyle.opacity); change(target, 'opacity', currentStyle.opacity);
} }
if (currentStyle.strokeLinecap) { if (currentStyle.strokeLinecap) {
change(target, 'stroke-linecap', currentStyle.strokeLinecap); change(target, 'stroke-linecap', currentStyle.strokeLinecap);
} }
if (currentStyle.strokeLinejoin) { if (currentStyle.strokeLinejoin) {
change(target, 'stroke-linejoin', currentStyle.strokeLinejoin); change(target, 'stroke-linejoin', currentStyle.strokeLinejoin);
} }
@ -164,8 +187,8 @@ var svgEditorExtension_eyedropper = (function () {
} }
}); });
case 9: case 8:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -173,7 +196,7 @@ var svgEditorExtension_eyedropper = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,42 @@
var svgEditorExtension_foreignobject = (function () { var svgEditorExtension_foreignobject = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-foreignobject.js * ext-foreignobject.js
* *
@ -39,30 +45,32 @@ var svgEditorExtension_foreignobject = (function () {
* @copyright 2010 Jacques Distler, 2010 Alexis Deveria * @copyright 2010 Jacques Distler, 2010 Alexis Deveria
* *
*/ */
var extForeignobject = { var extForeignobject = {
name: 'foreignobject', name: 'foreignobject',
init: function () { init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) { var _init = _asyncToGenerator(
var svgEditor, text2xml, NS, importLocale, $, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; /*#__PURE__*/
return regeneratorRuntime.wrap(function _callee$(_context) { regeneratorRuntime.mark(function _callee2(S) {
var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context2.prev = _context2.next) {
case 0: case 0:
setAttr = function setAttr(attr, val) { setAttr = function _ref6(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val); svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
}; };
showForeignEditor = function showForeignEditor() { showForeignEditor = function _ref5() {
var elt = selElems[0]; var elt = selElems[0];
if (!elt || editingforeign) { if (!elt || editingforeign) {
return; return;
} }
editingforeign = true; editingforeign = true;
toggleSourceButtons(true); toggleSourceButtons(true);
elt.removeAttribute('fill'); elt.removeAttribute('fill');
var str = svgCanvas.svgToString(elt, 0); var str = svgCanvas.svgToString(elt, 0);
$('#svg_source_textarea').val(str); $('#svg_source_textarea').val(str);
$('#svg_source_editor').fadeIn(); $('#svg_source_editor').fadeIn();
@ -70,61 +78,68 @@ var svgEditorExtension_foreignobject = (function () {
$('#svg_source_textarea').focus(); $('#svg_source_textarea').focus();
}; };
setForeignString = function setForeignString(xmlString) { setForeignString = function _ref4(xmlString) {
var elt = selElems[0]; var elt = selElems[0]; // The parent `Element` to append to
try { try {
// convert string into XML document // convert string into XML document
var newDoc = text2xml('<svg xmlns="' + NS.SVG + '" xmlns:xlink="' + NS.XLINK + '">' + xmlString + '</svg>'); var newDoc = text2xml('<svg xmlns="' + NS.SVG + '" xmlns:xlink="' + NS.XLINK + '">' + xmlString + '</svg>'); // run it through our sanitizer to remove anything we do not support
// run it through our sanitizer to remove anything we do not support
svgCanvas.sanitizeSvg(newDoc.documentElement); svgCanvas.sanitizeSvg(newDoc.documentElement);
elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true)); elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true));
svgCanvas.call('changed', [elt]); svgCanvas.call('changed', [elt]);
svgCanvas.clearSelection(); svgCanvas.clearSelection();
} catch (e) { } catch (e) {
console.log(e); // Todo: Surface error to user
console.log(e); // eslint-disable-line no-console
return false; return false;
} }
return true; return true;
}; };
toggleSourceButtons = function toggleSourceButtons(on) { toggleSourceButtons = function _ref3(on) {
$('#tool_source_save, #tool_source_cancel').toggle(!on); $('#tool_source_save, #tool_source_cancel').toggle(!on);
$('#foreign_save, #foreign_cancel').toggle(on); $('#foreign_save, #foreign_cancel').toggle(on);
}; };
showPanel = function showPanel(on) { showPanel = function _ref2(on) {
var fcRules = $('#fc_rules'); var fcRules = $('#fc_rules');
if (!fcRules.length) { if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head'); fcRules = $('<style id="fc_rules"></style>').appendTo('head');
} }
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }'); fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#foreignObject_panel').toggle(on); $('#foreignObject_panel').toggle(on);
}; };
svgEditor = this; svgEditor = this;
text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale; $ = S.$, text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale;
$ = jQuery;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
svgdoc = S.svgroot.parentNode.ownerDocument; svgdoc = S.svgroot.parentNode.ownerDocument;
_context.next = 12; _context2.next = 11;
return importLocale(); return importLocale();
case 12: case 11:
strings = _context.sent; strings = _context2.sent;
properlySourceSizeTextArea = function properlySourceSizeTextArea() { properlySourceSizeTextArea = function properlySourceSizeTextArea() {
// TODO: remove magic numbers here and get values from CSS // TODO: remove magic numbers here and get values from CSS
var height = $('#svg_source_container').height() - 80; var height = $('#svg_source_container').height() - 80;
$('#svg_source_textarea').css('height', height); $('#svg_source_textarea').css('height', height);
}; };
/**
* @param {boolean} on
* @returns {undefined}
*/
selElems = void 0, started = void 0, newFO = void 0, editingforeign = false;
editingforeign = false;
/** /**
* This function sets the content of element elt to the input XML. * This function sets the content of element elt to the input XML.
* @param {string} xmlString - The XML text * @param {string} xmlString - The XML text
* @param {Element} elt - the parent element to append to
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise. * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/ */
@ -179,7 +194,7 @@ var svgEditorExtension_foreignobject = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context2.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml', svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
@ -196,88 +211,129 @@ var svgEditorExtension_foreignobject = (function () {
editingforeign = false; editingforeign = false;
$('#svg_source_textarea').blur(); $('#svg_source_textarea').blur();
toggleSourceButtons(false); toggleSourceButtons(false);
}; }; // TODO: Needs to be done after orig icon loads
// TODO: Needs to be done after orig icon loads
setTimeout(function () { setTimeout(function () {
// Create source save/cancel buttons // Create source save/cancel buttons
/* const save = */$('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click(function () {
if (!editingforeign) {
return;
}
if (!setForeignString($('#svg_source_textarea').val())) { /* const save = */
$.confirm('Errors found. Revert to original?', function (ok) { $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click(
if (!ok) { /*#__PURE__*/
return false; _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
var ok;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (editingforeign) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
if (setForeignString($('#svg_source_textarea').val())) {
_context.next = 11;
break;
}
_context.next = 5;
return $.confirm('Errors found. Revert to original?');
case 5:
ok = _context.sent;
if (ok) {
_context.next = 8;
break;
}
return _context.abrupt("return");
case 8:
endChanges();
_context.next = 12;
break;
case 11:
endChanges();
case 12:
case "end":
return _context.stop();
} }
endChanges(); }
}); }, _callee, this);
} else { })));
endChanges(); /* const cancel = */
}
// setSelectMode();
});
/* const cancel = */$('#tool_source_cancel').clone().hide().attr('id', 'foreign_cancel').unbind().appendTo('#tool_source_back').click(function () { $('#tool_source_cancel').clone().hide().attr('id', 'foreign_cancel').unbind().appendTo('#tool_source_back').click(function () {
endChanges(); endChanges();
}); });
}, 3000); }, 3000);
}, },
mouseDown: function mouseDown(opts) { mouseDown: function mouseDown(opts) {
// const e = opts.event; // const e = opts.event;
if (svgCanvas.getMode() !== 'foreign') {
if (svgCanvas.getMode() === 'foreign') { return undefined;
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'foreignObject',
attr: {
x: opts.start_x,
y: opts.start_y,
id: svgCanvas.getNextId(),
'font-size': 16, // cur_text.font_size,
width: '48',
height: '20',
style: 'pointer-events:inherit'
}
});
var m = svgdoc.createElementNS(NS.MATH, 'math');
m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH);
m.setAttribute('display', 'inline');
var mi = svgdoc.createElementNS(NS.MATH, 'mi');
mi.setAttribute('mathvariant', 'normal');
mi.textContent = '\u03A6';
var mo = svgdoc.createElementNS(NS.MATH, 'mo');
mo.textContent = '\u222A';
var mi2 = svgdoc.createElementNS(NS.MATH, 'mi');
mi2.textContent = '\u2133';
m.append(mi, mo, mi2);
newFO.append(m);
return {
started: true
};
} }
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'foreignObject',
attr: {
x: opts.start_x,
y: opts.start_y,
id: svgCanvas.getNextId(),
'font-size': 16,
// cur_text.font_size,
width: '48',
height: '20',
style: 'pointer-events:inherit'
}
});
var m = svgdoc.createElementNS(NS.MATH, 'math');
m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH);
m.setAttribute('display', 'inline');
var mi = svgdoc.createElementNS(NS.MATH, 'mi');
mi.setAttribute('mathvariant', 'normal');
mi.textContent = "\u03A6";
var mo = svgdoc.createElementNS(NS.MATH, 'mo');
mo.textContent = "\u222A";
var mi2 = svgdoc.createElementNS(NS.MATH, 'mi');
mi2.textContent = "\u2133";
m.append(mi, mo, mi2);
newFO.append(m);
return {
started: true
};
}, },
mouseUp: function mouseUp(opts) { mouseUp: function mouseUp(opts) {
// const e = opts.event; // const e = opts.event;
if (svgCanvas.getMode() === 'foreign' && started) { if (svgCanvas.getMode() !== 'foreign' || !started) {
var attrs = $(newFO).attr(['width', 'height']); return undefined;
var keep = attrs.width !== '0' || attrs.height !== '0';
svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
} }
var attrs = $(newFO).attr(['width', 'height']);
var keep = attrs.width !== '0' || attrs.height !== '0';
svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
}, },
selectedChanged: function selectedChanged(opts) { selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements // Use this to update the current selected elements
selElems = opts.elems; selElems = opts.elems;
var i = selElems.length; var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elem.tagName === 'foreignObject') { if (elem && elem.tagName === 'foreignObject') {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
$('#foreign_font_size').val(elem.getAttribute('font-size')); $('#foreign_font_size').val(elem.getAttribute('font-size'));
@ -292,21 +348,19 @@ var svgEditorExtension_foreignobject = (function () {
} }
} }
}, },
elementChanged: function elementChanged(opts) { elementChanged: function elementChanged(opts) {}
// const elem = opts.elems[0];
}
}); });
case 18: case 17:
case 'end': case "end":
return _context.stop(); return _context2.stop();
} }
} }
}, _callee, this); }, _callee2, this);
})); }));
function init(_x) { function init(_x) {
return _ref.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,42 @@
var svgEditorExtension_grid = (function () { var svgEditorExtension_grid = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-grid.js * ext-grid.js
* *
@ -39,71 +45,72 @@ var svgEditorExtension_grid = (function () {
* @copyright 2010 Redou Mine, 2010 Alexis Deveria * @copyright 2010 Redou Mine, 2010 Alexis Deveria
* *
*/ */
var extGrid = { var extGrid = {
name: 'grid', name: 'grid',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var NS = _ref.NS, /*#__PURE__*/
getTypeMap = _ref.getTypeMap, regeneratorRuntime.mark(function _callee(_ref) {
importLocale = _ref.importLocale; var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridDefs, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons;
var strings, svgEditor, $, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
gridUpdate = function gridUpdate() { gridUpdate = function _ref3() {
if (showGrid) { if (showGrid) {
updateGrid(svgCanvas.getZoom()); updateGrid(svgCanvas.getZoom());
} }
$('#canvasGrid').toggle(showGrid); $('#canvasGrid').toggle(showGrid);
$('#view_grid').toggleClass('push_button_pressed tool_button'); $('#view_grid').toggleClass('push_button_pressed tool_button');
}; };
updateGrid = function updateGrid(zoom) { updateGrid = function _ref2(zoom) {
// TODO: Try this with <line> elements, then compare performance difference // TODO: Try this with <line> elements, then compare performance difference
var unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px var unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px
var uMulti = unit * zoom;
// Calculate the main number interval var uMulti = unit * zoom; // Calculate the main number interval
var rawM = 100 / uMulti; var rawM = 100 / uMulti;
var multi = 1; var multi = 1;
for (var i = 0; i < intervals.length; i++) { for (var i = 0; i < intervals.length; i++) {
var num = intervals[i]; var num = intervals[i];
multi = num; multi = num;
if (rawM <= num) { if (rawM <= num) {
break; break;
} }
} }
var bigInt = multi * uMulti;
// Set the canvas size to the width of the container var bigInt = multi * uMulti; // Set the canvas size to the width of the container
hcanvas.width = bigInt; hcanvas.width = bigInt;
hcanvas.height = bigInt; hcanvas.height = bigInt;
var ctx = hcanvas.getContext('2d'); var ctx = hcanvas.getContext('2d');
var curD = 0.5; var curD = 0.5;
var part = bigInt / 10; var part = bigInt / 10;
ctx.globalAlpha = 0.2; ctx.globalAlpha = 0.2;
ctx.strokeStyle = svgEditor.curConfig.gridColor; ctx.strokeStyle = svgEditor.curConfig.gridColor;
for (var _i = 1; _i < 10; _i++) { for (var _i = 1; _i < 10; _i++) {
var subD = Math.round(part * _i) + 0.5; var subD = Math.round(part * _i) + 0.5; // const lineNum = (i % 2)?12:10;
// const lineNum = (i % 2)?12:10;
var lineNum = 0; var lineNum = 0;
ctx.moveTo(subD, bigInt); ctx.moveTo(subD, bigInt);
ctx.lineTo(subD, lineNum); ctx.lineTo(subD, lineNum);
ctx.moveTo(bigInt, subD); ctx.moveTo(bigInt, subD);
ctx.lineTo(lineNum, subD); ctx.lineTo(lineNum, subD);
} }
ctx.stroke(); ctx.stroke();
ctx.beginPath(); ctx.beginPath();
ctx.globalAlpha = 0.5; ctx.globalAlpha = 0.5;
ctx.moveTo(curD, bigInt); ctx.moveTo(curD, bigInt);
ctx.lineTo(curD, 0); ctx.lineTo(curD, 0);
ctx.moveTo(bigInt, curD); ctx.moveTo(bigInt, curD);
ctx.lineTo(0, curD); ctx.lineTo(0, curD);
ctx.stroke(); ctx.stroke();
var datauri = hcanvas.toDataURL('image/png'); var datauri = hcanvas.toDataURL('image/png');
gridimg.setAttribute('width', bigInt); gridimg.setAttribute('width', bigInt);
gridimg.setAttribute('height', bigInt); gridimg.setAttribute('height', bigInt);
@ -112,22 +119,18 @@ var svgEditorExtension_grid = (function () {
svgCanvas.setHref(gridimg, datauri); svgCanvas.setHref(gridimg, datauri);
}; };
_context.next = 4; $ = _ref.$, NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale;
_context.next = 5;
return importLocale(); return importLocale();
case 4: case 5:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
svgdoc = document.getElementById('svgcanvas').ownerDocument, assignAttributes = svgCanvas.assignAttributes, hcanvas = document.createElement('canvas'), canvBG = $('#canvasBackground'), units = getTypeMap(), intervals = [0.01, 0.1, 1, 10, 100, 1000]; svgdoc = document.getElementById('svgcanvas').ownerDocument, assignAttributes = svgCanvas.assignAttributes, hcanvas = document.createElement('canvas'), canvBG = $('#canvasBackground'), units = getTypeMap(), intervals = [0.01, 0.1, 1, 10, 100, 1000];
showGrid = svgEditor.curConfig.showGrid || false; showGrid = svgEditor.curConfig.showGrid || false;
$(hcanvas).hide().appendTo('body'); $(hcanvas).hide().appendTo('body');
canvasGrid = svgdoc.createElementNS(NS.SVG, 'svg'); canvasGrid = svgdoc.createElementNS(NS.SVG, 'svg');
assignAttributes(canvasGrid, { assignAttributes(canvasGrid, {
id: 'canvasGrid', id: 'canvasGrid',
width: '100%', width: '100%',
@ -138,21 +141,20 @@ var svgEditorExtension_grid = (function () {
display: 'none' display: 'none'
}); });
canvBG.append(canvasGrid); canvBG.append(canvasGrid);
gridDefs = svgdoc.createElementNS(NS.SVG, 'defs'); // grid-pattern
// grid-pattern
gridPattern = svgdoc.createElementNS(NS.SVG, 'pattern'); gridPattern = svgdoc.createElementNS(NS.SVG, 'pattern');
assignAttributes(gridPattern, { assignAttributes(gridPattern, {
id: 'gridpattern', id: 'gridpattern',
patternUnits: 'userSpaceOnUse', patternUnits: 'userSpaceOnUse',
x: 0, // -(value.strokeWidth / 2), // position for strokewidth x: 0,
y: 0, // -(value.strokeWidth / 2), // position for strokewidth // -(value.strokeWidth / 2), // position for strokewidth
y: 0,
// -(value.strokeWidth / 2), // position for strokewidth
width: 100, width: 100,
height: 100 height: 100
}); });
gridimg = svgdoc.createElementNS(NS.SVG, 'image'); gridimg = svgdoc.createElementNS(NS.SVG, 'image');
assignAttributes(gridimg, { assignAttributes(gridimg, {
x: 0, x: 0,
y: 0, y: 0,
@ -160,11 +162,10 @@ var svgEditorExtension_grid = (function () {
height: 100 height: 100
}); });
gridPattern.append(gridimg); gridPattern.append(gridimg);
$('#svgroot defs').append(gridPattern); gridDefs.append(gridPattern);
$('#canvasGrid').append(gridDefs); // grid-box
// grid-box
gridBox = svgdoc.createElementNS(NS.SVG, 'rect'); gridBox = svgdoc.createElementNS(NS.SVG, 'rect');
assignAttributes(gridBox, { assignAttributes(gridBox, {
width: '100%', width: '100%',
height: '100%', height: '100%',
@ -176,6 +177,11 @@ var svgEditorExtension_grid = (function () {
style: 'pointer-events: none; display:visible;' style: 'pointer-events: none; display:visible;'
}); });
$('#canvasGrid').append(gridBox); $('#canvasGrid').append(gridBox);
/**
*
* @param {Float} zoom
* @returns {undefined}
*/
buttons = [{ buttons = [{
id: 'view_grid', id: 'view_grid',
@ -189,10 +195,9 @@ var svgEditorExtension_grid = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml', svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml',
zoomChanged: function zoomChanged(zoom) { zoomChanged: function zoomChanged(zoom) {
if (showGrid) { if (showGrid) {
updateGrid(zoom); updateGrid(zoom);
@ -203,14 +208,13 @@ var svgEditorExtension_grid = (function () {
gridUpdate(); gridUpdate();
} }
}, },
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button); return Object.assign(buttons[i], button);
}) })
}); });
case 25: case 27:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -218,7 +222,7 @@ var svgEditorExtension_grid = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,74 +1,80 @@
var svgEditorExtension_helloworld = (function () { var svgEditorExtension_helloworld = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
}
return step("next");
});
};
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
} }
return function (arr, i) { if (info.done) {
if (Array.isArray(arr)) { resolve(value);
return arr; } else {
} else if (Symbol.iterator in Object(arr)) { Promise.resolve(value).then(_next, _throw);
return sliceIterator(arr, i); }
} else { }
throw new TypeError("Invalid attempt to destructure non-iterable instance");
} function _asyncToGenerator(fn) {
}; return function () {
}(); var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
/* globals jQuery */
/** /**
* ext-helloworld.js * ext-helloworld.js
* *
@ -86,42 +92,38 @@ var svgEditorExtension_helloworld = (function () {
var extHelloworld = { var extHelloworld = {
name: 'helloworld', name: 'helloworld',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var importLocale = _ref.importLocale; /*#__PURE__*/
var strings, svgEditor, $, svgCanvas; regeneratorRuntime.mark(function _callee(_ref) {
var $, importLocale, strings, svgEditor, svgCanvas;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
_context.next = 2; $ = _ref.$, importLocale = _ref.importLocale;
_context.next = 3;
return importLocale(); return importLocale();
case 2: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
// For more notes on how to make an icon file, see the source of // For more notes on how to make an icon file, see the source of
// the helloworld-icon.xml // the helloworld-icon.xml
svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml', svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml',
// Multiple buttons can be added in this array // Multiple buttons can be added in this array
buttons: [{ buttons: [{
// Must match the icon ID in helloworld-icon.xml // Must match the icon ID in helloworld-icon.xml
id: 'hello_world', id: 'hello_world',
// Fallback, e.g., for `file:///` access
// Fallback, e.g., for `file://` access
icon: svgEditor.curConfig.extIconsPath + 'helloworld.png', icon: svgEditor.curConfig.extIconsPath + 'helloworld.png',
// This indicates that the button will be added to the "mode" // This indicates that the button will be added to the "mode"
// button panel on the left side // button panel on the left side
type: 'mode', type: 'mode',
// Tooltip text // Tooltip text
title: strings.buttons[0].title, title: strings.buttons[0].title,
// Events // Events
events: { events: {
click: function click() { click: function click() {
@ -139,41 +141,39 @@ var svgEditorExtension_helloworld = (function () {
if (svgCanvas.getMode() === 'hello_world') { if (svgCanvas.getMode() === 'hello_world') {
// The returned object must include "started" with // The returned object must include "started" with
// a value of true in order for mouseUp to be triggered // a value of true in order for mouseUp to be triggered
return { started: true }; return {
started: true
};
} }
return undefined;
}, },
// This is triggered from anywhere, but "started" must have been set // This is triggered from anywhere, but "started" must have been set
// to true (see above). Note that "opts" is an object with event info // to true (see above). Note that "opts" is an object with event info
mouseUp: function mouseUp(opts) { mouseUp: function mouseUp(opts) {
// Check the mode on mouseup // Check the mode on mouseup
if (svgCanvas.getMode() === 'hello_world') { if (svgCanvas.getMode() === 'hello_world') {
var zoom = svgCanvas.getZoom(); var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value
// Get the actual coordinate by dividing by the zoom value
var x = opts.mouse_x / zoom; var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom; var y = opts.mouse_y / zoom; // We do our own formatting
// We do our own formatting
var text = strings.text; var text = strings.text;
[['x', x], ['y', y]].forEach(function (_ref2) {
[['x', x], ['y', y]].forEach(function (_ref3) { var _ref3 = _slicedToArray(_ref2, 2),
var _ref4 = slicedToArray(_ref3, 2), prop = _ref3[0],
prop = _ref4[0], val = _ref3[1];
val = _ref4[1];
text = text.replace('{' + prop + '}', val); text = text.replace('{' + prop + '}', val);
}); }); // Show the text using the custom alert function
// Show the text using the custom alert function
$.alert(text); $.alert(text);
} }
} }
}); });
case 7: case 7:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -181,7 +181,7 @@ var svgEditorExtension_helloworld = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,56 @@
var svgEditorExtension_imagelib = (function () { var svgEditorExtension_imagelib = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function _typeof(obj) {
return function () { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
var gen = fn.apply(this, arguments); _typeof = function (obj) {
return new Promise(function (resolve, reject) { return typeof obj;
function step(key, arg) { };
try { } else {
var info = gen[key](arg); _typeof = function (obj) {
var value = info.value; return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
} catch (error) { };
reject(error); }
return;
}
if (info.done) { return _typeof(obj);
resolve(value); }
} else {
return Promise.resolve(value).then(function (value) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
step("next", value); try {
}, function (err) { var info = gen[key](arg);
step("throw", err); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-imagelib.js * ext-imagelib.js
* *
@ -42,32 +62,29 @@ var svgEditorExtension_imagelib = (function () {
var extImagelib = { var extImagelib = {
name: 'imagelib', name: 'imagelib',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var decode64 = _ref.decode64, /*#__PURE__*/
importLocale = _ref.importLocale; regeneratorRuntime.mark(function _callee2(_ref) {
var imagelibStrings, svgEditor, $, uiStrings, svgCanvas, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons; var $, decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context2.prev = _context2.next) {
case 0: case 0:
showBrowser = function showBrowser() { showBrowser = function _ref10() {
var browser = $('#imgbrowse'); var browser = $('#imgbrowse');
if (!browser.length) { if (!browser.length) {
$('<div id=imgbrowse_holder><div id=imgbrowse class=toolbar_button>' + '</div></div>').insertAfter('#svg_docprops'); $('<div id=imgbrowse_holder><div id=imgbrowse class=toolbar_button>' + '</div></div>').insertAfter('#svg_docprops');
browser = $('#imgbrowse'); browser = $('#imgbrowse');
var allLibs = imagelibStrings.select_lib; var allLibs = imagelibStrings.select_lib;
var libOpts = $('<ul id=imglib_opts>').appendTo(browser); var libOpts = $('<ul id=imglib_opts>').appendTo(browser);
var frame = $('<iframe/>').prependTo(browser).hide().wrap('<div id=lib_framewrap>'); var frame = $('<iframe/>').prependTo(browser).hide().wrap('<div id=lib_framewrap>');
var header = $('<h1>').prependTo(browser).text(allLibs).css({ var header = $('<h1>').prependTo(browser).text(allLibs).css({
position: 'absolute', position: 'absolute',
top: 0, top: 0,
left: 0, left: 0,
width: '100%' width: '100%'
}); });
var cancel = $('<button>' + uiStrings.common.cancel + '</button>').appendTo(browser).on('click touchend', function () { var cancel = $('<button>' + uiStrings.common.cancel + '</button>').appendTo(browser).on('click touchend', function () {
$('#imgbrowse_holder').hide(); $('#imgbrowse_holder').hide();
}).css({ }).css({
@ -75,9 +92,11 @@ var svgEditorExtension_imagelib = (function () {
top: 5, top: 5,
right: -10 right: -10
}); });
var leftBlock = $('<span>').css({
var leftBlock = $('<span>').css({ position: 'absolute', top: 5, left: 10 }).appendTo(browser); position: 'absolute',
top: 5,
left: 10
}).appendTo(browser);
var back = $('<button hidden>' + imagelibStrings.show_list + '</button>').appendTo(leftBlock).on('click touchend', function () { var back = $('<button hidden>' + imagelibStrings.show_list + '</button>').appendTo(leftBlock).on('click touchend', function () {
frame.attr('src', 'about:blank').hide(); frame.attr('src', 'about:blank').hide();
libOpts.show(); libOpts.show();
@ -86,9 +105,11 @@ var svgEditorExtension_imagelib = (function () {
}).css({ }).css({
'margin-right': 5 'margin-right': 5
}).hide(); }).hide();
/* const type = */
/* const type = */$('<select><option value=s>' + imagelibStrings.import_single + '</option><option value=m>' + imagelibStrings.import_multi + '</option><option value=o>' + imagelibStrings.open + '</option></select>').appendTo(leftBlock).change(function () { $('<select><option value=s>' + imagelibStrings.import_single + '</option><option value=m>' + imagelibStrings.import_multi + '</option><option value=o>' + imagelibStrings.open + '</option></select>').appendTo(leftBlock).change(function () {
mode = $(this).val(); mode = $(this).val();
switch (mode) { switch (mode) {
case 's': case 's':
case 'o': case 'o':
@ -103,32 +124,29 @@ var svgEditorExtension_imagelib = (function () {
}).css({ }).css({
'margin-top': 10 'margin-top': 10
}); });
cancel.prepend($.getSvgIcon('cancel', true)); cancel.prepend($.getSvgIcon('cancel', true));
back.prepend($.getSvgIcon('tool_imagelib', true)); back.prepend($.getSvgIcon('tool_imagelib', true));
imagelibStrings.imgLibs.forEach(function (_ref6) {
var modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false; var name = _ref6.name,
$.each(imagelibStrings.imgLibs, function (i, _ref3) { url = _ref6.url,
var name = _ref3.name, description = _ref6.description;
url = _ref3.url,
description = _ref3.description;
$('<li>').appendTo(libOpts).text(name).on('click touchend', function () { $('<li>').appendTo(libOpts).text(name).on('click touchend', function () {
frame.attr('src', frame.attr('src', url).show();
// Todo: Adopt some standard formatting library like `fluent.js` instead
url.replace('{path}', svgEditor.curConfig.extIconsPath).replace('{modularVersion}', modularVersion ? imagelibStrings.moduleEnding || '-es' : '')).show();
header.text(name); header.text(name);
libOpts.hide(); libOpts.hide();
back.show(); back.show();
}).append('<span>' + description + '</span>'); }).append("<span>".concat(description, "</span>"));
}); });
} else { } else {
$('#imgbrowse_holder').show(); $('#imgbrowse_holder').show();
} }
}; };
toggleMulti = function toggleMulti(show) { toggleMulti = function _ref9(show) {
$('#lib_framewrap, #imglib_opts').css({ right: show ? 200 : 10 }); $('#lib_framewrap, #imglib_opts').css({
right: show ? 200 : 10
});
if (!preview) { if (!preview) {
preview = $('<div id=imglib_preview>').css({ preview = $('<div id=imglib_preview>').css({
position: 'absolute', position: 'absolute',
@ -139,16 +157,17 @@ var svgEditorExtension_imagelib = (function () {
background: '#fff', background: '#fff',
overflow: 'auto' overflow: 'auto'
}).insertAfter('#lib_framewrap'); }).insertAfter('#lib_framewrap');
submit = $('<button disabled>Import selected</button>').appendTo('#imgbrowse').on('click touchend', function () { submit = $('<button disabled>Import selected</button>').appendTo('#imgbrowse').on('click touchend', function () {
$.each(multiArr, function (i) { $.each(multiArr, function (i) {
var type = this[0]; var type = this[0];
var data = this[1]; var data = this[1];
if (type === 'svg') { if (type === 'svg') {
svgCanvas.importSvgString(data); svgCanvas.importSvgString(data);
} else { } else {
importImage(data); importImage(data);
} }
svgCanvas.moveSelectedElements(i * 20, i * 20, false); svgCanvas.moveSelectedElements(i * 20, i * 20, false);
}); });
preview.empty(); preview.empty();
@ -165,7 +184,7 @@ var svgEditorExtension_imagelib = (function () {
submit.toggle(show); submit.toggle(show);
}; };
importImage = function importImage(url) { importImage = function _ref8(url) {
var newImage = svgCanvas.addSVGElementFromJson({ var newImage = svgCanvas.addSVGElementFromJson({
element: 'image', element: 'image',
attr: { attr: {
@ -182,224 +201,362 @@ var svgEditorExtension_imagelib = (function () {
svgCanvas.setImageURL(url); svgCanvas.setImageURL(url);
}; };
closeBrowser = function closeBrowser() { closeBrowser = function _ref7() {
$('#imgbrowse_holder').hide(); $('#imgbrowse_holder').hide();
}; };
_context.next = 6; $ = _ref.$, decode64 = _ref.decode64, importLocale = _ref.importLocale, dropXMLInternalSubset = _ref.dropXMLInternalSubset;
_context2.next = 7;
return importLocale(); return importLocale();
case 6: case 7:
imagelibStrings = _context.sent; imagelibStrings = _context2.sent;
modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false;
svgEditor = this; svgEditor = this;
$ = jQuery; uiStrings = svgEditor.uiStrings, svgCanvas = svgEditor.canvas, extIconsPath = svgEditor.curConfig.extIconsPath;
uiStrings = svgEditor.uiStrings, svgCanvas = svgEditor.canvas; imagelibStrings.imgLibs = imagelibStrings.imgLibs.map(function (_ref2) {
var name = _ref2.name,
url = _ref2.url,
description = _ref2.description;
// Todo: Adopt some standard formatting library like `fluent.js` instead
url = url.replace(/\{path\}/g, extIconsPath).replace(/\{modularVersion\}/g, modularVersion ? imagelibStrings.moduleEnding || '-es' : '');
return {
name: name,
url: url,
description: description
};
});
allowedImageLibOrigins = imagelibStrings.imgLibs.map(function (_ref3) {
var url = _ref3.url;
try {
return new URL(url).origin;
} catch (err) {
return location.origin;
}
});
/**
*
* @returns {undefined}
*/
pending = {}; pending = {};
mode = 's'; mode = 's';
multiArr = []; multiArr = [];
transferStopped = false; transferStopped = false;
preview = void 0, submit = void 0; // Receive `postMessage` data
window.addEventListener('message',
/*#__PURE__*/
function () {
var _ref5 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref4) {
var origin, response, id, type, hasName, hasHref, char1, secondpos, entry, curMeta, svgStr, imgStr, name, message, pre, src, title, xml, ok;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
origin = _ref4.origin, response = _ref4.data;
if (!(!response || !['string', 'object'].includes(_typeof(response)))) {
_context.next = 3;
break;
}
window.addEventListener('message', function (evt) { return _context.abrupt("return");
// Receive `postMessage` data
var response = evt.data;
if (!response || typeof response !== 'string') { case 3:
// Do nothing _context.prev = 3;
return; // Todo: This block can be removed (and the above check changed to
} // insist on an object) if embedAPI moves away from a string to
try { // an object (if IE9 support not needed)
// Todo: This block can be removed (and the above check changed to response = _typeof(response) === 'object' ? response : JSON.parse(response);
// insist on an object) if embedAPI moves away from a string to
// an object (if IE9 support not needed)
response = JSON.parse(response);
if (response.namespace !== 'imagelib') {
return;
}
} catch (e) {
return;
}
var hasName = 'name' in response; if (!(response.namespace !== 'imagelib')) {
var hasHref = 'href' in response; _context.next = 7;
break;
}
if (!hasName && transferStopped) { return _context.abrupt("return");
transferStopped = false;
return;
}
var id = void 0; case 7:
if (hasHref) { if (!(!allowedImageLibOrigins.includes('*') && !allowedImageLibOrigins.includes(origin))) {
id = response.href; _context.next = 10;
response = response.data; break;
} }
// Hide possible transfer dialog box // Todo: Surface this error to user?
$('#dialog_box').hide(); console.log("Origin ".concat(origin, " not whitelisted for posting to ").concat(window.origin)); // eslint-disable-line no-console
var entry = void 0,
curMeta = void 0,
svgStr = void 0,
imgStr = void 0;
var type = hasName ? 'meta' : response.charAt(0);
switch (type) {
case 'meta':
{
// Metadata
transferStopped = false;
curMeta = response;
pending[curMeta.id] = curMeta; return _context.abrupt("return");
var name = curMeta.name || 'file'; case 10:
hasName = 'name' in response;
hasHref = 'href' in response;
var message = uiStrings.notification.retrieving.replace('%s', name); if (!(!hasName && transferStopped)) {
_context.next = 15;
break;
}
transferStopped = false;
return _context.abrupt("return");
case 15:
if (hasHref) {
id = response.href;
response = response.data;
} // Hide possible transfer dialog box
if (mode !== 'm') {
$.process_cancel(message, function () {
transferStopped = true;
// Should a message be sent back to the frame?
$('#dialog_box').hide(); $('#dialog_box').hide();
}); type = hasName ? 'meta' : response.charAt(0);
} else { _context.next = 28;
entry = $('<div>' + message + '</div>').data('id', curMeta.id); break;
preview.append(entry);
curMeta.entry = entry;
}
return; case 20:
} _context.prev = 20;
case '<': _context.t0 = _context["catch"](3);
svgStr = true;
break;
case 'd':
{
if (response.startsWith('data:image/svg+xml')) {
var pre = 'data:image/svg+xml;base64,';
var src = response.substring(pre.length);
response = decode64(src);
svgStr = true;
break;
} else if (response.startsWith('data:image/')) {
imgStr = true;
break;
}
}
// Else fall through
default:
// TODO: See if there's a way to base64 encode the binary data stream
// const str = 'data:;base64,' + svgedit.utilities.encode64(response, true);
// Assume it's raw image data if (!(typeof response === 'string')) {
// importImage(str); _context.next = 28;
break;
}
// Don't give warning as postMessage may have been used by something else char1 = response.charAt(0);
if (mode !== 'm') {
closeBrowser();
} else {
pending[id].entry.remove();
}
// $.alert('Unexpected data was returned: ' + response, function() {
// if (mode !== 'm') {
// closeBrowser();
// } else {
// pending[id].entry.remove();
// }
// });
return;
}
switch (mode) { if (!(char1 !== '{' && transferStopped)) {
case 's': _context.next = 27;
// Import one break;
if (svgStr) { }
svgCanvas.importSvgString(response);
} else if (imgStr) { transferStopped = false;
importImage(response); return _context.abrupt("return");
}
closeBrowser(); case 27:
break; if (char1 === '|') {
case 'm': secondpos = response.indexOf('|', 1);
// Import multiple id = response.substr(1, secondpos - 1);
multiArr.push([svgStr ? 'svg' : 'img', response]); response = response.substr(secondpos + 1);
curMeta = pending[id]; type = response.charAt(0);
var title = void 0; }
if (svgStr) {
if (curMeta && curMeta.name) { case 28:
title = curMeta.name; _context.t1 = type;
} else { _context.next = _context.t1 === 'meta' ? 31 : _context.t1 === '<' ? 47 : _context.t1 === 'd' ? 49 : 60;
// Try to find a title break;
var xml = new DOMParser().parseFromString(response, 'text/xml').documentElement;
title = $(xml).children('title').first().text() || '(SVG #' + response.length + ')'; case 31:
} // Metadata
if (curMeta) { transferStopped = false;
preview.children().each(function () { curMeta = response; // Should be safe to add dynamic property as passed metadata
if ($(this).data('id') === id) {
if (curMeta.preview_url) { pending[curMeta.id] = curMeta; // lgtm [js/remote-property-injection]
$(this).html('<img src="' + curMeta.preview_url + '">' + title);
name = curMeta.name || 'file';
message = uiStrings.notification.retrieving.replace('%s', name);
if (!(mode !== 'm')) {
_context.next = 43;
break;
}
_context.next = 39;
return $.process_cancel(message);
case 39:
transferStopped = true; // Should a message be sent back to the frame?
$('#dialog_box').hide();
_context.next = 46;
break;
case 43:
entry = $('<div>').text(message).data('id', curMeta.id);
preview.append(entry);
curMeta.entry = entry;
case 46:
return _context.abrupt("return");
case 47:
svgStr = true;
return _context.abrupt("break", 62);
case 49:
if (!response.startsWith('data:image/svg+xml')) {
_context.next = 57;
break;
}
pre = 'data:image/svg+xml;base64,';
src = response.substring(pre.length);
response = decode64(src);
svgStr = true;
return _context.abrupt("break", 62);
case 57:
if (!response.startsWith('data:image/')) {
_context.next = 60;
break;
}
imgStr = true;
return _context.abrupt("break", 62);
case 60:
// TODO: See if there's a way to base64 encode the binary data stream
// const str = 'data:;base64,' + svgedit.utilities.encode64(response, true);
// Assume it's raw image data
// importImage(str);
// Don't give warning as postMessage may have been used by something else
if (mode !== 'm') {
closeBrowser();
} else {
pending[id].entry.remove();
} // await $.alert('Unexpected data was returned: ' + response, function() {
// if (mode !== 'm') {
// closeBrowser();
// } else {
// pending[id].entry.remove();
// }
// });
return _context.abrupt("return");
case 62:
_context.t2 = mode;
_context.next = _context.t2 === 's' ? 65 : _context.t2 === 'm' ? 68 : _context.t2 === 'o' ? 72 : 83;
break;
case 65:
// Import one
if (svgStr) {
svgCanvas.importSvgString(response);
} else if (imgStr) {
importImage(response);
}
closeBrowser();
return _context.abrupt("break", 83);
case 68:
// Import multiple
multiArr.push([svgStr ? 'svg' : 'img', response]);
curMeta = pending[id];
if (svgStr) {
if (curMeta && curMeta.name) {
title = curMeta.name;
} else { } else {
$(this).text(title); // Try to find a title
} // `dropXMLInternalSubset` is to help prevent the billion laughs attack
submit.removeAttr('disabled'); xml = new DOMParser().parseFromString(dropXMLInternalSubset(response), 'text/xml').documentElement; // lgtm [js/xml-bomb]
}
});
} else {
preview.append('<div>' + title + '</div>');
submit.removeAttr('disabled');
}
} else {
if (curMeta && curMeta.preview_url) {
title = curMeta.name || '';
}
if (curMeta && curMeta.preview_url) {
entry = '<img src="' + curMeta.preview_url + '">' + title;
} else {
entry = '<img src="' + response + '">';
}
if (curMeta) { title = $(xml).children('title').first().text() || '(SVG #' + response.length + ')';
preview.children().each(function () { }
if ($(this).data('id') === id) {
$(this).html(entry); if (curMeta) {
submit.removeAttr('disabled'); preview.children().each(function () {
if ($(this).data('id') === id) {
if (curMeta.preview_url) {
$(this).html($('<span>').append($('<img>').attr('src', curMeta.preview_url), document.createTextNode(title)));
} else {
$(this).text(title);
}
submit.removeAttr('disabled');
}
});
} else {
preview.append($('<div>').text(title));
submit.removeAttr('disabled');
}
} else {
if (curMeta && curMeta.preview_url) {
title = curMeta.name || '';
}
if (curMeta && curMeta.preview_url) {
entry = $('<span>').append($('<img>').attr('src', curMeta.preview_url), document.createTextNode(title));
} else {
entry = $('<img>').attr('src', response);
}
if (curMeta) {
preview.children().each(function () {
if ($(this).data('id') === id) {
$(this).html(entry);
submit.removeAttr('disabled');
}
});
} else {
preview.append($('<div>').append(entry));
submit.removeAttr('disabled');
}
} }
});
} else { return _context.abrupt("break", 83);
preview.append($('<div>').append(entry));
submit.removeAttr('disabled'); case 72:
if (svgStr) {
_context.next = 74;
break;
}
return _context.abrupt("break", 83);
case 74:
closeBrowser();
_context.next = 77;
return svgEditor.openPrep();
case 77:
ok = _context.sent;
if (ok) {
_context.next = 80;
break;
}
return _context.abrupt("return");
case 80:
svgCanvas.clear();
svgCanvas.setSvgString(response); // updateCanvas();
return _context.abrupt("break", 83);
case 83:
case "end":
return _context.stop();
} }
} }
break; }, _callee, this, [[3, 20]]);
case 'o': }));
// Open
if (!svgStr) { return function (_x2) {
break; return _ref5.apply(this, arguments);
} };
svgEditor.openPrep(function (ok) { }(), true);
if (!ok) { /**
return; * @param {boolean} show
} * @returns {undefined}
svgCanvas.clear(); */
svgCanvas.setSvgString(response);
// updateCanvas();
});
closeBrowser();
break;
}
}, true);
buttons = [{ buttons = [{
id: 'tool_imagelib', id: 'tool_imagelib',
type: 'app_menu', // _flyout type: 'app_menu',
icon: svgEditor.curConfig.extIconsPath + 'imagelib.png', // _flyout
icon: extIconsPath + 'imagelib.png',
position: 4, position: 4,
events: { events: {
mouseup: showBrowser mouseup: showBrowser
} }
}]; }];
return _context.abrupt('return', { return _context2.abrupt("return", {
svgicons: svgEditor.curConfig.extIconsPath + 'ext-imagelib.xml', svgicons: extIconsPath + 'ext-imagelib.xml',
buttons: imagelibStrings.buttons.map(function (button, i) { buttons: imagelibStrings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button); return Object.assign(buttons[i], button);
}), }),
@ -408,16 +565,16 @@ var svgEditorExtension_imagelib = (function () {
} }
}); });
case 18: case 20:
case 'end': case "end":
return _context.stop(); return _context2.stop();
} }
} }
}, _callee, this); }, _callee2, this);
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_arrows_en = (function () {
var en = { var en = {
name: 'Arrows', name: 'Arrows',
langList: [{ id: 'arrow_none', textContent: 'No arrow' }], langList: [{
id: 'arrow_none',
textContent: 'No arrow'
}],
contextTools: [{ contextTools: [{
title: 'Select arrow type', title: 'Select arrow type',
options: { options: {

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_arrows_fr = (function () {
var fr = { var fr = {
name: 'Arrows', name: 'Arrows',
langList: [{ id: 'arrow_none', textContent: 'Sans flèche' }], langList: [{
id: 'arrow_none',
textContent: 'Sans flèche'
}],
contextTools: [{ contextTools: [{
title: 'Select arrow type', title: 'Select arrow type',
options: { options: {

View File

@ -0,0 +1,25 @@
var svgEditorExtensionLocale_arrows_zh_CN = (function () {
'use strict';
var zhCN = {
name: '箭头',
langList: [{
id: 'arrow_none',
textContent: '无箭头'
}],
contextTools: [{
title: '选择箭头类型',
options: {
none: '无箭头',
end: '----&gt;',
start: '&lt;----',
both: '&lt;---&gt;',
mid: '--&gt;--',
mid_bk: '--&lt;--'
}
}]
};
return zhCN;
}());

View File

@ -0,0 +1,15 @@
var svgEditorExtensionLocale_closepath_zh_CN = (function () {
'use strict';
var zhCN = {
name: '闭合路径',
buttons: [{
title: '打开路径'
}, {
title: '关闭路径'
}]
};
return zhCN;
}());

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_connector_en = (function () {
var en = { var en = {
name: 'Connector', name: 'Connector',
langList: [{ id: 'mode_connect', title: 'Connect two objects' }], langList: [{
id: 'mode_connect',
title: 'Connect two objects'
}],
buttons: [{ buttons: [{
title: 'Connect two objects' title: 'Connect two objects'
}] }]

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_connector_fr = (function () {
var fr = { var fr = {
name: 'Connector', name: 'Connector',
langList: [{ id: 'mode_connect', title: 'Connecter deux objets' }], langList: [{
id: 'mode_connect',
title: 'Connecter deux objets'
}],
buttons: [{ buttons: [{
title: 'Connect two objects' title: 'Connect two objects'
}] }]

View File

@ -0,0 +1,17 @@
var svgEditorExtensionLocale_connector_zh_CN = (function () {
'use strict';
var zhCN = {
name: '连接器',
langList: [{
id: 'mode_connect',
title: '连接两个对象'
}],
buttons: [{
title: '连接两个对象'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,14 @@
var svgEditorExtensionLocale_eyedropper_zh_CN = (function () {
'use strict';
var zhCN = {
name: '滴管',
buttons: [{
title: '滴管工具',
key: 'I'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,25 @@
var svgEditorExtensionLocale_foreignobject_zh_CN = (function () {
'use strict';
var zhCN = {
name: '外部对象',
buttons: [{
title: '外部对象工具'
}, {
title: '编辑外部对象内容'
}],
contextTools: [{
title: '改变外部对象宽度',
label: 'w'
}, {
title: '改变外部对象高度',
label: 'h'
}, {
title: '改变外部对象文字大小',
label: '文字大小'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,13 @@
var svgEditorExtensionLocale_grid_zh_CN = (function () {
'use strict';
var zhCN = {
name: '网格视图',
buttons: [{
title: '显示/隐藏网格'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,14 @@
var svgEditorExtensionLocale_helloworld_zh_CN = (function () {
'use strict';
var zhCN = {
name: 'Hello World',
text: 'Hello World!\n\n 请点击: {x}, {y}',
buttons: [{
title: "输出 'Hello World'"
}]
};
return zhCN;
}());

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_de = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,23 @@ var svgEditorExtensionLocale_imagelib_en = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations' // The site is no longer using our API, and they have added an
}, { // `X-Frame-Options` header which prevents our usage cross-origin:
name: 'Openclipart', // Getting messages like this in console:
url: 'https://openclipart.org/svgedit', // Refused to display 'https://openclipart.org/detail/307176/sign-bike' in a frame
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' // because it set 'X-Frame-Options' to 'sameorigin'.
// url: 'https://openclipart.org/svgedit',
// However, they do have a custom API which we are using here:
/*
{
name: 'Openclipart',
url: '{path}imagelib/openclipart{modularVersion}.html',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_fr = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_pl = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_pt_BR = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_ro = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_sk = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_sl = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -16,12 +16,18 @@ var svgEditorExtensionLocale_imagelib_zh_CN = (function () {
description: 'Demonstration library for SVG-edit on this server' description: 'Demonstration library for SVG-edit on this server'
}, { }, {
name: 'IAN Symbol Libraries', name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php', url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations' description: 'Free library of illustrations'
}, { /*
name: 'Openclipart', // See message in "en" locale for further details
url: 'https://openclipart.org/svgedit', ,
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.' {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}] }]
}; };

View File

@ -3,7 +3,61 @@ var svgEditorExtensionLocale_markers_en = (function () {
var en = { var en = {
name: 'Markers', name: 'Markers',
langList: [{ id: 'nomarker', title: 'No Marker' }, { id: 'leftarrow', title: 'Left Arrow' }, { id: 'rightarrow', title: 'Right Arrow' }, { id: 'textmarker', title: 'Text Marker' }, { id: 'forwardslash', title: 'Forward Slash' }, { id: 'reverseslash', title: 'Reverse Slash' }, { id: 'verticalslash', title: 'Vertical Slash' }, { id: 'box', title: 'Box' }, { id: 'star', title: 'Star' }, { id: 'xmark', title: 'X' }, { id: 'triangle', title: 'Triangle' }, { id: 'mcircle', title: 'Circle' }, { id: 'leftarrow_o', title: 'Open Left Arrow' }, { id: 'rightarrow_o', title: 'Open Right Arrow' }, { id: 'box_o', title: 'Open Box' }, { id: 'star_o', title: 'Open Star' }, { id: 'triangle_o', title: 'Open Triangle' }, { id: 'mcircle_o', title: 'Open Circle' }], langList: [{
id: 'nomarker',
title: 'No Marker'
}, {
id: 'leftarrow',
title: 'Left Arrow'
}, {
id: 'rightarrow',
title: 'Right Arrow'
}, {
id: 'textmarker',
title: 'Text Marker'
}, {
id: 'forwardslash',
title: 'Forward Slash'
}, {
id: 'reverseslash',
title: 'Reverse Slash'
}, {
id: 'verticalslash',
title: 'Vertical Slash'
}, {
id: 'box',
title: 'Box'
}, {
id: 'star',
title: 'Star'
}, {
id: 'xmark',
title: 'X'
}, {
id: 'triangle',
title: 'Triangle'
}, {
id: 'mcircle',
title: 'Circle'
}, {
id: 'leftarrow_o',
title: 'Open Left Arrow'
}, {
id: 'rightarrow_o',
title: 'Open Right Arrow'
}, {
id: 'box_o',
title: 'Open Box'
}, {
id: 'star_o',
title: 'Open Star'
}, {
id: 'triangle_o',
title: 'Open Triangle'
}, {
id: 'mcircle_o',
title: 'Open Circle'
}],
contextTools: [{ contextTools: [{
title: 'Start marker', title: 'Start marker',
label: 's' label: 's'

View File

@ -0,0 +1,81 @@
var svgEditorExtensionLocale_markers_zh_CN = (function () {
'use strict';
var zhCN = {
name: '标记',
langList: [{
id: 'nomarker',
title: '无标记'
}, {
id: 'leftarrow',
title: '左箭头'
}, {
id: 'rightarrow',
title: '右箭头'
}, {
id: 'textmarker',
title: '文本'
}, {
id: 'forwardslash',
title: '斜杠'
}, {
id: 'reverseslash',
title: '反斜杠'
}, {
id: 'verticalslash',
title: '垂直线'
}, {
id: 'box',
title: '方块'
}, {
id: 'star',
title: '星形'
}, {
id: 'xmark',
title: 'X'
}, {
id: 'triangle',
title: '三角形'
}, {
id: 'mcircle',
title: '圆形'
}, {
id: 'leftarrow_o',
title: '左箭头(空心)'
}, {
id: 'rightarrow_o',
title: '右箭头(空心)'
}, {
id: 'box_o',
title: '方块(空心)'
}, {
id: 'star_o',
title: '星形(空心)'
}, {
id: 'triangle_o',
title: '三角形(空心)'
}, {
id: 'mcircle_o',
title: '圆形(空心)'
}],
contextTools: [{
title: '起始标记',
label: 's'
}, {
title: '选择起始标记类型'
}, {
title: '中段标记',
label: 'm'
}, {
title: '选择中段标记类型'
}, {
title: '末端标记',
label: 'e'
}, {
title: '选择末端标记类型'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,13 @@
var svgEditorExtensionLocale_mathjax_zh_CN = (function () {
'use strict';
var zhCN = {
name: '数学',
buttons: [{
title: '添加数学计算'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,13 @@
var svgEditorExtensionLocale_panning_zh_CN = (function () {
'use strict';
var zhCN = {
name: '移动',
buttons: [{
title: '移动'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,74 @@
var svgEditorExtensionLocale_placemark_en = (function () {
'use strict';
var en = {
name: 'placemark',
langList: [{
id: 'nomarker',
title: 'No Marker'
}, {
id: 'leftarrow',
title: 'Left Arrow'
}, {
id: 'rightarrow',
title: 'Right Arrow'
}, {
id: 'forwardslash',
title: 'Forward Slash'
}, {
id: 'reverseslash',
title: 'Reverse Slash'
}, {
id: 'verticalslash',
title: 'Vertical Slash'
}, {
id: 'box',
title: 'Box'
}, {
id: 'star',
title: 'Star'
}, {
id: 'xmark',
title: 'X'
}, {
id: 'triangle',
title: 'Triangle'
}, {
id: 'mcircle',
title: 'Circle'
}, {
id: 'leftarrow_o',
title: 'Open Left Arrow'
}, {
id: 'rightarrow_o',
title: 'Open Right Arrow'
}, {
id: 'box_o',
title: 'Open Box'
}, {
id: 'star_o',
title: 'Open Star'
}, {
id: 'triangle_o',
title: 'Open Triangle'
}, {
id: 'mcircle_o',
title: 'Open Circle'
}],
buttons: [{
title: 'Placemark Tool'
}],
contextTools: [{
title: 'Select Place marker type'
}, {
title: 'Text on separated with ; ',
label: 'Text'
}, {
title: 'Font for text',
label: ''
}]
};
return en;
}());

View File

@ -0,0 +1,17 @@
var svgEditorExtensionLocale_polygon_zh_CN = (function () {
'use strict';
var zhCN = {
name: '多边形',
buttons: [{
title: '多边形工具'
}],
contextTools: [{
title: '边数',
label: '边数'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,10 @@
var svgEditorExtensionLocale_server_moinsave_zh_CN = (function () {
'use strict';
var zhCN = {
saved: '已保存! 返回视图!'
};
return zhCN;
}());

View File

@ -0,0 +1,10 @@
var svgEditorExtensionLocale_server_opensave_zh_CN = (function () {
'use strict';
var zhCN = {
uploading: '正在上传...'
};
return zhCN;
}());

View File

@ -0,0 +1,29 @@
var svgEditorExtensionLocale_shapes_zh_CN = (function () {
'use strict';
var zhCN = {
loading: '正在加载...',
categories: {
basic: '基本',
object: '对象',
symbol: '符号',
arrow: '箭头',
flowchart: '工作流',
animal: '动物',
game: '棋牌',
dialog_balloon: '会话框',
electronics: '电子',
math: '数学',
music: '音乐',
misc: '其他',
raphael_1: 'raphaeljs.com 集合 1',
raphael_2: 'raphaeljs.com 集合 2'
},
buttons: [{
title: '图元库'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,23 @@
var svgEditorExtensionLocale_star_zh_CN = (function () {
'use strict';
var zhCN = {
name: '星形',
buttons: [{
title: '星形工具'
}],
contextTools: [{
title: '顶点',
label: '顶点'
}, {
title: '钝度',
label: '钝度'
}, {
title: '径向',
label: '径向'
}]
};
return zhCN;
}());

View File

@ -0,0 +1,17 @@
var svgEditorExtensionLocale_storage_zh_CN = (function () {
'use strict';
var zhCN = {
message: '默认情况下, SVG-Edit 在本地保存配置参数和画布内容. 如果基于隐私考虑, ' + '您可以勾选以下选项修改配置.',
storagePrefsAndContent: '本地存储配置参数和SVG图',
storagePrefsOnly: '本地只存储配置参数',
storagePrefs: '本地存储配置参数',
storageNoPrefsOrContent: '本地不保存配置参数和SVG图',
storageNoPrefs: '本地不保存配置参数',
rememberLabel: '记住选择?',
rememberTooltip: '如果您勾选记住选择,将不再弹出本窗口.'
};
return zhCN;
}());

View File

@ -0,0 +1,13 @@
var svgEditorExtensionLocale_webappfind_zh_CN = (function () {
'use strict';
var zhCN = {
name: 'WebAppFind',
buttons: [{
title: '保存图片到磁盘'
}]
};
return zhCN;
}());

View File

@ -1,36 +1,42 @@
var svgEditorExtension_markers = (function () { var svgEditorExtension_markers = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-markers.js * ext-markers.js
* *
@ -64,15 +70,18 @@ var svgEditorExtension_markers = (function () {
var extMarkers = { var extMarkers = {
name: 'markers', name: 'markers',
init: function () { init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(S) { var _init = _asyncToGenerator(
var strings, svgEditor, $, svgCanvas, addElem, mtypes, markerPrefix, idPrefix, markerTypes, getLinked, setIcon, selElems, showPanel, addMarker, convertline, setMarker, colorChanged, updateReferences, triggerTextEntry, showTextPrompt, setArrowFromButton, getTitle, buildButtonList, contextTools; /*#__PURE__*/
return regeneratorRuntime.wrap(function _callee2$(_context2) { regeneratorRuntime.mark(function _callee3(S) {
var strings, svgEditor, $, svgCanvas, addElem, mtypes, markerPrefix, idPrefix, markerTypes, getLinked, setIcon, selElems, showPanel, addMarker, convertline, setMarker, colorChanged, updateReferences, triggerTextEntry, showTextPrompt, _showTextPrompt, setArrowFromButton, _setArrowFromButton, getTitle, buildButtonList, contextTools;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) { while (1) {
switch (_context2.prev = _context2.next) { switch (_context3.prev = _context3.next) {
case 0: case 0:
buildButtonList = function buildButtonList(lang) { buildButtonList = function _ref16() {
var buttons = []; var buttons = []; // const i = 0;
// const i = 0;
/* /*
buttons.push({ buttons.push({
id: idPrefix + 'markers_off', id: idPrefix + 'markers_off',
@ -96,6 +105,7 @@ var svgEditorExtension_markers = (function () {
panel: 'marker_panel' panel: 'marker_panel'
}); });
*/ */
$.each(mtypes, function (k, pos) { $.each(mtypes, function (k, pos) {
var listname = pos + '_marker_list'; var listname = pos + '_marker_list';
var def = true; var def = true;
@ -107,7 +117,9 @@ var svgEditorExtension_markers = (function () {
icon: svgEditor.curConfig.extIconsPath + 'markers-' + id + '.png', icon: svgEditor.curConfig.extIconsPath + 'markers-' + id + '.png',
title: title, title: title,
type: 'context', type: 'context',
events: { click: setArrowFromButton }, events: {
click: setArrowFromButton
},
panel: 'marker_panel', panel: 'marker_panel',
list: listname, list: listname,
isDefault: def isDefault: def
@ -118,147 +130,223 @@ var svgEditorExtension_markers = (function () {
return buttons; return buttons;
}; };
getTitle = function getTitle(id) { getTitle = function _ref15(id) {
var langList = strings.langList; var langList = strings.langList;
var item = langList.find(function (itm) {
var item = langList.find(function (item) { return itm.id === id;
return item.id === id;
}); });
return item ? item.title : id; return item ? item.title : id;
}; };
setArrowFromButton = function setArrowFromButton(obj) { _setArrowFromButton = function _ref14() {
var parts = this.id.split('_'); _setArrowFromButton = _asyncToGenerator(
var pos = parts[1]; /*#__PURE__*/
var val = parts[2]; regeneratorRuntime.mark(function _callee2(ev) {
if (parts[3]) { var parts, pos, val;
val += '_' + parts[3]; return regeneratorRuntime.wrap(function _callee2$(_context2) {
} while (1) {
switch (_context2.prev = _context2.next) {
case 0:
parts = this.id.split('_');
pos = parts[1];
val = parts[2];
if (val !== 'textmarker') { if (parts[3]) {
triggerTextEntry(pos, '\\' + val); val += '_' + parts[3];
} else { }
showTextPrompt(pos);
} if (!(val !== 'textmarker')) {
_context2.next = 8;
break;
}
triggerTextEntry(pos, '\\' + val);
_context2.next = 10;
break;
case 8:
_context2.next = 10;
return showTextPrompt(pos);
case 10:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
return _setArrowFromButton.apply(this, arguments);
}; };
showTextPrompt = function showTextPrompt(pos) { setArrowFromButton = function _ref13(_x3) {
var def = $('#' + pos + '_marker').val(); return _setArrowFromButton.apply(this, arguments);
if (def.substr(0, 1) === '\\') {
def = '';
}
$.prompt('Enter text for ' + pos + ' marker', def, function (txt) {
if (txt) {
triggerTextEntry(pos, txt);
}
});
}; };
triggerTextEntry = function triggerTextEntry(pos, val) { _showTextPrompt = function _ref12() {
_showTextPrompt = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(pos) {
var def, txt;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
def = $('#' + pos + '_marker').val();
if (def.substr(0, 1) === '\\') {
def = '';
}
_context.next = 4;
return $.prompt('Enter text for ' + pos + ' marker', def);
case 4:
txt = _context.sent;
if (txt) {
triggerTextEntry(pos, txt);
}
case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
return _showTextPrompt.apply(this, arguments);
};
showTextPrompt = function _ref11(_x2) {
return _showTextPrompt.apply(this, arguments);
};
triggerTextEntry = function _ref10(pos, val) {
$('#' + pos + '_marker').val(val); $('#' + pos + '_marker').val(val);
$('#' + pos + '_marker').change(); $('#' + pos + '_marker').change(); // const txtbox = $('#'+pos+'_marker');
// const txtbox = $('#'+pos+'_marker');
// if (val.substr(0,1)=='\\') {txtbox.hide();} // if (val.substr(0,1)=='\\') {txtbox.hide();}
// else {txtbox.show();} // else {txtbox.show();}
}; };
updateReferences = function updateReferences(el) { updateReferences = function _ref9(el) {
$.each(mtypes, function (i, pos) { $.each(mtypes, function (i, pos) {
var id = markerPrefix + pos + '_' + el.id; var id = markerPrefix + pos + '_' + el.id;
var markerName = 'marker-' + pos; var markerName = 'marker-' + pos;
var marker = getLinked(el, markerName); var marker = getLinked(el, markerName);
if (!marker || !marker.attributes.se_type) { if (!marker || !marker.attributes.se_type) {
return; return;
} // not created by this extension } // not created by this extension
var url = el.getAttribute(markerName); var url = el.getAttribute(markerName);
if (url) { if (url) {
var len = el.id.length; var len = el.id.length;
var linkid = url.substr(-len - 1, len); var linkid = url.substr(-len - 1, len);
if (el.id !== linkid) { if (el.id !== linkid) {
var val = $('#' + pos + '_marker').attr('value'); var val = $('#' + pos + '_marker').attr('value');
addMarker(id, val); addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')'); svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') { if (el.tagName === 'line' && pos === 'mid') {
el = convertline(el); el = convertline(el);
} }
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
} }
} }
}); });
}; };
colorChanged = function colorChanged(elem) { colorChanged = function _ref8(elem) {
var color = elem.getAttribute('stroke'); var color = elem.getAttribute('stroke');
$.each(mtypes, function (i, pos) { $.each(mtypes, function (i, pos) {
var marker = getLinked(elem, 'marker-' + pos); var marker = getLinked(elem, 'marker-' + pos);
if (!marker) { if (!marker) {
return; return;
} }
if (!marker.attributes.se_type) { if (!marker.attributes.se_type) {
return; return;
} // not created by this extension } // not created by this extension
var ch = marker.lastElementChild; var ch = marker.lastElementChild;
if (!ch) { if (!ch) {
return; return;
} }
var curfill = ch.getAttribute('fill'); var curfill = ch.getAttribute('fill');
var curstroke = ch.getAttribute('stroke'); var curstroke = ch.getAttribute('stroke');
if (curfill && curfill !== 'none') { if (curfill && curfill !== 'none') {
ch.setAttribute('fill', color); ch.setAttribute('fill', color);
} }
if (curstroke && curstroke !== 'none') { if (curstroke && curstroke !== 'none') {
ch.setAttribute('stroke', color); ch.setAttribute('stroke', color);
} }
}); });
}; };
setMarker = function setMarker() { setMarker = function _ref7() {
var poslist = { start_marker: 'start', mid_marker: 'mid', end_marker: 'end' }; var poslist = {
start_marker: 'start',
mid_marker: 'mid',
end_marker: 'end'
};
var pos = poslist[this.id]; var pos = poslist[this.id];
var markerName = 'marker-' + pos; var markerName = 'marker-' + pos;
var el = selElems[0]; var el = selElems[0];
var marker = getLinked(el, markerName); var marker = getLinked(el, markerName);
if (marker) { if (marker) {
$(marker).remove(); $(marker).remove();
} }
el.removeAttribute(markerName); el.removeAttribute(markerName);
var val = this.value; var val = this.value;
if (val === '') { if (val === '') {
val = '\\nomarker'; val = '\\nomarker';
} }
if (val === '\\nomarker') { if (val === '\\nomarker') {
setIcon(pos, val); setIcon(pos, val);
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
return; return;
} } // Set marker on element
// Set marker on element
var id = markerPrefix + pos + '_' + el.id; var id = markerPrefix + pos + '_' + el.id;
addMarker(id, val); addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')'); svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') { if (el.tagName === 'line' && pos === 'mid') {
el = convertline(el); convertline(el);
} }
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
setIcon(pos, val); setIcon(pos, val);
}; };
convertline = function convertline(elem) { convertline = function _ref6(elem) {
// this routine came from the connectors extension // this routine came from the connectors extension
// it is needed because midpoint markers don't work with line elements // it is needed because midpoint markers don't work with line elements
if (!(elem.tagName === 'line')) { if (!(elem.tagName === 'line')) {
return elem; return elem;
} } // Convert to polyline to accept mid-arrow
// Convert to polyline to accept mid-arrow
var x1 = Number(elem.getAttribute('x1')); var x1 = Number(elem.getAttribute('x1'));
var x2 = Number(elem.getAttribute('x2')); var x2 = Number(elem.getAttribute('x2'));
var y1 = Number(elem.getAttribute('y1')); var y1 = Number(elem.getAttribute('y1'));
var y2 = Number(elem.getAttribute('y2')); var y2 = Number(elem.getAttribute('y2'));
var id = elem.id; var id = elem.id;
var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' '; var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' ';
var pline = addElem({ var pline = addElem({
element: 'polyline', element: 'polyline',
@ -274,15 +362,14 @@ var svgEditorExtension_markers = (function () {
// get any existing marker definitions // get any existing marker definitions
var nam = 'marker-' + pos; var nam = 'marker-' + pos;
var m = elem.getAttribute(nam); var m = elem.getAttribute(nam);
if (m) { if (m) {
pline.setAttribute(nam, elem.getAttribute(nam)); pline.setAttribute(nam, elem.getAttribute(nam));
} }
}); });
var batchCmd = new S.BatchCommand(); var batchCmd = new S.BatchCommand();
batchCmd.addSubCommand(new S.RemoveElementCommand(elem, elem.parentNode)); batchCmd.addSubCommand(new S.RemoveElementCommand(elem, elem.parentNode));
batchCmd.addSubCommand(new S.InsertElementCommand(pline)); batchCmd.addSubCommand(new S.InsertElementCommand(pline));
$(elem).after(pline).remove(); $(elem).after(pline).remove();
svgCanvas.clearSelection(); svgCanvas.clearSelection();
pline.id = id; pline.id = id;
@ -291,32 +378,33 @@ var svgEditorExtension_markers = (function () {
return pline; return pline;
}; };
addMarker = function addMarker(id, val) { addMarker = function _ref5(id, val) {
var txtBoxBg = '#ffffff'; var txtBoxBg = '#ffffff';
var txtBoxBorder = 'none'; var txtBoxBorder = 'none';
var txtBoxStrokeWidth = 0; var txtBoxStrokeWidth = 0;
var marker = svgCanvas.getElem(id); var marker = svgCanvas.getElem(id);
if (marker) { if (marker) {
return; return undefined;
} }
if (val === '' || val === '\\nomarker') { if (val === '' || val === '\\nomarker') {
return; return undefined;
} }
var el = selElems[0]; var el = selElems[0];
var color = el.getAttribute('stroke'); var color = el.getAttribute('stroke'); // NOTE: Safari didn't like a negative value in viewBox
// NOTE: Safari didn't like a negative value in viewBox
// so we use a standardized 0 0 100 100 // so we use a standardized 0 0 100 100
// with 50 50 being mapped to the marker position // with 50 50 being mapped to the marker position
var strokeWidth = 10; var strokeWidth = 10;
var refX = 50; var refX = 50;
var refY = 50; var refY = 50;
var viewBox = '0 0 100 100'; var viewBox = '0 0 100 100';
var markerWidth = 5; var markerWidth = 5;
var markerHeight = 5; var markerHeight = 5;
var seType = void 0; var seType;
if (val.substr(0, 1) === '\\') { if (val.substr(0, 1) === '\\') {
seType = val.substr(1); seType = val.substr(1);
} else { } else {
@ -324,10 +412,11 @@ var svgEditorExtension_markers = (function () {
} }
if (!markerTypes[seType]) { if (!markerTypes[seType]) {
return; return undefined;
} // an unknown type! } // an unknown type!
// create a generic marker // create a generic marker
marker = addElem({ marker = addElem({
element: 'marker', element: 'marker',
attr: { attr: {
@ -342,33 +431,32 @@ var svgEditorExtension_markers = (function () {
if (seType !== 'textmarker') { if (seType !== 'textmarker') {
var mel = addElem(markerTypes[seType]); var mel = addElem(markerTypes[seType]);
var fillcolor = seType.substr(-2) === '_o' ? 'none' : color; var fillcolor = seType.substr(-2) === '_o' ? 'none' : color;
mel.setAttribute('fill', fillcolor); mel.setAttribute('fill', fillcolor);
mel.setAttribute('stroke', color); mel.setAttribute('stroke', color);
mel.setAttribute('stroke-width', strokeWidth); mel.setAttribute('stroke-width', strokeWidth);
marker.append(mel); marker.append(mel);
} else { } else {
var text = addElem(markerTypes[seType]); var text = addElem(markerTypes[seType]); // have to add text to get bounding box
// have to add text to get bounding box
text.textContent = val; text.textContent = val;
var tb = text.getBBox(); var tb = text.getBBox(); // alert(tb.x + ' ' + tb.y + ' ' + tb.width + ' ' + tb.height);
// alert(tb.x + ' ' + tb.y + ' ' + tb.width + ' ' + tb.height);
var pad = 1; var pad = 1;
var bb = tb; var bb = tb;
bb.x = 0; bb.x = 0;
bb.y = 0; bb.y = 0;
bb.width += pad * 2; bb.width += pad * 2;
bb.height += pad * 2; bb.height += pad * 2; // shift text according to its size
// shift text according to its size
text.setAttribute('x', pad); text.setAttribute('x', pad);
text.setAttribute('y', bb.height - pad - tb.height / 4); // kludge? text.setAttribute('y', bb.height - pad - tb.height / 4); // kludge?
text.setAttribute('fill', color); text.setAttribute('fill', color);
refX = bb.width / 2 + pad; refX = bb.width / 2 + pad;
refY = bb.height / 2 + pad; refY = bb.height / 2 + pad;
viewBox = bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height; viewBox = bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height;
markerWidth = bb.width / 10; markerWidth = bb.width / 10;
markerHeight = bb.height / 10; markerHeight = bb.height / 10;
var box = addElem({ var box = addElem({
element: 'rect', element: 'rect',
attr: { attr: {
@ -391,21 +479,19 @@ var svgEditorExtension_markers = (function () {
marker.setAttribute('refX', refX); marker.setAttribute('refX', refX);
marker.setAttribute('refY', refY); marker.setAttribute('refY', refY);
svgCanvas.findDefs().append(marker); svgCanvas.findDefs().append(marker);
return marker; return marker;
}; };
showPanel = function showPanel(on) { showPanel = function _ref4(on) {
$('#marker_panel').toggle(on); $('#marker_panel').toggle(on);
if (on) { if (on) {
var el = selElems[0]; var el = selElems[0];
var val, ci;
var val = void 0,
ci = void 0;
$.each(mtypes, function (i, pos) { $.each(mtypes, function (i, pos) {
var m = getLinked(el, 'marker-' + pos); var m = getLinked(el, 'marker-' + pos);
var txtbox = $('#' + pos + '_marker'); var txtbox = $('#' + pos + '_marker');
if (!m) { if (!m) {
val = '\\nomarker'; val = '\\nomarker';
ci = val; ci = val;
@ -414,56 +500,62 @@ var svgEditorExtension_markers = (function () {
if (!m.attributes.se_type) { if (!m.attributes.se_type) {
return; return;
} // not created by this extension } // not created by this extension
val = '\\' + m.attributes.se_type.textContent; val = '\\' + m.attributes.se_type.textContent;
ci = val; ci = val;
if (val === '\\textmarker') { if (val === '\\textmarker') {
val = m.lastChild.textContent; val = m.lastChild.textContent; // txtbox.show(); // show text box
// txtbox.show(); // show text box
} else { } else {
txtbox.hide(); // hide text box txtbox.hide(); // hide text box
} }
} }
txtbox.val(val); txtbox.val(val);
setIcon(pos, ci); setIcon(pos, ci);
}); });
} }
}; };
setIcon = function setIcon(pos, id) { setIcon = function _ref3(pos, id) {
if (id.substr(0, 1) !== '\\') { if (id.substr(0, 1) !== '\\') {
id = '\\textmarker'; id = '\\textmarker';
} }
var ci = '#' + idPrefix + pos + '_' + id.substr(1); var ci = '#' + idPrefix + pos + '_' + id.substr(1);
svgEditor.setIcon('#cur_' + pos + '_marker_list', $(ci).children()); svgEditor.setIcon('#cur_' + pos + '_marker_list', $(ci).children());
$(ci).addClass('current').siblings().removeClass('current'); $(ci).addClass('current').siblings().removeClass('current');
}; };
getLinked = function getLinked(elem, attr) { getLinked = function _ref2(elem, attr) {
var str = elem.getAttribute(attr); var str = elem.getAttribute(attr);
if (!str) { if (!str) {
return null; return null;
} }
var m = str.match(/\(#(.*)\)/); var m = str.match(/\(#(.*)\)/);
if (!m || m.length !== 2) { if (!m || m.length !== 2) {
return null; return null;
} }
return svgCanvas.getElem(m[1]); return svgCanvas.getElem(m[1]);
}; };
_context2.next = 15; _context3.next = 17;
return S.importLocale(); return S.importLocale();
case 15: case 17:
strings = _context2.sent; strings = _context3.sent;
svgEditor = this; svgEditor = this;
$ = jQuery; $ = S.$;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
addElem = svgCanvas.addSVGElementFromJson; addElem = svgCanvas.addSVGElementFromJson;
mtypes = ['start', 'mid', 'end']; mtypes = ['start', 'mid', 'end'];
markerPrefix = 'se_marker_'; markerPrefix = 'se_marker_';
idPrefix = 'mkr_'; idPrefix = 'mkr_'; // note - to add additional marker types add them below with a unique id
// note - to add additional marker types add them below with a unique id
// and add the associated icon(s) to marker-icons.svg // and add the associated icon(s) to marker-icons.svg
// the geometry is normalized to a 100x100 box with the origin at lower left // the geometry is normalized to a 100x100 box with the origin at lower left
// Safari did not like negative values for low left of viewBox // Safari did not like negative values for low left of viewBox
@ -471,153 +563,167 @@ var svgEditorExtension_markers = (function () {
markerTypes = { markerTypes = {
nomarker: {}, nomarker: {},
leftarrow: { element: 'path', attr: { d: 'M0,50 L100,90 L70,50 L100,10 Z' } }, leftarrow: {
rightarrow: { element: 'path', attr: { d: 'M100,50 L0,90 L30,50 L0,10 Z' } }, element: 'path',
textmarker: { element: 'text', attr: { x: 0, y: 0, 'stroke-width': 0, stroke: 'none', 'font-size': 75, 'font-family': 'serif', 'text-anchor': 'left', attr: {
'xml:space': 'preserve' } }, d: 'M0,50 L100,90 L70,50 L100,10 Z'
forwardslash: { element: 'path', attr: { d: 'M30,100 L70,0' } }, }
reverseslash: { element: 'path', attr: { d: 'M30,0 L70,100' } }, },
verticalslash: { element: 'path', attr: { d: 'M50,0 L50,100' } }, rightarrow: {
box: { element: 'path', attr: { d: 'M20,20 L20,80 L80,80 L80,20 Z' } }, element: 'path',
star: { element: 'path', attr: { d: 'M10,30 L90,30 L20,90 L50,10 L80,90 Z' } }, attr: {
xmark: { element: 'path', attr: { d: 'M20,80 L80,20 M80,80 L20,20' } }, d: 'M100,50 L0,90 L30,50 L0,10 Z'
triangle: { element: 'path', attr: { d: 'M10,80 L50,20 L80,80 Z' } }, }
mcircle: { element: 'circle', attr: { r: 30, cx: 50, cy: 50 } } },
}; textmarker: {
element: 'text',
// duplicate shapes to support unfilled (open) marker types with an _o suffix attr: {
x: 0,
y: 0,
'stroke-width': 0,
stroke: 'none',
'font-size': 75,
'font-family': 'serif',
'text-anchor': 'left',
'xml:space': 'preserve'
}
},
forwardslash: {
element: 'path',
attr: {
d: 'M30,100 L70,0'
}
},
reverseslash: {
element: 'path',
attr: {
d: 'M30,0 L70,100'
}
},
verticalslash: {
element: 'path',
attr: {
d: 'M50,0 L50,100'
}
},
box: {
element: 'path',
attr: {
d: 'M20,20 L20,80 L80,80 L80,20 Z'
}
},
star: {
element: 'path',
attr: {
d: 'M10,30 L90,30 L20,90 L50,10 L80,90 Z'
}
},
xmark: {
element: 'path',
attr: {
d: 'M20,80 L80,20 M80,80 L20,20'
}
},
triangle: {
element: 'path',
attr: {
d: 'M10,80 L50,20 L80,80 Z'
}
},
mcircle: {
element: 'circle',
attr: {
r: 30,
cx: 50,
cy: 50
}
}
}; // duplicate shapes to support unfilled (open) marker types with an _o suffix
['leftarrow', 'rightarrow', 'box', 'star', 'mcircle', 'triangle'].forEach(function (v) { ['leftarrow', 'rightarrow', 'box', 'star', 'mcircle', 'triangle'].forEach(function (v) {
markerTypes[v + '_o'] = markerTypes[v]; markerTypes[v + '_o'] = markerTypes[v];
}); });
/** /**
* @param {Element} elem - A graphic element will have an attribute like marker-start * @param {Element} elem - A graphic element will have an attribute like marker-start
* @param {"marker-start"|"marker-mid"|"marker-end"} attr * @param {"marker-start"|"marker-mid"|"marker-end"} attr
* @returns {Element} The marker element that is linked to the graphic element * @returns {Element} The marker element that is linked to the graphic element
*/ */
selElems = void 0;
// toggles context tool panel off/on
// sets the controls with the selected element's settings
// called when the main system modifies an object
// this routine changes the associated markers to be the same color
// called when the main system creates or modifies an object
// primary purpose is create new markers for cloned objects
// simulate a change event a text box that stores the current element's marker type
/*
function setMarkerSet(obj) {
const parts = this.id.split('_');
const set = parts[2];
switch (set) {
case 'off':
triggerTextEntry('start','\\nomarker');
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\nomarker');
break;
case 'dimension':
triggerTextEntry('start','\\leftarrow');
triggerTextEntry('end','\\rightarrow');
showTextPrompt('mid');
break;
case 'label':
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\rightarrow');
showTextPrompt('start');
break;
}
}
*/
// callback function for a toolbar button click
// build the toolbar button array from the marker definitions
contextTools = [{ contextTools = [{
type: 'input', type: 'input',
panel: 'marker_panel', panel: 'marker_panel',
id: 'start_marker', id: 'start_marker',
size: 3, size: 3,
events: { change: setMarker } events: {
change: setMarker
}
}, { }, {
type: 'button-select', type: 'button-select',
panel: 'marker_panel', panel: 'marker_panel',
id: 'start_marker_list', id: 'start_marker_list',
colnum: 3, colnum: 3,
events: { change: setArrowFromButton } events: {
change: setArrowFromButton
}
}, { }, {
type: 'input', type: 'input',
panel: 'marker_panel', panel: 'marker_panel',
id: 'mid_marker', id: 'mid_marker',
defval: '', defval: '',
size: 3, size: 3,
events: { change: setMarker } events: {
change: setMarker
}
}, { }, {
type: 'button-select', type: 'button-select',
panel: 'marker_panel', panel: 'marker_panel',
id: 'mid_marker_list', id: 'mid_marker_list',
colnum: 3, colnum: 3,
events: { change: setArrowFromButton } events: {
change: setArrowFromButton
}
}, { }, {
type: 'input', type: 'input',
panel: 'marker_panel', panel: 'marker_panel',
id: 'end_marker', id: 'end_marker',
size: 3, size: 3,
events: { change: setMarker } events: {
change: setMarker
}
}, { }, {
type: 'button-select', type: 'button-select',
panel: 'marker_panel', panel: 'marker_panel',
id: 'end_marker_list', id: 'end_marker_list',
colnum: 3, colnum: 3,
events: { change: setArrowFromButton } events: {
change: setArrowFromButton
}
}]; }];
return _context2.abrupt('return', { return _context3.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'markers-icons.xml', svgicons: svgEditor.curConfig.extIconsPath + 'markers-icons.xml',
callback: function callback() { callback: function callback() {
$('#marker_panel').addClass('toolset').hide(); $('#marker_panel').addClass('toolset').hide();
}, },
addLangData: function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref2) {
var importLocale = _ref2.importLocale,
lang = _ref2.lang;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', { data: strings.langList });
case 1: /* async */
case 'end': addLangData: function addLangData(_ref) {
return _context.stop(); var importLocale = _ref.importLocale,
} lang = _ref.lang;
} return {
}, _callee, this); data: strings.langList
})); };
},
function addLangData(_x2) {
return _ref3.apply(this, arguments);
}
return addLangData;
}(),
selectedChanged: function selectedChanged(opts) { selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements // Use this to update the current selected elements
// console.log('selectChanged',opts); // console.log('selectChanged',opts);
selElems = opts.elems; selElems = opts.elems;
var markerElems = ['line', 'path', 'polyline', 'polygon']; var markerElems = ['line', 'path', 'polyline', 'polygon'];
var i = selElems.length; var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && markerElems.includes(elem.tagName)) { if (elem && markerElems.includes(elem.tagName)) {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
showPanel(true); showPanel(true);
@ -632,29 +738,29 @@ var svgEditorExtension_markers = (function () {
elementChanged: function elementChanged(opts) { elementChanged: function elementChanged(opts) {
// console.log('elementChanged',opts); // console.log('elementChanged',opts);
var elem = opts.elems[0]; var elem = opts.elems[0];
if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) { if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
colorChanged(elem); colorChanged(elem);
updateReferences(elem); updateReferences(elem);
} } // changing_flag = false; // Not apparently in use
// changing_flag = false; // Not apparently in use
},
},
buttons: buildButtonList(), buttons: buildButtonList(),
context_tools: strings.contextTools.map(function (contextTool, i) { context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool); return Object.assign(contextTools[i], contextTool);
}) })
}); });
case 28: case 29:
case 'end': case "end":
return _context2.stop(); return _context3.stop();
} }
} }
}, _callee2, this); }, _callee3, this);
})); }));
function init(_x) { function init(_x) {
return _ref.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,61 +1,49 @@
var svgEditorExtension_mathjax = (function () { var svgEditorExtension_mathjax = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
}
return step("next");
});
};
};
var _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; if (info.done) {
}; resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
// MIT License function _asyncToGenerator(fn) {
// From: https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js 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);
});
};
}
/** /**
* @module importModule * Add any of the whitelisted attributes to the script tag.
* @param {HTMLScriptElement} script
* @param {PlainObject.<string, string>} atts
* @returns {undefined}
*/ */
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"
}
function addScriptAtts(script, atts) { function addScriptAtts(script, atts) {
['id', 'class', 'type'].forEach(function (prop) { ['id', 'class', 'type'].forEach(function (prop) {
@ -63,85 +51,8 @@ var svgEditorExtension_mathjax = (function () {
script[prop] = atts[prop]; script[prop] = atts[prop];
} }
}); });
} } // Additions by Brett
// 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} url
* @param {module:importModule.ImportConfig} config
* @returns {*} The return depends on the export of the targeted module.
*/
var importSetGlobalDefault = function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url, config) {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', importSetGlobal(url, _extends({}, config, { returnDefault: true })));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function importSetGlobalDefault(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
/**
* @function module:importModule.importSetGlobal
* @param {string} url
* @param {module:importModule.ImportConfig} config
* @returns {ArbitraryModule|*} The return depends on the export of the targeted module.
*/
var importSetGlobal = function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(url, _ref2) {
var global = _ref2.global,
returnDefault = _ref2.returnDefault;
var modularVersion;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
// Todo: Replace calls to this function with `import()` when supported
modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false;
if (!modularVersion) {
_context2.next = 3;
break;
}
return _context2.abrupt('return', importModule(url, undefined, { returnDefault: returnDefault }));
case 3:
_context2.next = 5;
return importScript(url);
case 5:
return _context2.abrupt('return', window[global]);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function importSetGlobal(_x3, _x4) {
return _ref3.apply(this, arguments);
};
}();
// Addition by Brett
function importScript(url) { function importScript(url) {
var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@ -150,91 +61,62 @@ var svgEditorExtension_mathjax = (function () {
return importScript(u, atts); return importScript(u, atts);
})); }));
} }
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
// eslint-disable-line promise/avoid-new
var script = document.createElement('script'); var script = document.createElement('script');
var destructor = function destructor() { /**
script.onerror = null; *
script.onload = null; * @returns {undefined}
script.remove(); */
script.src = '';
}; function scriptOnError() {
script.defer = 'defer'; reject(new Error("Failed to import: ".concat(url)));
addScriptAtts(script, atts);
script.onerror = function () {
reject(new Error('Failed to import: ' + url));
destructor(); destructor();
}; }
script.onload = function () { /**
*
* @returns {undefined}
*/
function scriptOnLoad() {
resolve(); resolve();
destructor(); destructor();
}; }
script.src = url;
document.head.append(script);
});
}
function importModule(url) {
var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _ref4 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
_ref4$returnDefault = _ref4.returnDefault,
returnDefault = _ref4$returnDefault === undefined ? false : _ref4$returnDefault;
if (Array.isArray(url)) {
return Promise.all(url.map(function (u) {
return importModule(u, atts);
}));
}
return new Promise(function (resolve, reject) {
var vector = '$importModule$' + Math.random().toString(32).slice(2);
var script = document.createElement('script');
var destructor = function destructor() { var destructor = function destructor() {
delete window[vector]; script.removeEventListener('error', scriptOnError);
script.onerror = null; script.removeEventListener('load', scriptOnLoad);
script.onload = null;
script.remove(); script.remove();
URL.revokeObjectURL(script.src);
script.src = ''; script.src = '';
}; };
addScriptAtts(script, atts);
script.defer = 'defer';
script.type = 'module';
script.onerror = function () {
reject(new Error('Failed to import: ' + url));
destructor();
};
script.onload = function () {
resolve(window[vector]);
destructor();
};
var absURL = toAbsoluteURL(url);
var loader = 'import * as m from \'' + absURL.replace(/'/g, "\\'") + '\'; window.' + vector + ' = ' + (returnDefault ? 'm.default || ' : '') + 'm;'; // export Module
var blob = new Blob([loader], { type: 'text/javascript' });
script.src = URL.createObjectURL(blob);
script.defer = 'defer';
addScriptAtts(script, atts);
script.addEventListener('error', scriptOnError);
script.addEventListener('load', scriptOnLoad);
script.src = url;
document.head.append(script); document.head.append(script);
}); });
} }
/* globals jQuery, MathJax */
var extMathjax = { var extMathjax = {
name: 'mathjax', name: 'mathjax',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var importLocale = _ref.importLocale; /*#__PURE__*/
var strings, svgEditor, $, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons; regeneratorRuntime.mark(function _callee2(_ref) {
return regeneratorRuntime.wrap(function _callee$(_context) { var $, importLocale, strings, svgEditor, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context2.prev = _context2.next) {
case 0: case 0:
saveMath = function saveMath() { saveMath = function _ref2() {
var code = $('#mathjax_code_textarea').val(); var code = $('#mathjax_code_textarea').val(); // displaystyle to force MathJax NOT to use the inline style. Because it is
// displaystyle to force MathJax NOT to use the inline style. Because it is
// less fancy! // less fancy!
MathJax.Hub.queue.Push(['Text', math, '\\displaystyle{' + code + '}']);
MathJax.Hub.queue.Push(['Text', math, '\\displaystyle{' + code + '}']);
/* /*
* The MathJax library doesn't want to bloat your webpage so it creates * The MathJax library doesn't want to bloat your webpage so it creates
* every symbol (glymph) you need only once. These are saved in a `<svg>` on * every symbol (glymph) you need only once. These are saved in a `<svg>` on
@ -247,6 +129,7 @@ var svgEditorExtension_mathjax = (function () {
* to your formula's `<svg>` and copy the lot. So we have to replace each * to your formula's `<svg>` and copy the lot. So we have to replace each
* `<use>` tag by its `<path>`. * `<use>` tag by its `<path>`.
*/ */
MathJax.Hub.queue.Push(function () { MathJax.Hub.queue.Push(function () {
var mathjaxMath = $('.MathJax_SVG'); var mathjaxMath = $('.MathJax_SVG');
var svg = $(mathjaxMath.html()); var svg = $(mathjaxMath.html());
@ -254,10 +137,12 @@ var svgEditorExtension_mathjax = (function () {
// TODO: find a less pragmatic and more elegant solution to this. // TODO: find a less pragmatic and more elegant solution to this.
var id = $(this).attr('href') ? $(this).attr('href').slice(1) // Works in Chrome. var id = $(this).attr('href') ? $(this).attr('href').slice(1) // Works in Chrome.
: $(this).attr('xlink:href').slice(1); // Works in Firefox. : $(this).attr('xlink:href').slice(1); // Works in Firefox.
var glymph = $('#' + id).clone().removeAttr('id'); var glymph = $('#' + id).clone().removeAttr('id');
var x = $(this).attr('x'); var x = $(this).attr('x');
var y = $(this).attr('y'); var y = $(this).attr('y');
var transform = $(this).attr('transform'); var transform = $(this).attr('transform');
if (transform && (x || y)) { if (transform && (x || y)) {
glymph.attr('transform', transform + ' translate(' + x + ',' + y + ')'); glymph.attr('transform', transform + ' translate(' + x + ',' + y + ')');
} else if (transform) { } else if (transform) {
@ -265,30 +150,28 @@ var svgEditorExtension_mathjax = (function () {
} else if (x || y) { } else if (x || y) {
glymph.attr('transform', 'translate(' + x + ',' + y + ')'); glymph.attr('transform', 'translate(' + x + ',' + y + ')');
} }
$(this).replaceWith(glymph); $(this).replaceWith(glymph);
}); }); // Remove the style tag because it interferes with SVG-Edit.
// Remove the style tag because it interferes with SVG-Edit.
svg.removeAttr('style'); svg.removeAttr('style');
svg.attr('xmlns', 'http://www.w3.org/2000/svg'); svg.attr('xmlns', 'http://www.w3.org/2000/svg');
svgCanvas.importSvgString($('<div>').append(svg.clone()).html(), true); svgCanvas.importSvgString($('<div>').append(svg.clone()).html(), true);
svgCanvas.ungroupSelectedElement(); svgCanvas.ungroupSelectedElement(); // TODO: To undo the adding of the Formula you now have to undo twice.
// TODO: To undo the adding of the Formula you now have to undo twice.
// This should only be once! // This should only be once!
svgCanvas.moveSelectedElements(locationX, locationY, true); svgCanvas.moveSelectedElements(locationX, locationY, true);
}); });
}; };
_context.next = 3; $ = _ref.$, importLocale = _ref.importLocale;
_context2.next = 4;
return importLocale(); return importLocale();
case 3: case 4:
strings = _context.sent; strings = _context2.sent;
svgEditor = this; svgEditor = this;
$ = jQuery; svgCanvas = svgEditor.canvas; // Configuration of the MathJax extention.
svgCanvas = svgEditor.canvas;
// Configuration of the MathJax extention.
// This will be added to the head tag before MathJax is loaded. // This will be added to the head tag before MathJax is loaded.
/* mathjaxConfiguration = `<script type="text/x-mathjax-config"> /* mathjaxConfiguration = `<script type="text/x-mathjax-config">
@ -317,9 +200,8 @@ var svgEditorExtension_mathjax = (function () {
// Had been on https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG.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 // 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; mathjaxSrcSecure = 'mathjax/MathJax.min.js?config=TeX-AMS-MML_SVG.js', uiStrings = svgEditor.uiStrings;
math = void 0, locationX = void 0, locationY = void 0, mathjaxLoaded = false; 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
// TODO: Implement language support. Move these uiStrings to the locale files and the code to the langReady callback.
$.extend(uiStrings, { $.extend(uiStrings, {
mathjax: { mathjax: {
@ -330,117 +212,157 @@ var svgEditorExtension_mathjax = (function () {
title: 'Mathematics code editor' title: 'Mathematics code editor'
} }
}); });
/**
*
* @returns {undefined}
*/
buttons = [{ buttons = [{
id: 'tool_mathjax', id: 'tool_mathjax',
type: 'mode', type: 'mode',
icon: svgEditor.curConfig.extIconsPath + 'mathjax.png', icon: svgEditor.curConfig.extIconsPath + 'mathjax.png',
events: { events: {
click: function click() { click: function () {
// Only load Mathjax when needed, we don't want to strain Svg-Edit any more. var _click = _asyncToGenerator(
// From this point on it is very probable that it will be needed, so load it. /*#__PURE__*/
if (mathjaxLoaded === false) { regeneratorRuntime.mark(function _callee() {
$('<div id="mathjax">' + '<!-- Here is where MathJax creates the math -->' + '<div id="mathjax_creator" class="tex2jax_process" style="display:none">' + '$${}$$' + '</div>' + '<div id="mathjax_overlay"></div>' + '<div id="mathjax_container">' + '<div id="tool_mathjax_back" class="toolbar_button">' + '<button id="tool_mathjax_save">OK</button>' + '<button id="tool_mathjax_cancel">Cancel</button>' + '</div>' + '<fieldset>' + '<legend id="mathjax_legend">Mathematics Editor</legend>' + '<label>' + '<span id="mathjax_explication">Please type your mathematics in ' + '<a href="https://en.wikipedia.org/wiki/Help:Displaying_a_formula" target="_blank">TeX</a> code.</span></label>' + '<textarea id="mathjax_code_textarea" spellcheck="false"></textarea>' + '</fieldset>' + '</div>' + '</div>').insertAfter('#svg_prefs').hide(); 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.
// Make the MathEditor draggable. if (!(mathjaxLoaded === false)) {
$('#mathjax_container').draggable({ _context.next = 17;
cancel: 'button,fieldset', break;
containment: 'window' }
});
// Add functionality and picture to cancel button. $('<div id="mathjax">' + '<!-- Here is where MathJax creates the math -->' + '<div id="mathjax_creator" class="tex2jax_process" style="display:none">' + '$${}$$' + '</div>' + '<div id="mathjax_overlay"></div>' + '<div id="mathjax_container">' + '<div id="tool_mathjax_back" class="toolbar_button">' + '<button id="tool_mathjax_save">OK</button>' + '<button id="tool_mathjax_cancel">Cancel</button>' + '</div>' + '<fieldset>' + '<legend id="mathjax_legend">Mathematics Editor</legend>' + '<label>' + '<span id="mathjax_explication">Please type your mathematics in ' + '<a href="https://en.wikipedia.org/wiki/Help:Displaying_a_formula" target="_blank">TeX</a> code.</span></label>' + '<textarea id="mathjax_code_textarea" spellcheck="false"></textarea>' + '</fieldset>' + '</div>' + '</div>').insertAfter('#svg_prefs').hide(); // Make the MathEditor draggable.
$('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () {
$('#mathjax').hide();
});
// Add functionality and picture to the save button. $('#mathjax_container').draggable({
$('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () { cancel: 'button,fieldset',
saveMath(); containment: 'window'
$('#mathjax').hide(); }); // Add functionality and picture to cancel button.
});
// MathJax preprocessing has to ignore most of the page. $('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () {
$('body').addClass('tex2jax_ignore'); $('#mathjax').hide();
}); // Add functionality and picture to the save button.
// Now get (and run) the MathJax Library. $('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () {
// Todo: insert script with modules once widely supported saveMath();
// and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up $('#mathjax').hide();
// providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998 }); // MathJax preprocessing has to ignore most of the page.
/*
const modularVersion = !('svgEditor' in window) || $('body').addClass('tex2jax_ignore'); // Now get (and run) the MathJax Library.
!window.svgEditor || // Todo: insert script with modules once widely supported
window.svgEditor.modules !== false; // and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up
// Add as second argument to `importScript` // providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998
{
type: modularVersion /*
? 'module' // Make this the default when widely supported const modularVersion = !('svgEditor' in window) ||
: 'text/javascript' !window.svgEditor ||
} window.svgEditor.modules !== false;
// If only using modules, just use this: // Add as second argument to `importScript`
const {default: MathJax} = await importModule( // or `import()` when widely supported {
svgEditor.curConfig.extIconsPath + mathjaxSrcSecure type: modularVersion
); ? 'module' // Make this the default when widely supported
*/ : 'text/javascript'
importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure).then(function () { }
// When MathJax is loaded get the div where the math will be rendered. // If only using modules, just use this:
MathJax.Hub.queue.Push(function () { const {default: MathJax} = await importModule( // or `import()` when widely supported
math = MathJax.Hub.getAllJax('#mathjax_creator')[0]; svgEditor.curConfig.extIconsPath + mathjaxSrcSecure
console.log(math); );
mathjaxLoaded = true; */
console.log('MathJax Loaded'); // We use `extIconsPath` here for now as it does not vary with
}); // the modular type as does `extPath`
}).catch(function () {
console.log('Failed loadeing MathJax.'); _context.prev = 7;
$.alert('Failed loading MathJax. You will not be able to change the mathematics.'); _context.next = 10;
}); return importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure);
case 10:
// When MathJax is loaded get the div where the math will be rendered.
MathJax.Hub.queue.Push(function () {
math = MathJax.Hub.getAllJax('#mathjax_creator')[0];
console.log(math); // eslint-disable-line no-console
mathjaxLoaded = true;
console.log('MathJax Loaded'); // eslint-disable-line no-console
});
_context.next = 17;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](7);
console.log('Failed loading MathJax.'); // eslint-disable-line no-console
$.alert('Failed loading MathJax. You will not be able to change the mathematics.');
case 17:
case "end":
return _context.stop();
}
}
}, _callee, this, [[7, 13]]);
}));
function click() {
return _click.apply(this, arguments);
} }
// Set the mode.
svgCanvas.setMode('mathjax'); return click;
} }()
} }
}]; }];
return _context.abrupt('return', { return _context2.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'mathjax-icons.xml', svgicons: svgEditor.curConfig.extIconsPath + 'mathjax-icons.xml',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button); return Object.assign(buttons[i], button);
}), }),
mouseDown: function mouseDown() { mouseDown: function mouseDown() {
if (svgCanvas.getMode() === 'mathjax') { if (svgCanvas.getMode() === 'mathjax') {
return { started: true }; return {
started: true
};
} }
return undefined;
}, },
mouseUp: function mouseUp(opts) { mouseUp: function mouseUp(opts) {
if (svgCanvas.getMode() === 'mathjax') { if (svgCanvas.getMode() === 'mathjax') {
// Get the coordinates from your mouse. // Get the coordinates from your mouse.
var zoom = svgCanvas.getZoom(); var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value
// Get the actual coordinate by dividing by the zoom value
locationX = opts.mouse_x / zoom; locationX = opts.mouse_x / zoom;
locationY = opts.mouse_y / zoom; locationY = opts.mouse_y / zoom;
$('#mathjax').show(); $('#mathjax').show();
return { started: false }; // Otherwise the last selected object dissapears. return {
started: false
}; // Otherwise the last selected object dissapears.
} }
return undefined;
}, },
callback: function callback() { callback: function callback() {
$('<style>').text('#mathjax fieldset{' + 'padding: 5px;' + 'margin: 5px;' + 'border: 1px solid #DDD;' + '}' + '#mathjax label{' + 'display: block;' + 'margin: .5em;' + '}' + '#mathjax legend {' + 'max-width:195px;' + '}' + '#mathjax_overlay {' + 'position: absolute;' + 'top: 0;' + 'left: 0;' + 'right: 0;' + 'bottom: 0;' + 'background-color: black;' + 'opacity: 0.6;' + 'z-index: 20000;' + '}' + '#mathjax_container {' + 'position: absolute;' + 'top: 50px;' + 'padding: 10px;' + 'background-color: #B0B0B0;' + 'border: 1px outset #777;' + 'opacity: 1.0;' + 'font-family: Verdana, Helvetica, sans-serif;' + 'font-size: .8em;' + 'z-index: 20001;' + '}' + '#tool_mathjax_back {' + 'margin-left: 1em;' + 'overflow: auto;' + '}' + '#mathjax_legend{' + 'font-weight: bold;' + 'font-size:1.1em;' + '}' + '#mathjax_code_textarea {\\n' + 'margin: 5px .7em;' + 'overflow: hidden;' + 'width: 416px;' + 'display: block;' + 'height: 100px;' + '}').appendTo('head'); $('<style>').text('#mathjax fieldset{' + 'padding: 5px;' + 'margin: 5px;' + 'border: 1px solid #DDD;' + '}' + '#mathjax label{' + 'display: block;' + 'margin: .5em;' + '}' + '#mathjax legend {' + 'max-width:195px;' + '}' + '#mathjax_overlay {' + 'position: absolute;' + 'top: 0;' + 'left: 0;' + 'right: 0;' + 'bottom: 0;' + 'background-color: black;' + 'opacity: 0.6;' + 'z-index: 20000;' + '}' + '#mathjax_container {' + 'position: absolute;' + 'top: 50px;' + 'padding: 10px;' + 'background-color: #B0B0B0;' + 'border: 1px outset #777;' + 'opacity: 1.0;' + 'font-family: Verdana, Helvetica, sans-serif;' + 'font-size: .8em;' + 'z-index: 20001;' + '}' + '#tool_mathjax_back {' + 'margin-left: 1em;' + 'overflow: auto;' + '}' + '#mathjax_legend{' + 'font-weight: bold;' + 'font-size:1.1em;' + '}' + '#mathjax_code_textarea {\\n' + 'margin: 5px .7em;' + 'overflow: hidden;' + 'width: 416px;' + 'display: block;' + 'height: 100px;' + '}').appendTo('head'); // Add the MathJax configuration.
// Add the MathJax configuration.
// $(mathjaxConfiguration).appendTo('head'); // $(mathjaxConfiguration).appendTo('head');
} }
}); });
case 12: case 12:
case 'end': case "end":
return _context.stop(); return _context2.stop();
} }
} }
}, _callee, this); }, _callee2, this);
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,7 +1,6 @@
var svgEditorExtension_overview_window = (function () { var svgEditorExtension_overview_window = (function () {
'use strict'; 'use strict';
/* globals jQuery */
/** /**
* ext-overview_window.js * ext-overview_window.js
* *
@ -13,26 +12,25 @@ var svgEditorExtension_overview_window = (function () {
var extOverview_window = { var extOverview_window = {
name: 'overview_window', name: 'overview_window',
init: function init(_ref) { init: function init(_ref) {
var isChrome = _ref.isChrome, var $ = _ref.$,
isChrome = _ref.isChrome,
isIE = _ref.isIE; isIE = _ref.isIE;
var overviewWindowGlobals = {}; // Disabled in Chrome 48-, see https://github.com/SVG-Edit/svgedit/issues/26 and
var $ = jQuery;
var overviewWindowGlobals = {};
// Disabled in Chrome 48-, see https://github.com/SVG-Edit/svgedit/issues/26 and
// https://code.google.com/p/chromium/issues/detail?id=565120. // https://code.google.com/p/chromium/issues/detail?id=565120.
if (isChrome()) { if (isChrome()) {
var verIndex = navigator.userAgent.indexOf('Chrome/') + 7; var verIndex = navigator.userAgent.indexOf('Chrome/') + 7;
var chromeVersion = parseInt(navigator.userAgent.substring(verIndex), 10); var chromeVersion = parseInt(navigator.userAgent.substring(verIndex));
if (chromeVersion < 49) { if (chromeVersion < 49) {
return; return undefined;
} }
} } // Define and insert the base html element.
// Define and insert the base html element.
var propsWindowHtml = '<div id="overview_window_content_pane" style="width:100%; word-wrap:break-word; display:inline-block; margin-top:20px;">' + '<div id="overview_window_content" style="position:relative; left:12px; top:0px;">' + '<div style="background-color:#A0A0A0; display:inline-block; overflow:visible;">' + '<svg id="overviewMiniView" width="150" height="100" x="0" y="0" viewBox="0 0 4800 3600" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' + '<use x="0" y="0" xlink:href="#svgroot"> </use>' + '</svg>' + '<div id="overview_window_view_box" style="min-width:50px; min-height:50px; position:absolute; top:30px; left:30px; z-index:5; background-color:rgba(255,0,102,0.3);">' + '</div>' + '</div>' + '</div>' + '</div>'; var propsWindowHtml = '<div id="overview_window_content_pane" style="width:100%; word-wrap:break-word; display:inline-block; margin-top:20px;">' + '<div id="overview_window_content" style="position:relative; left:12px; top:0px;">' + '<div style="background-color:#A0A0A0; display:inline-block; overflow:visible;">' + '<svg id="overviewMiniView" width="150" height="100" x="0" y="0" viewBox="0 0 4800 3600" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' + '<use x="0" y="0" xlink:href="#svgroot"> </use>' + '</svg>' + '<div id="overview_window_view_box" style="min-width:50px; min-height:50px; position:absolute; top:30px; left:30px; z-index:5; background-color:rgba(255,0,102,0.3);">' + '</div>' + '</div>' + '</div>' + '</div>';
$('#sidepanels').append(propsWindowHtml); $('#sidepanels').append(propsWindowHtml); // Define dynamic animation of the view box.
// Define dynamic animation of the view box.
var updateViewBox = function updateViewBox() { var updateViewBox = function updateViewBox() {
var portHeight = parseFloat($('#workarea').css('height')); var portHeight = parseFloat($('#workarea').css('height'));
var portWidth = parseFloat($('#workarea').css('width')); var portWidth = parseFloat($('#workarea').css('width'));
@ -42,32 +40,30 @@ var svgEditorExtension_overview_window = (function () {
var windowHeight = parseFloat($('#svgcanvas').css('height')); var windowHeight = parseFloat($('#svgcanvas').css('height'));
var overviewWidth = $('#overviewMiniView').attr('width'); var overviewWidth = $('#overviewMiniView').attr('width');
var overviewHeight = $('#overviewMiniView').attr('height'); var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxX = portX / windowWidth * overviewWidth; var viewBoxX = portX / windowWidth * overviewWidth;
var viewBoxY = portY / windowHeight * overviewHeight; var viewBoxY = portY / windowHeight * overviewHeight;
var viewBoxWidth = portWidth / windowWidth * overviewWidth; var viewBoxWidth = portWidth / windowWidth * overviewWidth;
var viewBoxHeight = portHeight / windowHeight * overviewHeight; var viewBoxHeight = portHeight / windowHeight * overviewHeight;
$('#overview_window_view_box').css('min-width', viewBoxWidth + 'px'); $('#overview_window_view_box').css('min-width', viewBoxWidth + 'px');
$('#overview_window_view_box').css('min-height', viewBoxHeight + 'px'); $('#overview_window_view_box').css('min-height', viewBoxHeight + 'px');
$('#overview_window_view_box').css('top', viewBoxY + 'px'); $('#overview_window_view_box').css('top', viewBoxY + 'px');
$('#overview_window_view_box').css('left', viewBoxX + 'px'); $('#overview_window_view_box').css('left', viewBoxX + 'px');
}; };
$('#workarea').scroll(function () { $('#workarea').scroll(function () {
if (!overviewWindowGlobals.viewBoxDragging) { if (!overviewWindowGlobals.viewBoxDragging) {
updateViewBox(); updateViewBox();
} }
}); });
$('#workarea').resize(updateViewBox); $('#workarea').resize(updateViewBox);
updateViewBox(); updateViewBox(); // Compensate for changes in zoom and canvas size.
// Compensate for changes in zoom and canvas size.
var updateViewDimensions = function updateViewDimensions() { var updateViewDimensions = function updateViewDimensions() {
var viewWidth = $('#svgroot').attr('width'); var viewWidth = $('#svgroot').attr('width');
var viewHeight = $('#svgroot').attr('height'); var viewHeight = $('#svgroot').attr('height');
var viewX = 640; var viewX = 640;
var viewY = 480; var viewY = 480;
if (isIE()) { if (isIE()) {
// This has only been tested with Firefox 10 and IE 9 (without chrome frame). // This has only been tested with Firefox 10 and IE 9 (without chrome frame).
// I am not sure if if is Firefox or IE that is being non compliant here. // I am not sure if if is Firefox or IE that is being non compliant here.
@ -85,10 +81,11 @@ var svgEditorExtension_overview_window = (function () {
$('#overviewMiniView').attr('height', svgHeightNew); $('#overviewMiniView').attr('height', svgHeightNew);
updateViewBox(); updateViewBox();
}; };
updateViewDimensions();
// Set up the overview window as a controller for the view port. updateViewDimensions(); // Set up the overview window as a controller for the view port.
overviewWindowGlobals.viewBoxDragging = false; overviewWindowGlobals.viewBoxDragging = false;
var updateViewPortFromViewBox = function updateViewPortFromViewBox() { var updateViewPortFromViewBox = function updateViewPortFromViewBox() {
var windowWidth = parseFloat($('#svgcanvas').css('width')); var windowWidth = parseFloat($('#svgcanvas').css('width'));
var windowHeight = parseFloat($('#svgcanvas').css('height')); var windowHeight = parseFloat($('#svgcanvas').css('height'));
@ -96,13 +93,12 @@ var svgEditorExtension_overview_window = (function () {
var overviewHeight = $('#overviewMiniView').attr('height'); var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxX = parseFloat($('#overview_window_view_box').css('left')); var viewBoxX = parseFloat($('#overview_window_view_box').css('left'));
var viewBoxY = parseFloat($('#overview_window_view_box').css('top')); var viewBoxY = parseFloat($('#overview_window_view_box').css('top'));
var portX = viewBoxX / overviewWidth * windowWidth; var portX = viewBoxX / overviewWidth * windowWidth;
var portY = viewBoxY / overviewHeight * windowHeight; var portY = viewBoxY / overviewHeight * windowHeight;
$('#workarea').scrollLeft(portX); $('#workarea').scrollLeft(portX);
$('#workarea').scrollTop(portY); $('#workarea').scrollTop(portY);
}; };
$('#overview_window_view_box').draggable({ $('#overview_window_view_box').draggable({
containment: 'parent', containment: 'parent',
drag: updateViewPortFromViewBox, drag: updateViewPortFromViewBox,
@ -121,19 +117,21 @@ var svgEditorExtension_overview_window = (function () {
var overviewHeight = $('#overviewMiniView').attr('height'); var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxWidth = parseFloat($('#overview_window_view_box').css('min-width')); var viewBoxWidth = parseFloat($('#overview_window_view_box').css('min-width'));
var viewBoxHeight = parseFloat($('#overview_window_view_box').css('min-height')); var viewBoxHeight = parseFloat($('#overview_window_view_box').css('min-height'));
var viewBoxX = mouseX - 0.5 * viewBoxWidth; var viewBoxX = mouseX - 0.5 * viewBoxWidth;
var viewBoxY = mouseY - 0.5 * viewBoxHeight; var viewBoxY = mouseY - 0.5 * viewBoxHeight; // deal with constraints
// deal with constraints
if (viewBoxX < 0) { if (viewBoxX < 0) {
viewBoxX = 0; viewBoxX = 0;
} }
if (viewBoxY < 0) { if (viewBoxY < 0) {
viewBoxY = 0; viewBoxY = 0;
} }
if (viewBoxX + viewBoxWidth > overviewWidth) { if (viewBoxX + viewBoxWidth > overviewWidth) {
viewBoxX = overviewWidth - viewBoxWidth; viewBoxX = overviewWidth - viewBoxWidth;
} }
if (viewBoxY + viewBoxHeight > overviewHeight) { if (viewBoxY + viewBoxHeight > overviewHeight) {
viewBoxY = overviewHeight - viewBoxHeight; viewBoxY = overviewHeight - viewBoxHeight;
} }
@ -142,7 +140,6 @@ var svgEditorExtension_overview_window = (function () {
$('#overview_window_view_box').css('left', viewBoxX + 'px'); $('#overview_window_view_box').css('left', viewBoxX + 'px');
updateViewPortFromViewBox(); updateViewPortFromViewBox();
}); });
return { return {
name: 'overview window', name: 'overview window',
canvasUpdated: updateViewDimensions, canvasUpdated: updateViewDimensions,

View File

@ -1,34 +1,41 @@
var svgEditorExtension_panning = (function () { var svgEditorExtension_panning = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/** /**
* ext-panning.js * ext-panning.js
@ -38,23 +45,26 @@ var svgEditorExtension_panning = (function () {
* @copyright 2013 Luis Aguirre * @copyright 2013 Luis Aguirre
* *
*/ */
/* /*
This is a very basic SVG-Edit extension to let tablet/mobile devices pan without problem This is a very basic SVG-Edit extension to let tablet/mobile devices pan without problem
*/ */
var extPanning = { var extPanning = {
name: 'panning', name: 'panning',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var importLocale = _ref.importLocale; /*#__PURE__*/
var strings, svgEditor, svgCanvas, buttons; regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, strings, svgEditor, svgCanvas, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
_context.next = 2; importLocale = _ref.importLocale;
_context.next = 3;
return importLocale(); return importLocale();
case 2: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
@ -68,7 +78,7 @@ var svgEditorExtension_panning = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'ext-panning.xml', svgicons: svgEditor.curConfig.extIconsPath + 'ext-panning.xml',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
@ -77,8 +87,12 @@ var svgEditorExtension_panning = (function () {
mouseDown: function mouseDown() { mouseDown: function mouseDown() {
if (svgCanvas.getMode() === 'ext-panning') { if (svgCanvas.getMode() === 'ext-panning') {
svgEditor.setPanning(true); svgEditor.setPanning(true);
return { started: true }; return {
started: true
};
} }
return undefined;
}, },
mouseUp: function mouseUp() { mouseUp: function mouseUp() {
if (svgCanvas.getMode() === 'ext-panning') { if (svgCanvas.getMode() === 'ext-panning') {
@ -88,11 +102,13 @@ var svgEditorExtension_panning = (function () {
element: null element: null
}; };
} }
return undefined;
} }
}); });
case 7: case 8:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -100,7 +116,7 @@ var svgEditorExtension_panning = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,27 +1,33 @@
var svgEditorExtension_php_savefile = (function () { var svgEditorExtension_php_savefile = (function () {
'use strict'; 'use strict';
/* globals jQuery */
// TODO: Might add support for "exportImage" custom // TODO: Might add support for "exportImage" custom
// handler as in "ext-server_opensave.js" (and in savefile.php) // handler as in "ext-server_opensave.js" (and in savefile.php)
var extPhp_savefile = { var extPhp_savefile = {
name: 'php_savefile', name: 'php_savefile',
init: function init() { init: function init(_ref) {
var $ = _ref.$;
var svgEditor = this; var svgEditor = this;
var $ = jQuery;
var svgCanvas = svgEditor.canvas; var svgCanvas = svgEditor.canvas;
/**
* Get file name out of SVGEdit document title.
* @returns {string}
*/
function getFileNameFromTitle() { function getFileNameFromTitle() {
var title = svgCanvas.getDocumentTitle(); var title = svgCanvas.getDocumentTitle();
return title.trim(); return title.trim();
} }
var saveSvgAction = svgEditor.curConfig.extPath + 'savefile.php'; var saveSvgAction = svgEditor.curConfig.extPath + 'savefile.php';
svgEditor.setCustomHandlers({ svgEditor.setCustomHandlers({
save: function save(win, data) { save: function save(win, data) {
var svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data, var svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data,
filename = getFileNameFromTitle(); filename = getFileNameFromTitle();
$.post(saveSvgAction, {
$.post(saveSvgAction, { output_svg: svg, filename: filename }); output_svg: svg,
filename: filename
});
} }
}); });
} }

710
dist/extensions/ext-placemark.js vendored Normal file
View File

@ -0,0 +1,710 @@
var svgEditorExtension_placemark = (function () {
'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
/**
* ext-placemark.js
*
*
* @copyright 2010 CloudCanvas, Inc. All rights reserved
*
*/
var extPlacemark = {
name: 'placemark',
init: function () {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var svgEditor, svgCanvas, addElem, $, importLocale, selElems, started, newPM, strings, markerTypes, showPanel, getLinked, updateText, updateFont, addMarker, setMarker, colorChanged, updateReferences, setArrowFromButton, getTitle, addMarkerButtons, buttons, contextTools;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
addMarkerButtons = function _ref11(buttons) {
Object.keys(markerTypes).forEach(function (id) {
var title = getTitle(String(id));
buttons.push({
id: 'placemark_marker_' + id,
svgicon: id,
icon: svgEditor.curConfig.extIconsPath + 'markers-' + id + '.png',
title: title,
type: 'context',
events: {
click: setArrowFromButton
},
panel: 'placemark_panel',
list: 'placemark_marker',
isDefault: id === 'leftarrow'
});
});
return buttons;
};
getTitle = function _ref10(id) {
var langList = strings.langList;
var item = langList.find(function (itm) {
return itm.id === id;
});
return item ? item.title : id;
};
setArrowFromButton = function _ref9(ev) {
var parts = this.id.split('_');
var val = parts[2];
if (parts[3]) {
val += '_' + parts[3];
}
$('#placemark_marker').attr('value', val);
};
updateReferences = function _ref8(el) {
var id = 'placemark_marker_' + el.id;
var markerName = 'marker-start';
var marker = getLinked(el, markerName);
if (!marker || !marker.attributes.class) {
return;
} // not created by this extension
var url = el.getAttribute(markerName);
if (url) {
var len = el.id.length;
var linkid = url.substr(-len - 1, len);
if (el.id !== linkid) {
var val = $('#placemark_marker').attr('value') || 'leftarrow';
addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
svgCanvas.call('changed', selElems);
}
}
};
colorChanged = function _ref7(el) {
var color = el.getAttribute('stroke');
var marker = getLinked(el, 'marker-start'); // console.log(marker);
if (!marker) {
return;
}
if (!marker.attributes.class) {
return;
} // not created by this extension
var ch = marker.lastElementChild;
if (!ch) {
return;
}
var curfill = ch.getAttribute('fill');
var curstroke = ch.getAttribute('stroke');
if (curfill && curfill !== 'none') {
ch.setAttribute('fill', color);
}
if (curstroke && curstroke !== 'none') {
ch.setAttribute('stroke', color);
}
};
setMarker = function _ref6(el, val) {
var markerName = 'marker-start';
var marker = getLinked(el, markerName);
if (marker) {
$(marker).remove();
}
el.removeAttribute(markerName);
if (val === 'nomarker') {
svgCanvas.call('changed', [el]);
return;
} // Set marker on element
var id = 'placemark_marker_' + el.id;
addMarker(id, val);
el.setAttribute(markerName, 'url(#' + id + ')');
svgCanvas.call('changed', [el]);
};
addMarker = function _ref5(id, val) {
var marker = svgCanvas.getElem(id);
if (marker) {
return undefined;
} // console.log(id);
if (val === '' || val === 'nomarker') {
return undefined;
}
var color = svgCanvas.getColor('stroke'); // NOTE: Safari didn't like a negative value in viewBox
// so we use a standardized 0 0 100 100
// with 50 50 being mapped to the marker position
var scale = 2; // parseFloat($('#marker_size').val());
var strokeWidth = 10;
var refX = 50;
var refY = 50;
var viewBox = '0 0 100 100';
var markerWidth = 5 * scale;
var markerHeight = 5 * scale;
var seType = val;
if (!markerTypes[seType]) {
return undefined;
} // an unknown type!
// positional markers(arrows) at end of line
if (seType.includes('left')) refX = 0;
if (seType.includes('right')) refX = 100; // create a generic marker
marker = addElem({
element: 'marker',
attr: {
id: id,
markerUnits: 'strokeWidth',
orient: 'auto',
style: 'pointer-events:none',
class: seType
}
});
var mel = addElem(markerTypes[seType]);
var fillcolor = seType.substr(-2) === '_o' ? 'none' : color;
mel.setAttribute('fill', fillcolor);
mel.setAttribute('stroke', color);
mel.setAttribute('stroke-width', strokeWidth);
marker.append(mel);
marker.setAttribute('viewBox', viewBox);
marker.setAttribute('markerWidth', markerWidth);
marker.setAttribute('markerHeight', markerHeight);
marker.setAttribute('refX', refX);
marker.setAttribute('refY', refY);
svgCanvas.findDefs().append(marker);
return marker;
};
updateFont = function _ref4(font) {
font = font.split(' ');
var fontSize = parseInt(font.pop());
font = font.join(' ');
selElems.forEach(function (elem) {
if (elem && elem.getAttribute('class').includes('placemark')) {
$(elem).children().each(function (_, i) {
var _i$id$split3 = i.id.split('_'),
_i$id$split4 = _slicedToArray(_i$id$split3, 3),
type = _i$id$split4[2];
if (type === 'txt') {
$(i).attr({
'font-family': font,
'font-size': fontSize
});
}
});
}
});
};
updateText = function _ref3(txt) {
var items = txt.split(';');
selElems.forEach(function (elem) {
if (elem && elem.getAttribute('class').includes('placemark')) {
$(elem).children().each(function (_, i) {
var _i$id$split = i.id.split('_'),
_i$id$split2 = _slicedToArray(_i$id$split, 4),
type = _i$id$split2[2],
n = _i$id$split2[3];
if (type === 'txt') {
$(i).text(items[n]);
}
});
}
});
};
getLinked = function _ref2(elem, attr) {
if (!elem) {
return null;
}
var str = elem.getAttribute(attr);
if (!str) {
return null;
}
var m = str.match(/\(#(.*)\)/);
if (!m || m.length !== 2) {
return null;
}
return svgCanvas.getElem(m[1]);
};
showPanel = function _ref(on) {
$('#placemark_panel').toggle(on);
};
svgEditor = this;
svgCanvas = svgEditor.canvas;
addElem = svgCanvas.addSVGElementFromJson;
$ = S.$, importLocale = S.importLocale; // {svgcontent},
_context.next = 17;
return importLocale();
case 17:
strings = _context.sent;
markerTypes = {
nomarker: {},
forwardslash: {
element: 'path',
attr: {
d: 'M30,100 L70,0'
}
},
reverseslash: {
element: 'path',
attr: {
d: 'M30,0 L70,100'
}
},
verticalslash: {
element: 'path',
attr: {
d: 'M50,0 L50,100'
}
},
xmark: {
element: 'path',
attr: {
d: 'M20,80 L80,20 M80,80 L20,20'
}
},
leftarrow: {
element: 'path',
attr: {
d: 'M0,50 L100,90 L70,50 L100,10 Z'
}
},
rightarrow: {
element: 'path',
attr: {
d: 'M100,50 L0,90 L30,50 L0,10 Z'
}
},
box: {
element: 'path',
attr: {
d: 'M20,20 L20,80 L80,80 L80,20 Z'
}
},
star: {
element: 'path',
attr: {
d: 'M10,30 L90,30 L20,90 L50,10 L80,90 Z'
}
},
mcircle: {
element: 'circle',
attr: {
r: 30,
cx: 50,
cy: 50
}
},
triangle: {
element: 'path',
attr: {
d: 'M10,80 L50,20 L80,80 Z'
}
}
}; // duplicate shapes to support unfilled (open) marker types with an _o suffix
['leftarrow', 'rightarrow', 'box', 'star', 'mcircle', 'triangle'].forEach(function (v) {
markerTypes[v + '_o'] = markerTypes[v];
});
/**
*
* @param {boolean} on
* @returns {undefined}
*/
buttons = [{
id: 'tool_placemark',
icon: svgEditor.curConfig.extIconsPath + 'placemark.png',
type: 'mode',
position: 12,
events: {
click: function click() {
showPanel(true);
svgCanvas.setMode('placemark');
}
}
}];
contextTools = [{
type: 'button-select',
panel: 'placemark_panel',
id: 'placemark_marker',
colnum: 3,
events: {
change: setArrowFromButton
}
}, {
type: 'input',
panel: 'placemark_panel',
id: 'placemarkText',
size: 20,
defval: '',
events: {
change: function change() {
updateText(this.value);
}
}
}, {
type: 'input',
panel: 'placemark_panel',
id: 'placemarkFont',
size: 7,
defval: 'Arial 10',
events: {
change: function change() {
updateFont(this.value);
}
}
}];
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'placemark-icons.xml',
buttons: addMarkerButtons(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() {
$('#placemark_panel').hide(); // const endChanges = function(){};
},
mouseDown: function mouseDown(opts) {
// const rgb = svgCanvas.getColor('fill');
var sRgb = svgCanvas.getColor('stroke');
var sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() === 'placemark') {
started = true;
var id = svgCanvas.getNextId();
var items = $('#placemarkText').val().split(';');
var font = $('#placemarkFont').val().split(' ');
var fontSize = parseInt(font.pop());
font = font.join(' ');
var x0 = opts.start_x + 10,
y0 = opts.start_y + 10;
var maxlen = 0;
var children = [{
element: 'line',
attr: {
id: id + '_pline_0',
fill: 'none',
stroke: sRgb,
'stroke-width': sWidth,
'stroke-linecap': 'round',
x1: opts.start_x,
y1: opts.start_y,
x2: x0,
y2: y0
}
}];
items.forEach(function (i, n) {
maxlen = Math.max(maxlen, i.length);
children.push({
element: 'line',
attr: {
id: id + '_tline_' + n,
fill: 'none',
stroke: sRgb,
'stroke-width': sWidth,
'stroke-linecap': 'round',
x1: x0,
y1: y0 + (fontSize + 6) * n,
x2: x0 + i.length * fontSize * 0.5 + fontSize,
y2: y0 + (fontSize + 6) * n
}
});
children.push({
element: 'text',
attr: {
id: id + '_txt_' + n,
fill: sRgb,
stroke: 'none',
'stroke-width': 0,
x: x0 + 3,
y: y0 - 3 + (fontSize + 6) * n,
'font-family': font,
'font-size': fontSize,
'text-anchor': 'start'
},
children: [i]
});
});
if (items.length > 0) {
children.push({
element: 'line',
attr: {
id: id + '_vline_0',
fill: 'none',
stroke: sRgb,
'stroke-width': sWidth,
'stroke-linecap': 'round',
x1: x0,
y1: y0,
x2: x0,
y2: y0 + (fontSize + 6) * (items.length - 1)
}
});
}
newPM = svgCanvas.addSVGElementFromJson({
element: 'g',
attr: {
id: id,
class: 'placemark',
fontSize: fontSize,
maxlen: maxlen,
lines: items.length,
x: opts.start_x,
y: opts.start_y,
px: opts.start_x,
py: opts.start_y
},
children: children
});
setMarker(newPM.firstElementChild, $('#placemark_marker').attr('value') || 'leftarrow');
return {
started: true
};
}
return undefined;
},
mouseMove: function mouseMove(opts) {
if (!started) {
return undefined;
}
if (svgCanvas.getMode() === 'placemark') {
var x = opts.mouse_x / svgCanvas.getZoom();
var y = opts.mouse_y / svgCanvas.getZoom();
var _$$attr = $(newPM).attr(['fontSize', 'maxlen', 'lines', 'px', 'py']),
fontSize = _$$attr.fontSize,
maxlen = _$$attr.maxlen,
lines = _$$attr.lines,
px = _$$attr.px,
py = _$$attr.py;
$(newPM).attr({
x: x,
y: y
});
$(newPM).children().each(function (_, i) {
var _i$id$split5 = i.id.split('_'),
_i$id$split6 = _slicedToArray(_i$id$split5, 4),
type = _i$id$split6[2],
n = _i$id$split6[3];
var y0 = y + (fontSize + 6) * n,
x0 = x + maxlen * fontSize * 0.5 + fontSize;
var nx = x + (x0 - x) / 2 < px ? x0 : x;
var ny = y + (fontSize + 6) * (lines - 1) / 2 < py ? y + (fontSize + 6) * (lines - 1) : y;
if (type === 'pline') {
i.setAttribute('x2', nx);
i.setAttribute('y2', ny);
}
if (type === 'tline') {
i.setAttribute('x1', x);
i.setAttribute('y1', y0);
i.setAttribute('x2', x0);
i.setAttribute('y2', y0);
}
if (type === 'vline') {
i.setAttribute('x1', nx);
i.setAttribute('y1', y);
i.setAttribute('x2', nx);
i.setAttribute('y2', y + (fontSize + 6) * (lines - 1));
}
if (type === 'txt') {
i.setAttribute('x', x + fontSize / 2);
i.setAttribute('y', y0 - 3);
}
});
return {
started: true
};
}
return undefined;
},
mouseUp: function mouseUp() {
if (svgCanvas.getMode() === 'placemark') {
var _$$attr2 = $(newPM).attr(['x', 'y', 'px', 'py']),
x = _$$attr2.x,
y = _$$attr2.y,
px = _$$attr2.px,
py = _$$attr2.py;
return {
keep: x != px && y != py,
// eslint-disable-line eqeqeq
element: newPM
};
}
return undefined;
},
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
selElems = opts.elems;
selElems.forEach(function (elem) {
if (elem && elem.getAttribute('class').includes('placemark')) {
var txt = [];
$(elem).children().each(function (n, i) {
var _i$id$split7 = i.id.split('_'),
_i$id$split8 = _slicedToArray(_i$id$split7, 3),
type = _i$id$split8[2];
if (type === 'txt') {
$('#placemarkFont').val(i.getAttribute('font-family') + ' ' + i.getAttribute('font-size'));
txt.push($(i).text());
}
});
$('#placemarkText').val(txt.join(';'));
showPanel(true);
} else {
showPanel(false);
}
});
},
elementChanged: function elementChanged(opts) {
opts.elems.forEach(function (elem) {
if (elem.id.includes('pline_0')) {
// need update marker of pline_0
colorChanged(elem);
updateReferences(elem);
}
});
}
});
case 23:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
};
return extPlacemark;
}());

View File

@ -1,36 +1,42 @@
var svgEditorExtension_polygon = (function () { var svgEditorExtension_polygon = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-polygon.js * ext-polygon.js
* *
@ -41,67 +47,46 @@ var svgEditorExtension_polygon = (function () {
var extPolygon = { var extPolygon = {
name: 'polygon', name: 'polygon',
init: function () { init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) { var _init = _asyncToGenerator(
var svgEditor, $, svgCanvas, importLocale, editingitex, strings, selElems, started, newFO, showPanel, setAttr, cot, sec, buttons, contextTools; /*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var svgEditor, svgCanvas, $, importLocale, editingitex, strings, selElems, started, newFO, showPanel, setAttr, cot, sec, buttons, contextTools;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
sec = function sec(n) { sec = function _ref4(n) {
return 1 / Math.cos(n); return 1 / Math.cos(n);
}; };
cot = function cot(n) { cot = function _ref3(n) {
return 1 / Math.tan(n); return 1 / Math.tan(n);
}; };
setAttr = function setAttr(attr, val) { setAttr = function _ref2(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val); svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
}; };
showPanel = function showPanel(on) { showPanel = function _ref(on) {
var fcRules = $('#fc_rules'); var fcRules = $('#fc_rules');
if (!fcRules.length) { if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head'); fcRules = $('<style id="fc_rules"></style>').appendTo('head');
} }
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }'); fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#polygon_panel').toggle(on); $('#polygon_panel').toggle(on);
}; };
svgEditor = this; svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
importLocale = S.importLocale, editingitex = false; $ = S.$, importLocale = S.importLocale, editingitex = false;
_context.next = 10; _context.next = 9;
return importLocale(); return importLocale();
case 10: case 9:
strings = _context.sent; strings = _context.sent;
selElems = void 0, started = void 0, newFO = void 0;
// const ccZoom;
// const wEl, hEl;
// const wOffset, hOffset;
// const ccRBG;
// const ccOpacity;
// const brushW, brushH;
// const ccDebug = document.getElementById('debugpanel');
/* const properlySourceSizeTextArea = function(){
// TODO: remove magic numbers here and get values from CSS
const height = $('#svg_source_container').height() - 80;
$('#svg_source_textarea').css('height', height);
}; */
/*
function toggleSourceButtons(on){
$('#tool_source_save, #tool_source_cancel').toggle(!on);
$('#polygon_save, #polygon_cancel').toggle(on);
}
*/
/** /**
* Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3 * Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3
@ -110,6 +95,7 @@ var svgEditorExtension_polygon = (function () {
* @param {string} tex The itex text. * @param {string} tex The itex text.
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise. * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/ */
/* /*
function setItexString(tex) { function setItexString(tex) {
const mathns = 'http://www.w3.org/1998/Math/MathML', const mathns = 'http://www.w3.org/1998/Math/MathML',
@ -170,7 +156,7 @@ var svgEditorExtension_polygon = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg', svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
@ -179,123 +165,122 @@ var svgEditorExtension_polygon = (function () {
context_tools: strings.contextTools.map(function (contextTool, i) { context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool); return Object.assign(contextTools[i], contextTool);
}), }),
callback: function callback() { callback: function callback() {
$('#polygon_panel').hide(); $('#polygon_panel').hide();
// TODO: Needs to be done after orig icon loads
setTimeout(function () { setTimeout(function () {
// Create source save/cancel buttons // Create source save/cancel buttons
/* const save = */$('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
/* const save = */
$('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
if (!editingitex) { if (!editingitex) {
return; return;
} } // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint?
// }
// setSelectMode(); // setSelectMode();
}); });
/* const cancel = */
/* const cancel = */$('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () { $('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () {
}); });
}, 3000); }, 3000);
}, },
mouseDown: function mouseDown(opts) { mouseDown: function mouseDown(opts) {
// const e = opts.event; if (svgCanvas.getMode() !== 'polygon') {
var rgb = svgCanvas.getColor('fill'); return undefined;
// const ccRgbEl = rgb.substring(1, rgb.length); } // const e = opts.event;
var sRgb = svgCanvas.getColor('stroke');
// ccSRgbEl = sRgb.substring(1, rgb.length);
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(); var sWidth = svgCanvas.getStrokeWidth();
started = true;
if (svgCanvas.getMode() === 'polygon') { newFO = svgCanvas.addSVGElementFromJson({
started = true; element: 'polygon',
attr: {
newFO = svgCanvas.addSVGElementFromJson({ cx: opts.start_x,
element: 'polygon', cy: opts.start_y,
attr: { id: svgCanvas.getNextId(),
cx: opts.start_x, shape: 'regularPoly',
cy: opts.start_y, sides: document.getElementById('polySides').value,
id: svgCanvas.getNextId(), orient: 'x',
shape: 'regularPoly', edge: 0,
sides: document.getElementById('polySides').value, fill: rgb,
orient: 'x', strokecolor: sRgb,
edge: 0, strokeWidth: sWidth
fill: rgb, }
strokecolor: sRgb, });
strokeWidth: sWidth return {
} started: true
}); };
return {
started: true
};
}
}, },
mouseMove: function mouseMove(opts) { mouseMove: function mouseMove(opts) {
if (!started) { if (!started || svgCanvas.getMode() !== 'polygon') {
return; return undefined;
} } // const e = opts.event;
if (svgCanvas.getMode() === 'polygon') {
// 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.setAttributeNS(null, 'edge', edg);
var inradius = edg / 2 * cot(Math.PI / sides); var c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']);
var circumradius = inradius * sec(Math.PI / sides); var x = opts.mouse_x;
var points = ''; var y = opts.mouse_y;
for (var s = 0; sides >= s; s++) { var cx = c.cx,
var angle = 2.0 * Math.PI * s / sides; cy = c.cy,
x = circumradius * Math.cos(angle) + cx; fill = c.fill,
y = circumradius * Math.sin(angle) + cy; 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 = '';
points += x + ',' + y + ' '; 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');
// const poly = newFO.createElementNS(NS.SVG, 'polygon');
newFO.setAttributeNS(null, 'points', points); newFO.setAttribute('points', points);
newFO.setAttributeNS(null, 'fill', fill); newFO.setAttribute('fill', fill);
newFO.setAttributeNS(null, 'stroke', strokecolor); newFO.setAttribute('stroke', strokecolor);
newFO.setAttributeNS(null, 'stroke-width', strokeWidth); newFO.setAttribute('stroke-width', strokeWidth); // newFO.setAttribute('transform', 'rotate(-90)');
// newFO.setAttributeNS(null, 'transform', 'rotate(-90)'); // const shape = newFO.getAttribute('shape');
// const shape = newFO.getAttributeNS(null, 'shape'); // newFO.append(poly);
// newFO.append(poly); // DrawPoly(cx, cy, sides, edg, orient);
// DrawPoly(cx, cy, sides, edg, orient);
return { return {
started: true started: true
}; };
}
}, },
mouseUp: function mouseUp(opts) { mouseUp: function mouseUp(opts) {
if (svgCanvas.getMode() === 'polygon') { if (svgCanvas.getMode() !== 'polygon') {
var attrs = $(newFO).attr('edge'); return undefined;
var keep = attrs.edge !== '0';
// svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
} }
var attrs = $(newFO).attr('edge');
var keep = attrs.edge !== '0'; // svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
}, },
selectedChanged: function selectedChanged(opts) { selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements // Use this to update the current selected elements
selElems = opts.elems; selElems = opts.elems;
var i = selElems.length; var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elem.getAttributeNS(null, 'shape') === 'regularPoly') {
if (elem && elem.getAttribute('shape') === 'regularPoly') {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
$('#polySides').val(elem.getAttribute('sides')); $('#polySides').val(elem.getAttribute('sides'));
showPanel(true); showPanel(true);
} else { } else {
showPanel(false); showPanel(false);
@ -305,13 +290,11 @@ var svgEditorExtension_polygon = (function () {
} }
} }
}, },
elementChanged: function elementChanged(opts) { elementChanged: function elementChanged(opts) {}
// const elem = opts.elems[0];
}
}); });
case 15: case 13:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -319,7 +302,7 @@ var svgEditorExtension_polygon = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,80 @@
var svgEditorExtension_shapes = (function () { var svgEditorExtension_shapes = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
/* globals jQuery */
/** /**
* ext-shapes.js * ext-shapes.js
* *
@ -42,14 +86,15 @@ var svgEditorExtension_shapes = (function () {
var extShapes = { var extShapes = {
name: 'shapes', name: 'shapes',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var importLocale = _ref.importLocale; /*#__PURE__*/
var strings, svgEditor, $, canv, svgroot, lastBBox, categories, library, modeId, startClientPos, currentD, curShapeId, curShape, startX, startY, curLib, loadIcons, makeButtons, loadLibrary, buttons; regeneratorRuntime.mark(function _callee(_ref) {
var $, importLocale, strings, svgEditor, canv, svgroot, lastBBox, categories, library, modeId, startClientPos, currentD, curShapeId, curShape, startX, startY, curLib, loadIcons, makeButtons, loadLibrary, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
loadLibrary = function loadLibrary(catId) { loadLibrary = function _ref8(catId) {
var lib = library[catId]; var lib = library[catId];
if (!lib) { if (!lib) {
@ -65,61 +110,59 @@ var svgEditorExtension_shapes = (function () {
}); });
return; return;
} }
curLib = lib; curLib = lib;
if (!lib.buttons.length) { if (!lib.buttons.length) {
makeButtons(catId, lib); makeButtons(catId, lib);
} }
loadIcons(); loadIcons();
}; };
makeButtons = function makeButtons(cat, shapes) { makeButtons = function _ref7(cat, shapes) {
var size = curLib.size || 300; var size = curLib.size || 300;
var fill = curLib.fill || false; var fill = curLib.fill || false;
var off = size * 0.05; var off = size * 0.05;
var vb = [-off, -off, size + off * 2, size + off * 2].join(' '); var vb = [-off, -off, size + off * 2, size + off * 2].join(' ');
var stroke = fill ? 0 : size / 30; var stroke = fill ? 0 : size / 30;
var shapeIcon = new DOMParser().parseFromString('<svg xmlns="http://www.w3.org/2000/svg">' + '<svg viewBox="' + vb + '">' + '<path fill="' + (fill ? '#333' : 'none') + '" stroke="#000" stroke-width="' + stroke + '" /></svg></svg>', 'text/xml'); var shapeIcon = new DOMParser().parseFromString('<svg xmlns="http://www.w3.org/2000/svg">' + '<svg viewBox="' + vb + '">' + '<path fill="' + (fill ? '#333' : 'none') + '" stroke="#000" stroke-width="' + stroke + '" /></svg></svg>', 'text/xml');
var width = 24; var width = 24;
var height = 24; var height = 24;
shapeIcon.documentElement.setAttribute('width', width); shapeIcon.documentElement.setAttribute('width', width);
shapeIcon.documentElement.setAttribute('height', height); shapeIcon.documentElement.setAttribute('height', height);
var svgElem = $(document.importNode(shapeIcon.documentElement, true)); var svgElem = $(document.importNode(shapeIcon.documentElement, true));
var data = shapes.data; var data = shapes.data;
curLib.buttons = Object.entries(data).map(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
id = _ref3[0],
pathD = _ref3[1];
curLib.buttons = [];
for (var id in data) {
var pathD = data[id];
var icon = svgElem.clone(); var icon = svgElem.clone();
icon.find('path').attr('d', pathD); icon.find('path').attr('d', pathD);
var iconBtn = icon.wrap('<div class="tool_button">').parent().attr({ var iconBtn = icon.wrap('<div class="tool_button">').parent().attr({
id: modeId + '_' + id, id: modeId + '_' + id,
title: id title: id
}); }); // Store for later use
// Store for later use
curLib.buttons.push(iconBtn[0]); return iconBtn[0];
} });
}; };
loadIcons = function loadIcons() { loadIcons = function _ref6() {
$('#shape_buttons').empty().append(curLib.buttons); $('#shape_buttons').empty().append(curLib.buttons);
}; };
_context.next = 5; $ = _ref.$, importLocale = _ref.importLocale;
_context.next = 6;
return importLocale(); return importLocale();
case 5: case 6:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
$ = jQuery;
canv = svgEditor.canvas; canv = svgEditor.canvas;
svgroot = canv.getRootElem(); svgroot = canv.getRootElem();
lastBBox = {}; lastBBox = {}; // This populates the category list
// This populates the category list
categories = strings.categories; categories = strings.categories;
library = { library = {
@ -153,19 +196,23 @@ var svgEditorExtension_shapes = (function () {
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', 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', 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' 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: [] buttons: []
} }
}; };
modeId = 'shapelib'; modeId = 'shapelib';
startClientPos = {}; startClientPos = {};
currentD = void 0, curShapeId = void 0, curShape = void 0, startX = void 0, startY = void 0;
curLib = library.basic; curLib = library.basic;
/**
*
* @returns {undefined}
*/
buttons = [{ buttons = [{
id: 'tool_shapelib', id: 'tool_shapelib',
icon: svgEditor.curConfig.extIconsPath + 'shapes.png', icon: svgEditor.curConfig.extIconsPath + 'shapes.png',
type: 'mode_flyout', // _flyout type: 'mode_flyout',
// _flyout
position: 6, position: 6,
events: { events: {
click: function click() { click: function click() {
@ -173,22 +220,18 @@ var svgEditorExtension_shapes = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
svgicons: svgEditor.curConfig.extIconsPath + 'ext-shapes.xml', svgicons: svgEditor.curConfig.extIconsPath + 'ext-shapes.xml',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button); return Object.assign(buttons[i], button);
}), }),
callback: function callback() { callback: function callback() {
$('<style>').text('#shape_buttons {' + 'overflow: auto;' + 'width: 180px;' + 'max-height: 300px;' + 'display: table-cell;' + 'vertical-align: middle;' + '}' + '#shape_cats {' + 'min-width: 110px;' + 'display: table-cell;' + 'vertical-align: middle;' + 'height: 300px;' + '}' + '#shape_cats > div {' + 'line-height: 1em;' + 'padding: .5em;' + 'border:1px solid #B0B0B0;' + 'background: #E8E8E8;' + 'margin-bottom: -1px;' + '}' + '#shape_cats div:hover {' + 'background: #FFFFCC;' + '}' + '#shape_cats div.current {' + 'font-weight: bold;' + '}').appendTo('head'); $('<style>').text("\n #shape_buttons {\n overflow: auto;\n width: 180px;\n max-height: 300px;\n display: table-cell;\n vertical-align: middle;\n }\n #shape_cats {\n min-width: 110px;\n display: table-cell;\n vertical-align: middle;\n height: 300px;\n }\n #shape_cats > div {\n line-height: 1em;\n padding: .5em;\n border:1px solid #B0B0B0;\n background: #E8E8E8;\n margin-bottom: -1px;\n }\n #shape_cats div:hover {\n background: #FFFFCC;\n }\n #shape_cats div.current {\n font-weight: bold;\n }\n ").appendTo('head');
var btnDiv = $('<div id="shape_buttons">'); var btnDiv = $('<div id="shape_buttons">');
$('#tools_shapelib > *').wrapAll(btnDiv); $('#tools_shapelib > *').wrapAll(btnDiv);
var shower = $('#tools_shapelib_show'); var shower = $('#tools_shapelib_show');
loadLibrary('basic'); // Do mouseup on parent element rather than each button
loadLibrary('basic');
// Do mouseup on parent element rather than each button
$('#shape_buttons').mouseup(function (evt) { $('#shape_buttons').mouseup(function (evt) {
var btn = $(evt.target).closest('div.tool_button'); var btn = $(evt.target).closest('div.tool_button');
@ -201,55 +244,50 @@ var svgEditorExtension_shapes = (function () {
shower.append(copy).attr('data-curopt', '#' + btn[0].id) // This sets the current mode shower.append(copy).attr('data-curopt', '#' + btn[0].id) // This sets the current mode
.mouseup(); .mouseup();
canv.setMode(modeId); canv.setMode(modeId);
curShapeId = btn[0].id.substr((modeId + '_').length); curShapeId = btn[0].id.substr((modeId + '_').length);
currentD = curLib.data[curShapeId]; currentD = curLib.data[curShapeId];
$('.tools_flyout').fadeOut(); $('.tools_flyout').fadeOut();
}); });
var shapeCats = $('<div id="shape_cats">'); var shapeCats = $('<div id="shape_cats">');
var catStr = ''; var catStr = '';
$.each(categories, function (id, label) { $.each(categories, function (id, label) {
catStr += '<div data-cat=' + id + '>' + label + '</div>'; catStr += '<div data-cat=' + id + '>' + label + '</div>';
}); });
shapeCats.html(catStr).children().bind('mouseup', function () { shapeCats.html(catStr).children().bind('mouseup', function () {
var catlink = $(this); var catlink = $(this);
catlink.siblings().removeClass('current'); catlink.siblings().removeClass('current');
catlink.addClass('current'); catlink.addClass('current');
loadLibrary(catlink.attr('data-cat')); // Get stuff
loadLibrary(catlink.attr('data-cat'));
// Get stuff
return false; return false;
}); });
shapeCats.children().eq(0).addClass('current'); shapeCats.children().eq(0).addClass('current');
$('#tools_shapelib').append(shapeCats); $('#tools_shapelib').append(shapeCats);
shower.mouseup(function () { shower.mouseup(function () {
canv.setMode(currentD ? modeId : 'select'); canv.setMode(currentD ? modeId : 'select');
}); });
$('#tool_shapelib').remove(); $('#tool_shapelib').remove();
var h = $('#tools_shapelib').height(); var h = $('#tools_shapelib').height();
$('#tools_shapelib').css({ $('#tools_shapelib').css({
'margin-top': -(h / 2 - 15), 'margin-top': -(h / 2 - 15),
'margin-left': 3 'margin-left': 3
}); }); // Now add shape categories from locale
// Now add shape categories from locale
var cats = {}; var cats = {};
for (var o in categories) { Object.entries(categories).forEach(function (_ref4) {
cats['#shape_cats [data-cat="' + o + '"]'] = categories[o]; var _ref5 = _slicedToArray(_ref4, 2),
} o = _ref5[0],
categoryName = _ref5[1];
cats['#shape_cats [data-cat="' + o + '"]'] = categoryName;
});
this.setStrings('content', cats); this.setStrings('content', cats);
}, },
mouseDown: function mouseDown(opts) { mouseDown: function mouseDown(opts) {
var mode = canv.getMode(); var mode = canv.getMode();
if (mode !== modeId) { if (mode !== modeId) {
return; return undefined;
} }
startX = opts.start_x; startX = opts.start_x;
@ -257,10 +295,8 @@ var svgEditorExtension_shapes = (function () {
startY = opts.start_y; startY = opts.start_y;
var y = startY; var y = startY;
var curStyle = canv.getStyle(); var curStyle = canv.getStyle();
startClientPos.x = opts.event.clientX; startClientPos.x = opts.event.clientX;
startClientPos.y = opts.event.clientY; startClientPos.y = opts.event.clientY;
curShape = canv.addSVGElementFromJson({ curShape = canv.addSVGElementFromJson({
element: 'path', element: 'path',
curStyles: true, curStyles: true,
@ -270,43 +306,39 @@ var svgEditorExtension_shapes = (function () {
opacity: curStyle.opacity / 2, opacity: curStyle.opacity / 2,
style: 'pointer-events:none' style: 'pointer-events:none'
} }
}); }); // Make sure shape uses absolute values
// Make sure shape uses absolute values
if (/[a-z]/.test(currentD)) { if (/[a-z]/.test(currentD)) {
currentD = curLib.data[curShapeId] = canv.pathActions.convertPath(curShape); currentD = curLib.data[curShapeId] = canv.pathActions.convertPath(curShape);
curShape.setAttribute('d', currentD); curShape.setAttribute('d', currentD);
canv.pathActions.fixEnd(curShape); canv.pathActions.fixEnd(curShape);
} }
curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.005) translate(' + -x + ',' + -y + ')'); curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.005) translate(' + -x + ',' + -y + ')');
canv.recalculateDimensions(curShape); canv.recalculateDimensions(curShape);
/* const tlist = */
/* const tlist = */canv.getTransformList(curShape); canv.getTransformList(curShape);
lastBBox = curShape.getBBox(); lastBBox = curShape.getBBox();
return { return {
started: true started: true
}; };
}, },
mouseMove: function mouseMove(opts) { mouseMove: function mouseMove(opts) {
var mode = canv.getMode(); var mode = canv.getMode();
if (mode !== modeId) { if (mode !== modeId) {
return; return;
} }
var zoom = canv.getZoom(); var zoom = canv.getZoom();
var evt = opts.event; var evt = opts.event;
var x = opts.mouse_x / zoom; var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom; var y = opts.mouse_y / zoom;
var tlist = canv.getTransformList(curShape), var tlist = canv.getTransformList(curShape),
box = curShape.getBBox(), box = curShape.getBBox(),
left = box.x, left = box.x,
top = box.y; top = box.y; // {width, height} = box,
// {width, height} = box,
// const dx = (x - startX), dy = (y - startY); // const dx = (x - startX), dy = (y - startY);
var newbox = { var newbox = {
@ -315,7 +347,6 @@ var svgEditorExtension_shapes = (function () {
width: Math.abs(x - startX), width: Math.abs(x - startX),
height: Math.abs(y - startY) height: Math.abs(y - startY)
}; };
/* /*
// This is currently serving no purpose, so commenting out // This is currently serving no purpose, so commenting out
let sy = height ? (height + dy) / height : 1, let sy = height ? (height + dy) / height : 1,
@ -323,49 +354,48 @@ var svgEditorExtension_shapes = (function () {
*/ */
var sx = newbox.width / lastBBox.width || 1; var sx = newbox.width / lastBBox.width || 1;
var sy = newbox.height / lastBBox.height || 1; var sy = newbox.height / lastBBox.height || 1; // Not perfect, but mostly works...
// Not perfect, but mostly works...
var tx = 0; var tx = 0;
if (x < startX) { if (x < startX) {
tx = lastBBox.width; tx = lastBBox.width;
} }
var ty = 0; var ty = 0;
if (y < startY) { if (y < startY) {
ty = lastBBox.height; ty = lastBBox.height;
} } // update the transform list with translate,scale,translate
// update the transform list with translate,scale,translate
var translateOrigin = svgroot.createSVGTransform(), var translateOrigin = svgroot.createSVGTransform(),
scale = svgroot.createSVGTransform(), scale = svgroot.createSVGTransform(),
translateBack = svgroot.createSVGTransform(); translateBack = svgroot.createSVGTransform();
translateOrigin.setTranslate(-(left + tx), -(top + ty)); translateOrigin.setTranslate(-(left + tx), -(top + ty));
if (!evt.shiftKey) { if (!evt.shiftKey) {
var max = Math.min(Math.abs(sx), Math.abs(sy)); var max = Math.min(Math.abs(sx), Math.abs(sy));
sx = max * (sx < 0 ? -1 : 1); sx = max * (sx < 0 ? -1 : 1);
sy = max * (sy < 0 ? -1 : 1); sy = max * (sy < 0 ? -1 : 1);
} }
scale.setScale(sx, sy);
scale.setScale(sx, sy);
translateBack.setTranslate(left + tx, top + ty); translateBack.setTranslate(left + tx, top + ty);
tlist.appendItem(translateBack); tlist.appendItem(translateBack);
tlist.appendItem(scale); tlist.appendItem(scale);
tlist.appendItem(translateOrigin); tlist.appendItem(translateOrigin);
canv.recalculateDimensions(curShape); canv.recalculateDimensions(curShape);
lastBBox = curShape.getBBox(); lastBBox = curShape.getBBox();
}, },
mouseUp: function mouseUp(opts) { mouseUp: function mouseUp(opts) {
var mode = canv.getMode(); var mode = canv.getMode();
if (mode !== modeId) { if (mode !== modeId) {
return; return undefined;
} }
var keepObject = opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y; var keepObject = opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y;
return { return {
keep: keepObject, keep: keepObject,
element: curShape, element: curShape,
@ -374,8 +404,8 @@ var svgEditorExtension_shapes = (function () {
} }
}); });
case 19: case 18:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -383,7 +413,7 @@ var svgEditorExtension_shapes = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,42 @@
var svgEditorExtension_star = (function () { var svgEditorExtension_star = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/* globals jQuery */
/** /**
* ext-star.js * ext-star.js
* *
@ -41,44 +47,40 @@ var svgEditorExtension_star = (function () {
var extStar = { var extStar = {
name: 'star', name: 'star',
init: function () { init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) { var _init = _asyncToGenerator(
var svgEditor, $, svgCanvas, importLocale, selElems, started, newFO, strings, showPanel, setAttr, buttons, contextTools; /*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var svgEditor, svgCanvas, $, importLocale, selElems, started, newFO, strings, showPanel, setAttr, buttons, contextTools;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
setAttr = function setAttr(attr, val) { setAttr = function _ref2(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val); svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
}; };
showPanel = function showPanel(on) { showPanel = function _ref(on) {
var fcRules = $('#fc_rules'); var fcRules = $('#fc_rules');
if (!fcRules.length) { if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head'); fcRules = $('<style id="fc_rules"></style>').appendTo('head');
} }
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }'); fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#star_panel').toggle(on); $('#star_panel').toggle(on);
}; };
svgEditor = this; svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
importLocale = S.importLocale; // {svgcontent}, $ = S.$, importLocale = S.importLocale; // {svgcontent},
selElems = void 0, started = void 0, newFO = void 0; _context.next = 7;
// edg = 0,
// newFOG, newFOGParent, newDef, newImageName, newMaskID,
// undoCommand = 'Not image',
// modeChangeG, ccZoom, wEl, hEl, wOffset, hOffset, ccRgbEl, brushW, brushH;
_context.next = 9;
return importLocale(); return importLocale();
case 9: case 7:
strings = _context.sent; strings = _context.sent;
/* /*
function cot(n){ function cot(n){
return 1 / Math.tan(n); return 1 / Math.tan(n);
@ -128,7 +130,7 @@ var svgEditorExtension_star = (function () {
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'star-icons.svg', svgicons: svgEditor.curConfig.extIconsPath + 'star-icons.svg',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
@ -138,19 +140,17 @@ var svgEditorExtension_star = (function () {
return Object.assign(contextTools[i], contextTool); return Object.assign(contextTools[i], contextTool);
}), }),
callback: function callback() { callback: function callback() {
$('#star_panel').hide(); $('#star_panel').hide(); // const endChanges = function(){};
// const endChanges = function(){};
}, },
mouseDown: function mouseDown(opts) { mouseDown: function mouseDown(opts) {
var rgb = svgCanvas.getColor('fill'); var rgb = svgCanvas.getColor('fill'); // const ccRgbEl = rgb.substring(1, rgb.length);
// const ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke'); var sRgb = svgCanvas.getColor('stroke'); // const ccSRgbEl = sRgb.substring(1, rgb.length);
// const ccSRgbEl = sRgb.substring(1, rgb.length);
var sWidth = svgCanvas.getStrokeWidth(); var sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() === 'star') { if (svgCanvas.getMode() === 'star') {
started = true; started = true;
newFO = svgCanvas.addSVGElementFromJson({ newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon', element: 'polygon',
attr: { attr: {
@ -172,14 +172,16 @@ var svgEditorExtension_star = (function () {
started: true started: true
}; };
} }
return undefined;
}, },
mouseMove: function mouseMove(opts) { mouseMove: function mouseMove(opts) {
if (!started) { if (!started) {
return; return undefined;
} }
if (svgCanvas.getMode() === 'star') { if (svgCanvas.getMode() === 'star') {
var c = $(newFO).attr(['cx', 'cy', 'point', 'orient', 'fill', 'strokecolor', 'strokeWidth', 'radialshift']); var c = $(newFO).attr(['cx', 'cy', 'point', 'orient', 'fill', 'strokecolor', 'strokeWidth', 'radialshift']);
var x = opts.mouse_x; var x = opts.mouse_x;
var y = opts.mouse_y; var y = opts.mouse_y;
var cx = c.cx, var cx = c.cx,
@ -192,13 +194,13 @@ var svgEditorExtension_star = (function () {
orient = c.orient, orient = c.orient,
circumradius = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5, circumradius = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5,
inradius = circumradius / document.getElementById('starRadiusMulitplier').value; inradius = circumradius / document.getElementById('starRadiusMulitplier').value;
newFO.setAttribute('r', circumradius);
newFO.setAttributeNS(null, 'r', circumradius); newFO.setAttribute('r2', inradius);
newFO.setAttributeNS(null, 'r2', inradius);
var polyPoints = ''; var polyPoints = '';
for (var s = 0; point >= s; s++) { for (var s = 0; point >= s; s++) {
var angle = 2.0 * Math.PI * (s / point); var angle = 2.0 * Math.PI * (s / point);
if (orient === 'point') { if (orient === 'point') {
angle -= Math.PI / 2; angle -= Math.PI / 2;
} else if (orient === 'edge') { } else if (orient === 'edge') {
@ -207,53 +209,59 @@ var svgEditorExtension_star = (function () {
x = circumradius * Math.cos(angle) + cx; x = circumradius * Math.cos(angle) + cx;
y = circumradius * Math.sin(angle) + cy; y = circumradius * Math.sin(angle) + cy;
polyPoints += x + ',' + y + ' '; polyPoints += x + ',' + y + ' ';
if (inradius != null) { if (!isNaN(inradius)) {
angle = 2.0 * Math.PI * (s / point) + Math.PI / point; angle = 2.0 * Math.PI * (s / point) + Math.PI / point;
if (orient === 'point') { if (orient === 'point') {
angle -= Math.PI / 2; angle -= Math.PI / 2;
} else if (orient === 'edge') { } else if (orient === 'edge') {
angle = angle + Math.PI / point - Math.PI / 2; angle = angle + Math.PI / point - Math.PI / 2;
} }
angle += radialshift;
angle += radialshift;
x = inradius * Math.cos(angle) + cx; x = inradius * Math.cos(angle) + cx;
y = inradius * Math.sin(angle) + cy; y = inradius * Math.sin(angle) + cy;
polyPoints += x + ',' + y + ' '; polyPoints += x + ',' + y + ' ';
} }
} }
newFO.setAttributeNS(null, 'points', polyPoints);
newFO.setAttributeNS(null, 'fill', fill);
newFO.setAttributeNS(null, 'stroke', strokecolor);
newFO.setAttributeNS(null, 'stroke-width', strokeWidth);
/* const shape = */newFO.getAttributeNS(null, 'shape');
newFO.setAttribute('points', polyPoints);
newFO.setAttribute('fill', fill);
newFO.setAttribute('stroke', strokecolor);
newFO.setAttribute('stroke-width', strokeWidth);
/* const shape = */
newFO.getAttribute('shape');
return { return {
started: true started: true
}; };
} }
return undefined;
}, },
mouseUp: function mouseUp() { mouseUp: function mouseUp() {
if (svgCanvas.getMode() === 'star') { if (svgCanvas.getMode() === 'star') {
var attrs = $(newFO).attr(['r']); var attrs = $(newFO).attr(['r']); // svgCanvas.addToSelection([newFO], true);
// svgCanvas.addToSelection([newFO], true);
return { return {
keep: attrs.r !== '0', keep: attrs.r !== '0',
element: newFO element: newFO
}; };
} }
return undefined;
}, },
selectedChanged: function selectedChanged(opts) { selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements // Use this to update the current selected elements
selElems = opts.elems; selElems = opts.elems;
var i = selElems.length; var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elem.getAttributeNS(null, 'shape') === 'star') {
if (elem && elem.getAttribute('shape') === 'star') {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
// $('#starRadiusMulitplier').val(elem.getAttribute('r2')); // $('#starRadiusMulitplier').val(elem.getAttribute('r2'));
$('#starNumPoints').val(elem.getAttribute('point')); $('#starNumPoints').val(elem.getAttribute('point'));
@ -267,13 +275,11 @@ var svgEditorExtension_star = (function () {
} }
} }
}, },
elementChanged: function elementChanged(opts) { elementChanged: function elementChanged(opts) {}
// const elem = opts.elems[0];
}
}); });
case 13: case 11:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -281,7 +287,7 @@ var svgEditorExtension_star = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,36 +1,80 @@
var svgEditorExtension_storage = (function () { var svgEditorExtension_storage = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
/* globals jQuery */
/** /**
* ext-storage.js * ext-storage.js
* *
@ -55,26 +99,31 @@ var svgEditorExtension_storage = (function () {
*/ */
var extStorage = { var extStorage = {
name: 'storage', name: 'storage',
init: function init() { init: function init(_ref) {
var $ = _ref.$;
var svgEditor = this; var svgEditor = this;
var $ = jQuery; var svgCanvas = svgEditor.canvas; // We could empty any already-set data for users when they decline storage,
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 // 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; // said "no"; instead, we'll let those who already set it, delete it themselves;
// to change, set the "emptyStorageOnDecline" config setting to true // to change, set the "emptyStorageOnDecline" config setting to true
// in svgedit-config-iife.js/svgedit-config-es.js. // in svgedit-config-iife.js/svgedit-config-es.js.
var _svgEditor$curConfig = svgEditor.curConfig, var _svgEditor$curConfig = svgEditor.curConfig,
emptyStorageOnDecline = _svgEditor$curConfig.emptyStorageOnDecline, emptyStorageOnDecline = _svgEditor$curConfig.emptyStorageOnDecline,
noStorageOnLoad = _svgEditor$curConfig.noStorageOnLoad, noStorageOnLoad = _svgEditor$curConfig.noStorageOnLoad,
forceStorage = _svgEditor$curConfig.forceStorage; forceStorage = _svgEditor$curConfig.forceStorage;
var storage = svgEditor.storage; var storage = svgEditor.storage,
updateCanvas = svgEditor.updateCanvas;
/**
* Replace `storagePrompt` parameter within URL.
* @param {string} val
* @returns {undefined}
*/
function replaceStoragePrompt(val) { function replaceStoragePrompt(val) {
val = val ? 'storagePrompt=' + val : ''; val = val ? 'storagePrompt=' + val : '';
var loc = top.location; // Allow this to work with the embedded editor as well var loc = top.location; // Allow this to work with the embedded editor as well
if (loc.href.includes('storagePrompt=')) { if (loc.href.includes('storagePrompt=')) {
loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) { loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
return (val ? n1 : '') + val + (!val && amp ? n1 : amp || ''); return (val ? n1 : '') + val + (!val && amp ? n1 : amp || '');
@ -83,9 +132,18 @@ var svgEditorExtension_storage = (function () {
loc.href += (loc.href.includes('?') ? '&' : '?') + val; 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 {undefined}
*/
function setSVGContentStorage(val) { function setSVGContentStorage(val) {
if (storage) { if (storage) {
var name = 'svgedit-' + svgEditor.curConfig.canvasName; var name = 'svgedit-' + svgEditor.curConfig.canvasName;
if (!val) { if (!val) {
storage.removeItem(name); storage.removeItem(name);
} else { } else {
@ -93,29 +151,43 @@ var svgEditorExtension_storage = (function () {
} }
} }
} }
/**
* Set the cookie to expire.
* @param {string} cookie
* @returns {undefined}
*/
function expireCookie(cookie) { function expireCookie(cookie) {
document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT'; document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
} }
/**
* Expire the storage cookie.
* @returns {undefined}
*/
function removeStoragePrefCookie() { function removeStoragePrefCookie() {
expireCookie('store'); expireCookie('svgeditstore');
} }
/**
* Empties storage for each of the current preferences.
* @returns {undefined}
*/
function emptyStorage() { function emptyStorage() {
setSVGContentStorage(''); setSVGContentStorage('');
for (var name in svgEditor.curPrefs) { Object.keys(svgEditor.curPrefs).forEach(function (name) {
if (svgEditor.curPrefs.hasOwnProperty(name)) { name = 'svg-edit-' + name;
name = 'svg-edit-' + name;
if (storage) {
storage.removeItem(name);
}
expireCookie(name);
}
}
}
// emptyStorage(); if (storage) {
storage.removeItem(name);
}
expireCookie(name);
});
} // emptyStorage();
/** /**
* Listen for unloading: If and only if opted in by the user, set the content * Listen for unloading: If and only if opted in by the user, set the content
@ -124,175 +196,219 @@ var svgEditorExtension_storage = (function () {
* content into storage) * content into storage)
* 2. Use localStorage to set SVG contents (potentially too large to allow in cookies) * 2. Use localStorage to set SVG contents (potentially too large to allow in cookies)
* 3. Use localStorage (where available) or cookies to set preferences. * 3. Use localStorage (where available) or cookies to set preferences.
* @returns {undefined}
*/ */
function setupBeforeUnloadListener() { function setupBeforeUnloadListener() {
window.addEventListener('beforeunload', function (e) { window.addEventListener('beforeunload', function (e) {
// Don't save anything unless the user opted in to storage // Don't save anything unless the user opted in to storage
if (!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)) { if (!document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/)) {
return; return;
} }
if (document.cookie.match(/(?:^|;\s*)store=prefsAndContent/)) {
if (document.cookie.match(/(?:^|;\s*)svgeditstore=prefsAndContent/)) {
setSVGContentStorage(svgCanvas.getSvgString()); setSVGContentStorage(svgCanvas.getSvgString());
} }
svgEditor.setConfig({ no_save_warning: true }); // No need for explicit saving at all once storage is on svgEditor.setConfig({
no_save_warning: true
}); // No need for explicit saving at all once storage is on
// svgEditor.showSaveWarning = false; // svgEditor.showSaveWarning = false;
var curPrefs = svgEditor.curPrefs; 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;
for (var key in curPrefs) { if (!store) {
if (curPrefs.hasOwnProperty(key)) { return;
// It's our own config, so we don't need to iterate up the prototype chain
var val = curPrefs[key];
var store = val !== undefined;
key = 'svg-edit-' + key;
if (!store) {
continue;
}
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';
}
} }
}
}, false); 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; var loaded = false;
return { return {
name: 'storage', name: 'storage',
langReady: function () { langReady: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _langReady = _asyncToGenerator(
var importLocale = _ref.importLocale; /*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref4) {
var _$$deparam$querystrin, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight; var importLocale, _$$deparam$querystrin, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight, _ref5, pref, checked;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
importLocale = _ref4.importLocale;
_$$deparam$querystrin = $.deparam.querystring(true), storagePrompt = _$$deparam$querystrin.storagePrompt; _$$deparam$querystrin = $.deparam.querystring(true), storagePrompt = _$$deparam$querystrin.storagePrompt;
_context.next = 3; _context.next = 4;
return importLocale(); return importLocale();
case 3: case 4:
confirmSetStorage = _context.sent; confirmSetStorage = _context.sent;
message = confirmSetStorage.message, storagePrefsAndContent = confirmSetStorage.storagePrefsAndContent, storagePrefsOnly = confirmSetStorage.storagePrefsOnly, storagePrefs = confirmSetStorage.storagePrefs, storageNoPrefsOrContent = confirmSetStorage.storageNoPrefsOrContent, storageNoPrefs = confirmSetStorage.storageNoPrefs, rememberLabel = confirmSetStorage.rememberLabel, rememberTooltip = confirmSetStorage.rememberTooltip; 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
// No need to run this one-time dialog again just because the user
// changes the language // changes the language
if (!loaded) { if (!loaded) {
_context.next = 7; _context.next = 8;
break; break;
} }
return _context.abrupt('return'); return _context.abrupt("return");
case 7: case 8:
loaded = true; loaded = true; // Note that the following can load even if "noStorageOnLoad" is
// Note that the following can load even if "noStorageOnLoad" is
// set to false; to avoid any chance of storage, avoid this // set to false; to avoid any chance of storage, avoid this
// extension! (and to avoid using any prior storage, set the // extension! (and to avoid using any prior storage, set the
// config option "noStorageOnLoad" to true). // config option "noStorageOnLoad" to true).
if (!forceStorage && (
// If the URL has been explicitly set to always prompt the if (!(!forceStorage && ( // If the URL has been explicitly set to always prompt the
// user (e.g., so one can be pointed to a URL where one // user (e.g., so one can be pointed to a URL where one
// can alter one's settings, say to prevent future storage)... // can alter one's settings, say to prevent future storage)...
storagePrompt === true || storagePrompt === true || // ...or...if the URL at least doesn't explicitly prevent a
// ...or...if the URL at least doesn't explicitly prevent a
// storage prompt (as we use for users who // storage prompt (as we use for users who
// don't want to set cookies at all but who don't want // don't want to set cookies at all but who don't want
// continual prompts about it)... // continual prompts about it)...
storagePrompt !== false && storagePrompt !== false && // ...and this user hasn't previously indicated a desire for storage
// ...and this user hasn't previously indicated a desire for storage !document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/) // ...then show the storage prompt.
!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/) ))) {
// ...then show the storage prompt. _context.next = 44;
)) { break;
options = []; }
if (storage) { options = [];
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 if (storage) {
oldContainerWidth = $('#dialog_container')[0].style.width, oldContainerMarginLeft = $('#dialog_container')[0].style.marginLeft, oldContentHeight = $('#dialog_content')[0].style.height, oldContainerHeight = $('#dialog_container')[0].style.height; options.unshift({
value: 'prefsAndContent',
$('#dialog_content')[0].style.height = '120px'; text: storagePrefsAndContent
$('#dialog_container')[0].style.height = '170px'; }, {
$('#dialog_container')[0].style.width = '800px'; value: 'prefsOnly',
$('#dialog_container')[0].style.marginLeft = '-400px'; text: storagePrefsOnly
}, {
// Open select-with-checkbox dialog value: 'noPrefsOrContent',
// From svg-editor.js text: storageNoPrefsOrContent
$.select(message, options, function (pref, checked) {
if (pref && pref !== 'noPrefsOrContent') {
// 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 = 'store=' + 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) {
replaceStoragePrompt();
return;
}
} else {
// 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) {
// Open a URL which won't set storage and won't prompt user about storage
replaceStoragePrompt('false');
return;
}
}
// 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.storagePromptClosed = true;
}, null, null, {
label: rememberLabel,
checked: false,
tooltip: rememberTooltip
}); });
} else if (!noStorageOnLoad || forceStorage) { } 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:
_ref5 = _context.sent;
pref = _ref5.response;
checked = _ref5.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(); setupBeforeUnloadListener();
} }
case 9: case 45:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -300,7 +416,7 @@ var svgEditorExtension_storage = (function () {
})); }));
function langReady(_x) { function langReady(_x) {
return _ref2.apply(this, arguments); return _langReady.apply(this, arguments);
} }
return langReady; return langReady;

View File

@ -1,34 +1,41 @@
var svgEditorExtension_webappfind = (function () { var svgEditorExtension_webappfind = (function () {
'use strict'; 'use strict';
var asyncToGenerator = function (fn) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
return function () { try {
var gen = fn.apply(this, arguments); var info = gen[key](arg);
return new Promise(function (resolve, reject) { var value = info.value;
function step(key, arg) { } catch (error) {
try { reject(error);
var info = gen[key](arg); return;
var value = info.value; }
} catch (error) {
reject(error);
return;
}
if (info.done) { if (info.done) {
resolve(value); resolve(value);
} else { } else {
return Promise.resolve(value).then(function (value) { Promise.resolve(value).then(_next, _throw);
step("next", value); }
}, function (err) { }
step("throw", err);
}); 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);
} }
return step("next"); function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
}); });
}; };
}; }
/** /**
* Depends on Firefox add-on and executables from {@link https://github.com/brettz9/webappfind} * Depends on Firefox add-on and executables from {@link https://github.com/brettz9/webappfind}
@ -36,26 +43,25 @@ var svgEditorExtension_webappfind = (function () {
* @license MIT * @license MIT
* @todo See WebAppFind Readme for SVG-related todos * @todo See WebAppFind Readme for SVG-related todos
*/ */
var extWebappfind = { var extWebappfind = {
name: 'webappfind', name: 'webappfind',
init: function () { init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) { var _init = _asyncToGenerator(
var importLocale = _ref.importLocale; /*#__PURE__*/
var strings, svgEditor, saveMessage, readMessage, excludedMessages, pathID, buttons; regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, $, strings, svgEditor, saveMessage, readMessage, excludedMessages, pathID, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
_context.next = 2; importLocale = _ref.importLocale, $ = _ref.$;
_context.next = 3;
return importLocale(); return importLocale();
case 2: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
saveMessage = 'save', readMessage = 'read', excludedMessages = [readMessage, saveMessage]; saveMessage = 'save', readMessage = 'read', excludedMessages = [readMessage, saveMessage];
pathID = void 0;
this.canvas.bind('message', this.canvas.bind('message',
/** /**
* @param {external:Window} win * @param {external:Window} win
@ -64,19 +70,20 @@ var svgEditorExtension_webappfind = (function () {
* @throws {Error} Unexpected event type * @throws {Error} Unexpected event type
* @returns {undefined} * @returns {undefined}
*/ */
function (win, _ref3) { function (win, _ref2) {
var data = _ref3.data, var data = _ref2.data,
origin = _ref3.origin; origin = _ref2.origin;
// eslint-disable-line no-shadow
// console.log('data, origin', data, origin); // console.log('data, origin', data, origin);
var type = void 0, var type, content;
content = void 0;
try { try {
// May throw if data is not an object
var _data$webappfind = data.webappfind; var _data$webappfind = data.webappfind;
type = _data$webappfind.type; type = _data$webappfind.type;
pathID = _data$webappfind.pathID; pathID = _data$webappfind.pathID;
content = _data$webappfind.content; content = _data$webappfind.content;
// May throw if data is not an object
if (origin !== location.origin || // We are only interested in a message sent as though within this URL by our browser add-on if (origin !== location.origin || // We are only interested in a message sent as though within this URL by our browser add-on
excludedMessages.includes(type) // Avoid our post below (other messages might be possible in the future which may also need to be excluded if your subsequent code makes assumptions on the type of message this is) excludedMessages.includes(type) // Avoid our post below (other messages might be possible in the future which may also need to be excluded if your subsequent code makes assumptions on the type of message this is)
) { ) {
@ -90,19 +97,20 @@ var svgEditorExtension_webappfind = (function () {
case 'view': case 'view':
// Populate the contents // Populate the contents
svgEditor.loadFromString(content); svgEditor.loadFromString(content);
/* if ($('#tool_save_file')) { /* if ($('#tool_save_file')) {
$('#tool_save_file').disabled = false; $('#tool_save_file').disabled = false;
} */ } */
break; break;
case 'save-end': case 'save-end':
alert('save complete for pathID ' + pathID + '!'); $.alert("save complete for pathID ".concat(pathID, "!"));
break; break;
default: default:
throw new Error('Unexpected WebAppFind event type'); throw new Error('Unexpected WebAppFind event type');
} }
}); });
/* /*
window.postMessage({ window.postMessage({
webappfind: { webappfind: {
@ -115,31 +123,34 @@ var svgEditorExtension_webappfind = (function () {
: window.location.origin : window.location.origin
); );
*/ */
buttons = [{ buttons = [{
id: 'webappfind_save', // id: 'webappfind_save',
//
icon: svgEditor.curConfig.extIconsPath + 'webappfind.png', icon: svgEditor.curConfig.extIconsPath + 'webappfind.png',
type: 'app_menu', type: 'app_menu',
position: 4, // Before 0-based index position 4 (after the regular "Save Image (S)") position: 4,
// Before 0-based index position 4 (after the regular "Save Image (S)")
events: { events: {
click: function click() { click: function click() {
if (!pathID) { if (!pathID) {
// Not ready yet as haven't received first payload // Not ready yet as haven't received first payload
return; return;
} }
window.postMessage({ window.postMessage({
webappfind: { webappfind: {
type: saveMessage, type: saveMessage,
pathID: pathID, pathID: pathID,
content: svgEditor.canvas.getSvgString() content: svgEditor.canvas.getSvgString()
} }
}, window.location.origin === 'null' }, window.location.origin === 'null' // Avoid "null" string error for `file:` protocol (even
// Avoid "null" string error for `file:` protocol (even
// though file protocol not currently supported by add-on) // though file protocol not currently supported by add-on)
? '*' : window.location.origin); ? '*' : window.location.origin);
} }
} }
}]; }];
return _context.abrupt('return', { return _context.abrupt("return", {
name: strings.name, name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'webappfind-icon.svg', svgicons: svgEditor.curConfig.extIconsPath + 'webappfind-icon.svg',
buttons: strings.buttons.map(function (button, i) { buttons: strings.buttons.map(function (button, i) {
@ -148,7 +159,7 @@ var svgEditorExtension_webappfind = (function () {
}); });
case 9: case 9:
case 'end': case "end":
return _context.stop(); return _context.stop();
} }
} }
@ -156,7 +167,7 @@ var svgEditorExtension_webappfind = (function () {
})); }));
function init(_x) { function init(_x) {
return _ref2.apply(this, arguments); return _init.apply(this, arguments);
} }
return init; return init;

View File

@ -1,11 +1,39 @@
var svgEditorExtension_xdomain_messaging = (function () { var svgEditorExtension_xdomain_messaging = (function () {
'use strict'; 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { function _typeof(obj) {
return typeof obj; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
} : function (obj) { _typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof 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) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
/** /**
* Should not be needed for same domain control (just call via child frame), * Should not be needed for same domain control (just call via child frame),
@ -17,42 +45,51 @@ var svgEditorExtension_xdomain_messaging = (function () {
init: function init() { init: function init() {
var svgEditor = this; var svgEditor = this;
var svgCanvas = svgEditor.canvas; var svgCanvas = svgEditor.canvas;
try { try {
window.addEventListener('message', function (e) { window.addEventListener('message', function (e) {
// We accept and post strings for the sake of IE9 support // We accept and post strings for the sake of IE9 support
if (typeof e.data !== 'string' || e.data.charAt() === '|') { if (!e.data || !['string', 'object'].includes(_typeof(e.data)) || e.data.charAt() === '|') {
return; return;
} }
var data = JSON.parse(e.data);
if (!data || (typeof data === 'undefined' ? 'undefined' : _typeof(data)) !== 'object' || data.namespace !== 'svgCanvas') { var data = _typeof(e.data) === 'object' ? e.data : JSON.parse(e.data);
if (!data || _typeof(data) !== 'object' || data.namespace !== 'svgCanvas') {
return; return;
} } // The default is not to allow any origins, including even the same domain or
// 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
// if run on a file:// URL See svgedit-config-es.js for an example of how
// to configure // to configure
var allowedOrigins = svgEditor.curConfig.allowedOrigins; var allowedOrigins = svgEditor.curConfig.allowedOrigins;
if (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) { if (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) {
console.log('Origin ' + e.origin + ' not whitelisted for posting to ' + window.origin); console.log("Origin ".concat(e.origin, " not whitelisted for posting to ").concat(window.origin)); // eslint-disable-line no-console
return; return;
} }
var cbid = data.id; var cbid = data.id;
var name = data.name, var name = data.name,
args = data.args; args = data.args;
var message = { var message = {
namespace: 'svg-edit', namespace: 'svg-edit',
id: cbid id: cbid
}; };
try { try {
message.result = svgCanvas[name].apply(svgCanvas, args); // 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) { } catch (err) {
message.error = err.message; message.error = err.message;
} }
e.source.postMessage(JSON.stringify(message), '*'); e.source.postMessage(JSON.stringify(message), '*');
}, false); });
} catch (err) { } catch (err) {
console.log('Error with xdomain message listener: ' + err); console.log('Error with xdomain message listener: ' + err); // eslint-disable-line no-console
} }
} }
}; };

View File

@ -1,66 +1,83 @@
(function () { (function () {
'use strict'; 'use strict';
var _extends = Object.assign || function (target) { function _extends() {
for (var i = 1; i < arguments.length; i++) { _extends = Object.assign || function (target) {
var source = arguments[i]; for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) { for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) { if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key]; target[key] = source[key];
}
} }
} }
}
return target; return target;
}; };
return _extends.apply(this, arguments);
}
/* globals jQuery */ /* globals jQuery */
var $ = jQuery; var $ = jQuery;
$('a').click(function () { $('a').click(function () {
var href = this.href; var href = this.href;
var target = window.parent; var target = window.parent;
var post = function post(message) { var post = function post(message) {
// Todo: Make origin customizable as set by opening window // Todo: Make origin customizable as set by opening window
// Todo: If dropping IE9, avoid stringifying // Todo: If dropping IE9, avoid stringifying
target.postMessage(JSON.stringify(_extends({ target.postMessage(JSON.stringify(_extends({
namespace: 'imagelib' namespace: 'imagelib'
}, message)), '*'); }, message)), '*');
}; }; // Convert Non-SVG images to data URL first
// Convert Non-SVG images to data URL first
// (this could also have been done server-side by the library) // (this could also have been done server-side by the library)
// Send metadata (also indicates file is about to be sent) // Send metadata (also indicates file is about to be sent)
post({ post({
name: $(this).text(), name: $(this).text(),
id: href id: href
}); });
if (!this.href.includes('.svg')) {
if (!href.includes('.svg')) {
var img = new Image(); var img = new Image();
img.onload = function () { img.addEventListener('load', function () {
var canvas = document.createElement('canvas'); var canvas = document.createElement('canvas');
canvas.width = this.width; canvas.width = this.width;
canvas.height = this.height; canvas.height = this.height; // load the raster image into the canvas
// load the raster image into the canvas
canvas.getContext('2d').drawImage(this, 0, 0); canvas.getContext('2d').drawImage(this, 0, 0); // retrieve the data: URL
// retrieve the data: URL
var data = void 0; var data;
try { try {
data = canvas.toDataURL(); data = canvas.toDataURL();
} catch (err) { } catch (err) {
// This fails in Firefox with file:// URLs :( // This fails in Firefox with `file:///` URLs :(
alert('Data URL conversion failed: ' + err); // Todo: This could use a generic alert library instead
alert('Data URL conversion failed: ' + err); // eslint-disable-line no-alert
data = ''; data = '';
} }
post({ href: href, data: data });
}; post({
href: href,
data: data
});
});
img.src = href; img.src = href;
} else { } else {
// Do ajax request for image's href value // Do ajax request for image's href value
$.get(href, function (data) { $.get(href, function (data) {
post({ href: href, data: data }); post({
href: href,
data: data
});
}, 'html'); // 'html' is necessary to keep returned data as a string }, 'html'); // 'html' is necessary to keep returned data as a string
} }
return false; return false;
}); });

3352
dist/extensions/imagelib/openclipart.js vendored Normal file

File diff suppressed because it is too large Load Diff

21731
dist/index-es.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

21737
dist/index-umd.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,77 +1,85 @@
(function () { (function () {
'use strict'; 'use strict';
var classCallCheck = function (instance, Constructor) { function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) { if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function"); throw new TypeError("Cannot call a class as a function");
} }
}; }
var createClass = function () { function _defineProperties(target, props) {
function defineProperties(target, props) { for (var i = 0; i < props.length; i++) {
for (var i = 0; i < props.length; i++) { var descriptor = props[i];
var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false;
descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true;
descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true;
if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor);
Object.defineProperty(target, descriptor.key, descriptor);
}
} }
}
return function (Constructor, protoProps, staticProps) { function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps); if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps); if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor; return Constructor;
}; }
}();
var slicedToArray = function () { function _slicedToArray(arr, i) {
function sliceIterator(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
var _arr = []; }
var _n = true;
var _d = false;
var _e = undefined;
try { function _toConsumableArray(arr) {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
_arr.push(_s.value); }
if (i && _arr.length === i) break; function _arrayWithoutHoles(arr) {
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) { if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2; return arr2;
} else {
return Array.from(arr);
} }
}; }
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
/** /**
* For parsing color values * For parsing color values
@ -224,157 +232,166 @@
whitesmoke: 'f5f5f5', whitesmoke: 'f5f5f5',
yellow: 'ffff00', yellow: 'ffff00',
yellowgreen: '9acd32' yellowgreen: '9acd32'
}; }; // array of color definition objects
// array of color definition objects
var colorDefs = [{ 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)'], example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
process: function process(bits) { process: function process(_) {
return [parseInt(bits[1], 10), parseInt(bits[2], 10), parseInt(bits[3], 10)]; for (var _len = arguments.length, bits = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
bits[_key - 1] = arguments[_key];
}
return bits.map(function (b) {
return parseInt(b);
});
} }
}, { }, {
re: /^(\w{2})(\w{2})(\w{2})$/, re: /^(\w{2})(\w{2})(\w{2})$/,
example: ['#00ff00', '336699'], example: ['#00ff00', '336699'],
process: function process(bits) { process: function process(_) {
return [parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16)]; for (var _len2 = arguments.length, bits = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
bits[_key2 - 1] = arguments[_key2];
}
return bits.map(function (b) {
return parseInt(b, 16);
});
} }
}, { }, {
re: /^(\w{1})(\w{1})(\w{1})$/, re: /^(\w{1})(\w{1})(\w{1})$/,
example: ['#fb0', 'f0f'], example: ['#fb0', 'f0f'],
process: function process(bits) { process: function process(_) {
return [parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16)]; for (var _len3 = arguments.length, bits = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
bits[_key3 - 1] = arguments[_key3];
}
return bits.map(function (b) {
return parseInt(b + b, 16);
});
} }
}]; }];
/** /**
* A class to parse color values * A class to parse color values.
*/ */
var RGBColor = function () { var RGBColor =
/*#__PURE__*/
function () {
/** /**
* @param {string} colorString * @param {string} colorString
*/ */
function RGBColor(colorString) { function RGBColor(colorString) {
classCallCheck(this, RGBColor); var _this = this;
this.ok = false; _classCallCheck(this, RGBColor);
this.ok = false; // strip any leading #
// strip any leading #
if (colorString.charAt(0) === '#') { if (colorString.charAt(0) === '#') {
// remove # if any // remove # if any
colorString = colorString.substr(1, 6); colorString = colorString.substr(1, 6);
} }
colorString = colorString.replace(/ /g, ''); colorString = colorString.replace(/ /g, '');
colorString = colorString.toLowerCase(); colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches
// before getting into regexps, try simple matches
// and overwrite the input // and overwrite the input
if (colorString in simpleColors) { if (colorString in simpleColors) {
colorString = simpleColors[colorString]; colorString = simpleColors[colorString];
} } // end of simple type-in colors
// end of simple type-in colors
// search through the definitions to find a match // search through the definitions to find a match
for (var i = 0; i < colorDefs.length; i++) {
var re = colorDefs[i].re;
var processor = colorDefs[i].process;
colorDefs.forEach(function (_ref) {
var re = _ref.re,
processor = _ref.process;
var bits = re.exec(colorString); var bits = re.exec(colorString);
if (bits) { if (bits) {
var _processor = processor(bits), var _processor = processor.apply(void 0, _toConsumableArray(bits)),
_processor2 = slicedToArray(_processor, 3), _processor2 = _slicedToArray(_processor, 3),
r = _processor2[0], r = _processor2[0],
g = _processor2[1], g = _processor2[1],
b = _processor2[2]; b = _processor2[2];
Object.assign(this, { r: r, g: g, b: b }); Object.assign(_this, {
this.ok = true; r: r,
g: g,
b: b
});
_this.ok = true;
} }
} }, this); // validate/cleanup values
// validate/cleanup values
this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r; 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.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; this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b;
} } // some getters
// some getters
/** /**
* @returns {string} * @returns {string}
*/ */
createClass(RGBColor, [{ _createClass(RGBColor, [{
key: 'toRGB', key: "toRGB",
value: function toRGB() { value: function toRGB() {
return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
} }
/** /**
* @returns {string} * @returns {string}
*/ */
}, { }, {
key: 'toHex', key: "toHex",
value: function toHex() { value: function toHex() {
var r = this.r.toString(16); var r = this.r.toString(16);
var g = this.g.toString(16); var g = this.g.toString(16);
var b = this.b.toString(16); var b = this.b.toString(16);
if (r.length === 1) { if (r.length === 1) {
r = '0' + r; r = '0' + r;
} }
if (g.length === 1) { if (g.length === 1) {
g = '0' + g; g = '0' + g;
} }
if (b.length === 1) { if (b.length === 1) {
b = '0' + b; b = '0' + b;
} }
return '#' + r + g + b; return '#' + r + g + b;
} }
/**
* help
* @returns {HTMLUListElement}
*/
}, {
key: 'getHelpXML',
value: function getHelpXML() {
var examples = [];
// add regexps
for (var i = 0; i < colorDefs.length; i++) {
var example = colorDefs[i].example;
for (var j = 0; j < example.length; j++) {
examples[examples.length] = example[j];
}
}
// add type-in colors
examples.push.apply(examples, toConsumableArray(Object.keys(simpleColors)));
var xml = document.createElement('ul');
xml.setAttribute('id', 'rgbcolor-examples');
for (var _i = 0; _i < examples.length; _i++) {
try {
var listItem = document.createElement('li');
var listColor = new RGBColor(examples[_i]);
var exampleDiv = document.createElement('div');
exampleDiv.style.cssText = 'margin: 3px;\nborder: 1px solid black;\nbackground: ' + listColor.toHex() + ';\ncolor: ' + listColor.toHex() + ';';
exampleDiv.append('test');
var listItemValue = ' ' + examples[_i] + ' -> ' + listColor.toRGB() + ' -> ' + listColor.toHex();
listItem.append(exampleDiv, listItemValue);
xml.append(listItem);
} catch (e) {}
}
return xml;
}
}]); }]);
return RGBColor; return RGBColor;
}(); }();
/* globals jsPDF */ RGBColor.getHelpXML = function () {
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 = "\nmargin: 3px;\nborder: 1px solid black;\nbackground: ".concat(listColor.toHex(), ";\ncolor: ").concat(listColor.toHex(), ";");
exampleDiv.append('test');
var listItemValue = " ".concat(example, " -> ").concat(listColor.toRGB(), " -> ").concat(listColor.toHex());
listItem.append(exampleDiv, listItemValue);
return listItem;
} catch (e) {
return '';
}
})));
return xml;
};
var jsPDFAPI = jsPDF.API; var jsPDFAPI = jsPDF.API;
var pdfSvgAttr = { var pdfSvgAttr = {
@ -384,6 +401,8 @@
rect: ['x', 'y', 'width', 'height', 'stroke', 'fill', 'stroke-width'], rect: ['x', 'y', 'width', 'height', 'stroke', 'fill', 'stroke-width'],
ellipse: ['cx', 'cy', 'rx', 'ry', 'stroke', 'fill', 'stroke-width'], ellipse: ['cx', 'cy', 'rx', 'ry', 'stroke', 'fill', 'stroke-width'],
circle: ['cx', 'cy', 'r', 'stroke', 'fill', 'stroke-width'], circle: ['cx', 'cy', 'r', 'stroke', 'fill', 'stroke-width'],
polygon: ['points', 'stroke', 'fill', 'stroke-width'],
// polyline attributes are the same as those of polygon
text: ['x', 'y', 'font-size', 'font-family', 'text-anchor', 'font-weight', 'font-style', 'fill'] text: ['x', 'y', 'font-size', 'font-family', 'text-anchor', 'font-weight', 'font-style', 'fill']
}; };
@ -403,12 +422,50 @@
toRemove.push(a.name); toRemove.push(a.name);
} }
}); });
toRemove.forEach(function (a) { toRemove.forEach(function (a) {
node.removeAttribute(a.name); node.removeAttribute(a.name);
}); });
}; };
var numRgx = /[+-]?(?:\d+\.\d*|\d+|\.\d+)(?:[eE]\d+|[eE][+-]\d+|)/g;
var getLinesOptionsOfPoly = function getLinesOptionsOfPoly(node) {
var nums = node.getAttribute('points');
nums = nums && nums.match(numRgx) || [];
if (nums && nums.length) {
nums = nums.map(function (n) {
return Number(n);
});
if (nums.length % 2) {
nums.length--;
}
}
if (nums.length < 4) {
console.log('invalid points attribute:', node); // eslint-disable-line no-console
return undefined;
}
var _nums = nums,
_nums2 = _slicedToArray(_nums, 2),
x = _nums2[0],
y = _nums2[1],
lines = [];
for (var i = 2; i < nums.length; i += 2) {
lines.push([nums[i] - nums[i - 2], nums[i + 1] - nums[i - 1]]);
}
return {
x: x,
y: y,
lines: lines
};
};
var svgElementToPdf = function svgElementToPdf(element, pdf, options) { var svgElementToPdf = function svgElementToPdf(element, pdf, options) {
// pdf is a jsPDF object // pdf is a jsPDF object
// console.log('options =', options); // console.log('options =', options);
@ -419,11 +476,14 @@
// console.log('passing: ', node); // console.log('passing: ', node);
// let hasStrokeColor = false; // let hasStrokeColor = false;
var hasFillColor = false; var hasFillColor = false;
var fillRGB = void 0; var fillRGB;
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle', 'text'])) {
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle', 'polygon', 'polyline', 'text'])) {
var fillColor = node.getAttribute('fill'); var fillColor = node.getAttribute('fill');
if (attributeIsNotEmpty(fillColor)) { if (attributeIsNotEmpty(fillColor)) {
fillRGB = new RGBColor(fillColor); fillRGB = new RGBColor(fillColor);
if (fillRGB.ok) { if (fillRGB.ok) {
hasFillColor = true; hasFillColor = true;
colorMode = 'F'; colorMode = 'F';
@ -432,132 +492,194 @@
} }
} }
} }
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle'])) {
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle', 'polygon', 'polyline'])) {
if (hasFillColor) { if (hasFillColor) {
pdf.setFillColor(fillRGB.r, fillRGB.g, fillRGB.b); pdf.setFillColor(fillRGB.r, fillRGB.g, fillRGB.b);
} }
if (attributeIsNotEmpty(node, 'stroke-width')) { if (attributeIsNotEmpty(node, 'stroke-width')) {
pdf.setLineWidth(k * parseInt(node.getAttribute('stroke-width'), 10)); pdf.setLineWidth(k * parseInt(node.getAttribute('stroke-width')));
} }
var strokeColor = node.getAttribute('stroke'); var strokeColor = node.getAttribute('stroke');
if (attributeIsNotEmpty(strokeColor)) { if (attributeIsNotEmpty(strokeColor)) {
var strokeRGB = new RGBColor(strokeColor); var strokeRGB = new RGBColor(strokeColor);
if (strokeRGB.ok) { if (strokeRGB.ok) {
// hasStrokeColor = true; // hasStrokeColor = true;
pdf.setDrawColor(strokeRGB.r, strokeRGB.g, strokeRGB.b); pdf.setDrawColor(strokeRGB.r, strokeRGB.g, strokeRGB.b);
if (colorMode === 'F') { if (colorMode === 'F') {
colorMode = 'FD'; colorMode = 'FD';
} else { } else {
colorMode = null; colorMode = 'S';
} }
} else { } else {
colorMode = null; colorMode = null;
} }
} }
} }
switch (node.tagName.toLowerCase()) {
var tag = node.tagName.toLowerCase();
switch (tag) {
case 'svg': case 'svg':
case 'a': case 'a':
case 'g': case 'g':
svgElementToPdf(node, pdf, options); svgElementToPdf(node, pdf, options);
removeAttributes(node, pdfSvgAttr.g); removeAttributes(node, pdfSvgAttr.g);
break; break;
case 'line': case 'line':
pdf.line(k * parseInt(node.getAttribute('x1'), 10), k * parseInt(node.getAttribute('y1'), 10), k * parseInt(node.getAttribute('x2'), 10), k * parseInt(node.getAttribute('y2'), 10)); pdf.line(k * parseInt(node.getAttribute('x1')), k * parseInt(node.getAttribute('y1')), k * parseInt(node.getAttribute('x2')), k * parseInt(node.getAttribute('y2')));
removeAttributes(node, pdfSvgAttr.line); removeAttributes(node, pdfSvgAttr.line);
break; break;
case 'rect': case 'rect':
pdf.rect(k * parseInt(node.getAttribute('x'), 10), k * parseInt(node.getAttribute('y'), 10), k * parseInt(node.getAttribute('width'), 10), k * parseInt(node.getAttribute('height'), 10), colorMode); pdf.rect(k * parseInt(node.getAttribute('x')), k * parseInt(node.getAttribute('y')), k * parseInt(node.getAttribute('width')), k * parseInt(node.getAttribute('height')), colorMode);
removeAttributes(node, pdfSvgAttr.rect); removeAttributes(node, pdfSvgAttr.rect);
break; break;
case 'ellipse': case 'ellipse':
pdf.ellipse(k * parseInt(node.getAttribute('cx'), 10), k * parseInt(node.getAttribute('cy'), 10), k * parseInt(node.getAttribute('rx'), 10), k * parseInt(node.getAttribute('ry'), 10), colorMode); pdf.ellipse(k * parseInt(node.getAttribute('cx')), k * parseInt(node.getAttribute('cy')), k * parseInt(node.getAttribute('rx')), k * parseInt(node.getAttribute('ry')), colorMode);
removeAttributes(node, pdfSvgAttr.ellipse); removeAttributes(node, pdfSvgAttr.ellipse);
break; break;
case 'circle': case 'circle':
pdf.circle(k * parseInt(node.getAttribute('cx'), 10), k * parseInt(node.getAttribute('cy'), 10), k * parseInt(node.getAttribute('r'), 10), colorMode); pdf.circle(k * parseInt(node.getAttribute('cx')), k * parseInt(node.getAttribute('cy')), k * parseInt(node.getAttribute('r')), colorMode);
removeAttributes(node, pdfSvgAttr.circle); removeAttributes(node, pdfSvgAttr.circle);
break; break;
case 'text':
if (node.hasAttribute('font-family')) {
switch ((node.getAttribute('font-family') || '').toLowerCase()) {
case 'serif':
pdf.setFont('times');break;
case 'monospace':
pdf.setFont('courier');break;
default:
node.setAttribute('font-family', 'sans-serif');
pdf.setFont('helvetica');
}
}
if (hasFillColor) {
pdf.setTextColor(fillRGB.r, fillRGB.g, fillRGB.b);
}
var fontType = '';
if (node.hasAttribute('font-weight')) {
if (node.getAttribute('font-weight') === 'bold') {
fontType = 'bold';
} else {
node.removeAttribute('font-weight');
}
}
if (node.hasAttribute('font-style')) {
if (node.getAttribute('font-style') === 'italic') {
fontType += 'italic';
} else {
node.removeAttribute('font-style');
}
}
pdf.setFontType(fontType);
var pdfFontSize = node.hasAttribute('font-size') ? parseInt(node.getAttribute('font-size'), 10) : 16;
var getWidth = function getWidth(node) { case 'polygon':
var box = void 0; case 'polyline':
try { {
box = node.getBBox(); // Firefox on MacOS will raise error here var linesOptions = getLinesOptionsOfPoly(node);
} catch (err) {
// copy and append to body so that getBBox is available if (linesOptions) {
var nodeCopy = node.cloneNode(true); pdf.lines(linesOptions.lines, k * linesOptions.x, k * linesOptions.y, [k, k], colorMode, tag === 'polygon' // polygon is closed, polyline is not closed
var svg = node.ownerSVGElement.cloneNode(false); );
svg.appendChild(nodeCopy);
document.body.appendChild(svg);
try {
box = nodeCopy.getBBox();
} catch (err) {
box = { width: 0 };
}
document.body.removeChild(svg);
} }
return box.width;
}; removeAttributes(node, pdfSvgAttr.polygon);
// FIXME: use more accurate positioning!! break; // TODO: path
var x = void 0,
y = void 0,
xOffset = 0;
if (node.hasAttribute('text-anchor')) {
switch (node.getAttribute('text-anchor')) {
case 'end':
xOffset = getWidth(node);break;
case 'middle':
xOffset = getWidth(node) / 2;break;
case 'start':
break;
case 'default':
node.setAttribute('text-anchor', 'start');break;
}
x = parseInt(node.getAttribute('x'), 10) - xOffset;
y = parseInt(node.getAttribute('y'), 10);
} }
// console.log('fontSize:', pdfFontSize, 'text:', node.textContent);
pdf.setFontSize(pdfFontSize).text(k * x, k * y, node.textContent); case 'text':
removeAttributes(node, pdfSvgAttr.text); {
break; if (node.hasAttribute('font-family')) {
// TODO: image switch ((node.getAttribute('font-family') || '').toLowerCase()) {
case 'serif':
pdf.setFont('times');
break;
case 'monospace':
pdf.setFont('courier');
break;
default:
node.setAttribute('font-family', 'sans-serif');
pdf.setFont('helvetica');
}
}
if (hasFillColor) {
pdf.setTextColor(fillRGB.r, fillRGB.g, fillRGB.b);
}
var fontType = '';
if (node.hasAttribute('font-weight')) {
if (node.getAttribute('font-weight') === 'bold') {
fontType = 'bold';
} else {
node.removeAttribute('font-weight');
}
}
if (node.hasAttribute('font-style')) {
if (node.getAttribute('font-style') === 'italic') {
fontType += 'italic';
} else {
node.removeAttribute('font-style');
}
}
pdf.setFontType(fontType);
var pdfFontSize = node.hasAttribute('font-size') ? parseInt(node.getAttribute('font-size')) : 16;
/**
*
* @param {Element} elem
* @returns {Float}
*/
var getWidth = function getWidth(elem) {
var box;
try {
box = elem.getBBox(); // Firefox on MacOS will raise error here
} catch (err) {
// copy and append to body so that getBBox is available
var nodeCopy = elem.cloneNode(true);
var svg = elem.ownerSVGElement.cloneNode(false);
svg.appendChild(nodeCopy);
document.body.appendChild(svg);
try {
box = nodeCopy.getBBox();
} catch (error) {
box = {
width: 0
};
}
document.body.removeChild(svg);
}
return box.width;
}; // FIXME: use more accurate positioning!!
var x,
y,
xOffset = 0;
if (node.hasAttribute('text-anchor')) {
switch (node.getAttribute('text-anchor')) {
case 'end':
xOffset = getWidth(node);
break;
case 'middle':
xOffset = getWidth(node) / 2;
break;
case 'start':
break;
case 'default':
node.setAttribute('text-anchor', 'start');
break;
}
x = parseInt(node.getAttribute('x')) - xOffset;
y = parseInt(node.getAttribute('y'));
} // console.log('fontSize:', pdfFontSize, 'text:', node.textContent);
pdf.setFontSize(pdfFontSize).text(k * x, k * y, node.textContent);
removeAttributes(node, pdfSvgAttr.text);
break; // TODO: image
}
default: default:
if (remove) { if (remove) {
console.log("can't translate to pdf:", node); console.log("can't translate to pdf:", node); // eslint-disable-line no-console
node.remove(); node.remove();
} }
} }
}); });
return pdf; return pdf;
@ -571,6 +693,7 @@
if (typeof element === 'string') { if (typeof element === 'string') {
element = new DOMParser().parseFromString(element, 'text/xml').documentElement; element = new DOMParser().parseFromString(element, 'text/xml').documentElement;
} }
svgElementToPdf(element, this, options); svgElementToPdf(element, this, options);
return this; return this;
}; };

View File

@ -209,7 +209,7 @@ var svgEditorLang_af = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_ar = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_az = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_be = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_bg = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_ca = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_cs = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_cy = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_da = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_de = (function () {
unsavedChanges: 'Es sind nicht-gespeicherte Änderungen vorhanden.', unsavedChanges: 'Es sind nicht-gespeicherte Änderungen vorhanden.',
enterNewLinkURL: 'Geben Sie die neue URL ein', enterNewLinkURL: 'Geben Sie die neue URL ein',
errorLoadingSVG: 'Fehler: Kann SVG-Daten nicht laden', errorLoadingSVG: 'Fehler: Kann SVG-Daten nicht laden',
URLloadFail: 'Kann von dieser URL nicht laden', URLLoadFail: 'Kann von dieser URL nicht laden',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_el = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_en = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_es = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_et = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_fa = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_fi = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...", retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_fr = (function () {
unsavedChanges: 'Il y a des changements non sauvegardés.', unsavedChanges: 'Il y a des changements non sauvegardés.',
enterNewLinkURL: "Entrez la nouvelle URL de l'hyperlien", enterNewLinkURL: "Entrez la nouvelle URL de l'hyperlien",
errorLoadingSVG: 'Erreur : Impossible de charger les données SVG', errorLoadingSVG: 'Erreur : Impossible de charger les données SVG',
URLloadFail: "Impossible de charger l'URL", URLLoadFail: "Impossible de charger l'URL",
retrieving: 'Récupération de « %s »…', retrieving: 'Récupération de « %s »…',
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_fy = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: 'Retrieving \'%s\'...', retrieving: 'Retrieving \'%s\'...',
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_ga = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: 'Retrieving \'%s\' ...', retrieving: 'Retrieving \'%s\' ...',
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_gl = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: 'Retrieving \'%s\' ...', retrieving: 'Retrieving \'%s\' ...',
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_he = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: 'Retrieving \'%s\' ...', retrieving: 'Retrieving \'%s\' ...',
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

@ -209,7 +209,7 @@ var svgEditorLang_hi = (function () {
unsavedChanges: 'There are unsaved changes.', unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL', enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data', errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL', URLLoadFail: 'Unable to load from URL',
retrieving: 'Retrieving \'%s\' ...', retrieving: 'Retrieving \'%s\' ...',
popupWindowBlocked: 'Popup window may be blocked by browser', popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoBlur: 'Blurred elements will appear as un-blurred',

Some files were not shown because too many files have changed in this diff Show More