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": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
["@babel/preset-env"]
]
}

View File

@ -21,7 +21,6 @@ editor/js-hotkeys
editor/jspdf/jspdf.min.js
editor/jspdf/underscore-min.js
editor/extensions/imagelib/jquery.min.js
editor/extensions/mathjax
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
build/

3
.htmlhintrc Normal file
View File

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

View File

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

View File

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

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
[![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
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
### [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)
(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>.
## 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>
```
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
These steps are only needed if you wish to set up your own npm package
@ -82,6 +115,17 @@ incorporating SVGEdit.
## 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-19 Published 3.0.0-rc.1 allowing for extensions and locales to be
expressed as modules

View File

@ -1,5 +1,5 @@
/* eslint-env node */
const fs = require('promise-fs');
import fs from 'promise-fs';
const filesAndReplacements = [
{
@ -32,6 +32,22 @@ const filesAndReplacements = [
[
'<script src="external/dom-polyfill/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="../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 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}) => {
return p.then(async () => {
let data;
try {
data = await fs.readFile(input, 'utf8');
} catch (err) {
console.log(`Error reading ${input} file`, err);
}
(async () => {
await filesAndReplacements.reduce(async (p, {input, output, replacements}) => {
await p;
let data;
try {
data = await fs.readFile(input, 'utf8');
} catch (err) {
console.log(`Error reading ${input} file`, err); // eslint-disable-line no-console
}
data = replacements.reduce((s, [find, replacement]) => {
return s.replace(find, replacement);
}, data);
data = replacements.reduce((s, [fnd, replacement]) => {
return s.replace(fnd, replacement);
}, data);
try {
await fs.writeFile(output, data);
} catch (err) {
console.log(`Error writing file: ${err}`, err);
return;
}
console.log(`Completed file ${input} rewriting!`);
});
}, Promise.resolve()).then(() => {
console.log('Finished!');
});
try {
await fs.writeFile(output, data);
} catch (err) {
console.log(`Error writing file: ${err}`, err); // eslint-disable-line no-console
return;
}
console.log(`Completed file ${input} rewriting!`); // eslint-disable-line no-console
}, Promise.resolve());
console.log('Finished!'); // eslint-disable-line no-console
})();

View File

@ -6,6 +6,7 @@
<script src="../editor/jquery.min.js"></script>
<script src="../editor/jquery-ui/jquery-ui-1.8.17.custom.min.js"></script>
<style> #svgroot { overflow: hidden; } </style>
<link rel="shortcut icon" type="image/x-icon" href="../editor/images/logo.png" />
</head>
<body>
@ -24,7 +25,7 @@
</div>
<script type="module">
import Canvas from '../editor/svgcanvas.js';
import SvgCanvas from '../editor/svgcanvas.js';
const container = document.querySelector('#editorContainer');
const {width, height} = {width: 500, height: 300};
@ -41,7 +42,7 @@ const config = {
baseUnit: 'px',
};
window.canvas = new Canvas(container, config);
window.canvas = new SvgCanvas(container, config);
canvas.updateCanvas(width, height);
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 () {
'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
/**
* @module DOMPolyfill
*/
/**
*
* @param {Node} o
* @param {module:DOMPolyfill~ParentNode|module:DOMPolyfill~ChildNode} ps
* @returns {undefined}
*/
function mixin(o, ps) {
if (!o) return;
Object.keys(ps).forEach(function (p) {
if (p in o || p in o.prototype) {
return;
}
try {
Object.defineProperty(o.prototype, p, Object.getOwnPropertyDescriptor(ps, p));
} catch (ex) {
@ -17,14 +42,23 @@
}
});
}
/**
*
* @param {Node[]} nodes
* @returns {Node}
*/
function convertNodesIntoANode(nodes) {
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) {
return nodes[0];
}
var node = document.createDocumentFragment();
nodes.forEach(function (n) {
node.appendChild(n);
@ -34,7 +68,7 @@
var ParentNode = {
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];
}
@ -42,7 +76,7 @@
this.insertBefore(nodes, this.firstChild);
},
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];
}
@ -50,12 +84,10 @@
this.appendChild(nodes);
}
};
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
var ChildNode = {
@ -64,13 +96,14 @@
if (!parent) return;
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];
}
while (nodes.includes(viablePreviousSibling)) {
viablePreviousSibling = viablePreviousSibling.previousSibling;
}
var node = convertNodesIntoANode(nodes);
parent.insertBefore(node, viablePreviousSibling ? viablePreviousSibling.nextSibling : parent.firstChild);
},
@ -79,13 +112,14 @@
if (!parent) return;
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];
}
while (nodes.includes(viableNextSibling)) {
viableNextSibling = viableNextSibling.nextSibling;
}
var node = convertNodesIntoANode(nodes);
parent.insertBefore(node, viableNextSibling);
},
@ -94,13 +128,14 @@
if (!parent) return;
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];
}
while (nodes.includes(viableNextSibling)) {
viableNextSibling = viableNextSibling.nextSibling;
}
var node = convertNodesIntoANode(nodes);
if (this.parentNode === parent) {
@ -113,10 +148,10 @@
if (!this.parentNode) {
return;
}
this.parentNode.removeChild(this);
}
};
mixin(DocumentType, ChildNode);
mixin(Element, ChildNode);
mixin(CharacterData, ChildNode);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,74 +1,80 @@
var svgEditorExtension_helloworld = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
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;
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
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");
}
};
}();
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");
}
/* globals jQuery */
/**
* ext-helloworld.js
*
@ -86,42 +92,38 @@ var svgEditorExtension_helloworld = (function () {
var extHelloworld = {
name: 'helloworld',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, $, svgCanvas;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var $, importLocale, strings, svgEditor, svgCanvas;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
$ = _ref.$, importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 2:
case 3:
strings = _context.sent;
svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas;
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
// For more notes on how to make an icon file, see the source of
// the helloworld-icon.xml
svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml',
// Multiple buttons can be added in this array
buttons: [{
// Must match the icon ID in helloworld-icon.xml
id: 'hello_world',
// Fallback, e.g., for `file://` access
// Fallback, e.g., for `file:///` access
icon: svgEditor.curConfig.extIconsPath + 'helloworld.png',
// This indicates that the button will be added to the "mode"
// button panel on the left side
type: 'mode',
// Tooltip text
title: strings.buttons[0].title,
// Events
events: {
click: function click() {
@ -139,41 +141,39 @@ var svgEditorExtension_helloworld = (function () {
if (svgCanvas.getMode() === 'hello_world') {
// The returned object must include "started" with
// a value of true in order for mouseUp to be triggered
return { started: true };
return {
started: true
};
}
return undefined;
},
// This is triggered from anywhere, but "started" must have been set
// to true (see above). Note that "opts" is an object with event info
mouseUp: function mouseUp(opts) {
// Check the mode on mouseup
if (svgCanvas.getMode() === 'hello_world') {
var zoom = svgCanvas.getZoom();
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 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;
[['x', x], ['y', y]].forEach(function (_ref3) {
var _ref4 = slicedToArray(_ref3, 2),
prop = _ref4[0],
val = _ref4[1];
[['x', x], ['y', y]].forEach(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
prop = _ref3[0],
val = _ref3[1];
text = text.replace('{' + prop + '}', val);
});
}); // Show the text using the custom alert function
// Show the text using the custom alert function
$.alert(text);
}
}
});
case 7:
case 'end':
case "end":
return _context.stop();
}
}
@ -181,7 +181,7 @@ var svgEditorExtension_helloworld = (function () {
}));
function init(_x) {
return _ref2.apply(this, arguments);
return _init.apply(this, arguments);
}
return init;

View File

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

