* stricter linter

* Update .eslintrc.js

* Update control-points.js
master
JFH 2021-05-01 15:26:36 +02:00 committed by GitHub
parent 0d2048c53d
commit a90fe20d32
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 273 additions and 647 deletions

View File

@ -1,15 +1,10 @@
node_modules node_modules
ignore
coverage coverage
instrumented instrumented
dist dist
docs/jsdoc
archive archive
jsconfig.json
mochawesome-report mochawesome-report
releases
!.eslintrc.js !.eslintrc.js
!.ncurc.js !.ncurc.js
@ -21,11 +16,6 @@ svgedit-custom.css
# Vendor/minified files # Vendor/minified files
src/editor/jquery.min.js src/editor/jquery.min.js
src/editor/jspdf/jspdf.min.js
src/editor/jspdf/underscore-min.js
src/editor/extensions/ext-mathjax/mathjax src/editor/extensions/ext-mathjax/mathjax
# jquery files
src/editor/jgraduate/jQuery.jPicker.js

View File

@ -8,7 +8,8 @@ module.exports = {
"plugin:promise/recommended", "plugin:promise/recommended",
"plugin:import/errors", "plugin:import/errors",
"plugin:markdown/recommended", "plugin:markdown/recommended",
"plugin:sonarjs/recommended" "plugin:sonarjs/recommended",
"eslint:recommended"
], ],
plugins: ["jsdoc", "promise", "html", "import", "sonarjs"], plugins: ["jsdoc", "promise", "html", "import", "sonarjs"],
parserOptions: { parserOptions: {
@ -19,262 +20,47 @@ module.exports = {
browser: true, browser: true,
es6: true es6: true
}, },
settings: {
polyfills: [
// These are the primary polyfills needed by regular users if
// not present, e.g., with core-js-bundle; also those under
// extensions
"fetch",
"Promise",
"Promise.all",
// 'Set',
"Uint8Array",
"URL"
]
},
rules: { rules: {
// check-examples is not picking up eslint config properly in some "node/no-unsupported-features/es-syntax": 0,
// environments; see also discussion above "no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
// `mocha-cleanup/no-assertions-outside-it` "sonarjs/cognitive-complexity": ["warn", 40],
"sonarjs/cognitive-complexity": 0, "sonarjs/no-duplicate-string": 0,
"sonarjs/no-duplicate-string": 0,
"sonarjs/no-collapsible-if": 0,
"sonarjs/no-small-switch": 0,
"sonarjs/no-identical-functions": 0,
"sonarjs/no-duplicated-branches": 0,
"jsdoc/check-examples": [
"warn",
{
rejectExampleCodeRegex: "^`",
checkDefaults: true,
checkParams: true,
checkProperties: true
}
],
// The Babel transform seems to have a problem converting these
"prefer-named-capture-group": "off",
"jsdoc/require-file-overview": [
"error",
{
tags: {
file: {
initialCommentsOnly: true,
preventDuplicates: true
},
license: {
initialCommentsOnly: true,
preventDuplicates: true
},
copyright: {
initialCommentsOnly: true,
preventDuplicates: true
},
author: {
initialCommentsOnly: true,
preventDuplicates: true
},
module: {
initialCommentsOnly: true,
preventDuplicates: true
},
exports: {
initialCommentsOnly: true,
preventDuplicates: true
}
}
}
],
// Warning or Off for now but should be reviewed
// Override these rules which are difficult for us
// to apply at this time
"default-case": "off",
"require-unicode-regexp": "off",
"max-len": ["warn", { ignoreComments: true, code: 130 }], // 130 is too much but too many occurences
"eslint-comments/require-description": "off",
"compat/compat": "error",
"consistent-this": "off",
"import/no-anonymous-default-export": "off",
"node/no-unsupported-features/node-builtins": "warn",
"prefer-exponentiation-operator": "warn",
"node/no-unsupported-features/es-syntax": "off",
"no-unsanitized/method": [
"error",
{
escape: {
methods: ["encodeURIComponent", "encodeURI"]
}
}
]
}, },
overrides: [ overrides: [
// Locales have no need for importing outside of SVG-Edit
// and translations may need a longer line length
{ {
files: [ files: [ 'cypress/**/*'],
'src/editor/locale/lang.*.js', extends: [
'src/editor/extensions/*/locale/**', "plugin:cypress/recommended"
'docs/tutorials/ExtensionDocs.md/*.js'
],
rules: {
"import/no-anonymous-default-export": "off",
"max-len": "off",
"node/no-missing-import": "off",
"import/no-unresolved": "off"
}
},
// These browser files don't do importing or requiring
{
files: [
"src/editor/touch.js",
"src/editor/typedefs.js",
"src/editor/redirect-on-no-module-support.js",
"src/editor/extensions/ext-imagelib/index.js",
"screencasts/svgopen2010/script.js"
],
rules: {
"import/unambiguous": ["off"]
}
},
{
files: ["**/*.html", "screencasts/**"],
globals: {
root: "off"
},
settings: {
polyfills: [
"document.querySelector",
"history",
"history.pushState",
"history.replaceState",
"location.hash",
"navigator",
"Number.parseFloat",
"Number.parseInt",
"Number.isNaN"
]
},
rules: {
"import/unambiguous": "off"
}
},
{
// As consumed by jsdoc, cannot be expressed as ESM
files: ["docs/jsdoc-config.js"],
parserOptions: {
sourceType: "script"
},
globals: {
module: false
},
rules: {
"import/no-commonjs": "off",
strict: "off"
}
},
{
files: ["cypress/**"],
extends: [
"plugin:cypress/recommended",
"plugin:mocha/recommended",
"plugin:mocha-cleanup/recommended-no-limits",
"plugin:@fintechstudios/chai-as-promised/recommended",
"plugin:chai-expect-keywords/recommended",
"plugin:chai-expect/recommended",
"plugin:chai-friendly/recommended"
], ],
env: { env: {
mocha: true,
node: true node: true
}, },
settings: { globals: {
polyfills: [ "assert": true
"console",
"Date.now",
"document.body",
"document.createElementNS",
"document.head",
"DOMParser",
"Number.isNaN",
"Object.keys",
"Object.entries",
"Promise"
]
}, },
rules: { rules: {
// These errors are caused in Cypress files if user has not // with ci, instrumented is not created before linter
// yet instrumented code; need to reinvestigate why we had to "import/no-unresolved": [2, { ignore: ['instrumented'] }],
// instrument separately from nyc mocha "node/no-missing-import": 0
"import/no-unresolved": ["error", { ignore: ["/instrumented/"] }],
"node/no-missing-import": "off",
"jsdoc/check-examples": "off",
"chai-expect-keywords/no-unsupported-keywords": [
"error",
{
allowChaiDOM: true
}
],
// Would be good but seems necessary due to some bugs in Cypress
// in detecting visibility
// 'cypress/no-force': 0,
// Good but would be difficult to enforce (and data-* may not be less
// brittle than IDs/classes anyways)
// 'cypress/require-data-selectors': 0,
"cypress/assertion-before-screenshot": 2,
// Conflicts with Cypress `should`
"mocha-cleanup/invalid-assertions": 0,
// Might see about working around to avoid the option limitation,
// but convenient
"mocha-cleanup/no-expressions-in-assertions": [
"error",
{
replacementsOnly: true
}
],
// Too oppressive when planning to extend a section
"mocha/no-hooks-for-single-case": 0,
// Would be good to enable but needs some refactoring
"mocha/no-setup-in-describe": 0,
"mocha-cleanup/no-outside-declaration": 0,
// Useful to ensure allowing `this.timeout()`, etc., but a
// little oppressive
"mocha/no-mocha-arrows": 0,
// Useful if enabling the regular `prefer-arrow-callback`
// 'mocha/prefer-arrow-callback': 2
"jsdoc/require-jsdoc": 0,
"no-console": 0,
"import/unambiguous": 0
} }
}, },
{ {
// Node files files: [ 'docs/**/*'],
files: [ rules: { // md files have example that don't need a strict checking
"docs/jsdoc-config.js", "no-undef": 0,
"build/build-html.js", "import/no-unresolved": 0,
"rollup.config.js", "node/no-missing-import": 0,
"rollup-config.config.js" "jsdoc/check-examples": [
], "warn",
env: { {
node: true rejectExampleCodeRegex: "^`",
}, checkDefaults: true,
settings: { checkParams: true,
polyfills: ["console", "Promise.resolve"] checkProperties: true
}, }
globals: { ]
require: true
},
rules: {
// We can't put Rollup in npmignore or user can't get access,
// and we have too many modules to add to `peerDependencies`
// so this rule can know them to be available, so we instead
// disable
"node/no-unpublished-import": "off"
} }
} }
] ]
}; };

View File

@ -8,7 +8,6 @@ describe('UI - Accessibility', function () {
cy.injectAxe(); cy.injectAxe();
}); });
// https://www.npmjs.com/package/cypress-axe // https://www.npmjs.com/package/cypress-axe
// eslint-disable-next-line mocha/no-skipped-tests
it.skip('Has no detectable a11y violations on load', () => { it.skip('Has no detectable a11y violations on load', () => {
// Configure aXe and test the page at initial load // Configure aXe and test the page at initial load
cy.configureAxe({ cy.configureAxe({

View File

@ -20,7 +20,7 @@ describe('UI - Control Points', function () {
</svg>`, {force: true, parseSpecialCharSequences: false}); </svg>`, {force: true, parseSpecialCharSequences: false});
cy.get('#tool_source_save').click({force: true}); cy.get('#tool_source_save').click({force: true});
cy.get('#svg_1').click().click(); cy.get('#svg_1').click({force: true}).click({force: true});
cy.get('#pathpointgrip_0').trigger('mousedown', {which: 1, force: true}) cy.get('#pathpointgrip_0').trigger('mousedown', {which: 1, force: true})
.trigger('mousemove', randomOffset(), randomOffset(), {force: true}) .trigger('mousemove', randomOffset(), randomOffset(), {force: true})

View File

@ -8,7 +8,6 @@ describe('Key commands', function () {
visitAndApproveStorage(); visitAndApproveStorage();
}); });
// eslint-disable-next-line mocha/no-skipped-tests
it.skip('cmd-A on empty canvas should not cause an error', function () { it.skip('cmd-A on empty canvas should not cause an error', function () {
cy.get('body').type('{cmd}a'); cy.get('body').type('{cmd}a');
}); });

View File

@ -44,7 +44,7 @@ describe('draw.Drawing', function () {
const getCurrentDrawing = function () { const getCurrentDrawing = function () {
return currentDrawing_; return currentDrawing_;
}; };
const setCurrentGroup = (cg) => { /* empty fn */ }; const setCurrentGroup = () => { /* empty fn */ };
draw.init( draw.init(
/** /**
* @implements {module:draw.DrawCanvasInit} * @implements {module:draw.DrawCanvasInit}

View File

@ -9,12 +9,12 @@ describe('history', function () {
// TODO(codedread): Write tests for handling history events. // TODO(codedread): Write tests for handling history events.
// Mocked out methods. // Mocked out methods.
transformlist.changeRemoveElementFromListMap((elem) => { /* empty fn */ }); transformlist.changeRemoveElementFromListMap(() => { /* empty fn */ });
utilities.mock({ utilities.mock({
getHref (elem) { return '#foo'; }, getHref () { return '#foo'; },
setHref (elem, val) { /* empty fn */ }, setHref () { /* empty fn */ },
getRotationAngle (elem) { return 0; } getRotationAngle () { return 0; }
}); });
// const svg = document.createElementNS(NS.SVG, 'svg'); // const svg = document.createElementNS(NS.SVG, 'svg');
@ -452,7 +452,7 @@ describe('history', function () {
assert.equal(val, sethrefvalue); assert.equal(val, sethrefvalue);
justCalled = 'setHref'; justCalled = 'setHref';
}, },
getRotationAngle (elem) { return 0; } getRotationAngle () { return 0; }
}); });
gethrefvalue = '#newhref'; gethrefvalue = '#newhref';
@ -488,7 +488,7 @@ describe('history', function () {
it('Test BatchCommand', function () { it('Test BatchCommand', function () {
let concatResult = ''; let concatResult = '';
MockCommand.prototype.apply = function (handler) { concatResult += this.text; }; MockCommand.prototype.apply = function () { concatResult += this.text; };
const batch = new hstory.BatchCommand(); const batch = new hstory.BatchCommand();
assert.ok(batch.unapply); assert.ok(batch.unapply);

View File

@ -55,7 +55,7 @@ describe('utilities bbox', function () {
const type = seg.pathSegType; const type = seg.pathSegType;
if (type === 1) { continue; } if (type === 1) { continue; }
const pts = []; const pts = [];
['', 1, 2].forEach(function (n, j) { ['', 1, 2].forEach(function (n) {
const x = seg['x' + n], y = seg['y' + n]; const x = seg['x' + n], y = seg['y' + n];
if (x !== undefined && y !== undefined) { if (x !== undefined && y !== undefined) {
const pt = math.transformPoint(x, y, m); const pt = math.transformPoint(x, y, m);

View File

@ -135,7 +135,7 @@ describe('utilities performance', function () {
continue; continue;
} }
const pts = []; const pts = [];
['', 1, 2].forEach(function (n, j) { ['', 1, 2].forEach(function (n) {
const x = seg['x' + n], const x = seg['x' + n],
y = seg['y' + n]; y = seg['y' + n];
if (x !== undefined && y !== undefined) { if (x !== undefined && y !== undefined) {

View File

@ -348,7 +348,7 @@ describe('utilities', function () {
const elem = { const elem = {
tagName: 'something unknown', tagName: 'something unknown',
id: 'something-unknown', id: 'something-unknown',
getAttribute (attr) { return ''; }, getAttribute () { return ''; },
parentNode: svgroot parentNode: svgroot
}; };
const path = convertToPath(elem, attrs, mockaddSVGElementFromJson, mockPathActions, mockClearSelection, mockAddToSelection, mockHistory, mockAddCommandToHistory); const path = convertToPath(elem, attrs, mockaddSVGElementFromJson, mockPathActions, mockClearSelection, mockAddToSelection, mockHistory, mockAddCommandToHistory);

View File

@ -3,7 +3,7 @@
* @param {external:chai_utils} utils * @param {external:chai_utils} utils
* @returns {void} * @returns {void}
*/ */
function setAssertionMethods (_chai, utils) { function setAssertionMethods (_chai, _utils) {
return (method) => { return (method) => {
return (...args) => { return (...args) => {
const {result, message, actual, expected} = method(...args); const {result, message, actual, expected} = method(...args);

View File

@ -32,7 +32,7 @@ Cypress.Commands.add(
{ {
prevSubject: true prevSubject: true
}, },
(subject, snapshotOptions) => { (subject, _snapshotOptions) => {
let html = subject[0].outerHTML; let html = subject[0].outerHTML;
for (const attribute of ngAttributes) { for (const attribute of ngAttributes) {

View File

@ -8,7 +8,7 @@ the SVG file differently:
### Example ### Example
```js ```js
svgEditor.setCustomHandlers({ svgEditor.setCustomHandlers({
save (win, data) { save (_win, _data) {
// Save svg // Save svg
} }
}); });

View File

@ -27,7 +27,7 @@ This is the general format for an extension:
```js ```js
export default { export default {
name: 'extensionname', name: 'extensionname',
init (methods) { init (_methods) {
return extensionData; return extensionData;
} }
}; };
@ -83,7 +83,7 @@ export default {
mouseDown () { mouseDown () {
// ... // ...
}, },
mouseUp (opts) { mouseUp (_opts) {
// ... // ...
} }
}; };

14
package-lock.json generated
View File

@ -60,7 +60,7 @@
"eslint-plugin-eslint-comments": "3.2.0", "eslint-plugin-eslint-comments": "3.2.0",
"eslint-plugin-html": "^6.1.2", "eslint-plugin-html": "^6.1.2",
"eslint-plugin-import": "^2.22.1", "eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsdoc": "^32.3.2", "eslint-plugin-jsdoc": "^32.3.3",
"eslint-plugin-markdown": "^2.1.0", "eslint-plugin-markdown": "^2.1.0",
"eslint-plugin-mocha": "8.1.0", "eslint-plugin-mocha": "8.1.0",
"eslint-plugin-mocha-cleanup": "1.9.1", "eslint-plugin-mocha-cleanup": "1.9.1",
@ -10277,9 +10277,9 @@
} }
}, },
"node_modules/eslint-plugin-jsdoc": { "node_modules/eslint-plugin-jsdoc": {
"version": "32.3.2", "version": "32.3.3",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.2.tgz", "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.3.tgz",
"integrity": "sha512-kcdg0OvhI466KgMYXwxGvP6+m9J/sIBg0Jkn9eDU5lnM6RSVM27M9zKZim2XY6AUbbdqmkBPEP4ixvtBXRHktQ==", "integrity": "sha512-WxXohbMYlZvCt3r7MepwT++nTLsO4CPegWcm5toM4IGq3MBmYkG+Uf5yDa+n1MwPXLg+KbJqAsI19hmkVD7MPg==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"comment-parser": "1.1.5", "comment-parser": "1.1.5",
@ -33395,9 +33395,9 @@
} }
}, },
"eslint-plugin-jsdoc": { "eslint-plugin-jsdoc": {
"version": "32.3.2", "version": "32.3.3",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.2.tgz", "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.3.tgz",
"integrity": "sha512-kcdg0OvhI466KgMYXwxGvP6+m9J/sIBg0Jkn9eDU5lnM6RSVM27M9zKZim2XY6AUbbdqmkBPEP4ixvtBXRHktQ==", "integrity": "sha512-WxXohbMYlZvCt3r7MepwT++nTLsO4CPegWcm5toM4IGq3MBmYkG+Uf5yDa+n1MwPXLg+KbJqAsI19hmkVD7MPg==",
"dev": true, "dev": true,
"requires": { "requires": {
"comment-parser": "1.1.5", "comment-parser": "1.1.5",

View File

@ -15,14 +15,15 @@
"scripts": { "scripts": {
"lint": "eslint --ext js,html,md .", "lint": "eslint --ext js,html,md .",
"test": "run-s cypress:instrument cypress:test", "test": "run-s cypress:instrument cypress:test",
"cypress:instrument": "rimraf instrumented && cp-cli src instrumented && nyc instrument --compact=false src instrumented",
"cypress:test": "start-server-and-test start http://localhost:8000/instrumented/editor/index.html cypress:run", "cypress:test": "start-server-and-test start http://localhost:8000/instrumented/editor/index.html cypress:run",
"cypress:run": "run-s -n -c cypress:run-no-badge report-summary-mocha-full",
"build": "rollup -c", "build": "rollup -c",
"build:watch": "rollup -c --watch", "build:watch": "rollup -c --watch",
"start": "web-dev-server --node-resolve", "start": "web-dev-server --node-resolve",
"start:watch": "web-dev-server --node-resolve --watch", "start:watch": "web-dev-server --node-resolve --watch",
"cypress:open": "run-p start cypress:open-no-start", "cypress:open": "run-p start cypress:open-no-start",
"cypress:open-no-start": "cypress open", "cypress:open-no-start": "cypress open",
"cypress:instrument": "rimraf instrumented && cp-cli src instrumented && nyc instrument --compact=false src instrumented",
"add-release": "git submodule add --depth=1 -b \"release-v$npm_config_release\" -- https://github.com/SVG-Edit/svgedit.git \"releases/svg-edit-$npm_config_release\"", "add-release": "git submodule add --depth=1 -b \"release-v$npm_config_release\" -- https://github.com/SVG-Edit/svgedit.git \"releases/svg-edit-$npm_config_release\"",
"add-new-release": "cross-var npm run add-release --release=$npm_package_version && cross-var git config --file=.gitmodules submodule.releases/latest.branch \"release-v$npm_package_version\"", "add-new-release": "cross-var npm run add-release --release=$npm_package_version && cross-var git config --file=.gitmodules submodule.releases/latest.branch \"release-v$npm_package_version\"",
"remove-release": "git submodule deinit -f \"releases/svg-edit-$npm_config_release\" && rm -rf .git/modules/releases/svg-edit-$npm_config_release && git rm -f releases/svg-edit-$npm_config_release", "remove-release": "git submodule deinit -f \"releases/svg-edit-$npm_config_release\" && rm -rf .git/modules/releases/svg-edit-$npm_config_release && git rm -f releases/svg-edit-$npm_config_release",
@ -60,7 +61,6 @@
"cypress:merge": "mochawesome-merge \"cypress/results/mochaw*.json\" > mochawesome.json && marge mochawesome.json && mbg --file ./mochawesome.json --badge_output badges/tests-badge.svg", "cypress:merge": "mochawesome-merge \"cypress/results/mochaw*.json\" > mochawesome.json && marge mochawesome.json && mbg --file ./mochawesome.json --badge_output badges/tests-badge.svg",
"cypress:run-only": "rimraf \"cypress/results/mochaw*.json\" && rimraf \".nyc_output/*\" && cypress run -q", "cypress:run-only": "rimraf \"cypress/results/mochaw*.json\" && rimraf \".nyc_output/*\" && cypress run -q",
"cypress:run-no-badge": "run-s -c cypress:run-only cypress:merge", "cypress:run-no-badge": "run-s -c cypress:run-only cypress:merge",
"cypress:run": "run-s -n -c cypress:run-no-badge report-summary-mocha-full",
"mochawesome-cli": "node tools/mochawesome-cli.js", "mochawesome-cli": "node tools/mochawesome-cli.js",
"mochawesome-cli-dot": "npm run mochawesome-cli -- --dot", "mochawesome-cli-dot": "npm run mochawesome-cli -- --dot",
"report-no-mochawesome": "nyc report", "report-no-mochawesome": "nyc report",
@ -102,8 +102,12 @@
"not IE < 12", "not IE < 12",
"not Chrome < 75", "not Chrome < 75",
"not FireFox < 68", "not FireFox < 68",
"not Safari < 10", "not Safari < 11",
"not ios_saf < 10" "not ios_saf < 10",
"not android < 5",
"not op_mini all",
"not Edge < 18",
"not dead"
], ],
"dependencies": { "dependencies": {
"@babel/polyfill": "7.12.1", "@babel/polyfill": "7.12.1",
@ -158,7 +162,7 @@
"eslint-plugin-eslint-comments": "3.2.0", "eslint-plugin-eslint-comments": "3.2.0",
"eslint-plugin-html": "^6.1.2", "eslint-plugin-html": "^6.1.2",
"eslint-plugin-import": "^2.22.1", "eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsdoc": "^32.3.2", "eslint-plugin-jsdoc": "^32.3.3",
"eslint-plugin-markdown": "^2.1.0", "eslint-plugin-markdown": "^2.1.0",
"eslint-plugin-mocha": "8.1.0", "eslint-plugin-mocha": "8.1.0",
"eslint-plugin-mocha-cleanup": "1.9.1", "eslint-plugin-mocha-cleanup": "1.9.1",

View File

@ -1,3 +1,4 @@
/* eslint-disable node/no-unpublished-import */
/* eslint-env node */ /* eslint-env node */
// This rollup script is run by the command: // This rollup script is run by the command:
// 'npm run build' // 'npm run build'

View File

@ -1,5 +1,5 @@
/* eslint-disable max-len */ /* eslint-disable max-len */
/* globals jQuery seConfirm seAlert */ /* globals seConfirm seAlert $ */
/** /**
* The main module for the visual SVG this. * The main module for the visual SVG this.
* *
@ -19,8 +19,6 @@ import { isMac } from '../common/browser.js';
import SvgCanvas from '../svgcanvas/svgcanvas.js'; import SvgCanvas from '../svgcanvas/svgcanvas.js';
import ConfigObj from './ConfigObj.js'; import ConfigObj from './ConfigObj.js';
import {mergeDeep} from './components/jgraduate/Util.js';
import EditorStartup from './EditorStartup.js'; import EditorStartup from './EditorStartup.js';
import LeftPanel from './panels/LeftPanel.js'; import LeftPanel from './panels/LeftPanel.js';
import TopPanel from './panels/TopPanel.js'; import TopPanel from './panels/TopPanel.js';
@ -29,7 +27,7 @@ import LayersPanel from './panels/LayersPanel.js';
import MainMenu from './MainMenu.js'; import MainMenu from './MainMenu.js';
import { getParentsUntil } from './components/jgraduate/Util.js'; import { getParentsUntil } from './components/jgraduate/Util.js';
const { $id, $qa, isNullish, encode64, decode64, blankPageObjectURL } = SvgCanvas; const { $id, $qa, isNullish, decode64, blankPageObjectURL } = SvgCanvas;
/** /**
@ -531,6 +529,7 @@ class Editor extends EditorStartup {
this.workarea.scroll(); this.workarea.scroll();
} }
// eslint-disable-next-line sonarjs/no-collapsible-if
if (this.configObj.urldata.storagePrompt !== true && this.storagePromptState === 'ignore') { if (this.configObj.urldata.storagePrompt !== true && this.storagePromptState === 'ignore') {
if ($id("dialog_box") != null) $id("dialog_box").style.display = 'none'; if ($id("dialog_box") != null) $id("dialog_box").style.display = 'none';
} }
@ -618,6 +617,7 @@ class Editor extends EditorStartup {
this.multiselected = (elems.length >= 2 && !isNullish(elems[1])); this.multiselected = (elems.length >= 2 && !isNullish(elems[1]));
// Only updating fields for single elements for now // Only updating fields for single elements for now
if (!this.multiselected) { if (!this.multiselected) {
// eslint-disable-next-line sonarjs/no-small-switch
switch (mode) { switch (mode) {
case 'rotate': { case 'rotate': {
const ang = this.svgCanvas.getRotationAngle(elem); const ang = this.svgCanvas.getRotationAngle(elem);
@ -764,7 +764,7 @@ class Editor extends EditorStartup {
} else { } else {
this.curContext = null; this.curContext = null;
} }
$id('cur_context_panel').style.display = (Boolean(context)) ? 'block' : 'none'; $id('cur_context_panel').style.display = context ? 'block' : 'none';
// eslint-disable-next-line no-unsanitized/property // eslint-disable-next-line no-unsanitized/property
$id('cur_context_panel').innerHTML = linkStr; $id('cur_context_panel').innerHTML = linkStr;
@ -801,9 +801,6 @@ class Editor extends EditorStartup {
*/ */
async extAdded(win, ext) { async extAdded(win, ext) {
const self = this;
// eslint-disable-next-line sonarjs/no-unused-collection
let btnSelects = [];
if (!ext) { if (!ext) {
return undefined; return undefined;
} }
@ -820,117 +817,6 @@ class Editor extends EditorStartup {
} }
}; };
if (ext.context_tools) {
ext.context_tools.forEach(function (tool, i) {
// Add select tool
const contId = tool.container_id ? (' id="' + tool.container_id + '"') : '';
let panel = $id(tool.panel);
// create the panel if it doesn't exist
if (!panel) {
panel = document.createElement("div");
panel.id = tool.panel;
$id('tools_top').appendChild(panel);
}
let html;
// TODO: Allow support for other types, or adding to existing tool
switch (tool.type) {
case 'tool_button': {
html = document.createElement("div");
html.className = "tool_button";
html.textContent = tool.id
panel.appendChild(html);
if (tool.events) {
tool.events.forEach((func, evt) => {
html.addEventListener(evt, func);
});
}
break;
} case 'select': {
label = document.createElement("label");
if (tool.container_id) {
label.id = tool.container_id;
}
html = '<select id="' + tool.id + '">';
tool.options.forEach((text, val) => {
const sel = (val === tool.defval) ? ' selected' : '';
html += '<option value="' + val + '"' + sel + '>' + text + '</option>';
});
html += '</select>';
// eslint-disable-next-line no-unsanitized/property
label.innerHTML = html;
// Creates the tool, hides & adds it, returns the select element
panel.appendChild(label);
const sel = label.querySelector('select');
tool.events.forEach((func, evt) => {
sel.addEventListener(evt, func);
});
break;
} case 'button-select': {
const div = document.createElement("div");
div.id = tool.id;
div.className = "dropdown toolset";
div.title = tool.title;
// eslint-disable-next-line no-unsanitized/property
div.innerHTML = '<div id="cur_' + tool.id + '" class="icon_label"></div><button></button>';
const list = document.createElement("ul");
list.id = tool.id;
if ($id('option_lists')) $id('option_lists').appendChild(list);
if (tool.colnum) {
list.className = ('optcols' + tool.colnum);
}
panel.appendChild(div);
// Creates the tool, hides & adds it, returns the select element
btnSelects.push({
elem: ('#' + tool.id),
list: ('#' + tool.id + '_opts'),
title: tool.title,
callback: tool.events.change,
cur: ('#cur_' + tool.id)
});
break;
} case 'input': {
const html = document.createElement("label");
if (tool.container_id) { html.id = tool.container_id; }
html.innerHTML
// eslint-disable-next-line no-unsanitized/property
html.innerHTML = '<span id="' + tool.id + '_label">' +
tool.label + ':</span>' +
'<input id="' + tool.id + '" title="' + tool.title +
'" size="' + (tool.size || '4') +
'" value="' + (tool.defval || '') + '" type="text"/>';
// Creates the tool, hides & adds it, returns the select element
// Add to given tool.panel
panel.appendChild(html);
const inp = html.querySelector('input');
if (tool.spindata) {
inp.SpinButton(tool.spindata);
}
if (tool?.events !== undefined) {
Object.entries(tool.events).forEach((entry) => {
const [evt, func] = entry;
inp.addEventListener(evt, func);
});
}
break;
} default:
break;
}
});
}
if (ext.events) { if (ext.events) {
this.leftPanel.add(ext.events.id, ext.events.click); this.leftPanel.add(ext.events.id, ext.events.click);
} }
@ -1177,7 +1063,7 @@ class Editor extends EditorStartup {
const oldLayerName = ($id('#layerlist')) ? $id('#layerlist').querySelector('tr.layersel td.layername').textContent : ""; const oldLayerName = ($id('#layerlist')) ? $id('#layerlist').querySelector('tr.layersel td.layername').textContent : "";
const renameLayer = (oldLayerName === this.uiStrings.common.layer + ' 1'); const renameLayer = (oldLayerName === this.uiStrings.common.layer + ' 1');
this.svgCanvas.setUiStrings(allStrings); // this.svgCanvas.setUiStrings(allStrings);
this.setTitles(); this.setTitles();
if (renameLayer) { if (renameLayer) {

View File

@ -62,7 +62,7 @@ class EditorStartup {
*/ */
async init () { async init () {
const self = this; const self = this;
const { i18next, langParam } = await putLocale(this.configObj.pref('lang'), this.goodLangs); const { i18next } = await putLocale(this.configObj.pref('lang'), this.goodLangs);
this.i18next = i18next; this.i18next = i18next;
// allow to prepare the dom without display // allow to prepare the dom without display
this.$svgEditor.style.visibility = 'hidden'; this.$svgEditor.style.visibility = 'hidden';
@ -291,6 +291,7 @@ class EditorStartup {
if (evt.type === 'mouseup') { panning = false; } if (evt.type === 'mouseup') { panning = false; }
return false; return false;
}); });
// eslint-disable-next-line sonarjs/no-identical-functions
$id('svgcanvas').addEventListener('mousemove', function(evt) { $id('svgcanvas').addEventListener('mousemove', function(evt) {
if (panning === false) { return true; } if (panning === false) { return true; }
@ -313,7 +314,7 @@ class EditorStartup {
return true; return true;
}); });
window.addEventListener('mouseup', function(evt) { window.addEventListener('mouseup', function() {
panning = false; panning = false;
}); });
@ -362,7 +363,7 @@ class EditorStartup {
}; };
const liElems = document.getElementById('svg_editor').querySelectorAll('button, select, input:not(#text)'); const liElems = document.getElementById('svg_editor').querySelectorAll('button, select, input:not(#text)');
Array.prototype.forEach.call(liElems, function(el, i){ Array.prototype.forEach.call(liElems, function(el){
el.addEventListener("focus", (e) => { el.addEventListener("focus", (e) => {
inp = e.currentTarget; inp = e.currentTarget;
this.uiContext = 'toolbars'; this.uiContext = 'toolbars';
@ -402,7 +403,7 @@ class EditorStartup {
height: getHeight() height: getHeight()
}; };
window.addEventListener('resize', (evt) => { window.addEventListener('resize', () => {
Object.entries(winWh).forEach(([type, val]) => { Object.entries(winWh).forEach(([type, val]) => {
const curval = (type === 'width') ? window.innerWidth - 15 : window.innerHeight; const curval = (type === 'width') ? window.innerWidth - 15 : window.innerHeight;
this.workarea['scroll' + (type === 'width' ? 'Left' : 'Top')] -= (curval - val) / 2; this.workarea['scroll' + (type === 'width' ? 'Left' : 'Top')] -= (curval - val) / 2;
@ -531,7 +532,7 @@ class EditorStartup {
$id('tool_wireframe').click(); $id('tool_wireframe').click();
} }
$id('rulers').style.display = (Boolean(this.configObj.curConfig.showRulers)) ? 'block' : 'none'; $id('rulers').style.display = (this.configObj.curConfig.showRulers) ? 'block' : 'none';
if (this.configObj.curConfig.showRulers) { if (this.configObj.curConfig.showRulers) {
$editDialog.setAttribute('showrulers', true); $editDialog.setAttribute('showrulers', true);
@ -712,6 +713,7 @@ class EditorStartup {
/** /**
* @type {module:SVGthis.ExtensionObject} * @type {module:SVGthis.ExtensionObject}
*/ */
// eslint-disable-next-line no-unsanitized/method
const imported = await import(`./extensions/${encodeURIComponent(extname)}/${encodeURIComponent(extname)}.js`); const imported = await import(`./extensions/${encodeURIComponent(extname)}/${encodeURIComponent(extname)}.js`);
const {name = extname, init: initfn} = imported.default; const {name = extname, init: initfn} = imported.default;
return this.addExtension(name, (initfn && initfn.bind(this)), {$, langParam: 'en'}); /** @todo change to current lng */ return this.addExtension(name, (initfn && initfn.bind(this)), {$, langParam: 'en'}); /** @todo change to current lng */
@ -735,9 +737,10 @@ class EditorStartup {
/** /**
* @type {module:SVGthis.ExtensionObject} * @type {module:SVGthis.ExtensionObject}
*/ */
// eslint-disable-next-line no-unsanitized/method
const imported = await import(encodeURI(extPathName)); const imported = await import(encodeURI(extPathName));
const {name, init: initfn} = imported.default; const {name, init: initfn} = imported.default;
return this.addExtension(name, (initfn && initfn.bind(this)), {$, langParam}); return this.addExtension(name, (initfn && initfn.bind(this)), {$});
} catch (err) { } catch (err) {
// Todo: Add config to alert any errors // Todo: Add config to alert any errors
console.error('Extension failed to load: ' + extPathName + '; ', err); console.error('Extension failed to load: ' + extPathName + '; ', err);
@ -748,12 +751,12 @@ class EditorStartup {
this.svgCanvas.bind( this.svgCanvas.bind(
'extensions_added', 'extensions_added',
/** /**
* @param {external:Window} win * @param {external:Window} _win
* @param {module:svgcanvas.SvgCanvas#event:extensions_added} data * @param {module:svgcanvas.SvgCanvas#event:extensions_added} _data
* @listens module:SvgCanvas#event:extensions_added * @listens module:SvgCanvas#event:extensions_added
* @returns {void} * @returns {void}
*/ */
(win, data) => { (_win, _data) => {
this.extensionsAdded = true; this.extensionsAdded = true;
this.setAll(); this.setAll();

View File

@ -1,3 +1,4 @@
/* globals seConfirm, seAlert */
import SvgCanvas from "../svgcanvas/svgcanvas.js"; import SvgCanvas from "../svgcanvas/svgcanvas.js";
import {convertUnit, isValidUnit} from '../common/units.js'; import {convertUnit, isValidUnit} from '../common/units.js';
import {isChrome} from '../common/browser.js'; import {isChrome} from '../common/browser.js';
@ -181,7 +182,7 @@ class MainMenu {
const blob = new Blob([popHTML], { type: "text/html" }); const blob = new Blob([popHTML], { type: "text/html" });
popURL = URL.createObjectURL(blob); popURL = URL.createObjectURL(blob);
} else { } else {
popURL = "data:text/html;base64;charset=utf-8," + encode64(popHTML); popURL = "data:text/html;base64;charset=utf-8," + popHTML;
} }
this.editor.loadingURL = popURL; this.editor.loadingURL = popURL;
} }
@ -334,13 +335,13 @@ class MainMenu {
this.clickOpen(); this.clickOpen();
window.dispatchEvent(new CustomEvent("openImage")); window.dispatchEvent(new CustomEvent("openImage"));
}); });
$id("tool_import").addEventListener("click", e => { $id("tool_import").addEventListener("click", () => {
this.clickImport(); this.clickImport();
window.dispatchEvent(new CustomEvent("importImages")); window.dispatchEvent(new CustomEvent("importImages"));
}); });
$id("tool_save").addEventListener( $id("tool_save").addEventListener(
"click", "click",
function(e) { function() {
const $editorDialog = document.getElementById("se-svg-editor-dialog"); const $editorDialog = document.getElementById("se-svg-editor-dialog");
const editingsource = $editorDialog.getAttribute("dialog") === "open"; const editingsource = $editorDialog.getAttribute("dialog") === "open";
if (editingsource) { if (editingsource) {
@ -351,7 +352,7 @@ class MainMenu {
}.bind(this) }.bind(this)
); );
// this.clickExport.bind(this) // this.clickExport.bind(this)
$id("tool_export").addEventListener("click", function(e) { $id("tool_export").addEventListener("click", function() {
document document
.getElementById("se-export-dialog") .getElementById("se-export-dialog")
.setAttribute("dialog", "open"); .setAttribute("dialog", "open");

View File

@ -1,3 +1,4 @@
/* eslint-disable sonarjs/no-collapsible-if */
/** /**
* @param {any} obj * @param {any} obj
* @returns {any} * @returns {any}
@ -9,7 +10,7 @@ export function findPos(obj) {
do { do {
curleft += obj.offsetLeft; curleft += obj.offsetLeft;
curtop += obj.offsetTop; curtop += obj.offsetTop;
} while (obj = obj.offsetParent); } while (obj == obj.offsetParent);
return { left: curleft, top: curtop }; return { left: curleft, top: curtop };
} }
return { left: curleft, top: curtop }; return { left: curleft, top: curtop };
@ -93,7 +94,7 @@ export function getClosest(elem, selector) {
} }
} }
return null; return null;
}; }
/** /**
* Get all DOM element up the tree that contain a class, ID, or data attribute * Get all DOM element up the tree that contain a class, ID, or data attribute
@ -142,7 +143,7 @@ export function getClosest(elem, selector) {
} else { } else {
return parents; return parents;
} }
}; }
export function getParentsUntil(elem, parent, selector) { export function getParentsUntil(elem, parent, selector) {
let parents = []; let parents = [];
@ -214,4 +215,4 @@ export function getParentsUntil(elem, parent, selector) {
} else { } else {
return parents; return parents;
} }
}; }

View File

@ -46,8 +46,8 @@ const ns = {
if (!window.console) { if (!window.console) {
window.console = { window.console = {
log (str) { /* empty fn */ }, log () { /* empty fn */ },
dir (str) { /* empty fn */ } dir () { /* empty fn */ }
}; };
} }
@ -156,34 +156,6 @@ function mkElem (name, attrs, newparent) {
return elem; return elem;
} }
function deepExtend(out) {
out = out || {};
for (let i = 1, len = arguments.length; i < len; ++i) {
let obj = arguments[i];
if (!obj) {
continue;
}
for (const key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
// based on https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
out[key] = deepExtend(out[key], obj[key]);
continue;
}
out[key] = obj[key];
}
}
return out;
}
/** /**
* @typedef {PlainObject} module:jGraduate.ColorOpac Object may have one or both values * @typedef {PlainObject} module:jGraduate.ColorOpac Object may have one or both values
* @property {string} [color] #Hex color * @property {string} [color] #Hex color
@ -221,8 +193,6 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
$settings = Object.assign({}, jGraduateDefaults, options || {}), $settings = Object.assign({}, jGraduateDefaults, options || {}),
id = $this.getAttribute('id'), id = $this.getAttribute('id'),
idref = '#' + $this.getAttribute('id') + ' '; idref = '#' + $this.getAttribute('id') + ' ';
// JFH !!!!!
const $shadowRoot = elem.parentNode;
if (!idref) { if (!idref) {
// eslint-disable-next-line no-alert // eslint-disable-next-line no-alert
@ -561,7 +531,7 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
$elem.style.top = e.target.value * MAX; $elem.style.top = e.target.value * MAX;
} }
}; };
for (const [i, attr] of ['x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'fx', 'fy'].entries()) { for (const [, attr] of ['x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'fx', 'fy'].entries()) {
const isRadial = isNaN(attr[1]); const isRadial = isNaN(attr[1]);
let attrval = curGradient.getAttribute(attr); let attrval = curGradient.getAttribute(attr);
@ -653,7 +623,7 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
window: {title: 'Pick the start color and opacity for the gradient'}, window: {title: 'Pick the start color and opacity for the gradient'},
images: {clientPath: $settings.images.clientPath}, images: {clientPath: $settings.images.clientPath},
color: {active: colr, alphaSupport: true} color: {active: colr, alphaSupport: true}
}, function (clr, arg2) { }, function (clr) {
stopColor = clr.val('hex') ? ('#' + clr.val('hex')) : 'none'; stopColor = clr.val('hex') ? ('#' + clr.val('hex')) : 'none';
stopOpacity = clr.val('a') !== null ? clr.val('a') / 256 : 1; stopOpacity = clr.val('a') !== null ? clr.val('a') / 256 : 1;
colorhandle.setAttribute('fill', stopColor); colorhandle.setAttribute('fill', stopColor);
@ -1118,7 +1088,7 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
val: angleVal val: angleVal
} }
}; };
for (const [index, [type, data]] of Object.entries(Object.entries(sliders))) { for (const [, [type, data]] of Object.entries(Object.entries(sliders))) {
const handle = $this.querySelector(data.handle); const handle = $this.querySelector(data.handle);
const sInput = $this.querySelector(data.input); const sInput = $this.querySelector(data.input);
handle.addEventListener('mousedown', function (evt) { handle.addEventListener('mousedown', function (evt) {
@ -1190,7 +1160,7 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
evt.preventDefault(); evt.preventDefault();
}; };
const stopSlider = function (evt) { const stopSlider = function () {
$win.removeEventListener('mousemove', dragSlider); $win.removeEventListener('mousemove', dragSlider);
$win.removeEventListener('mouseup', stopSlider); $win.removeEventListener('mouseup', stopSlider);
slider = null; slider = null;

View File

@ -48,6 +48,7 @@ export class SeListItem extends HTMLElement {
*/ */
attributeChangedCallback (name, oldValue, newValue) { attributeChangedCallback (name, oldValue, newValue) {
if (oldValue === newValue) return; if (oldValue === newValue) return;
// eslint-disable-next-line sonarjs/no-small-switch
switch (name) { switch (name) {
case 'option': case 'option':
this.$menuitem.setAttribute('option', newValue); this.$menuitem.setAttribute('option', newValue);

View File

@ -178,6 +178,7 @@ export class SESpinInput extends HTMLElement {
this.value = e.target.value; this.value = e.target.value;
this.dispatchEvent(this.$event); this.dispatchEvent(this.$event);
}); });
// eslint-disable-next-line sonarjs/no-identical-functions
this.$input.addEventListener('click', (e) => { this.$input.addEventListener('click', (e) => {
e.preventDefault(); e.preventDefault();
this.value = e.target.value; this.value = e.target.value;

View File

@ -107,6 +107,7 @@ export class SeCMenuLayerDialog extends HTMLElement {
*/ */
attributeChangedCallback (name, oldValue, newValue) { attributeChangedCallback (name, oldValue, newValue) {
if (oldValue === newValue) return; if (oldValue === newValue) return;
// eslint-disable-next-line sonarjs/no-small-switch
switch (name) { switch (name) {
case 'value': case 'value':
this.source = newValue; this.source = newValue;

View File

@ -483,13 +483,13 @@ export class SeEditPrefsDialog extends HTMLElement {
* @returns {void} * @returns {void}
*/ */
connectedCallback () { connectedCallback () {
const onCancelHandler = (ev) => { const onCancelHandler = () => {
const closeEvent = new CustomEvent('change', {detail: { const closeEvent = new CustomEvent('change', {detail: {
dialog: 'closed' dialog: 'closed'
}}); }});
this.dispatchEvent(closeEvent); this.dispatchEvent(closeEvent);
}; };
const onSaveHandler = (ev) => { const onSaveHandler = () => {
const color = this.$bgBlocks.querySelector('.cur_background').dataset.bgColor || '#FFF'; const color = this.$bgBlocks.querySelector('.cur_background').dataset.bgColor || '#FFF';
const closeEvent = new CustomEvent('change', {detail: { const closeEvent = new CustomEvent('change', {detail: {
lang: this.$langSelect.value, lang: this.$langSelect.value,
@ -506,7 +506,7 @@ export class SeEditPrefsDialog extends HTMLElement {
}; };
// Set up editor background functionality // Set up editor background functionality
const currentObj = this; const currentObj = this;
this.colorBlocks.forEach(function (e, i) { this.colorBlocks.forEach(function (e) {
const newdiv = document.createElement('div'); const newdiv = document.createElement('div');
if (e === 'chessboard') { if (e === 'chessboard') {
newdiv.dataset.bgColor = e; newdiv.dataset.bgColor = e;

View File

@ -119,6 +119,7 @@ export class SeExportDialog extends HTMLElement {
* @returns {void} * @returns {void}
*/ */
attributeChangedCallback (name, oldValue, newValue) { attributeChangedCallback (name, oldValue, newValue) {
// eslint-disable-next-line sonarjs/no-small-switch
switch (name) { switch (name) {
case 'dialog': case 'dialog':
if (newValue === 'open') { if (newValue === 'open') {

View File

@ -323,7 +323,7 @@ export class SeImgPropDialog extends HTMLElement {
this.$canvasHeight.removeAttribute('disabled'); this.$canvasHeight.removeAttribute('disabled');
} }
}; };
const onSaveHandler = (ev) => { const onSaveHandler = () => {
let saveOpt = ''; let saveOpt = '';
const w = this.$canvasWidth.value; const w = this.$canvasWidth.value;
const h = this.$canvasHeight.value; const h = this.$canvasHeight.value;
@ -355,7 +355,7 @@ export class SeImgPropDialog extends HTMLElement {
this.$resolution.selectedIndex = 0; this.$resolution.selectedIndex = 0;
this.dispatchEvent(closeEvent); this.dispatchEvent(closeEvent);
}; };
const onCancelHandler = (ev) => { const onCancelHandler = () => {
const closeEvent = new CustomEvent('change', {detail: { const closeEvent = new CustomEvent('change', {detail: {
dialog: 'closed' dialog: 'closed'
}}); }});

View File

@ -204,13 +204,13 @@ export class SeSvgSourceEditorDialog extends HTMLElement {
* @returns {void} * @returns {void}
*/ */
connectedCallback () { connectedCallback () {
const onCancelHandler = (ev) => { const onCancelHandler = () => {
const closeEvent = new CustomEvent('change', {detail: { const closeEvent = new CustomEvent('change', {detail: {
dialog: 'closed' dialog: 'closed'
}}); }});
this.dispatchEvent(closeEvent); this.dispatchEvent(closeEvent);
}; };
const onCopyHandler = (ev) => { const onCopyHandler = () => {
const closeEvent = new CustomEvent('change', { const closeEvent = new CustomEvent('change', {
detail: { detail: {
copy: 'click', copy: 'click',
@ -219,7 +219,7 @@ export class SeSvgSourceEditorDialog extends HTMLElement {
}); });
this.dispatchEvent(closeEvent); this.dispatchEvent(closeEvent);
}; };
const onSaveHandler = (ev) => { const onSaveHandler = () => {
const closeEvent = new CustomEvent('change', {detail: { const closeEvent = new CustomEvent('change', {detail: {
value: this.$sourceTxt.value, value: this.$sourceTxt.value,
dialog: 'close' dialog: 'close'

View File

@ -47,7 +47,7 @@ export const dragmove = function(target, handler, parent, onStart, onEnd, onDrag
}); });
// On leaving click, stop moving. // On leaving click, stop moving.
document.addEventListener(_isTouch ? "touchend" : "mouseup", function(e) { document.addEventListener(_isTouch ? "touchend" : "mouseup", function() {
if (onEnd && hasStarted) { if (onEnd && hasStarted) {
onEnd(target, parent, parseInt(target.style.left), parseInt(target.style.top)); onEnd(target, parent, parseInt(target.style.left), parseInt(target.style.top));
} }
@ -57,7 +57,7 @@ export const dragmove = function(target, handler, parent, onStart, onEnd, onDrag
}); });
// On leaving click, stop moving. // On leaving click, stop moving.
document.addEventListener(_isTouch ? "touchmove" : "mousemove", function(e) { document.addEventListener(_isTouch ? "touchmove" : "mousemove", function() {
if (onDrag && hasStarted) { if (onDrag && hasStarted) {
onDrag(target, parseInt(target.style.left), parseInt(target.style.top)); onDrag(target, parseInt(target.style.left), parseInt(target.style.top));
} }

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* Attaches items to DOM for Embedded SVG support. * Attaches items to DOM for Embedded SVG support.
* @module EmbeddedSVGEditDOM * @module EmbeddedSVGEditDOM
@ -6,8 +5,6 @@
import EmbeddedSVGEdit from './embedapi.js'; import EmbeddedSVGEdit from './embedapi.js';
import {isChrome} from '../common/browser.js'; import {isChrome} from '../common/browser.js';
const $ = jQuery;
let svgCanvas = null; let svgCanvas = null;
/** /**
@ -110,6 +107,7 @@ iframe.src = frameBase + framePath +
iframe.addEventListener('load', function () { iframe.addEventListener('load', function () {
svgCanvas = new EmbeddedSVGEdit(frame, [new URL(frameBase).origin]); svgCanvas = new EmbeddedSVGEdit(frame, [new URL(frameBase).origin]);
const {$id} = svgCanvas;
// Hide main button, as we will be controlling new, load, save, etc. from the host document // Hide main button, as we will be controlling new, load, save, etc. from the host document
let doc; let doc;
try { try {

View File

@ -11,6 +11,7 @@ const loadExtensionTranslation = async function (svgEditor) {
let translationModule; let translationModule;
const lang = svgEditor.configObj.pref('lang') const lang = svgEditor.configObj.pref('lang')
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -29,7 +30,7 @@ export default {
const {$id} = svgCanvas; const {$id} = svgCanvas;
const const
addElem = svgCanvas.addSVGElementFromJson, addElem = svgCanvas.addSVGElementFromJson,
{nonce, $} = S, {nonce} = S,
prefix = 'se_arrow_'; prefix = 'se_arrow_';
let selElems, arrowprefix, randomizeIds = S.randomize_ids; let selElems, arrowprefix, randomizeIds = S.randomize_ids;
@ -50,7 +51,7 @@ export default {
* @param {Window} win * @param {Window} win
* @returns {void} * @returns {void}
*/ */
function unsetArrowNonce (win) { function unsetArrowNonce (_win) {
randomizeIds = false; randomizeIds = false;
arrowprefix = prefix; arrowprefix = prefix;
pathdata.fw.id = arrowprefix + 'fw'; pathdata.fw.id = arrowprefix + 'fw';
@ -216,7 +217,7 @@ export default {
const mtypes = ['start', 'mid', 'end']; const mtypes = ['start', 'mid', 'end'];
const defs = svgCanvas.findDefs(); const defs = svgCanvas.findDefs();
mtypes.forEach(function(type, i){ mtypes.forEach(function(type){
const marker = getLinked(elem, 'marker-' + type); const marker = getLinked(elem, 'marker-' + type);
if (!marker) { return; } if (!marker) { return; }
@ -251,8 +252,8 @@ export default {
// Check if last marker can be removed // Check if last marker can be removed
let remove = true; let remove = true;
const sElements = S.svgcontent.querySelectorAll('line, polyline, path, polygon'); const sElements = S.svgcontent.querySelectorAll('line, polyline, path, polygon');
Array.prototype.forEach.call(sElements, function(element, i){ Array.prototype.forEach.call(sElements, function(element){
mtypes.forEach(function(mtype, j){ mtypes.forEach(function(mtype){
if (element.getAttribute('marker-' + mtype) === 'url(#' + marker.id + ')') { if (element.getAttribute('marker-' + mtype) === 'url(#' + marker.id + ')') {
remove = false; remove = false;
return remove; return remove;
@ -293,7 +294,7 @@ export default {
// Set ID so it can be translated in locale file // Set ID so it can be translated in locale file
$id('arrow_list option').setAttribute('id', 'connector_no_arrow'); $id('arrow_list option').setAttribute('id', 'connector_no_arrow');
}, },
async addLangData ({lang, importLocale}) { async addLangData ({_lang, importLocale}) {
const {langList} = await importLocale(); const {langList} = await importLocale();
return { return {
data: langList data: langList

View File

@ -10,6 +10,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -23,7 +24,7 @@ const loadExtensionTranslation = async function (lang) {
// The button toggles whether the path is open or closed // The button toggles whether the path is open or closed
export default { export default {
name: 'closepath', name: 'closepath',
async init ({importLocale, $}) { async init ({_importLocale}) {
const svgEditor = this; const svgEditor = this;
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;
const {$id} = svgCanvas; const {$id} = svgCanvas;
@ -34,8 +35,8 @@ export default {
closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1, closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1,
showbutton = closed ? 'tool_openpath' : 'tool_closepath', showbutton = closed ? 'tool_openpath' : 'tool_closepath',
hidebutton = closed ? 'tool_closepath' : 'tool_openpath'; hidebutton = closed ? 'tool_closepath' : 'tool_openpath';
$id("hidebutton").style.display = 'none'; $id(hidebutton).style.display = 'none';
$id("showbutton").style.display = 'block'; $id(showbutton).style.display = 'block';
}; };
const showPanel = function (on) { const showPanel = function (on) {
$id('closepath_panel').style.display = (on) ? 'block' : 'none'; $id('closepath_panel').style.display = (on) ? 'block' : 'none';

View File

@ -10,6 +10,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -197,7 +198,7 @@ export default {
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
Array.prototype.forEach.call(connectors, function (ethis, i) { Array.prototype.forEach.call(connectors, function (ethis) {
let addThis; let addThis;
// Grab the ends // Grab the ends
const parts = []; const parts = [];
@ -220,7 +221,7 @@ export default {
addThis = false; addThis = false;
// The connected element might be part of a selected group // The connected element might be part of a selected group
const parents = svgCanvas.getParents(cElem.parentNode); const parents = svgCanvas.getParents(cElem.parentNode);
Array.prototype.forEach.call(parents, function (el, i) { Array.prototype.forEach.call(parents, function (el) {
if (elems.includes(el)) { if (elems.includes(el)) {
// Pretend this element is selected // Pretend this element is selected
addThis = true; addThis = true;
@ -364,7 +365,7 @@ export default {
svgCanvas.setMode('connector'); svgCanvas.setMode('connector');
}); });
}, },
/* async */ addLangData({ lang }) { // , importLocale: importLoc /* async */ addLangData({ _lang }) { // , importLocale: importLoc
return { return {
data: strings.langList data: strings.langList
}; };
@ -505,7 +506,7 @@ export default {
const connStr = startId + ' ' + endId; const connStr = startId + ' ' + endId;
const altStr = endId + ' ' + startId; const altStr = endId + ' ' + startId;
// Don't create connector if one already exists // Don't create connector if one already exists
const dupe = Array.prototype.filter.call(svgcontent.querySelectorAll('.se_connector'), function (aThis, i) { const dupe = Array.prototype.filter.call(svgcontent.querySelectorAll('.se_connector'), function (aThis) {
const conn = aThis.getAttributeNS(seNs, 'connector'); const conn = aThis.getAttributeNS(seNs, 'connector');
if (conn === connStr || conn === altStr) { return true; } if (conn === connStr || conn === altStr) { return true; }
return false; return false;

View File

@ -10,6 +10,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -24,7 +25,7 @@ export default {
async init(S) { async init(S) {
const svgEditor = this; const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
const { $, ChangeElementCommand } = S, // , svgcontent, const { ChangeElementCommand } = S, // , svgcontent,
// svgdoc = S.svgroot.parentNode.ownerDocument, // svgdoc = S.svgroot.parentNode.ownerDocument,
{ svgCanvas } = svgEditor, { svgCanvas } = svgEditor,
addToHistory = function (cmd) { svgCanvas.undoMgr.addCommandToHistory(cmd); }, addToHistory = function (cmd) { svgCanvas.undoMgr.addCommandToHistory(cmd); },

View File

@ -10,6 +10,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -23,7 +24,7 @@ export default {
name: 'foreignobject', name: 'foreignobject',
async init (S) { async init (S) {
const svgEditor = this; const svgEditor = this;
const {$, text2xml, NS} = S; const {text2xml, NS} = S;
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;
const {$id} = svgCanvas; const {$id} = svgCanvas;
const const
@ -35,7 +36,7 @@ export default {
const properlySourceSizeTextArea = function () { const properlySourceSizeTextArea = function () {
// TODO: remove magic numbers here and get values from CSS // TODO: remove magic numbers here and get values from CSS
const height = parseFloat(getComputedStyle($id(svg_source_container), null).height.replace("px", "")) - 80; const height = parseFloat(getComputedStyle($id('svg_source_container'), null).height.replace("px", "")) - 80;
$id('svg_source_textarea').style.height = height + "px"; $id('svg_source_textarea').style.height = height + "px";
}; };
@ -207,7 +208,7 @@ export default {
// const oldElement = $id('tool_source_save'); // const oldElement = $id('tool_source_save');
// oldElement.parentNode.replaceChild(toolSourceSave, oldElement); // oldElement.parentNode.replaceChild(toolSourceSave, oldElement);
$id('tool_source_back').append(toolSourceSave); $id('tool_source_back').append(toolSourceSave);
toolSourceSave.addEventListener('click', (e) => function () { toolSourceSave.addEventListener('click', () => function () {
if (!editingforeign) { return; } if (!editingforeign) { return; }
if (!setForeignString($id('svg_source_textarea').value)) { if (!setForeignString($id('svg_source_textarea').value)) {
@ -225,7 +226,7 @@ export default {
toolSourceCancel.style.display = 'none'; toolSourceCancel.style.display = 'none';
toolSourceCancel.id = 'foreign_cancel'; toolSourceCancel.id = 'foreign_cancel';
$id('tool_source_back').append(toolSourceCancel); $id('tool_source_back').append(toolSourceCancel);
toolSourceCancel.addEventListener('click', (e) => function () { toolSourceCancel.addEventListener('click', () => function () {
endChanges(); endChanges();
}); });
// unbind() // unbind()
@ -268,7 +269,7 @@ export default {
started: true started: true
}; };
}, },
mouseUp (opts) { mouseUp (_opts) {
// const e = opts.event; // const e = opts.event;
if (svgCanvas.getMode() !== 'foreign' || !started) { if (svgCanvas.getMode() !== 'foreign' || !started) {
return undefined; return undefined;
@ -306,7 +307,7 @@ export default {
} }
} }
}, },
elementChanged (opts) { elementChanged (_opts) {
// const elem = opts.elems[0]; // const elem = opts.elems[0];
} }
}; };

View File

@ -10,6 +10,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -21,7 +22,7 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'grid', name: 'grid',
async init ({$, NS, getTypeMap}) { async init ({NS, getTypeMap}) {
const svgEditor = this; const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;

View File

@ -16,6 +16,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -27,7 +28,7 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'helloworld', name: 'helloworld',
async init ({$, importLocale}) { async init ({_importLocale}) {
const svgEditor = this; const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;

View File

@ -12,6 +12,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -23,7 +24,7 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'imagelib', name: 'imagelib',
async init({ $, decode64, dropXMLInternalSubset }) { async init({ decode64, dropXMLInternalSubset }) {
const svgEditor = this; const svgEditor = this;
const { $id } = svgEditor.svgCanvas; const { $id } = svgEditor.svgCanvas;
const imagelibStrings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const imagelibStrings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
@ -436,6 +437,7 @@ export default {
header.textContent = allLibs; header.textContent = allLibs;
back.style.display = 'none'; back.style.display = 'none';
}); });
// eslint-disable-next-line sonarjs/no-identical-functions
back.addEventListener('touchend', function () { back.addEventListener('touchend', function () {
frame.setAttribute('src', 'about:blank'); frame.setAttribute('src', 'about:blank');
frame.style.display = 'none'; frame.style.display = 'none';
@ -479,6 +481,7 @@ export default {
libOpts.style.display = 'none'; libOpts.style.display = 'none';
back.style.display = 'block'; back.style.display = 'block';
}); });
// eslint-disable-next-line sonarjs/no-identical-functions
li.addEventListener('touchend', function () { li.addEventListener('touchend', function () {
frame.setAttribute('src', url); frame.setAttribute('src', url);
frame.style.display = 'block'; frame.style.display = 'block';

View File

@ -1,7 +1,7 @@
/* globals jQuery */ /* globals jQuery */
const $ = jQuery; const $ = jQuery;
const atags = document.querySelectorAll('a'); const atags = document.querySelectorAll('a');
Array.prototype.forEach.call(atags, function (aEle, i) { Array.prototype.forEach.call(atags, function (aEle) {
aEle.addEventListener('click', function (event) { aEle.addEventListener('click', function (event) {
const { href } = event.currentTarget; const { href } = event.currentTarget;
const target = window.parent; const target = window.parent;

View File

@ -32,6 +32,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -452,7 +453,7 @@ export default {
* @param {Event} ev * @param {Event} ev
* @returns {Promise<void>} Resolves to `undefined` * @returns {Promise<void>} Resolves to `undefined`
*/ */
async function setArrowFromButton (ev) { async function setArrowFromButton () {
const parts = this.id.split('_'); const parts = this.id.split('_');
const pos = parts[1]; const pos = parts[1];
let val = parts[2]; let val = parts[2];
@ -579,7 +580,7 @@ export default {
$id("marker_panel").style.display = 'none'; $id("marker_panel").style.display = 'none';
} }
}, },
/* async */ addLangData ({importLocale, lang}) { /* async */ addLangData ({_importLocale, _lang}) {
return {data: strings.langList}; return {data: strings.langList};
}, },
selectedChanged (opts) { selectedChanged (opts) {

View File

@ -11,6 +11,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console

View File

@ -18,7 +18,7 @@
export default { export default {
name: 'opensave', name: 'opensave',
init ({$, decode64, encode64}) { init ({encode64}) {
const svgEditor = this; const svgEditor = this;
svgEditor.setCustomHandlers({ svgEditor.setCustomHandlers({

View File

@ -11,7 +11,7 @@ import { dragmove } from '../../../editor/dragmove/dragmove.js';
export default { export default {
name: 'overview_window', name: 'overview_window',
init ({$, isChrome}) { init ({_$, isChrome}) {
const svgEditor = this; const svgEditor = this;
const {$id} = svgEditor.svgCanvas; const {$id} = svgEditor.svgCanvas;
const overviewWindowGlobals = {}; const overviewWindowGlobals = {};
@ -102,8 +102,8 @@ export default {
const windowHeight = parseFloat(getComputedStyle($id("svgcanvas"), null).height.replace("px", "")); const windowHeight = parseFloat(getComputedStyle($id("svgcanvas"), null).height.replace("px", ""));
const overviewWidth = parseFloat(getComputedStyle($id("overviewMiniView"), null).width.replace("px", "")); const overviewWidth = parseFloat(getComputedStyle($id("overviewMiniView"), null).width.replace("px", ""));
const overviewHeight = parseFloat(getComputedStyle($id("overviewMiniView"), null).height.replace("px", "")); const overviewHeight = parseFloat(getComputedStyle($id("overviewMiniView"), null).height.replace("px", ""));
const viewBoxX = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('left').replace("px", ""));; const viewBoxX = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('left').replace("px", ""));
const viewBoxY = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('top').replace("px", ""));; const viewBoxY = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('top').replace("px", ""));
const portX = viewBoxX / overviewWidth * windowWidth; const portX = viewBoxX / overviewWidth * windowWidth;
@ -115,7 +115,7 @@ export default {
overviewWindowGlobals.viewBoxDragging = true; overviewWindowGlobals.viewBoxDragging = true;
updateViewPortFromViewBox(); updateViewPortFromViewBox();
}; };
const onEnd = (el, parent, x, y) => { const onEnd = (el, parent, _x, _y) => {
if((el.offsetLeft + el.offsetWidth) > parseFloat(getComputedStyle(parent, null).width.replace("px", ""))){ if((el.offsetLeft + el.offsetWidth) > parseFloat(getComputedStyle(parent, null).width.replace("px", ""))){
el.style.left = (parseFloat(getComputedStyle(parent, null).width.replace("px", "")) - el.offsetWidth) + 'px'; el.style.left = (parseFloat(getComputedStyle(parent, null).width.replace("px", "")) - el.offsetWidth) + 'px';
} else if(el.offsetLeft < 0){ } else if(el.offsetLeft < 0){
@ -142,8 +142,8 @@ export default {
const mouseY = (evt.offsetY || evt.originalEvent.layerY); const mouseY = (evt.offsetY || evt.originalEvent.layerY);
const overviewWidth = parseFloat(getComputedStyle($id("overviewMiniView"), null).width.replace("px", "")); const overviewWidth = parseFloat(getComputedStyle($id("overviewMiniView"), null).width.replace("px", ""));
const overviewHeight = parseFloat(getComputedStyle($id("overviewMiniView"), null).height.replace("px", "")); const overviewHeight = parseFloat(getComputedStyle($id("overviewMiniView"), null).height.replace("px", ""));
const viewBoxWidth = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('min-width').replace("px", ""));; const viewBoxWidth = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('min-width').replace("px", ""));
const viewBoxHeight = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('min-height').replace("px", ""));; const viewBoxHeight = parseFloat(getComputedStyle($id("overview_window_view_box"), null).getPropertyValue('min-height').replace("px", ""));
let viewBoxX = mouseX - 0.5 * viewBoxWidth; let viewBoxX = mouseX - 0.5 * viewBoxWidth;
let viewBoxY = mouseY - 0.5 * viewBoxHeight; let viewBoxY = mouseY - 0.5 * viewBoxHeight;

View File

@ -13,6 +13,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -24,9 +25,7 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'panning', name: 'panning',
async init({ async init() {
importLocale
}) {
const svgEditor = this; const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
const { const {

View File

@ -9,6 +9,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -20,12 +21,11 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'placemark', name: 'placemark',
async init (S) { async init (_S) {
const svgEditor = this; const svgEditor = this;
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;
const {$id} = svgCanvas; const {$id} = svgCanvas;
const addElem = svgCanvas.addSVGElementFromJson; const addElem = svgCanvas.addSVGElementFromJson;
const {$} = S; // {svgcontent},
let let
selElems, selElems,
// editingitex = false, // editingitex = false,
@ -108,7 +108,7 @@ export default {
Array.prototype.forEach.call(elements, function(i, _){ Array.prototype.forEach.call(elements, function(i, _){
const [, , type, n] = i.id.split('_'); const [, , type, n] = i.id.split('_');
if (type === 'txt') { if (type === 'txt') {
t.textContent = items[n]; txt.textContent = items[n];
} }
}); });
} }
@ -261,7 +261,7 @@ export default {
* @param {Event} ev * @param {Event} ev
* @returns {void} * @returns {void}
*/ */
function setArrowFromButton (ev) { function setArrowFromButton (_ev) {
const parts = this.id.split('_'); const parts = this.id.split('_');
let val = parts[2]; let val = parts[2];
if (parts[3]) { val += '_' + parts[3]; } if (parts[3]) { val += '_' + parts[3]; }
@ -533,7 +533,7 @@ export default {
if (elem && elem.getAttribute('class').includes('placemark')) { if (elem && elem.getAttribute('class').includes('placemark')) {
const txt = []; const txt = [];
const elements = elem.children; const elements = elem.children;
Array.prototype.forEach.call(elements, function(i, n){ Array.prototype.forEach.call(elements, function(i){
const [, , type] = i.id.split('_'); const [, , type] = i.id.split('_');
if (type === 'txt') { if (type === 'txt') {
$id('placemarkFont').value = ( $id('placemarkFont').value = (

View File

@ -9,6 +9,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -20,12 +21,11 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'polygon', name: 'polygon',
async init (S) { async init (_S) {
const svgEditor = this; const svgEditor = this;
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;
const {$id} = svgCanvas; const {$id} = svgCanvas;
const {$} = S; // const editingitex = false;
const editingitex = false;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
let selElems; let selElems;
let started; let started;
@ -137,7 +137,7 @@ export default {
const cx = Number(newFO.getAttribute('cx')); const cx = Number(newFO.getAttribute('cx'));
const cy = Number(newFO.getAttribute('cy')); const cy = Number(newFO.getAttribute('cy'));
const sides = Number(newFO.getAttribute('sides')); const sides = Number(newFO.getAttribute('sides'));
const orient = newFO.getAttribute('orient'); // const orient = newFO.getAttribute('orient');
const fill = newFO.getAttribute('fill'); const fill = newFO.getAttribute('fill');
const strokecolor = newFO.getAttribute('strokecolor'); const strokecolor = newFO.getAttribute('strokecolor');
const strokeWidth = Number(newFO.getAttribute('strokeWidth')); const strokeWidth = Number(newFO.getAttribute('strokeWidth'));
@ -169,7 +169,7 @@ export default {
}; };
}, },
mouseUp (opts) { mouseUp () {
if (svgCanvas.getMode() !== 'polygon') { if (svgCanvas.getMode() !== 'polygon') {
return undefined; return undefined;
} }
@ -201,7 +201,7 @@ export default {
} }
} }
}, },
elementChanged (opts) { elementChanged () {
// const elem = opts.elems[0]; // const elem = opts.elems[0];
} }
}; };

View File

@ -12,6 +12,7 @@ import {Canvg as canvg} from 'canvg';
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -23,7 +24,7 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'server_moinsave', name: 'server_moinsave',
async init ({$, encode64, importLocale}) { async init ({encode64}) {
const svgEditor = this; const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;

View File

@ -11,6 +11,7 @@ import {Canvg as canvg} from 'canvg';
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console

View File

@ -9,7 +9,7 @@
export default { export default {
name: 'shapes', name: 'shapes',
init ({$}) { init () {
const svgEditor = this; const svgEditor = this;
const canv = svgEditor.svgCanvas; const canv = svgEditor.svgCanvas;
const {$id} = canv; const {$id} = canv;

View File

@ -9,6 +9,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -20,11 +21,10 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'star', name: 'star',
async init (S) { async init (_S) {
const svgEditor = this; const svgEditor = this;
const {svgCanvas} = svgEditor; const {svgCanvas} = svgEditor;
const {$id} = svgCanvas; const {$id} = svgCanvas;
const {$} = S; // {svgcontent},
let selElems; let selElems;
let started; let started;
let newFO; let newFO;
@ -223,7 +223,7 @@ export default {
} }
} }
}, },
elementChanged (opts) { elementChanged (_opts) {
// const elem = opts.elems[0]; // const elem = opts.elems[0];
} }
}; };

View File

@ -56,7 +56,7 @@ const replaceStoragePrompt = (val) => {
export default { export default {
name: 'storage', name: 'storage',
init ({$}) { init () {
const svgEditor = this; const svgEditor = this;
const {svgCanvas, storage} = svgEditor; const {svgCanvas, storage} = svgEditor;
@ -148,7 +148,7 @@ export default {
* @returns {void} * @returns {void}
*/ */
function setupBeforeUnloadListener () { function setupBeforeUnloadListener () {
window.addEventListener('beforeunload', function (e) { window.addEventListener('beforeunload', function () {
// Don't save anything unless the user opted in to storage // Don't save anything unless the user opted in to storage
if (!(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/).test(document.cookie)) { if (!(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/).test(document.cookie)) {
return; return;

View File

@ -9,6 +9,7 @@
const loadExtensionTranslation = async function (lang) { const loadExtensionTranslation = async function (lang) {
let translationModule; let translationModule;
try { try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`); translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) { } catch (_error) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -20,7 +21,7 @@ const loadExtensionTranslation = async function (lang) {
export default { export default {
name: 'webappfind', name: 'webappfind',
async init ({$}) { async init () {
const svgEditor = this; const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang')); const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
const saveMessage = 'save', const saveMessage = 'save',

View File

@ -72,6 +72,7 @@ export const putLocale = async function (givenParam, goodLangs) {
if (!goodLangs.includes(langParam) && langParam !== 'test') { if (!goodLangs.includes(langParam) && langParam !== 'test') {
langParam = 'en'; langParam = 'en';
} }
// eslint-disable-next-line no-unsanitized/method
const module = await import(`./locale/lang.${encodeURIComponent(langParam)}.js`); const module = await import(`./locale/lang.${encodeURIComponent(langParam)}.js`);
i18next.init({ i18next.init({
lng: langParam, lng: langParam,

View File

@ -1,7 +1,7 @@
import SvgCanvas from '../../svgcanvas/svgcanvas.js'; import SvgCanvas from '../../svgcanvas/svgcanvas.js';
import {jGraduate} from '../components/jgraduate/jQuery.jGraduate.js'; import {jGraduate} from '../components/jgraduate/jQuery.jGraduate.js';
const {$id, $qa} = SvgCanvas; const {$id} = SvgCanvas;
/* /*
* register actions for left panel * register actions for left panel
@ -100,6 +100,7 @@ class BottomPanel {
} }
if (bNoStroke && bNoFill) { if (bNoStroke && bNoFill) {
// eslint-disable-next-line sonarjs/no-identical-functions
buttonsNeedingFillAndStroke.forEach((btn) => { buttonsNeedingFillAndStroke.forEach((btn) => {
// if btn is pressed, change to select button // if btn is pressed, change to select button
if ($id(btn).pressed) { if ($id(btn).pressed) {

View File

@ -143,7 +143,6 @@ class LayersPanel {
</div> </div>
`; `;
this.editor.$svgEditor.append(template.content.cloneNode(true)); this.editor.$svgEditor.append(template.content.cloneNode(true));
this.editor.svgCanvas = this.editor.svgCanvas;
// layer menu added to DOM // layer menu added to DOM
const menuMore = document.createElement("se-cmenu-layers"); const menuMore = document.createElement("se-cmenu-layers");
menuMore.setAttribute("id", "se-cmenu-layers-more"); menuMore.setAttribute("id", "se-cmenu-layers-more");
@ -193,14 +192,14 @@ class LayersPanel {
this.allowmove = true; this.allowmove = true;
}, 20); }, 20);
}); });
$id("sidepanel_handle").addEventListener("mouseup", evt => { $id("sidepanel_handle").addEventListener("mouseup", _evt => {
if (!this.sidedragging) { if (!this.sidedragging) {
this.toggleSidePanel(); this.toggleSidePanel();
} }
this.sidedrag = -1; this.sidedrag = -1;
this.sidedragging = false; this.sidedragging = false;
}); });
window.addEventListener("mouseup", evt => { window.addEventListener("mouseup", _evt => {
this.sidedrag = -1; this.sidedrag = -1;
this.sidedragging = false; this.sidedragging = false;
$id("svg_editor").removeEventListener( $id("svg_editor").removeEventListener(
@ -247,7 +246,7 @@ class LayersPanel {
// TODO: make this behavior less brittle (svg-editor should get which // TODO: make this behavior less brittle (svg-editor should get which
// layer is selected from the canvas and then select that one in the UI) // layer is selected from the canvas and then select that one in the UI)
const elements = document.querySelectorAll('#layerlist tr.layer'); const elements = document.querySelectorAll('#layerlist tr.layer');
Array.prototype.forEach.call(elements, function(el, i){ Array.prototype.forEach.call(elements, function(el){
el.classList.remove('layersel'); el.classList.remove('layersel');
}); });
document.querySelector('#layerlist tr.layer').classList.add('layersel'); document.querySelector('#layerlist tr.layer').classList.add('layersel');
@ -284,7 +283,7 @@ class LayersPanel {
var i = 0; var i = 0;
do { do {
i++; i++;
} while (el = el.previousElementSibling); } while (el == el.previousElementSibling);
return i; return i;
} }
@ -419,7 +418,7 @@ class LayersPanel {
evt.currentTarget.textContent evt.currentTarget.textContent
); );
}); });
element.addEventListener('mouseout', function(evt) { element.addEventListener('mouseout', function(_evt) {
self.toggleHighlightLayer(self.editor.svgCanvas); self.toggleHighlightLayer(self.editor.svgCanvas);
}); });
}); });

View File

@ -34,7 +34,7 @@ html, body, div{
#svg_editor { #svg_editor {
font-size: 8pt; font-size: 8pt;
font-family: Verdana, Helvetica, Arial; font-family: Verdana, Helvetica, Arial;
color: var(--text-color);; color: var(--text-color);
} }
a { a {

View File

@ -1,15 +1,11 @@
/* globals jQuery */
/** /**
* Tools for clear. * Tools for clear.
* @module clear * @module clear
* @license MIT * @license MIT
* @copyright 2011 Jeff Schiller * @copyright 2011 Jeff Schiller
*/ */
import jQueryPluginSVG from './jQuery.attr.js';
import {NS} from '../common/namespaces.js'; import {NS} from '../common/namespaces.js';
const $ = jQueryPluginSVG(jQuery);
let clearContext_ = null; let clearContext_ = null;
/** /**

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* Manipulating coordinates. * Manipulating coordinates.
* @module coords * @module coords
@ -13,8 +12,6 @@ import {
} from './math.js'; } from './math.js';
import { getTransformList } from './svgtransformlist.js'; import { getTransformList } from './svgtransformlist.js';
const $ = jQuery;
// this is how we map paths to our preferred relative segment types // this is how we map paths to our preferred relative segment types
const pathMap = [ const pathMap = [
0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a', 0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a',

View File

@ -27,7 +27,7 @@ export const copyElem = function (el, getNextId) {
} }
// now create copies of all children // now create copies of all children
el.childNodes.forEach(function(child, i){ el.childNodes.forEach(function(child){
switch (child.nodeType) { switch (child.nodeType) {
case 1: // element node case 1: // element node
newEl.append(copyElem(child, getNextId)); newEl.append(copyElem(child, getNextId));

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* Tools for drawing. * Tools for drawing.
* @module draw * @module draw
@ -22,8 +21,6 @@ import {
} from './history.js'; } from './history.js';
import {getParentsUntil} from '../editor/components/jgraduate/Util.js'; import {getParentsUntil} from '../editor/components/jgraduate/Util.js';
const $ = jQuery;
const visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'.split(','); const visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'.split(',');
const RandomizeModes = { const RandomizeModes = {

View File

@ -309,7 +309,7 @@ export const setZoomMethod = function (zoomLevel) {
const res = elemContext_.getCanvas().getResolution(); const res = elemContext_.getCanvas().getResolution();
elemContext_.getSVGContent().setAttribute('viewBox', '0 0 ' + res.w / zoomLevel + ' ' + res.h / zoomLevel); elemContext_.getSVGContent().setAttribute('viewBox', '0 0 ' + res.w / zoomLevel + ' ' + res.h / zoomLevel);
elemContext_.setCurrentZoom(zoomLevel); elemContext_.setCurrentZoom(zoomLevel);
selectedElements.forEach(function(elem, i){ selectedElements.forEach(function(elem){
if (!elem) { return; } if (!elem) { return; }
elemContext_.getCanvas().selectorManager.requestSelector(elem).resize(); elemContext_.getCanvas().selectorManager.requestSelector(elem).resize();
}); });
@ -431,7 +431,7 @@ export const findDuplicateGradient = function (grad) {
}; };
let diff = false; let diff = false;
radAttrs.forEach(function (attr, j) { radAttrs.forEach(function (attr) {
if (gradAttrs[attr] !== ogAttrs[attr]) { diff = true; } if (gradAttrs[attr] !== ogAttrs[attr]) { diff = true; }
}); });
@ -513,6 +513,7 @@ export const setStrokeWidthMethod = function (val) {
* @param {Element} e * @param {Element} e
* @returns {void} * @returns {void}
*/ */
// eslint-disable-next-line sonarjs/no-identical-functions
function addNonG(e) { function addNonG(e) {
if (e.nodeName !== 'g') { if (e.nodeName !== 'g') {
elems.push(e); elems.push(e);

View File

@ -1,11 +1,9 @@
/* globals jQuery */
/** /**
* Tools for event. * Tools for event.
* @module event * @module event
* @license MIT * @license MIT
* @copyright 2011 Jeff Schiller * @copyright 2011 Jeff Schiller
*/ */
import jQueryPluginSVG from './jQuery.attr.js'; // Needed for SVG attribute
import { import {
assignAttributes, cleanupElement, getElem, getRotationAngle, snapToGrid, walkTree, assignAttributes, cleanupElement, getElem, getRotationAngle, snapToGrid, walkTree,
getBBox as utilsGetBBox, isNullish, preventClickDefault, setHref getBBox as utilsGetBBox, isNullish, preventClickDefault, setHref
@ -31,7 +29,6 @@ const {
InsertElementCommand InsertElementCommand
} = hstry; } = hstry;
const $ = jQueryPluginSVG(jQuery);
let eventContext_ = null; let eventContext_ = null;
/** /**
@ -92,7 +89,7 @@ export const mouseMoveEvent = function (evt) {
if (!eventContext_.getStarted()) { return; } if (!eventContext_.getStarted()) { return; }
if (evt.button === 1 || eventContext_.getCanvas().spaceKey) { return; } if (evt.button === 1 || eventContext_.getCanvas().spaceKey) { return; }
let i, xya, c, cx, cy, dx, dy, len, angle, box, let i, xya, cx, cy, dx, dy, len, angle, box,
selected = selectedElements[0]; selected = selectedElements[0];
const const
pt = transformPoint(evt.pageX, evt.pageY, eventContext_.getrootSctm()), pt = transformPoint(evt.pageX, evt.pageY, eventContext_.getrootSctm()),
@ -559,7 +556,7 @@ export const mouseUpEvent = function (evt) {
// TODO: Make true when in multi-unit mode // TODO: Make true when in multi-unit mode
const useUnit = false; // (eventContext_.getCurConfig().baseUnit !== 'px'); const useUnit = false; // (eventContext_.getCurConfig().baseUnit !== 'px');
eventContext_.setStarted(false); eventContext_.setStarted(false);
let attrs, t; let t;
switch (eventContext_.getCurrentMode()) { switch (eventContext_.getCurrentMode()) {
// intentionally fall-through to select here // intentionally fall-through to select here
case 'resize': case 'resize':
@ -671,29 +668,32 @@ export const mouseUpEvent = function (evt) {
element = eventContext_.getCanvas().pathActions.smoothPolylineIntoPath(element); element = eventContext_.getCanvas().pathActions.smoothPolylineIntoPath(element);
} }
break; break;
} case 'line': } case 'line': {
const x1 = element.getAttribute('x1'); const x1 = element.getAttribute('x1');
const y1 = element.getAttribute('y1'); const y1 = element.getAttribute('y1');
const x2 = element.getAttribute('x2'); const x2 = element.getAttribute('x2');
const y2 = element.getAttribute('y2'); const y2 = element.getAttribute('y2');
keep = (x1 !== x2 || y1 !== y2); keep = (x1 !== x2 || y1 !== y2);
}
break; break;
case 'foreignObject': case 'foreignObject':
case 'square': case 'square':
case 'rect': case 'rect':
case 'image': case 'image': {
const width = element.getAttribute('width'); const width = element.getAttribute('width');
const height = element.getAttribute('height'); const height = element.getAttribute('height');
// Image should be kept regardless of size (use inherit dimensions later) // Image should be kept regardless of size (use inherit dimensions later)
keep = (width || height) || eventContext_.getCurrentMode() === 'image'; keep = (width || height) || eventContext_.getCurrentMode() === 'image';
}
break; break;
case 'circle': case 'circle':
keep = (element.getAttribute('r') !== '0'); keep = (element.getAttribute('r') !== '0');
break; break;
case 'ellipse': case 'ellipse': {
const rx = element.getAttribute('rx'); const rx = element.getAttribute('rx');
const ry = element.getAttribute('ry'); const ry = element.getAttribute('ry');
keep = (rx || ry); keep = (rx || ry);
}
break; break;
case 'fhellipse': case 'fhellipse':
if ((eventContext_.getFreehand('maxx') - eventContext_.getFreehand('minx')) > 0 && if ((eventContext_.getFreehand('maxx') - eventContext_.getFreehand('minx')) > 0 &&
@ -787,7 +787,7 @@ export const mouseUpEvent = function (evt) {
mouse_y: mouseY mouse_y: mouseY
}, true); }, true);
extResult.forEach(function(r, i){ extResult.forEach(function(r){
if (r) { if (r) {
keep = r.keep || keep; keep = r.keep || keep;
({ element } = r); ({ element } = r);
@ -1064,7 +1064,7 @@ export const mouseDownEvent = function (evt) {
const bb = {}; const bb = {};
for (const [key, val] of Object.entries(eventContext_.getInitBbox())) { for (const [key, val] of Object.entries(eventContext_.getInitBbox())) {
bb[key] = val / currentZoom; bb[key] = val / currentZoom;
}; }
eventContext_.setInitBbox(bb); eventContext_.setInitBbox(bb);
// append three dummy transforms to the tlist so that // append three dummy transforms to the tlist so that
@ -1292,7 +1292,7 @@ export const mouseDownEvent = function (evt) {
selectedElements selectedElements
}, true); }, true);
extResult.forEach(function(r, i){ extResult.forEach(function(r){
if (r && r.started) { if (r && r.started) {
eventContext_.setStarted(true); eventContext_.setStarted(true);
} }

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* Provides tools for the layer concept. * Provides tools for the layer concept.
* @module layer * @module layer
@ -10,7 +9,6 @@
import {NS} from '../common/namespaces.js'; import {NS} from '../common/namespaces.js';
import {toXml, walkTree, isNullish} from './utilities.js'; import {toXml, walkTree, isNullish} from './utilities.js';
const $ = jQuery;
/** /**
* This class encapsulates the concept of a layer in the drawing. It can be constructed with * This class encapsulates the concept of a layer in the drawing. It can be constructed with

View File

@ -1,12 +1,7 @@
/* globals jQuery */
import jQueryPluginSVG from './jQuery.attr.js'; // Needed for SVG attribute setting and array form with `attr`
import { import {
getStrokedBBoxDefaultVisible getStrokedBBoxDefaultVisible
} from './utilities.js'; } from './utilities.js';
import * as hstry from './history.js'; import * as hstry from './history.js';
// Constants
const $ = jQueryPluginSVG(jQuery);
const { const {
InsertElementCommand, BatchCommand InsertElementCommand, BatchCommand
@ -118,7 +113,7 @@ export const pasteElementsMethod = function (type, x, y) {
dx = [], dx = [],
dy = []; dy = [];
pasted.forEach(function(item, i){ pasted.forEach(function(_item){
dx.push(cx); dx.push(cx);
dy.push(cy); dy.push(cy);
}); });

View File

@ -114,6 +114,7 @@ export const convertPath = function (pth, toRel) {
case 2: // absolute move (M) case 2: // absolute move (M)
case 4: // absolute line (L) case 4: // absolute line (L)
case 18: // absolute smooth quad (T) case 18: // absolute smooth quad (T)
case 10: // absolute elliptical arc (A)
x -= curx; x -= curx;
y -= cury; y -= cury;
// Fallthrough // Fallthrough
@ -165,9 +166,6 @@ export const convertPath = function (pth, toRel) {
} }
d += pathDSegment(letter, [[x1, y1], [x, y]]); d += pathDSegment(letter, [[x1, y1], [x, y]]);
break; break;
case 10: // absolute elliptical arc (A)
x -= curx;
y -= cury;
// Fallthrough // Fallthrough
case 11: // relative elliptical arc (a) case 11: // relative elliptical arc (a)
if (toRel) { if (toRel) {
@ -449,7 +447,7 @@ export const pathActionsMethod = (function () {
const newD = newpath.getAttribute('d'); const newD = newpath.getAttribute('d');
const origD = path.elem.getAttribute('d'); const origD = path.elem.getAttribute('d');
path.elem.setAttribute('d', origD + newD); path.elem.setAttribute('d', origD + newD);
newpath.parentNode.removeChild(el); newpath.parentNode.removeChild();
if (path.matrix) { if (path.matrix) {
pathActionsContext_.recalcRotatedPath(); pathActionsContext_.recalcRotatedPath();
} }
@ -859,7 +857,7 @@ export const pathActionsMethod = (function () {
* @param {boolean} remove Not in use * @param {boolean} remove Not in use
* @returns {void} * @returns {void}
*/ */
clear (remove) { clear () {
editorContext_ = pathActionsContext_.getEditorContext(); editorContext_ = pathActionsContext_.getEditorContext();
const drawnPath = editorContext_.getDrawnPath(); const drawnPath = editorContext_.getDrawnPath();
currentPath = null; currentPath = null;
@ -870,7 +868,7 @@ export const pathActionsMethod = (function () {
elem.parentNode.removeChild(elem); elem.parentNode.removeChild(elem);
const pathpointgripContainer = getElem('pathpointgrip_container'); const pathpointgripContainer = getElem('pathpointgrip_container');
const elements = pathpointgripContainer.querySelectorAll('*'); const elements = pathpointgripContainer.querySelectorAll('*');
Array.prototype.forEach.call(elements, function(el, i){ Array.prototype.forEach.call(elements, function(el){
el.style.display = 'none'; el.style.display = 'none';
}); });
firstCtrl = null; firstCtrl = null;
@ -911,7 +909,7 @@ export const pathActionsMethod = (function () {
const type = seg.pathSegType; const type = seg.pathSegType;
if (type === 1) { continue; } if (type === 1) { continue; }
const pts = []; const pts = [];
['', 1, 2].forEach(function(n, j){ ['', 1, 2].forEach(function(n){
const x = seg['x' + n], y = seg['y' + n]; const x = seg['x' + n], y = seg['y' + n];
if (x !== undefined && y !== undefined) { if (x !== undefined && y !== undefined) {
const pt = transformPoint(x, y, m); const pt = transformPoint(x, y, m);

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* Path functionality. * Path functionality.
* @module path * @module path
@ -20,7 +19,6 @@ import {
supportsPathInsertItemBefore, supportsPathReplaceItem, isWebkit supportsPathInsertItemBefore, supportsPathReplaceItem, isWebkit
} from '../common/browser.js'; } from '../common/browser.js';
const $ = jQuery;
let pathMethodsContext_ = null; let pathMethodsContext_ = null;
let editorContext_ = null; let editorContext_ = null;
@ -175,7 +173,7 @@ export const addPointGripMethod = function (index, x, y) {
pointGripContainer.append(pointGrip); pointGripContainer.append(pointGrip);
const grip = document.getElementById('pathpointgrip_' + index); const grip = document.getElementById('pathpointgrip_' + index);
grip?.addEventListener("dblclick", (e) => { grip?.addEventListener("dblclick", () => {
const path = pathMethodsContext_.getPathObj(); const path = pathMethodsContext_.getPathObj();
if (path) { if (path) {
path.setSegType(); path.setSegType();
@ -640,7 +638,7 @@ export class Path {
// fixed, needed to work on all found elements, not just first // fixed, needed to work on all found elements, not just first
const pointGripContainer = getGripContainerMethod(); const pointGripContainer = getGripContainerMethod();
const elements = pointGripContainer.querySelectorAll('*'); const elements = pointGripContainer.querySelectorAll('*');
Array.prototype.forEach.call(elements, function(el, i){ Array.prototype.forEach.call(elements, function(el){
el.style.display = 'none'; el.style.display = 'none';
}); });

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* Path functionality. * Path functionality.
* @module path * @module path
@ -25,8 +24,6 @@ import {
init as pathActionsInit, pathActionsMethod init as pathActionsInit, pathActionsMethod
} from './path-actions.js'; } from './path-actions.js';
const $ = jQuery;
const segData = { const segData = {
2: ['x', 'y'], // PATHSEG_MOVETO_ABS 2: ['x', 'y'], // PATHSEG_MOVETO_ABS
4: ['x', 'y'], // PATHSEG_LINETO_ABS 4: ['x', 'y'], // PATHSEG_LINETO_ABS
@ -244,7 +241,7 @@ export const init = function (editorContext) {
'Moveto', 'Lineto', 'CurvetoCubic', 'CurvetoQuadratic', 'Arc', 'Moveto', 'Lineto', 'CurvetoCubic', 'CurvetoQuadratic', 'Arc',
'LinetoHorizontal', 'LinetoVertical', 'CurvetoCubicSmooth', 'CurvetoQuadraticSmooth' 'LinetoHorizontal', 'LinetoVertical', 'CurvetoCubicSmooth', 'CurvetoQuadraticSmooth'
]; ];
pathFuncsStrs.forEach(function(s, i){ pathFuncsStrs.forEach(function(s){
pathFuncs.push(s + 'Abs'); pathFuncs.push(s + 'Abs');
pathFuncs.push(s + 'Rel'); pathFuncs.push(s + 'Rel');
}); });
@ -675,6 +672,7 @@ export const convertPath = function (pth, toRel) {
case 2: // absolute move (M) case 2: // absolute move (M)
case 4: // absolute line (L) case 4: // absolute line (L)
case 18: // absolute smooth quad (T) case 18: // absolute smooth quad (T)
case 10: // absolute elliptical arc (A)
x -= curx; x -= curx;
y -= cury; y -= cury;
// Fallthrough // Fallthrough
@ -726,9 +724,6 @@ export const convertPath = function (pth, toRel) {
} }
d += pathDSegment(letter, [[x1, y1], [x, y]]); d += pathDSegment(letter, [[x1, y1], [x, y]]);
break; break;
case 10: // absolute elliptical arc (A)
x -= curx;
y -= cury;
// Fallthrough // Fallthrough
case 11: // relative elliptical arc (a) case 11: // relative elliptical arc (a)
if (toRel) { if (toRel) {

View File

@ -225,7 +225,7 @@ export const recalculateDimensions = function (selected) {
} // switch on element type to get initial values } // switch on element type to get initial values
if (attrs.length) { if (attrs.length) {
Array.prototype.forEach.call(attrs, function (attr, i) { Array.prototype.forEach.call(attrs, function (attr) {
changes[attr] = selected.getAttribute(attr); changes[attr] = selected.getAttribute(attr);
}); });
for (const [attr, val] of Object.entries(changes)) { for (const [attr, val] of Object.entries(changes)) {

View File

@ -1,3 +1,4 @@
/* eslint-disable sonarjs/no-duplicate-string */
/** /**
* Tools for SVG sanitization. * Tools for SVG sanitization.
* @module sanitize * @module sanitize

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* DOM element selection box tools. * DOM element selection box tools.
* @module select * @module select
@ -12,8 +11,6 @@ import { getRotationAngle, getBBox, getStrokedBBox, isNullish } from './utilitie
import { transformListToTransform, transformBox, transformPoint } from './math.js'; import { transformListToTransform, transformBox, transformPoint } from './math.js';
import { getTransformList } from './svgtransformlist.js'; import { getTransformList } from './svgtransformlist.js';
const $ = jQuery;
let svgFactory_; let svgFactory_;
let config_; let config_;
let selectorManager_; // A Singleton let selectorManager_; // A Singleton

View File

@ -119,7 +119,7 @@ export const moveUpDownSelected = function (dir) {
const list = elementContext_.getIntersectionList(getStrokedBBoxDefaultVisible([selected])); const list = elementContext_.getIntersectionList(getStrokedBBoxDefaultVisible([selected]));
if (dir === 'Down') { list.reverse(); } if (dir === 'Down') { list.reverse(); }
Array.prototype.forEach.call(list, function (el, i) { Array.prototype.forEach.call(list, function (el) {
if (!foundCur) { if (!foundCur) {
if (el === selected) { if (el === selected) {
foundCur = true; foundCur = true;
@ -242,7 +242,7 @@ export const cloneSelectedElements = function (x, y) {
var i = 0; var i = 0;
do { do {
i++; i++;
} while (el = el.previousElementSibling); } while (el == el.previousElementSibling);
return i; return i;
} }
@ -460,6 +460,7 @@ export const groupSelectedElements = function (type, urlArg) {
let cmdStr = ''; let cmdStr = '';
let url; let url;
// eslint-disable-next-line sonarjs/no-small-switch
switch (type) { switch (type) {
case 'a': { case 'a': {
cmdStr = 'Make hyperlink'; cmdStr = 'Make hyperlink';
@ -827,7 +828,7 @@ export const convertToGroup = function (elem) {
// Give ID for any visible element missing one // Give ID for any visible element missing one
const visElems = g.querySelectorAll(elementContext_.getVisElems()); const visElems = g.querySelectorAll(elementContext_.getVisElems());
Array.prototype.forEach.call(visElems, function (el, i) { Array.prototype.forEach.call(visElems, function (el) {
if (!el.id) { el.id = elementContext_.getNextId(); } if (!el.id) { el.id = elementContext_.getNextId(); }
}); });

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* Tools for selection. * Tools for selection.
* @module selection * @module selection
@ -11,7 +10,6 @@ import {
isNullish, getBBox as utilsGetBBox, getStrokedBBoxDefaultVisible isNullish, getBBox as utilsGetBBox, getStrokedBBoxDefaultVisible
} from './utilities.js'; } from './utilities.js';
import { transformPoint, transformListToTransform, rectsIntersect } from './math.js'; import { transformPoint, transformListToTransform, rectsIntersect } from './math.js';
import jQueryPluginSVG from './jQuery.attr.js';
import { import {
getTransformList getTransformList
} from './svgtransformlist.js'; } from './svgtransformlist.js';
@ -19,7 +17,6 @@ import * as hstry from './history.js';
import { getClosest } from '../editor/components/jgraduate/Util.js'; import { getClosest } from '../editor/components/jgraduate/Util.js';
const { BatchCommand } = hstry; const { BatchCommand } = hstry;
const $ = jQueryPluginSVG(jQuery);
let selectionContext_ = null; let selectionContext_ = null;
/** /**
@ -243,7 +240,7 @@ export const getVisibleElementsAndBBoxes = function (parent) {
} }
const contentElems = []; const contentElems = [];
const elements = parent.children; const elements = parent.children;
Array.prototype.forEach.call(elements, function (elem, i) { Array.prototype.forEach.call(elements, function (elem) {
if (elem.getBBox) { if (elem.getBBox) {
contentElems.push({ elem, bbox: getStrokedBBoxDefaultVisible([elem]) }); contentElems.push({ elem, bbox: getStrokedBBoxDefaultVisible([elem]) });
} }

View File

@ -81,7 +81,7 @@ export const svgCanvasToString = function () {
// Unwrap gsvg if it has no special attributes (only id and style) // Unwrap gsvg if it has no special attributes (only id and style)
const gsvgElems = svgContext_.getSVGContent().querySelectorAll('g[data-gsvg]'); const gsvgElems = svgContext_.getSVGContent().querySelectorAll('g[data-gsvg]');
Array.prototype.forEach.call(gsvgElems, function (element, i) { Array.prototype.forEach.call(gsvgElems, function (element) {
const attrs = element.attributes; const attrs = element.attributes;
let len = attrs.length; let len = attrs.length;
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
@ -100,7 +100,7 @@ export const svgCanvasToString = function () {
// Rewrap gsvg // Rewrap gsvg
if (nakedSvgs.length) { if (nakedSvgs.length) {
Array.prototype.forEach.call(nakedSvgs, function (el, i) { Array.prototype.forEach.call(nakedSvgs, function (el) {
svgContext_.getCanvas().groupSvgElem(el); svgContext_.getCanvas().groupSvgElem(el);
}); });
} }
@ -162,7 +162,7 @@ export const svgToString = function (elem, indent) {
const csElements = elem.querySelectorAll('*'); const csElements = elem.querySelectorAll('*');
const cElements = Array.prototype.slice.call(csElements); const cElements = Array.prototype.slice.call(csElements);
cElements.push(elem); cElements.push(elem);
Array.prototype.forEach.call(cElements, function (el, i) { Array.prototype.forEach.call(cElements, function (el) {
// const el = this; // const el = this;
// for some elements have no attribute // for some elements have no attribute
const uri = el.namespaceURI; const uri = el.namespaceURI;
@ -171,7 +171,7 @@ export const svgToString = function (elem, indent) {
out.push(' xmlns:' + nsMap[uri] + '="' + uri + '"'); out.push(' xmlns:' + nsMap[uri] + '="' + uri + '"');
} }
if (el.attributes.length > 0) { if (el.attributes.length > 0) {
for (const [i, attr] of Object.entries(el.attributes)) { for (const [, attr] of Object.entries(el.attributes)) {
const u = attr.namespaceURI; const u = attr.namespaceURI;
if (u && !nsuris[u] && nsMap[u] !== 'xmlns' && nsMap[u] !== 'xml') { if (u && !nsuris[u] && nsMap[u] !== 'xmlns' && nsMap[u] !== 'xml') {
nsuris[u] = true; nsuris[u] = true;
@ -349,7 +349,7 @@ export const setSvgString = function (xmlString, preventUndo) {
// change image href vals if possible // change image href vals if possible
const elements = content.querySelectorAll('image'); const elements = content.querySelectorAll('image');
Array.prototype.forEach.call(elements, function (image, i) { Array.prototype.forEach.call(elements, function (image) {
preventClickDefault(image); preventClickDefault(image);
const val = svgContext_.getCanvas().getHref(this); const val = svgContext_.getCanvas().getHref(this);
if (val) { if (val) {
@ -361,7 +361,7 @@ export const setSvgString = function (xmlString, preventUndo) {
const url = decodeURIComponent(m[1]); const url = decodeURIComponent(m[1]);
// const url = decodeURIComponent(m.groups.url); // const url = decodeURIComponent(m.groups.url);
const iimg = new Image(); const iimg = new Image();
iimg.addEventListener("load", (e) => { iimg.addEventListener("load", () => {
image.setAttributeNS(NS.XLINK, 'xlink:href', url); image.setAttributeNS(NS.XLINK, 'xlink:href', url);
}); });
iimg.src = url; iimg.src = url;
@ -374,7 +374,7 @@ export const setSvgString = function (xmlString, preventUndo) {
// Wrap child SVGs in group elements // Wrap child SVGs in group elements
const svgElements = content.querySelectorAll('svg'); const svgElements = content.querySelectorAll('svg');
Array.prototype.forEach.call(svgElements, function (element, i) { Array.prototype.forEach.call(svgElements, function (element) {
// Skip if it's in a <defs> // Skip if it's in a <defs>
if (getClosest(element.parentNode, 'defs')) { return; } if (getClosest(element.parentNode, 'defs')) { return; }
@ -394,7 +394,7 @@ export const setSvgString = function (xmlString, preventUndo) {
if (isGecko()) { if (isGecko()) {
const svgDefs = findDefs(); const svgDefs = findDefs();
const findElems = content.querySelectorAll('linearGradient, radialGradient, pattern'); const findElems = content.querySelectorAll('linearGradient, radialGradient, pattern');
Array.prototype.forEach.call(findElems, function (ele, i) { Array.prototype.forEach.call(findElems, function (ele) {
svgDefs.appendChild(ele); svgDefs.appendChild(ele);
}); });
} }
@ -421,7 +421,7 @@ export const setSvgString = function (xmlString, preventUndo) {
attrs.height = vb[3]; attrs.height = vb[3];
// handle content that doesn't have a viewBox // handle content that doesn't have a viewBox
} else { } else {
['width', 'height'].forEach(function (dim, i) { ['width', 'height'].forEach(function (dim) {
// Set to 100 if not given // Set to 100 if not given
const val = content.getAttribute(dim) || '100%'; const val = content.getAttribute(dim) || '100%';
if (String(val).substr(-1) === '%') { if (String(val).substr(-1) === '%') {
@ -438,9 +438,9 @@ export const setSvgString = function (xmlString, preventUndo) {
// Give ID for any visible layer children missing one // Give ID for any visible layer children missing one
const chiElems = content.children; const chiElems = content.children;
Array.prototype.forEach.call(chiElems, function (chiElem, i) { Array.prototype.forEach.call(chiElems, function (chiElem) {
const visElems = chiElem.querySelectorAll(svgContext_.getVisElems()); const visElems = chiElem.querySelectorAll(svgContext_.getVisElems());
Array.prototype.forEach.call(visElems, function (elem, i) { Array.prototype.forEach.call(visElems, function (elem) {
if (!elem.id) { elem.id = svgContext_.getCanvas().getNextId(); } if (!elem.id) { elem.id = svgContext_.getCanvas().getNextId(); }
}); });
}); });
@ -565,7 +565,7 @@ export const importSvgString = function (xmlString) {
// https://bugzilla.mozilla.org/show_bug.cgi?id=353575 // https://bugzilla.mozilla.org/show_bug.cgi?id=353575
// TODO: Make this properly undo-able. // TODO: Make this properly undo-able.
const elements = svg.querySelectorAll('linearGradient, radialGradient, pattern'); const elements = svg.querySelectorAll('linearGradient, radialGradient, pattern');
Array.prototype.forEach.call(elements, function (el, i) { Array.prototype.forEach.call(elements, function (el) {
defs.appendChild(el); defs.appendChild(el);
}); });
} }
@ -653,7 +653,7 @@ export const embedImage = function (src) {
svgContext_.getCanvas().setGoodImage(src); svgContext_.getCanvas().setGoodImage(src);
resolve(svgContext_.getEncodableImages(src)); resolve(svgContext_.getEncodableImages(src));
}); });
imgI.addEventListener("error", (e) => { imgI.addEventListener("error", () => {
reject(new Error('Error loading image: ')); reject(new Error('Error loading image: '));
}); });
imgI.setAttribute('src', src); imgI.setAttribute('src', src);
@ -760,15 +760,15 @@ export const rasterExport = async function (imgType, quality, exportWindowName,
document.body.appendChild(canvasEx); document.body.appendChild(canvasEx);
} }
const c = $id('export_canvas'); const c = $id('export_canvas');
c.style.width = svgContext_.getCanvas().contentW + "px";; c.style.width = svgContext_.getCanvas().contentW + "px";
c.style.height = svgContext_.getCanvas().contentH + "px";; c.style.height = svgContext_.getCanvas().contentH + "px";
const canvg = svgContext_.getcanvg(); const canvg = svgContext_.getcanvg();
const ctx = c.getContext('2d'); const ctx = c.getContext('2d');
const v = canvg.fromString(ctx, svg); const v = canvg.fromString(ctx, svg);
// Render only first frame, ignoring animations. // Render only first frame, ignoring animations.
await v.render(); await v.render();
// Todo: Make async/await utility in place of `toBlob`, so we can remove this constructor // Todo: Make async/await utility in place of `toBlob`, so we can remove this constructor
return new Promise((resolve, reject) => { return new Promise((resolve) => {
const dataURLType = type.toLowerCase(); const dataURLType = type.toLowerCase();
const datauri = quality const datauri = quality
? c.toDataURL('image/' + dataURLType, quality) ? c.toDataURL('image/' + dataURLType, quality)
@ -903,7 +903,7 @@ export const uniquifyElemsMethod = function (g) {
// now search for all attributes on this element that might refer // now search for all attributes on this element that might refer
// to other elements // to other elements
svgContext_.getrefAttrs().forEach(function(attr, i){ svgContext_.getrefAttrs().forEach(function(attr){
const attrnode = n.getAttributeNode(attr); const attrnode = n.getAttributeNode(attr);
if (attrnode) { if (attrnode) {
// the incoming file has been sanitized, so we should be able to safely just strip off the leading # // the incoming file has been sanitized, so we should be able to safely just strip off the leading #
@ -1055,12 +1055,12 @@ export const convertGradientsMethod = function (elem) {
let elems = elem.querySelectorAll('linearGradient, radialGradient'); let elems = elem.querySelectorAll('linearGradient, radialGradient');
if (!elems.length && isWebkit()) { if (!elems.length && isWebkit()) {
// Bug in webkit prevents regular *Gradient selector search // Bug in webkit prevents regular *Gradient selector search
elems = Array.prototype.filter.call(elem.querySelectorAll('*'), function (curThis, i) { elems = Array.prototype.filter.call(elem.querySelectorAll('*'), function (curThis) {
return (curThis.tagName.includes('Gradient')); return (curThis.tagName.includes('Gradient'));
}); });
} }
Array.prototype.forEach.call(elems, function (grad, i) { Array.prototype.forEach.call(elems, function (grad) {
if (grad.getAttribute('gradientUnits') === 'userSpaceOnUse') { if (grad.getAttribute('gradientUnits') === 'userSpaceOnUse') {
const svgcontent = svgContext_.getSVGContent(); const svgcontent = svgContext_.getSVGContent();
// TODO: Support more than one element with this ref by duplicating parent grad // TODO: Support more than one element with this ref by duplicating parent grad

View File

@ -131,7 +131,7 @@ if (!window.console) {
if (window.opera) { if (window.opera) {
window.console.log = function (str) { window.opera.postError(str); }; window.console.log = function (str) { window.opera.postError(str); };
window.console.dir = function (str) { /* empty fn */ }; window.console.dir = function (_str) { /* empty fn */ };
} }
// Reenable after fixing eslint-plugin-jsdoc to handle // Reenable after fixing eslint-plugin-jsdoc to handle
@ -632,7 +632,7 @@ class SvgCanvas {
getCurrentZoom, getCurrentZoom,
getRubberBox() { return rubberBox; }, getRubberBox() { return rubberBox; },
setCurBBoxes(value) { curBBoxes = value; }, setCurBBoxes(value) { curBBoxes = value; },
getCurBBoxes(value) { return curBBoxes; }, getCurBBoxes(_value) { return curBBoxes; },
getCurrentResizeMode() { return currentResizeMode; }, getCurrentResizeMode() { return currentResizeMode; },
addCommandToHistory, addCommandToHistory,
getSelector() { return Selector; } getSelector() { return Selector; }
@ -2393,7 +2393,7 @@ class SvgCanvas {
this.convertToPath = function (elem, getBBox) { this.convertToPath = function (elem, getBBox) {
if (isNullish(elem)) { if (isNullish(elem)) {
const elems = selectedElements; const elems = selectedElements;
elems.forEach(function(el, i){ elems.forEach(function(el){
if (el) { canvas.convertToPath(el); } if (el) { canvas.convertToPath(el); }
}); });
return undefined; return undefined;

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/** /**
* @module text-actions Tools for Text edit functions * @module text-actions Tools for Text edit functions
* @license MIT * @license MIT
@ -6,7 +5,7 @@
* @copyright 2010 Alexis Deveria, 2010 Jeff Schiller * @copyright 2010 Alexis Deveria, 2010 Jeff Schiller
*/ */
import jQueryPluginSVG from './jQuery.attr.js';
import {NS} from '../common/namespaces.js'; import {NS} from '../common/namespaces.js';
import { import {
transformPoint, getMatrix transformPoint, getMatrix
@ -18,8 +17,6 @@ import {
supportsGoodTextCharPos supportsGoodTextCharPos
} from '../common/browser.js'; } from '../common/browser.js';
const $ = jQueryPluginSVG(jQuery);
let textActionsContext_ = null; let textActionsContext_ = null;
/** /**

View File

@ -581,7 +581,7 @@ function groupBBFix(selected) {
if (ref) { if (ref) {
let elements = []; let elements = [];
Array.prototype.forEach.call(ref.children, function (el, i) { Array.prototype.forEach.call(ref.children, function (el) {
const elem = el.cloneNode(true); const elem = el.cloneNode(true);
elem.setAttribute('visibility', 'hidden'); elem.setAttribute('visibility', 'hidden');
svgroot_.appendChild(elem); svgroot_.appendChild(elem);
@ -597,7 +597,7 @@ function groupBBFix(selected) {
let issue = false; let issue = false;
if (matched.length) { if (matched.length) {
Array.prototype.forEach.call(matched, function (match, i) { Array.prototype.forEach.call(matched, function (match) {
const bb = match.getBBox(); const bb = match.getBBox();
if (!bb.width || !bb.height) { if (!bb.width || !bb.height) {
issue = true; issue = true;
@ -741,7 +741,7 @@ export const getPathDFromSegments = function (pathSegments) {
export const getPathDFromElement = function (elem) { export const getPathDFromElement = function (elem) {
// Possibly the cubed root of 6, but 1.81 works best // Possibly the cubed root of 6, but 1.81 works best
let num = 1.81; let num = 1.81;
let d, a, rx, ry; let d, rx, ry;
switch (elem.tagName) { switch (elem.tagName) {
case 'ellipse': case 'ellipse':
case 'circle': { case 'circle': {
@ -765,12 +765,13 @@ export const getPathDFromElement = function (elem) {
} case 'path': } case 'path':
d = elem.getAttribute('d'); d = elem.getAttribute('d');
break; break;
case 'line': case 'line': {
const x1 = elem.getAttribute('x1'); const x1 = elem.getAttribute('x1');
const y1 = elem.getAttribute('y1'); const y1 = elem.getAttribute('y1');
const x2 = elem.getAttribute('x2'); const x2 = elem.getAttribute('x2');
const y2 = elem.getAttribute('y2'); const y2 = elem.getAttribute('y2');
d = 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2; d = 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2;
}
break; break;
case 'polyline': case 'polyline':
d = 'M' + elem.getAttribute('points'); d = 'M' + elem.getAttribute('points');
@ -827,7 +828,7 @@ export const getExtraAttributesForConvertToPath = function (elem) {
const attrs = {}; const attrs = {};
// TODO: make this list global so that we can properly maintain it // TODO: make this list global so that we can properly maintain it
// TODO: what about @transform, @clip-rule, @fill-rule, etc? // TODO: what about @transform, @clip-rule, @fill-rule, etc?
['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'].forEach(function(item, i){ ['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'].forEach(function(item){
const a = elem.getAttribute(item); const a = elem.getAttribute(item);
if (a) { if (a) {
attrs[item] = a; attrs[item] = a;
@ -1077,7 +1078,7 @@ export const getStrokedBBox = function (elems, addSVGElementFromJson, pathAction
if (!elems || !elems.length) { return false; } if (!elems || !elems.length) { return false; }
let fullBb; let fullBb;
elems.forEach(function(elem, i){ elems.forEach(function(elem){
if (fullBb) { return; } if (fullBb) { return; }
if (!elem.parentNode) { return; } if (!elem.parentNode) { return; }
fullBb = getBBoxWithTransform(elem, addSVGElementFromJson, pathActions); fullBb = getBBoxWithTransform(elem, addSVGElementFromJson, pathActions);
@ -1102,7 +1103,7 @@ export const getStrokedBBox = function (elems, addSVGElementFromJson, pathAction
maxX += offset; maxX += offset;
maxY += offset; maxY += offset;
} else { } else {
elems.forEach(function(elem, i){ elems.forEach(function(elem){
const curBb = getBBoxWithTransform(elem, addSVGElementFromJson, pathActions); const curBb = getBBoxWithTransform(elem, addSVGElementFromJson, pathActions);
if (curBb) { if (curBb) {
const offset = getStrokeOffsetForBBox(elem); const offset = getStrokeOffsetForBBox(elem);
@ -1140,7 +1141,7 @@ export const getVisibleElements = function (parentElement) {
const contentElems = []; const contentElems = [];
const childrens = parentElement.children const childrens = parentElement.children
Array.prototype.forEach.call(childrens, function (elem, i) { Array.prototype.forEach.call(childrens, function (elem) {
if (elem.getBBox) { if (elem.getBBox) {
contentElems.push(elem); contentElems.push(elem);
} }
@ -1230,7 +1231,7 @@ export const getElem = (supportsSelectors())
} }
: function (id) { : function (id) {
// jQuery lookup: twice as slow as xpath in FF // jQuery lookup: twice as slow as xpath in FF
return svgroot_.querySelector('[id=${id}]'); return svgroot_.querySelector(`[id=${id}]`);
}; };
/** /**
@ -1322,7 +1323,7 @@ export const snapToGrid = function (value) {
* @returns {void} * @returns {void}
*/ */
export const preventClickDefault = function (img) { export const preventClickDefault = function (img) {
const elements = document.querySelectorAll("img"); const elements = document.querySelectorAll(img);
Array.from(elements).forEach(function (element) { Array.from(elements).forEach(function (element) {
element.addEventListener('click', function (e) { element.addEventListener('click', function (e) {
e.preventDefault(); e.preventDefault();