View File

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

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_arrows_fr = (function () {
var fr = {
name: 'Arrows',
langList: [{ id: 'arrow_none', textContent: 'Sans flèche' }],
langList: [{
id: 'arrow_none',
textContent: 'Sans flèche'
}],
contextTools: [{
title: 'Select arrow type',
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 = {
name: 'Connector',
langList: [{ id: 'mode_connect', title: 'Connect two objects' }],
langList: [{
id: 'mode_connect',
title: 'Connect two objects'
}],
buttons: [{
title: 'Connect two objects'
}]

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_connector_fr = (function () {
var fr = {
name: 'Connector',
langList: [{ id: 'mode_connect', title: 'Connecter deux objets' }],
langList: [{
id: 'mode_connect',
title: 'Connecter deux objets'
}],
buttons: [{
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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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'
}, {
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php',
description: 'Free library of illustrations'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
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:
// Getting messages like this in console:
// Refused to display 'https://openclipart.org/detail/307176/sign-bike' in a frame
// 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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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'
}, {
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'
}, {
name: 'Openclipart',
url: 'https://openclipart.org/svgedit',
description: 'Share and Use Images. Over 50,000 Public Domain SVG Images and Growing.'
/*
// See message in "en" locale for further details
,
{
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 = {
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: [{
title: 'Start marker',
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 () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
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 {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
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-markers.js
*
@ -64,15 +70,18 @@ var svgEditorExtension_markers = (function () {
var extMarkers = {
name: 'markers',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(S) {
var strings, svgEditor, $, svgCanvas, addElem, mtypes, markerPrefix, idPrefix, markerTypes, getLinked, setIcon, selElems, showPanel, addMarker, convertline, setMarker, colorChanged, updateReferences, triggerTextEntry, showTextPrompt, setArrowFromButton, getTitle, buildButtonList, contextTools;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee3(S) {
var strings, svgEditor, $, svgCanvas, addElem, mtypes, markerPrefix, idPrefix, markerTypes, getLinked, setIcon, selElems, showPanel, addMarker, convertline, setMarker, colorChanged, updateReferences, triggerTextEntry, showTextPrompt, _showTextPrompt, setArrowFromButton, _setArrowFromButton, getTitle, buildButtonList, contextTools;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context2.prev = _context2.next) {
switch (_context3.prev = _context3.next) {
case 0:
buildButtonList = function buildButtonList(lang) {
var buttons = [];
// const i = 0;
buildButtonList = function _ref16() {
var buttons = []; // const i = 0;
/*
buttons.push({
id: idPrefix + 'markers_off',
@ -96,6 +105,7 @@ var svgEditorExtension_markers = (function () {
panel: 'marker_panel'
});
*/
$.each(mtypes, function (k, pos) {
var listname = pos + '_marker_list';
var def = true;
@ -107,7 +117,9 @@ var svgEditorExtension_markers = (function () {
icon: svgEditor.curConfig.extIconsPath + 'markers-' + id + '.png',
title: title,
type: 'context',
events: { click: setArrowFromButton },
events: {
click: setArrowFromButton
},
panel: 'marker_panel',
list: listname,
isDefault: def
@ -118,147 +130,223 @@ var svgEditorExtension_markers = (function () {
return buttons;
};
getTitle = function getTitle(id) {
getTitle = function _ref15(id) {
var langList = strings.langList;
var item = langList.find(function (item) {
return item.id === id;
var item = langList.find(function (itm) {
return itm.id === id;
});
return item ? item.title : id;
};
setArrowFromButton = function setArrowFromButton(obj) {
var parts = this.id.split('_');
var pos = parts[1];
var val = parts[2];
if (parts[3]) {
val += '_' + parts[3];
}
_setArrowFromButton = function _ref14() {
_setArrowFromButton = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(ev) {
var parts, pos, val;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
parts = this.id.split('_');
pos = parts[1];
val = parts[2];
if (val !== 'textmarker') {
triggerTextEntry(pos, '\\' + val);
} else {
showTextPrompt(pos);
}
if (parts[3]) {
val += '_' + parts[3];
}
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) {
var def = $('#' + pos + '_marker').val();
if (def.substr(0, 1) === '\\') {
def = '';
}
$.prompt('Enter text for ' + pos + ' marker', def, function (txt) {
if (txt) {
triggerTextEntry(pos, txt);
}
});
setArrowFromButton = function _ref13(_x3) {
return _setArrowFromButton.apply(this, arguments);
};
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').change();
// const txtbox = $('#'+pos+'_marker');
$('#' + pos + '_marker').change(); // const txtbox = $('#'+pos+'_marker');
// if (val.substr(0,1)=='\\') {txtbox.hide();}
// else {txtbox.show();}
};
updateReferences = function updateReferences(el) {
updateReferences = function _ref9(el) {
$.each(mtypes, function (i, pos) {
var id = markerPrefix + pos + '_' + el.id;
var markerName = 'marker-' + pos;
var marker = getLinked(el, markerName);
if (!marker || !marker.attributes.se_type) {
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 = $('#' + pos + '_marker').attr('value');
addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') {
el = convertline(el);
}
svgCanvas.call('changed', selElems);
}
}
});
};
colorChanged = function colorChanged(elem) {
colorChanged = function _ref8(elem) {
var color = elem.getAttribute('stroke');
$.each(mtypes, function (i, pos) {
var marker = getLinked(elem, 'marker-' + pos);
if (!marker) {
return;
}
if (!marker.attributes.se_type) {
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 setMarker() {
var poslist = { start_marker: 'start', mid_marker: 'mid', end_marker: 'end' };
setMarker = function _ref7() {
var poslist = {
start_marker: 'start',
mid_marker: 'mid',
end_marker: 'end'
};
var pos = poslist[this.id];
var markerName = 'marker-' + pos;
var el = selElems[0];
var marker = getLinked(el, markerName);
if (marker) {
$(marker).remove();
}
el.removeAttribute(markerName);
var val = this.value;
if (val === '') {
val = '\\nomarker';
}
if (val === '\\nomarker') {
setIcon(pos, val);
svgCanvas.call('changed', selElems);
return;
}
// Set marker on element
} // Set marker on element
var id = markerPrefix + pos + '_' + el.id;
addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') {
el = convertline(el);
convertline(el);
}
svgCanvas.call('changed', selElems);
setIcon(pos, val);
};
convertline = function convertline(elem) {
convertline = function _ref6(elem) {
// this routine came from the connectors extension
// it is needed because midpoint markers don't work with line elements
if (!(elem.tagName === 'line')) {
return elem;
}
} // Convert to polyline to accept mid-arrow
// Convert to polyline to accept mid-arrow
var x1 = Number(elem.getAttribute('x1'));
var x2 = Number(elem.getAttribute('x2'));
var y1 = Number(elem.getAttribute('y1'));
var y2 = Number(elem.getAttribute('y2'));
var id = elem.id;
var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' ';
var pline = addElem({
element: 'polyline',
@ -274,15 +362,14 @@ var svgEditorExtension_markers = (function () {
// get any existing marker definitions
var nam = 'marker-' + pos;
var m = elem.getAttribute(nam);
if (m) {
pline.setAttribute(nam, elem.getAttribute(nam));
}
});
var batchCmd = new S.BatchCommand();
batchCmd.addSubCommand(new S.RemoveElementCommand(elem, elem.parentNode));
batchCmd.addSubCommand(new S.InsertElementCommand(pline));
$(elem).after(pline).remove();
svgCanvas.clearSelection();
pline.id = id;
@ -291,32 +378,33 @@ var svgEditorExtension_markers = (function () {
return pline;
};
addMarker = function addMarker(id, val) {
addMarker = function _ref5(id, val) {
var txtBoxBg = '#ffffff';
var txtBoxBorder = 'none';
var txtBoxStrokeWidth = 0;
var marker = svgCanvas.getElem(id);
if (marker) {
return;
return undefined;
}
if (val === '' || val === '\\nomarker') {
return;
return undefined;
}
var el = selElems[0];
var color = el.getAttribute('stroke');
// NOTE: Safari didn't like a negative value in viewBox
var color = el.getAttribute('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 strokeWidth = 10;
var refX = 50;
var refY = 50;
var viewBox = '0 0 100 100';
var markerWidth = 5;
var markerHeight = 5;
var seType = void 0;
var seType;
if (val.substr(0, 1) === '\\') {
seType = val.substr(1);
} else {
@ -324,10 +412,11 @@ var svgEditorExtension_markers = (function () {
}
if (!markerTypes[seType]) {
return;
return undefined;
} // an unknown type!
// create a generic marker
marker = addElem({
element: 'marker',
attr: {
@ -342,33 +431,32 @@ var svgEditorExtension_markers = (function () {
if (seType !== 'textmarker') {
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);
} else {
var text = addElem(markerTypes[seType]);
// have to add text to get bounding box
var text = addElem(markerTypes[seType]); // have to add text to get bounding box
text.textContent = val;
var tb = text.getBBox();
// alert(tb.x + ' ' + tb.y + ' ' + tb.width + ' ' + tb.height);
var tb = text.getBBox(); // alert(tb.x + ' ' + tb.y + ' ' + tb.width + ' ' + tb.height);
var pad = 1;
var bb = tb;
bb.x = 0;
bb.y = 0;
bb.width += pad * 2;
bb.height += pad * 2;
// shift text according to its size
bb.height += pad * 2; // shift text according to its size
text.setAttribute('x', pad);
text.setAttribute('y', bb.height - pad - tb.height / 4); // kludge?
text.setAttribute('fill', color);
refX = bb.width / 2 + pad;
refY = bb.height / 2 + pad;
viewBox = bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height;
markerWidth = bb.width / 10;
markerHeight = bb.height / 10;
var box = addElem({
element: 'rect',
attr: {
@ -391,21 +479,19 @@ var svgEditorExtension_markers = (function () {
marker.setAttribute('refX', refX);
marker.setAttribute('refY', refY);
svgCanvas.findDefs().append(marker);
return marker;
};
showPanel = function showPanel(on) {
showPanel = function _ref4(on) {
$('#marker_panel').toggle(on);
if (on) {
var el = selElems[0];
var val = void 0,
ci = void 0;
var val, ci;
$.each(mtypes, function (i, pos) {
var m = getLinked(el, 'marker-' + pos);
var txtbox = $('#' + pos + '_marker');
if (!m) {
val = '\\nomarker';
ci = val;
@ -414,56 +500,62 @@ var svgEditorExtension_markers = (function () {
if (!m.attributes.se_type) {
return;
} // not created by this extension
val = '\\' + m.attributes.se_type.textContent;
ci = val;
if (val === '\\textmarker') {
val = m.lastChild.textContent;
// txtbox.show(); // show text box
val = m.lastChild.textContent; // txtbox.show(); // show text box
} else {
txtbox.hide(); // hide text box
}
}
txtbox.val(val);
setIcon(pos, ci);
});
}
};
setIcon = function setIcon(pos, id) {
setIcon = function _ref3(pos, id) {
if (id.substr(0, 1) !== '\\') {
id = '\\textmarker';
}
var ci = '#' + idPrefix + pos + '_' + id.substr(1);
svgEditor.setIcon('#cur_' + pos + '_marker_list', $(ci).children());
$(ci).addClass('current').siblings().removeClass('current');
};
getLinked = function getLinked(elem, attr) {
getLinked = function _ref2(elem, attr) {
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]);
};
_context2.next = 15;
_context3.next = 17;
return S.importLocale();
case 15:
strings = _context2.sent;
case 17:
strings = _context3.sent;
svgEditor = this;
$ = jQuery;
$ = S.$;
svgCanvas = svgEditor.canvas;
addElem = svgCanvas.addSVGElementFromJson;
mtypes = ['start', 'mid', 'end'];
markerPrefix = 'se_marker_';
idPrefix = 'mkr_';
// note - to add additional marker types add them below with a unique id
idPrefix = 'mkr_'; // note - to add additional marker types add them below with a unique id
// and add the associated icon(s) to marker-icons.svg
// 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
@ -471,153 +563,167 @@ var svgEditorExtension_markers = (function () {
markerTypes = {
nomarker: {},
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' } },
textmarker: { element: 'text', 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: {
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'
}
},
textmarker: {
element: 'text',
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) {
markerTypes[v + '_o'] = markerTypes[v];
});
/**
* @param {Element} elem - A graphic element will have an attribute like marker-start
* @param {"marker-start"|"marker-mid"|"marker-end"} attr
* @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 = [{
type: 'input',
panel: 'marker_panel',
id: 'start_marker',
size: 3,
events: { change: setMarker }
events: {
change: setMarker
}
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'start_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
events: {
change: setArrowFromButton
}
}, {
type: 'input',
panel: 'marker_panel',
id: 'mid_marker',
defval: '',
size: 3,
events: { change: setMarker }
events: {
change: setMarker
}
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'mid_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
events: {
change: setArrowFromButton
}
}, {
type: 'input',
panel: 'marker_panel',
id: 'end_marker',
size: 3,
events: { change: setMarker }
events: {
change: setMarker
}
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'end_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
events: {
change: setArrowFromButton
}
}];
return _context2.abrupt('return', {
return _context3.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'markers-icons.xml',
callback: function callback() {
$('#marker_panel').addClass('toolset').hide();
},
addLangData: function () {
var _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:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function addLangData(_x2) {
return _ref3.apply(this, arguments);
}
return addLangData;
}(),
/* async */
addLangData: function addLangData(_ref) {
var importLocale = _ref.importLocale,
lang = _ref.lang;
return {
data: strings.langList
};
},
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
// console.log('selectChanged',opts);
selElems = opts.elems;
var markerElems = ['line', 'path', 'polyline', 'polygon'];
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && markerElems.includes(elem.tagName)) {
if (opts.selectedElement && !opts.multiselected) {
showPanel(true);
@ -632,29 +738,29 @@ var svgEditorExtension_markers = (function () {
elementChanged: function elementChanged(opts) {
// console.log('elementChanged',opts);
var elem = opts.elems[0];
if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
colorChanged(elem);
updateReferences(elem);
}
// changing_flag = false; // Not apparently in use
},
} // changing_flag = false; // Not apparently in use
},
buttons: buildButtonList(),
context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool);
})
});
case 28:
case 'end':
return _context2.stop();
case 29:
case "end":
return _context3.stop();
}
}
}, _callee2, this);
}, _callee3, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
return _init.apply(this, arguments);
}
return init;

View File

@ -1,61 +1,49 @@
var svgEditorExtension_mathjax = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
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];
}
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
return target;
};
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
// MIT License
// From: https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js
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);
});
};
}
/**
* @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) {
['id', 'class', 'type'].forEach(function (prop) {
@ -63,85 +51,8 @@ var svgEditorExtension_mathjax = (function () {
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) {
var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@ -150,91 +61,62 @@ var svgEditorExtension_mathjax = (function () {
return importScript(u, atts);
}));
}
return new Promise(function (resolve, reject) {
// eslint-disable-line promise/avoid-new
var script = document.createElement('script');
var destructor = function destructor() {
script.onerror = null;
script.onload = null;
script.remove();
script.src = '';
};
script.defer = 'defer';
addScriptAtts(script, atts);
script.onerror = function () {
reject(new Error('Failed to import: ' + url));
/**
*
* @returns {undefined}
*/
function scriptOnError() {
reject(new Error("Failed to import: ".concat(url)));
destructor();
};
script.onload = function () {
}
/**
*
* @returns {undefined}
*/
function scriptOnLoad() {
resolve();
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() {
delete window[vector];
script.onerror = null;
script.onload = null;
script.removeEventListener('error', scriptOnError);
script.removeEventListener('load', scriptOnLoad);
script.remove();
URL.revokeObjectURL(script.src);
script.src = '';
};
addScriptAtts(script, atts);
script.defer = 'defer';
script.type = 'module';
script.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);
});
}
/* globals jQuery, MathJax */
var extMathjax = {
name: 'mathjax',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, $, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(_ref) {
var $, importLocale, strings, svgEditor, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context.prev = _context.next) {
switch (_context2.prev = _context2.next) {
case 0:
saveMath = function saveMath() {
var code = $('#mathjax_code_textarea').val();
// displaystyle to force MathJax NOT to use the inline style. Because it is
saveMath = function _ref2() {
var code = $('#mathjax_code_textarea').val(); // displaystyle to force MathJax NOT to use the inline style. Because it is
// 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
* 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
* `<use>` tag by its `<path>`.
*/
MathJax.Hub.queue.Push(function () {
var mathjaxMath = $('.MathJax_SVG');
var svg = $(mathjaxMath.html());
@ -254,10 +137,12 @@ var svgEditorExtension_mathjax = (function () {
// TODO: find a less pragmatic and more elegant solution to this.
var id = $(this).attr('href') ? $(this).attr('href').slice(1) // Works in Chrome.
: $(this).attr('xlink:href').slice(1); // Works in Firefox.
var glymph = $('#' + id).clone().removeAttr('id');
var x = $(this).attr('x');
var y = $(this).attr('y');
var transform = $(this).attr('transform');
if (transform && (x || y)) {
glymph.attr('transform', transform + ' translate(' + x + ',' + y + ')');
} else if (transform) {
@ -265,30 +150,28 @@ var svgEditorExtension_mathjax = (function () {
} else if (x || y) {
glymph.attr('transform', 'translate(' + x + ',' + y + ')');
}
$(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.attr('xmlns', 'http://www.w3.org/2000/svg');
svgCanvas.importSvgString($('<div>').append(svg.clone()).html(), true);
svgCanvas.ungroupSelectedElement();
// TODO: To undo the adding of the Formula you now have to undo twice.
svgCanvas.ungroupSelectedElement(); // TODO: To undo the adding of the Formula you now have to undo twice.
// This should only be once!
svgCanvas.moveSelectedElements(locationX, locationY, true);
});
};
_context.next = 3;
$ = _ref.$, importLocale = _ref.importLocale;
_context2.next = 4;
return importLocale();
case 3:
strings = _context.sent;
case 4:
strings = _context2.sent;
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.
/* 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
// 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;
math = void 0, locationX = void 0, locationY = void 0, mathjaxLoaded = false;
// TODO: Implement language support. Move these uiStrings to the locale files and the code to the langReady callback.
mathjaxLoaded = false; // TODO: Implement language support. Move these uiStrings to the locale files and
// the code to the langReady callback. Also i18nize alert and HTML below
$.extend(uiStrings, {
mathjax: {
@ -330,117 +212,157 @@ var svgEditorExtension_mathjax = (function () {
title: 'Mathematics code editor'
}
});
/**
*
* @returns {undefined}
*/
buttons = [{
id: 'tool_mathjax',
type: 'mode',
icon: svgEditor.curConfig.extIconsPath + 'mathjax.png',
events: {
click: function click() {
// Only load Mathjax when needed, we don't want to strain Svg-Edit any more.
// From this point on it is very probable that it will be needed, so load it.
if (mathjaxLoaded === false) {
$('<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();
click: function () {
var _click = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
// Set the mode.
svgCanvas.setMode('mathjax'); // Only load Mathjax when needed, we don't want to strain Svg-Edit any more.
// From this point on it is very probable that it will be needed, so load it.
// Make the MathEditor draggable.
$('#mathjax_container').draggable({
cancel: 'button,fieldset',
containment: 'window'
});
if (!(mathjaxLoaded === false)) {
_context.next = 17;
break;
}
// Add functionality and picture to cancel button.
$('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () {
$('#mathjax').hide();
});
$('<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.
// Add functionality and picture to the save button.
$('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () {
saveMath();
$('#mathjax').hide();
});
$('#mathjax_container').draggable({
cancel: 'button,fieldset',
containment: 'window'
}); // Add functionality and picture to cancel button.
// MathJax preprocessing has to ignore most of the page.
$('body').addClass('tex2jax_ignore');
$('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () {
$('#mathjax').hide();
}); // Add functionality and picture to the save button.
// Now get (and run) the MathJax Library.
// Todo: insert script with modules once widely supported
// and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up
// providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998
/*
const modularVersion = !('svgEditor' in window) ||
!window.svgEditor ||
window.svgEditor.modules !== false;
// Add as second argument to `importScript`
{
type: modularVersion
? 'module' // Make this the default when widely supported
: 'text/javascript'
}
// If only using modules, just use this:
const {default: MathJax} = await importModule( // or `import()` when widely supported
svgEditor.curConfig.extIconsPath + mathjaxSrcSecure
);
*/
importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure).then(function () {
// When MathJax is loaded get the div where the math will be rendered.
MathJax.Hub.queue.Push(function () {
math = MathJax.Hub.getAllJax('#mathjax_creator')[0];
console.log(math);
mathjaxLoaded = true;
console.log('MathJax Loaded');
});
}).catch(function () {
console.log('Failed loadeing MathJax.');
$.alert('Failed loading MathJax. You will not be able to change the mathematics.');
});
$('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () {
saveMath();
$('#mathjax').hide();
}); // MathJax preprocessing has to ignore most of the page.
$('body').addClass('tex2jax_ignore'); // Now get (and run) the MathJax Library.
// Todo: insert script with modules once widely supported
// and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up
// providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998
/*
const modularVersion = !('svgEditor' in window) ||
!window.svgEditor ||
window.svgEditor.modules !== false;
// Add as second argument to `importScript`
{
type: modularVersion
? 'module' // Make this the default when widely supported
: 'text/javascript'
}
// If only using modules, just use this:
const {default: MathJax} = await importModule( // or `import()` when widely supported
svgEditor.curConfig.extIconsPath + mathjaxSrcSecure
);
*/
// We use `extIconsPath` here for now as it does not vary with
// the modular type as does `extPath`
_context.prev = 7;
_context.next = 10;
return importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure);
case 10:
// When MathJax is loaded get the div where the math will be rendered.
MathJax.Hub.queue.Push(function () {
math = MathJax.Hub.getAllJax('#mathjax_creator')[0];
console.log(math); // eslint-disable-line no-console
mathjaxLoaded = true;
console.log('MathJax Loaded'); // eslint-disable-line no-console
});
_context.next = 17;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](7);
console.log('Failed loading MathJax.'); // eslint-disable-line no-console
$.alert('Failed loading MathJax. You will not be able to change the mathematics.');
case 17:
case "end":
return _context.stop();
}
}
}, _callee, 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,
svgicons: svgEditor.curConfig.extIconsPath + 'mathjax-icons.xml',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
mouseDown: function mouseDown() {
if (svgCanvas.getMode() === 'mathjax') {
return { started: true };
return {
started: true
};
}
return undefined;
},
mouseUp: function mouseUp(opts) {
if (svgCanvas.getMode() === 'mathjax') {
// Get the coordinates from your mouse.
var zoom = svgCanvas.getZoom();
// Get the actual coordinate by dividing by the zoom value
var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value
locationX = opts.mouse_x / zoom;
locationY = opts.mouse_y / zoom;
$('#mathjax').show();
return { started: false }; // Otherwise the last selected object dissapears.
return {
started: false
}; // Otherwise the last selected object dissapears.
}
return undefined;
},
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');
// Add the MathJax configuration.
$('<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.
// $(mathjaxConfiguration).appendTo('head');
}
});
case 12:
case 'end':
return _context.stop();
case "end":
return _context2.stop();
}
}
}, _callee, this);
}, _callee2, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
return _init.apply(this, arguments);
}
return init;

View File

@ -1,7 +1,6 @@
var svgEditorExtension_overview_window = (function () {
'use strict';
/* globals jQuery */
/**
* ext-overview_window.js
*
@ -13,26 +12,25 @@ var svgEditorExtension_overview_window = (function () {
var extOverview_window = {
name: 'overview_window',
init: function init(_ref) {
var isChrome = _ref.isChrome,
var $ = _ref.$,
isChrome = _ref.isChrome,
isIE = _ref.isIE;
var $ = jQuery;
var overviewWindowGlobals = {};
// Disabled in Chrome 48-, see https://github.com/SVG-Edit/svgedit/issues/26 and
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.
if (isChrome()) {
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) {
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>';
$('#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 portHeight = parseFloat($('#workarea').css('height'));
var portWidth = parseFloat($('#workarea').css('width'));
@ -42,32 +40,30 @@ var svgEditorExtension_overview_window = (function () {
var windowHeight = parseFloat($('#svgcanvas').css('height'));
var overviewWidth = $('#overviewMiniView').attr('width');
var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxX = portX / windowWidth * overviewWidth;
var viewBoxY = portY / windowHeight * overviewHeight;
var viewBoxWidth = portWidth / windowWidth * overviewWidth;
var viewBoxHeight = portHeight / windowHeight * overviewHeight;
$('#overview_window_view_box').css('min-width', viewBoxWidth + 'px');
$('#overview_window_view_box').css('min-height', viewBoxHeight + 'px');
$('#overview_window_view_box').css('top', viewBoxY + 'px');
$('#overview_window_view_box').css('left', viewBoxX + 'px');
};
$('#workarea').scroll(function () {
if (!overviewWindowGlobals.viewBoxDragging) {
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 viewWidth = $('#svgroot').attr('width');
var viewHeight = $('#svgroot').attr('height');
var viewX = 640;
var viewY = 480;
if (isIE()) {
// 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.
@ -85,10 +81,11 @@ var svgEditorExtension_overview_window = (function () {
$('#overviewMiniView').attr('height', svgHeightNew);
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;
var updateViewPortFromViewBox = function updateViewPortFromViewBox() {
var windowWidth = parseFloat($('#svgcanvas').css('width'));
var windowHeight = parseFloat($('#svgcanvas').css('height'));
@ -96,13 +93,12 @@ var svgEditorExtension_overview_window = (function () {
var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxX = parseFloat($('#overview_window_view_box').css('left'));
var viewBoxY = parseFloat($('#overview_window_view_box').css('top'));
var portX = viewBoxX / overviewWidth * windowWidth;
var portY = viewBoxY / overviewHeight * windowHeight;
$('#workarea').scrollLeft(portX);
$('#workarea').scrollTop(portY);
};
$('#overview_window_view_box').draggable({
containment: 'parent',
drag: updateViewPortFromViewBox,
@ -121,19 +117,21 @@ var svgEditorExtension_overview_window = (function () {
var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxWidth = parseFloat($('#overview_window_view_box').css('min-width'));
var viewBoxHeight = parseFloat($('#overview_window_view_box').css('min-height'));
var viewBoxX = mouseX - 0.5 * viewBoxWidth;
var viewBoxY = mouseY - 0.5 * viewBoxHeight;
// deal with constraints
var viewBoxY = mouseY - 0.5 * viewBoxHeight; // deal with constraints
if (viewBoxX < 0) {
viewBoxX = 0;
}
if (viewBoxY < 0) {
viewBoxY = 0;
}
if (viewBoxX + viewBoxWidth > overviewWidth) {
viewBoxX = overviewWidth - viewBoxWidth;
}
if (viewBoxY + viewBoxHeight > overviewHeight) {
viewBoxY = overviewHeight - viewBoxHeight;
}
@ -142,7 +140,6 @@ var svgEditorExtension_overview_window = (function () {
$('#overview_window_view_box').css('left', viewBoxX + 'px');
updateViewPortFromViewBox();
});
return {
name: 'overview window',
canvasUpdated: updateViewDimensions,

View File

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

View File

@ -1,27 +1,33 @@
var svgEditorExtension_php_savefile = (function () {
'use strict';
/* globals jQuery */
// TODO: Might add support for "exportImage" custom
// handler as in "ext-server_opensave.js" (and in savefile.php)
var extPhp_savefile = {
name: 'php_savefile',
init: function init() {
init: function init(_ref) {
var $ = _ref.$;
var svgEditor = this;
var $ = jQuery;
var svgCanvas = svgEditor.canvas;
/**
* Get file name out of SVGEdit document title.
* @returns {string}
*/
function getFileNameFromTitle() {
var title = svgCanvas.getDocumentTitle();
return title.trim();
}
var saveSvgAction = svgEditor.curConfig.extPath + 'savefile.php';
svgEditor.setCustomHandlers({
save: function save(win, data) {
var svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data,
filename = getFileNameFromTitle();
$.post(saveSvgAction, { output_svg: svg, filename: filename });
$.post(saveSvgAction, {
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 () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
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 {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
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-polygon.js
*
@ -41,67 +47,46 @@ var svgEditorExtension_polygon = (function () {
var extPolygon = {
name: 'polygon',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) {
var svgEditor, $, svgCanvas, importLocale, editingitex, strings, selElems, started, newFO, showPanel, setAttr, cot, sec, buttons, contextTools;
var _init = _asyncToGenerator(
/*#__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) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
sec = function sec(n) {
sec = function _ref4(n) {
return 1 / Math.cos(n);
};
cot = function cot(n) {
cot = function _ref3(n) {
return 1 / Math.tan(n);
};
setAttr = function setAttr(attr, val) {
setAttr = function _ref2(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems);
};
showPanel = function showPanel(on) {
showPanel = function _ref(on) {
var fcRules = $('#fc_rules');
if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head');
}
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#polygon_panel').toggle(on);
};
svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas;
importLocale = S.importLocale, editingitex = false;
_context.next = 10;
$ = S.$, importLocale = S.importLocale, editingitex = false;
_context.next = 9;
return importLocale();
case 10:
case 9:
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
@ -110,6 +95,7 @@ var svgEditorExtension_polygon = (function () {
* @param {string} tex The itex text.
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/
/*
function setItexString(tex) {
const mathns = 'http://www.w3.org/1998/Math/MathML',
@ -170,7 +156,7 @@ var svgEditorExtension_polygon = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg',
buttons: strings.buttons.map(function (button, i) {
@ -179,123 +165,122 @@ var svgEditorExtension_polygon = (function () {
context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool);
}),
callback: function callback() {
$('#polygon_panel').hide();
// TODO: Needs to be done after orig icon loads
setTimeout(function () {
// Create source save/cancel buttons
/* const save = */$('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
/* const save = */
$('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
if (!editingitex) {
return;
}
// }
} // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint?
// setSelectMode();
});
/* const cancel = */
/* 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);
},
mouseDown: function mouseDown(opts) {
// const e = opts.event;
var rgb = svgCanvas.getColor('fill');
// const ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke');
// ccSRgbEl = sRgb.substring(1, rgb.length);
if (svgCanvas.getMode() !== 'polygon') {
return undefined;
} // const e = opts.event;
var rgb = svgCanvas.getColor('fill'); // const ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke'); // ccSRgbEl = sRgb.substring(1, rgb.length);
var sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() === 'polygon') {
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon',
attr: {
cx: opts.start_x,
cy: opts.start_y,
id: svgCanvas.getNextId(),
shape: 'regularPoly',
sides: document.getElementById('polySides').value,
orient: 'x',
edge: 0,
fill: rgb,
strokecolor: sRgb,
strokeWidth: sWidth
}
});
return {
started: true
};
}
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon',
attr: {
cx: opts.start_x,
cy: opts.start_y,
id: svgCanvas.getNextId(),
shape: 'regularPoly',
sides: document.getElementById('polySides').value,
orient: 'x',
edge: 0,
fill: rgb,
strokecolor: sRgb,
strokeWidth: sWidth
}
});
return {
started: true
};
},
mouseMove: function mouseMove(opts) {
if (!started) {
return;
}
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;
if (!started || svgCanvas.getMode() !== 'polygon') {
return undefined;
} // const e = opts.event;
newFO.setAttributeNS(null, 'edge', edg);
var inradius = edg / 2 * cot(Math.PI / sides);
var circumradius = inradius * sec(Math.PI / sides);
var points = '';
for (var s = 0; sides >= s; s++) {
var angle = 2.0 * Math.PI * s / sides;
x = circumradius * Math.cos(angle) + cx;
y = circumradius * Math.sin(angle) + cy;
var c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']);
var x = opts.mouse_x;
var y = opts.mouse_y;
var cx = c.cx,
cy = c.cy,
fill = c.fill,
strokecolor = c.strokecolor,
strokeWidth = c.strokeWidth,
sides = c.sides,
edg = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5;
newFO.setAttribute('edge', edg);
var inradius = edg / 2 * cot(Math.PI / sides);
var circumradius = inradius * sec(Math.PI / sides);
var points = '';
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.setAttributeNS(null, 'fill', fill);
newFO.setAttributeNS(null, 'stroke', strokecolor);
newFO.setAttributeNS(null, 'stroke-width', strokeWidth);
// newFO.setAttributeNS(null, 'transform', 'rotate(-90)');
// const shape = newFO.getAttributeNS(null, 'shape');
// newFO.append(poly);
// DrawPoly(cx, cy, sides, edg, orient);
return {
started: true
};
}
newFO.setAttribute('points', points);
newFO.setAttribute('fill', fill);
newFO.setAttribute('stroke', strokecolor);
newFO.setAttribute('stroke-width', strokeWidth); // newFO.setAttribute('transform', 'rotate(-90)');
// const shape = newFO.getAttribute('shape');
// newFO.append(poly);
// DrawPoly(cx, cy, sides, edg, orient);
return {
started: true
};
},
mouseUp: function mouseUp(opts) {
if (svgCanvas.getMode() === 'polygon') {
var attrs = $(newFO).attr('edge');
var keep = attrs.edge !== '0';
// svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
if (svgCanvas.getMode() !== 'polygon') {
return undefined;
}
var attrs = $(newFO).attr('edge');
var keep = attrs.edge !== '0'; // svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
},
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
selElems = opts.elems;
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && elem.getAttributeNS(null, 'shape') === 'regularPoly') {
if (elem && elem.getAttribute('shape') === 'regularPoly') {
if (opts.selectedElement && !opts.multiselected) {
$('#polySides').val(elem.getAttribute('sides'));
showPanel(true);
} else {
showPanel(false);
@ -305,13 +290,11 @@ var svgEditorExtension_polygon = (function () {
}
}
},
elementChanged: function elementChanged(opts) {
// const elem = opts.elems[0];
}
elementChanged: function elementChanged(opts) {}
});
case 15:
case 'end':
case 13:
case "end":
return _context.stop();
}
}
@ -319,7 +302,7 @@ var svgEditorExtension_polygon = (function () {
}));
function init(_x) {
return _ref.apply(this, arguments);
return _init.apply(this, arguments);
}
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 () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
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 {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
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);
});
};
};
}
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
*
@ -42,14 +86,15 @@ var svgEditorExtension_shapes = (function () {
var extShapes = {
name: 'shapes',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, $, canv, svgroot, lastBBox, categories, library, modeId, startClientPos, currentD, curShapeId, curShape, startX, startY, curLib, loadIcons, makeButtons, loadLibrary, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
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) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
loadLibrary = function loadLibrary(catId) {
loadLibrary = function _ref8(catId) {
var lib = library[catId];
if (!lib) {
@ -65,61 +110,59 @@ var svgEditorExtension_shapes = (function () {
});
return;
}
curLib = lib;
if (!lib.buttons.length) {
makeButtons(catId, lib);
}
loadIcons();
};
makeButtons = function makeButtons(cat, shapes) {
makeButtons = function _ref7(cat, shapes) {
var size = curLib.size || 300;
var fill = curLib.fill || false;
var off = size * 0.05;
var vb = [-off, -off, size + off * 2, size + off * 2].join(' ');
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 width = 24;
var height = 24;
shapeIcon.documentElement.setAttribute('width', width);
shapeIcon.documentElement.setAttribute('height', height);
var svgElem = $(document.importNode(shapeIcon.documentElement, true));
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();
icon.find('path').attr('d', pathD);
var iconBtn = icon.wrap('<div class="tool_button">').parent().attr({
id: modeId + '_' + id,
title: id
});
// Store for later use
curLib.buttons.push(iconBtn[0]);
}
}); // Store for later use
return iconBtn[0];
});
};
loadIcons = function loadIcons() {
loadIcons = function _ref6() {
$('#shape_buttons').empty().append(curLib.buttons);
};
_context.next = 5;
$ = _ref.$, importLocale = _ref.importLocale;
_context.next = 6;
return importLocale();
case 5:
case 6:
strings = _context.sent;
svgEditor = this;
$ = jQuery;
canv = svgEditor.canvas;
svgroot = canv.getRootElem();
lastBBox = {};
// This populates the category list
lastBBox = {}; // This populates the category list
categories = strings.categories;
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',
plaque: 'm-0.00197,49.94376l0,0c27.5829,0 49.94327,-22.36036 49.94327,-49.94327l199.76709,0l0,0c0,27.5829 22.36037,49.94327 49.94325,49.94327l0,199.7671l0,0c-27.58289,0 -49.94325,22.36034 -49.94325,49.94325l-199.76709,0c0,-27.58292 -22.36037,-49.94325 -49.94327,-49.94325z',
page: 'm249.3298,298.99744l9.9335,-39.73413l39.73413,-9.93355l-49.66763,49.66768l-248.33237,0l0,-298.00001l298.00001,0l0,248.33234'
},
buttons: []
}
};
modeId = 'shapelib';
startClientPos = {};
currentD = void 0, curShapeId = void 0, curShape = void 0, startX = void 0, startY = void 0;
curLib = library.basic;
/**
*
* @returns {undefined}
*/
buttons = [{
id: 'tool_shapelib',
icon: svgEditor.curConfig.extIconsPath + 'shapes.png',
type: 'mode_flyout', // _flyout
type: 'mode_flyout',
// _flyout
position: 6,
events: {
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',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
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">');
$('#tools_shapelib > *').wrapAll(btnDiv);
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) {
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
.mouseup();
canv.setMode(modeId);
curShapeId = btn[0].id.substr((modeId + '_').length);
currentD = curLib.data[curShapeId];
$('.tools_flyout').fadeOut();
});
var shapeCats = $('<div id="shape_cats">');
var catStr = '';
$.each(categories, function (id, label) {
catStr += '<div data-cat=' + id + '>' + label + '</div>';
});
shapeCats.html(catStr).children().bind('mouseup', function () {
var catlink = $(this);
catlink.siblings().removeClass('current');
catlink.addClass('current');
loadLibrary(catlink.attr('data-cat')); // Get stuff
loadLibrary(catlink.attr('data-cat'));
// Get stuff
return false;
});
shapeCats.children().eq(0).addClass('current');
$('#tools_shapelib').append(shapeCats);
shower.mouseup(function () {
canv.setMode(currentD ? modeId : 'select');
});
$('#tool_shapelib').remove();
var h = $('#tools_shapelib').height();
$('#tools_shapelib').css({
'margin-top': -(h / 2 - 15),
'margin-left': 3
});
// Now add shape categories from locale
}); // Now add shape categories from locale
var cats = {};
for (var o in categories) {
cats['#shape_cats [data-cat="' + o + '"]'] = categories[o];
}
Object.entries(categories).forEach(function (_ref4) {
var _ref5 = _slicedToArray(_ref4, 2),
o = _ref5[0],
categoryName = _ref5[1];
cats['#shape_cats [data-cat="' + o + '"]'] = categoryName;
});
this.setStrings('content', cats);
},
mouseDown: function mouseDown(opts) {
var mode = canv.getMode();
if (mode !== modeId) {
return;
return undefined;
}
startX = opts.start_x;
@ -257,10 +295,8 @@ var svgEditorExtension_shapes = (function () {
startY = opts.start_y;
var y = startY;
var curStyle = canv.getStyle();
startClientPos.x = opts.event.clientX;
startClientPos.y = opts.event.clientY;
curShape = canv.addSVGElementFromJson({
element: 'path',
curStyles: true,
@ -270,43 +306,39 @@ var svgEditorExtension_shapes = (function () {
opacity: curStyle.opacity / 2,
style: 'pointer-events:none'
}
});
}); // Make sure shape uses absolute values
// Make sure shape uses absolute values
if (/[a-z]/.test(currentD)) {
currentD = curLib.data[curShapeId] = canv.pathActions.convertPath(curShape);
curShape.setAttribute('d', currentD);
canv.pathActions.fixEnd(curShape);
}
curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.005) translate(' + -x + ',' + -y + ')');
canv.recalculateDimensions(curShape);
/* const tlist = */
/* const tlist = */canv.getTransformList(curShape);
canv.getTransformList(curShape);
lastBBox = curShape.getBBox();
return {
started: true
};
},
mouseMove: function mouseMove(opts) {
var mode = canv.getMode();
if (mode !== modeId) {
return;
}
var zoom = canv.getZoom();
var evt = opts.event;
var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom;
var tlist = canv.getTransformList(curShape),
box = curShape.getBBox(),
left = box.x,
top = box.y;
// {width, height} = box,
top = box.y; // {width, height} = box,
// const dx = (x - startX), dy = (y - startY);
var newbox = {
@ -315,7 +347,6 @@ var svgEditorExtension_shapes = (function () {
width: Math.abs(x - startX),
height: Math.abs(y - startY)
};
/*
// This is currently serving no purpose, so commenting out
let sy = height ? (height + dy) / height : 1,
@ -323,49 +354,48 @@ var svgEditorExtension_shapes = (function () {
*/
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;
if (x < startX) {
tx = lastBBox.width;
}
var ty = 0;
if (y < startY) {
ty = lastBBox.height;
}
} // update the transform list with translate,scale,translate
// update the transform list with translate,scale,translate
var translateOrigin = svgroot.createSVGTransform(),
scale = svgroot.createSVGTransform(),
translateBack = svgroot.createSVGTransform();
translateOrigin.setTranslate(-(left + tx), -(top + ty));
if (!evt.shiftKey) {
var max = Math.min(Math.abs(sx), Math.abs(sy));
sx = max * (sx < 0 ? -1 : 1);
sy = max * (sy < 0 ? -1 : 1);
}
scale.setScale(sx, sy);
scale.setScale(sx, sy);
translateBack.setTranslate(left + tx, top + ty);
tlist.appendItem(translateBack);
tlist.appendItem(scale);
tlist.appendItem(translateOrigin);
canv.recalculateDimensions(curShape);
lastBBox = curShape.getBBox();
},
mouseUp: function mouseUp(opts) {
var mode = canv.getMode();
if (mode !== modeId) {
return;
return undefined;
}
var keepObject = opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y;
return {
keep: keepObject,
element: curShape,
@ -374,8 +404,8 @@ var svgEditorExtension_shapes = (function () {
}
});
case 19:
case 'end':
case 18:
case "end":
return _context.stop();
}
}
@ -383,7 +413,7 @@ var svgEditorExtension_shapes = (function () {
}));
function init(_x) {
return _ref2.apply(this, arguments);
return _init.apply(this, arguments);
}
return init;

View File

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

View File

@ -1,36 +1,80 @@
var svgEditorExtension_storage = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
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 {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
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);
});
};
};
}
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
*
@ -55,26 +99,31 @@ var svgEditorExtension_storage = (function () {
*/
var extStorage = {
name: 'storage',
init: function init() {
init: function init(_ref) {
var $ = _ref.$;
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
// said "no"; instead, we'll let those who already set it, delete it themselves;
// to change, set the "emptyStorageOnDecline" config setting to true
// in svgedit-config-iife.js/svgedit-config-es.js.
var _svgEditor$curConfig = svgEditor.curConfig,
emptyStorageOnDecline = _svgEditor$curConfig.emptyStorageOnDecline,
noStorageOnLoad = _svgEditor$curConfig.noStorageOnLoad,
forceStorage = _svgEditor$curConfig.forceStorage;
var storage = svgEditor.storage;
var storage = svgEditor.storage,
updateCanvas = svgEditor.updateCanvas;
/**
* Replace `storagePrompt` parameter within URL.
* @param {string} val
* @returns {undefined}
*/
function replaceStoragePrompt(val) {
val = val ? 'storagePrompt=' + val : '';
var loc = top.location; // Allow this to work with the embedded editor as well
if (loc.href.includes('storagePrompt=')) {
loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
return (val ? n1 : '') + val + (!val && amp ? n1 : amp || '');
@ -83,9 +132,18 @@ var svgEditorExtension_storage = (function () {
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) {
if (storage) {
var name = 'svgedit-' + svgEditor.curConfig.canvasName;
if (!val) {
storage.removeItem(name);
} else {
@ -93,29 +151,43 @@ var svgEditorExtension_storage = (function () {
}
}
}
/**
* Set the cookie to expire.
* @param {string} cookie
* @returns {undefined}
*/
function expireCookie(cookie) {
document.cookie = encodeURIComponent(cookie) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
}
/**
* Expire the storage cookie.
* @returns {undefined}
*/
function removeStoragePrefCookie() {
expireCookie('store');
expireCookie('svgeditstore');
}
/**
* Empties storage for each of the current preferences.
* @returns {undefined}
*/
function emptyStorage() {
setSVGContentStorage('');
for (var name in svgEditor.curPrefs) {
if (svgEditor.curPrefs.hasOwnProperty(name)) {
name = 'svg-edit-' + name;
if (storage) {
storage.removeItem(name);
}
expireCookie(name);
}
}
}
Object.keys(svgEditor.curPrefs).forEach(function (name) {
name = 'svg-edit-' + 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
@ -124,175 +196,219 @@ var svgEditorExtension_storage = (function () {
* content into storage)
* 2. Use localStorage to set SVG contents (potentially too large to allow in cookies)
* 3. Use localStorage (where available) or cookies to set preferences.
* @returns {undefined}
*/
function setupBeforeUnloadListener() {
window.addEventListener('beforeunload', function (e) {
// 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;
}
if (document.cookie.match(/(?:^|;\s*)store=prefsAndContent/)) {
if (document.cookie.match(/(?:^|;\s*)svgeditstore=prefsAndContent/)) {
setSVGContentStorage(svgCanvas.getSvgString());
}
svgEditor.setConfig({ no_save_warning: true }); // No need for explicit saving at all once storage is on
svgEditor.setConfig({
no_save_warning: true
}); // No need for explicit saving at all once storage is on
// svgEditor.showSaveWarning = false;
var curPrefs = svgEditor.curPrefs;
Object.entries(curPrefs).forEach(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
key = _ref3[0],
val = _ref3[1];
var store = val !== undefined;
key = 'svg-edit-' + key;
for (var key in curPrefs) {
if (curPrefs.hasOwnProperty(key)) {
// 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';
}
if (!store) {
return;
}
}
}, 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;
return {
name: 'storage',
langReady: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var _$$deparam$querystrin, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight;
var _langReady = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref4) {
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) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
importLocale = _ref4.importLocale;
_$$deparam$querystrin = $.deparam.querystring(true), storagePrompt = _$$deparam$querystrin.storagePrompt;
_context.next = 3;
_context.next = 4;
return importLocale();
case 3:
case 4:
confirmSetStorage = _context.sent;
message = confirmSetStorage.message, storagePrefsAndContent = confirmSetStorage.storagePrefsAndContent, storagePrefsOnly = confirmSetStorage.storagePrefsOnly, storagePrefs = confirmSetStorage.storagePrefs, storageNoPrefsOrContent = confirmSetStorage.storageNoPrefsOrContent, storageNoPrefs = confirmSetStorage.storageNoPrefs, rememberLabel = confirmSetStorage.rememberLabel, rememberTooltip = confirmSetStorage.rememberTooltip;
// No need to run this one-time dialog again just because the user
message = confirmSetStorage.message, storagePrefsAndContent = confirmSetStorage.storagePrefsAndContent, storagePrefsOnly = confirmSetStorage.storagePrefsOnly, storagePrefs = confirmSetStorage.storagePrefs, storageNoPrefsOrContent = confirmSetStorage.storageNoPrefsOrContent, storageNoPrefs = confirmSetStorage.storageNoPrefs, rememberLabel = confirmSetStorage.rememberLabel, rememberTooltip = confirmSetStorage.rememberTooltip; // No need to run this one-time dialog again just because the user
// changes the language
if (!loaded) {
_context.next = 7;
_context.next = 8;
break;
}
return _context.abrupt('return');
return _context.abrupt("return");
case 7:
loaded = true;
// Note that the following can load even if "noStorageOnLoad" is
case 8:
loaded = true; // Note that the following can load even if "noStorageOnLoad" is
// set to false; to avoid any chance of storage, avoid this
// extension! (and to avoid using any prior storage, set the
// config option "noStorageOnLoad" to true).
if (!forceStorage && (
// If the URL has been explicitly set to always prompt the
if (!(!forceStorage && ( // If the URL has been explicitly set to always prompt the
// user (e.g., so one can be pointed to a URL where one
// can alter one's settings, say to prevent future storage)...
storagePrompt === true ||
// ...or...if the URL at least doesn't explicitly prevent a
storagePrompt === true || // ...or...if the URL at least doesn't explicitly prevent a
// storage prompt (as we use for users who
// don't want to set cookies at all but who don't want
// continual prompts about it)...
storagePrompt !== false &&
// ...and this user hasn't previously indicated a desire for storage
!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)
// ...then show the storage prompt.
)) {
options = [];
storagePrompt !== false && // ...and this user hasn't previously indicated a desire for storage
!document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/) // ...then show the storage prompt.
))) {
_context.next = 44;
break;
}
if (storage) {
options.unshift({ value: 'prefsAndContent', text: storagePrefsAndContent }, { value: 'prefsOnly', text: storagePrefsOnly }, { value: 'noPrefsOrContent', text: storageNoPrefsOrContent });
} else {
options.unshift({ value: 'prefsOnly', text: storagePrefs }, { value: 'noPrefsOrContent', text: storageNoPrefs });
}
options = [];
// 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
$.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
if (storage) {
options.unshift({
value: 'prefsAndContent',
text: storagePrefsAndContent
}, {
value: 'prefsOnly',
text: storagePrefsOnly
}, {
value: 'noPrefsOrContent',
text: storageNoPrefsOrContent
});
} 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();
}
case 9:
case 'end':
case 45:
case "end":
return _context.stop();
}
}
@ -300,7 +416,7 @@ var svgEditorExtension_storage = (function () {
}));
function langReady(_x) {
return _ref2.apply(this, arguments);
return _langReady.apply(this, arguments);
}
return langReady;

View File

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

View File

@ -1,11 +1,39 @@
var svgEditorExtension_xdomain_messaging = (function () {
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
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);
}
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),
@ -17,42 +45,51 @@ var svgEditorExtension_xdomain_messaging = (function () {
init: function init() {
var svgEditor = this;
var svgCanvas = svgEditor.canvas;
try {
window.addEventListener('message', function (e) {
// We accept and post strings for the sake of IE9 support
if (typeof e.data !== 'string' || e.data.charAt() === '|') {
if (!e.data || !['string', 'object'].includes(_typeof(e.data)) || e.data.charAt() === '|') {
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;
}
// 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
} // The default is not to allow any origins, including even the same domain or
// if run on a `file:///` URL. See `svgedit-config-es.js` for an example of how
// to configure
var allowedOrigins = svgEditor.curConfig.allowedOrigins;
if (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) {
console.log('Origin ' + 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;
}
var cbid = data.id;
var name = data.name,
args = data.args;
var message = {
namespace: 'svg-edit',
id: cbid
};
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) {
message.error = err.message;
}
e.source.postMessage(JSON.stringify(message), '*');
}, false);
});
} 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 () {
'use strict';
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
return target;
};
return _extends.apply(this, arguments);
}
/* globals jQuery */
var $ = jQuery;
$('a').click(function () {
var href = this.href;
var target = window.parent;
var post = function post(message) {
// Todo: Make origin customizable as set by opening window
// Todo: If dropping IE9, avoid stringifying
target.postMessage(JSON.stringify(_extends({
namespace: 'imagelib'
}, message)), '*');
};
// Convert Non-SVG images to data URL first
}; // Convert Non-SVG images to data URL first
// (this could also have been done server-side by the library)
// Send metadata (also indicates file is about to be sent)
post({
name: $(this).text(),
id: href
});
if (!this.href.includes('.svg')) {
if (!href.includes('.svg')) {
var img = new Image();
img.onload = function () {
img.addEventListener('load', function () {
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
// load the raster image into the canvas
canvas.getContext('2d').drawImage(this, 0, 0);
// retrieve the data: URL
var data = void 0;
canvas.height = this.height; // load the raster image into the canvas
canvas.getContext('2d').drawImage(this, 0, 0); // retrieve the data: URL
var data;
try {
data = canvas.toDataURL();
} catch (err) {
// This fails in Firefox with file:// URLs :(
alert('Data URL conversion failed: ' + err);
// This fails in Firefox with `file:///` URLs :(
// Todo: This could use a generic alert library instead
alert('Data URL conversion failed: ' + err); // eslint-disable-line no-alert
data = '';
}
post({ href: href, data: data });
};
post({
href: href,
data: data
});
});
img.src = href;
} else {
// Do ajax request for image's href value
$.get(href, function (data) {
post({ href: href, data: data });
post({
href: href,
data: data
});
}, 'html'); // 'html' is necessary to keep returned data as a string
}
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 () {
'use strict';
var classCallCheck = function (instance, Constructor) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
}
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
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 (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) {
function _arrayWithoutHoles(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;
} 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
@ -224,157 +232,166 @@
whitesmoke: 'f5f5f5',
yellow: 'ffff00',
yellowgreen: '9acd32'
};
}; // array of color definition objects
// array of color definition objects
var colorDefs = [{
re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
process: function process(bits) {
return [parseInt(bits[1], 10), parseInt(bits[2], 10), parseInt(bits[3], 10)];
process: function process(_) {
for (var _len = arguments.length, bits = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
bits[_key - 1] = arguments[_key];
}
return bits.map(function (b) {
return parseInt(b);
});
}
}, {
re: /^(\w{2})(\w{2})(\w{2})$/,
example: ['#00ff00', '336699'],
process: function process(bits) {
return [parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16)];
process: function process(_) {
for (var _len2 = arguments.length, bits = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
bits[_key2 - 1] = arguments[_key2];
}
return bits.map(function (b) {
return parseInt(b, 16);
});
}
}, {
re: /^(\w{1})(\w{1})(\w{1})$/,
example: ['#fb0', 'f0f'],
process: function process(bits) {
return [parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16)];
process: function process(_) {
for (var _len3 = arguments.length, bits = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
bits[_key3 - 1] = arguments[_key3];
}
return bits.map(function (b) {
return parseInt(b + b, 16);
});
}
}];
/**
* A class to parse color values
* A class to parse color values.
*/
var RGBColor = function () {
var RGBColor =
/*#__PURE__*/
function () {
/**
* @param {string} 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) === '#') {
// remove # if any
colorString = colorString.substr(1, 6);
}
colorString = colorString.replace(/ /g, '');
colorString = colorString.toLowerCase();
// before getting into regexps, try simple matches
colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches
// and overwrite the input
if (colorString in simpleColors) {
colorString = simpleColors[colorString];
}
// end of simple type-in colors
} // end of simple type-in colors
// search through the definitions to find a match
for (var i = 0; i < colorDefs.length; i++) {
var re = colorDefs[i].re;
var processor = colorDefs[i].process;
colorDefs.forEach(function (_ref) {
var re = _ref.re,
processor = _ref.process;
var bits = re.exec(colorString);
if (bits) {
var _processor = processor(bits),
_processor2 = slicedToArray(_processor, 3),
var _processor = processor.apply(void 0, _toConsumableArray(bits)),
_processor2 = _slicedToArray(_processor, 3),
r = _processor2[0],
g = _processor2[1],
b = _processor2[2];
Object.assign(this, { r: r, g: g, b: b });
this.ok = true;
Object.assign(_this, {
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.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g;
this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b;
}
} // some getters
// some getters
/**
* @returns {string}
*/
createClass(RGBColor, [{
key: 'toRGB',
_createClass(RGBColor, [{
key: "toRGB",
value: function toRGB() {
return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
}
/**
* @returns {string}
*/
}, {
key: 'toHex',
key: "toHex",
value: function toHex() {
var r = this.r.toString(16);
var g = this.g.toString(16);
var b = this.b.toString(16);
if (r.length === 1) {
r = '0' + r;
}
if (g.length === 1) {
g = '0' + g;
}
if (b.length === 1) {
b = '0' + b;
}
return '#' + r + g + b;
}
/**
* 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;
}();
/* 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 pdfSvgAttr = {
@ -384,6 +401,8 @@
rect: ['x', 'y', 'width', 'height', 'stroke', 'fill', 'stroke-width'],
ellipse: ['cx', 'cy', 'rx', 'ry', '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']
};
@ -403,12 +422,50 @@
toRemove.push(a.name);
}
});
toRemove.forEach(function (a) {
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) {
// pdf is a jsPDF object
// console.log('options =', options);
@ -419,11 +476,14 @@
// console.log('passing: ', node);
// let hasStrokeColor = false;
var hasFillColor = false;
var fillRGB = void 0;
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle', 'text'])) {
var fillRGB;
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle', 'polygon', 'polyline', 'text'])) {
var fillColor = node.getAttribute('fill');
if (attributeIsNotEmpty(fillColor)) {
fillRGB = new RGBColor(fillColor);
if (fillRGB.ok) {
hasFillColor = true;
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) {
pdf.setFillColor(fillRGB.r, fillRGB.g, fillRGB.b);
}
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');
if (attributeIsNotEmpty(strokeColor)) {
var strokeRGB = new RGBColor(strokeColor);
if (strokeRGB.ok) {
// hasStrokeColor = true;
pdf.setDrawColor(strokeRGB.r, strokeRGB.g, strokeRGB.b);
if (colorMode === 'F') {
colorMode = 'FD';
} else {
colorMode = null;
colorMode = 'S';
}
} else {
colorMode = null;
}
}
}
switch (node.tagName.toLowerCase()) {
var tag = node.tagName.toLowerCase();
switch (tag) {
case 'svg':
case 'a':
case 'g':
svgElementToPdf(node, pdf, options);
removeAttributes(node, pdfSvgAttr.g);
break;
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);
break;
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);
break;
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);
break;
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);
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) {
var box = void 0;
try {
box = node.getBBox(); // Firefox on MacOS will raise error here
} catch (err) {
// copy and append to body so that getBBox is available
var nodeCopy = node.cloneNode(true);
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);
case 'polygon':
case 'polyline':
{
var linesOptions = getLinesOptionsOfPoly(node);
if (linesOptions) {
pdf.lines(linesOptions.lines, k * linesOptions.x, k * linesOptions.y, [k, k], colorMode, tag === 'polygon' // polygon is closed, polyline is not closed
);
}
return box.width;
};
// FIXME: use more accurate positioning!!
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);
removeAttributes(node, pdfSvgAttr.polygon);
break; // TODO: path
}
// console.log('fontSize:', pdfFontSize, 'text:', node.textContent);
pdf.setFontSize(pdfFontSize).text(k * x, k * y, node.textContent);
removeAttributes(node, pdfSvgAttr.text);
break;
// TODO: image
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')) : 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:
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();
}
}
});
return pdf;
@ -571,6 +693,7 @@
if (typeof element === 'string') {
element = new DOMParser().parseFromString(element, 'text/xml').documentElement;
}
svgElementToPdf(element, this, options);
return this;
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -209,7 +209,7 @@ var svgEditorLang_da = (function () {
unsavedChanges: 'There are unsaved changes.',
enterNewLinkURL: 'Enter the new hyperlink URL',
errorLoadingSVG: 'Error: Unable to load SVG data',
URLloadFail: 'Unable to load from URL',
URLLoadFail: 'Unable to load from URL',
retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser',
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.',
enterNewLinkURL: 'Geben Sie die neue URL ein',
errorLoadingSVG: 'Fehler: Kann SVG-Daten nicht laden',
URLloadFail: 'Kann von dieser URL nicht laden',
URLLoadFail: 'Kann von dieser URL nicht laden',
retrieving: "Retrieving '%s' ...",
popupWindowBlocked: 'Popup window may be blocked by browser',
exportNoBlur: 'Blurred elements will appear as un-blurred',

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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