* 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
ignore
coverage
instrumented
dist
docs/jsdoc
archive
jsconfig.json
mochawesome-report
releases
!.eslintrc.js
!.ncurc.js
@ -21,11 +16,6 @@ svgedit-custom.css
# Vendor/minified files
src/editor/jquery.min.js
src/editor/jspdf/jspdf.min.js
src/editor/jspdf/underscore-min.js
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:import/errors",
"plugin:markdown/recommended",
"plugin:sonarjs/recommended"
"plugin:sonarjs/recommended",
"eslint:recommended"
],
plugins: ["jsdoc", "promise", "html", "import", "sonarjs"],
parserOptions: {
@ -19,262 +20,47 @@ module.exports = {
browser: 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: {
// check-examples is not picking up eslint config properly in some
// environments; see also discussion above
// `mocha-cleanup/no-assertions-outside-it`
"sonarjs/cognitive-complexity": 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"]
}
}
]
"node/no-unsupported-features/es-syntax": 0,
"no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"sonarjs/cognitive-complexity": ["warn", 40],
"sonarjs/no-duplicate-string": 0,
},
overrides: [
// Locales have no need for importing outside of SVG-Edit
// and translations may need a longer line length
{
files: [
'src/editor/locale/lang.*.js',
'src/editor/extensions/*/locale/**',
'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"
files: [ 'cypress/**/*'],
extends: [
"plugin:cypress/recommended"
],
env: {
mocha: true,
node: true
},
settings: {
polyfills: [
"console",
"Date.now",
"document.body",
"document.createElementNS",
"document.head",
"DOMParser",
"Number.isNaN",
"Object.keys",
"Object.entries",
"Promise"
]
globals: {
"assert": true
},
rules: {
// These errors are caused in Cypress files if user has not
// yet instrumented code; need to reinvestigate why we had to
// instrument separately from nyc mocha
"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
// with ci, instrumented is not created before linter
"import/no-unresolved": [2, { ignore: ['instrumented'] }],
"node/no-missing-import": 0
}
},
{
// Node files
files: [
"docs/jsdoc-config.js",
"build/build-html.js",
"rollup.config.js",
"rollup-config.config.js"
],
env: {
node: true
},
settings: {
polyfills: ["console", "Promise.resolve"]
},
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"
files: [ 'docs/**/*'],
rules: { // md files have example that don't need a strict checking
"no-undef": 0,
"import/no-unresolved": 0,
"node/no-missing-import": 0,
"jsdoc/check-examples": [
"warn",
{
rejectExampleCodeRegex: "^`",
checkDefaults: true,
checkParams: true,
checkProperties: true
}
]
}
}
]
};
};

View File

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

View File

@ -20,7 +20,7 @@ describe('UI - Control Points', function () {
</svg>`, {force: true, parseSpecialCharSequences: false});
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})
.trigger('mousemove', randomOffset(), randomOffset(), {force: true})

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -27,7 +27,7 @@ This is the general format for an extension:
```js
export default {
name: 'extensionname',
init (methods) {
init (_methods) {
return extensionData;
}
};
@ -83,7 +83,7 @@ export default {
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-html": "^6.1.2",
"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-mocha": "8.1.0",
"eslint-plugin-mocha-cleanup": "1.9.1",
@ -10277,9 +10277,9 @@
}
},
"node_modules/eslint-plugin-jsdoc": {
"version": "32.3.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.2.tgz",
"integrity": "sha512-kcdg0OvhI466KgMYXwxGvP6+m9J/sIBg0Jkn9eDU5lnM6RSVM27M9zKZim2XY6AUbbdqmkBPEP4ixvtBXRHktQ==",
"version": "32.3.3",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.3.tgz",
"integrity": "sha512-WxXohbMYlZvCt3r7MepwT++nTLsO4CPegWcm5toM4IGq3MBmYkG+Uf5yDa+n1MwPXLg+KbJqAsI19hmkVD7MPg==",
"dev": true,
"dependencies": {
"comment-parser": "1.1.5",
@ -33395,9 +33395,9 @@
}
},
"eslint-plugin-jsdoc": {
"version": "32.3.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.2.tgz",
"integrity": "sha512-kcdg0OvhI466KgMYXwxGvP6+m9J/sIBg0Jkn9eDU5lnM6RSVM27M9zKZim2XY6AUbbdqmkBPEP4ixvtBXRHktQ==",
"version": "32.3.3",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-32.3.3.tgz",
"integrity": "sha512-WxXohbMYlZvCt3r7MepwT++nTLsO4CPegWcm5toM4IGq3MBmYkG+Uf5yDa+n1MwPXLg+KbJqAsI19hmkVD7MPg==",
"dev": true,
"requires": {
"comment-parser": "1.1.5",

View File

@ -15,14 +15,15 @@
"scripts": {
"lint": "eslint --ext js,html,md .",
"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:run": "run-s -n -c cypress:run-no-badge report-summary-mocha-full",
"build": "rollup -c",
"build:watch": "rollup -c --watch",
"start": "web-dev-server --node-resolve",
"start:watch": "web-dev-server --node-resolve --watch",
"cypress:open": "run-p start cypress:open-no-start",
"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-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",
@ -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: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": "run-s -n -c cypress:run-no-badge report-summary-mocha-full",
"mochawesome-cli": "node tools/mochawesome-cli.js",
"mochawesome-cli-dot": "npm run mochawesome-cli -- --dot",
"report-no-mochawesome": "nyc report",
@ -102,8 +102,12 @@
"not IE < 12",
"not Chrome < 75",
"not FireFox < 68",
"not Safari < 10",
"not ios_saf < 10"
"not Safari < 11",
"not ios_saf < 10",
"not android < 5",
"not op_mini all",
"not Edge < 18",
"not dead"
],
"dependencies": {
"@babel/polyfill": "7.12.1",
@ -158,7 +162,7 @@
"eslint-plugin-eslint-comments": "3.2.0",
"eslint-plugin-html": "^6.1.2",
"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-mocha": "8.1.0",
"eslint-plugin-mocha-cleanup": "1.9.1",

View File

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

View File

@ -1,5 +1,5 @@
/* eslint-disable max-len */
/* globals jQuery seConfirm seAlert */
/* globals seConfirm seAlert $ */
/**
* 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 ConfigObj from './ConfigObj.js';
import {mergeDeep} from './components/jgraduate/Util.js';
import EditorStartup from './EditorStartup.js';
import LeftPanel from './panels/LeftPanel.js';
import TopPanel from './panels/TopPanel.js';
@ -29,7 +27,7 @@ import LayersPanel from './panels/LayersPanel.js';
import MainMenu from './MainMenu.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();
}
// eslint-disable-next-line sonarjs/no-collapsible-if
if (this.configObj.urldata.storagePrompt !== true && this.storagePromptState === 'ignore') {
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]));
// Only updating fields for single elements for now
if (!this.multiselected) {
// eslint-disable-next-line sonarjs/no-small-switch
switch (mode) {
case 'rotate': {
const ang = this.svgCanvas.getRotationAngle(elem);
@ -764,7 +764,7 @@ class Editor extends EditorStartup {
} else {
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
$id('cur_context_panel').innerHTML = linkStr;
@ -801,9 +801,6 @@ class Editor extends EditorStartup {
*/
async extAdded(win, ext) {
const self = this;
// eslint-disable-next-line sonarjs/no-unused-collection
let btnSelects = [];
if (!ext) {
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) {
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 renameLayer = (oldLayerName === this.uiStrings.common.layer + ' 1');
this.svgCanvas.setUiStrings(allStrings);
// this.svgCanvas.setUiStrings(allStrings);
this.setTitles();
if (renameLayer) {

View File

@ -62,7 +62,7 @@ class EditorStartup {
*/
async init () {
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;
// allow to prepare the dom without display
this.$svgEditor.style.visibility = 'hidden';
@ -291,6 +291,7 @@ class EditorStartup {
if (evt.type === 'mouseup') { panning = false; }
return false;
});
// eslint-disable-next-line sonarjs/no-identical-functions
$id('svgcanvas').addEventListener('mousemove', function(evt) {
if (panning === false) { return true; }
@ -313,7 +314,7 @@ class EditorStartup {
return true;
});
window.addEventListener('mouseup', function(evt) {
window.addEventListener('mouseup', function() {
panning = false;
});
@ -362,7 +363,7 @@ class EditorStartup {
};
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) => {
inp = e.currentTarget;
this.uiContext = 'toolbars';
@ -402,7 +403,7 @@ class EditorStartup {
height: getHeight()
};
window.addEventListener('resize', (evt) => {
window.addEventListener('resize', () => {
Object.entries(winWh).forEach(([type, val]) => {
const curval = (type === 'width') ? window.innerWidth - 15 : window.innerHeight;
this.workarea['scroll' + (type === 'width' ? 'Left' : 'Top')] -= (curval - val) / 2;
@ -531,7 +532,7 @@ class EditorStartup {
$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) {
$editDialog.setAttribute('showrulers', true);
@ -712,6 +713,7 @@ class EditorStartup {
/**
* @type {module:SVGthis.ExtensionObject}
*/
// eslint-disable-next-line no-unsanitized/method
const imported = await import(`./extensions/${encodeURIComponent(extname)}/${encodeURIComponent(extname)}.js`);
const {name = extname, init: initfn} = imported.default;
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}
*/
// eslint-disable-next-line no-unsanitized/method
const imported = await import(encodeURI(extPathName));
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) {
// Todo: Add config to alert any errors
console.error('Extension failed to load: ' + extPathName + '; ', err);
@ -748,12 +751,12 @@ class EditorStartup {
this.svgCanvas.bind(
'extensions_added',
/**
* @param {external:Window} win
* @param {module:svgcanvas.SvgCanvas#event:extensions_added} data
* @param {external:Window} _win
* @param {module:svgcanvas.SvgCanvas#event:extensions_added} _data
* @listens module:SvgCanvas#event:extensions_added
* @returns {void}
*/
(win, data) => {
(_win, _data) => {
this.extensionsAdded = true;
this.setAll();

View File

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

View File

@ -1,3 +1,4 @@
/* eslint-disable sonarjs/no-collapsible-if */
/**
* @param {any} obj
* @returns {any}
@ -9,7 +10,7 @@ export function findPos(obj) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
} while (obj == obj.offsetParent);
return { left: curleft, top: curtop };
}
return { left: curleft, top: curtop };
@ -93,7 +94,7 @@ export function getClosest(elem, selector) {
}
}
return null;
};
}
/**
* 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 {
return parents;
}
};
}
export function getParentsUntil(elem, parent, selector) {
let parents = [];
@ -214,4 +215,4 @@ export function getParentsUntil(elem, parent, selector) {
} else {
return parents;
}
};
}

View File

@ -46,8 +46,8 @@ const ns = {
if (!window.console) {
window.console = {
log (str) { /* empty fn */ },
dir (str) { /* empty fn */ }
log () { /* empty fn */ },
dir () { /* empty fn */ }
};
}
@ -156,34 +156,6 @@ function mkElem (name, attrs, newparent) {
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
* @property {string} [color] #Hex color
@ -221,8 +193,6 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
$settings = Object.assign({}, jGraduateDefaults, options || {}),
id = $this.getAttribute('id'),
idref = '#' + $this.getAttribute('id') + ' ';
// JFH !!!!!
const $shadowRoot = elem.parentNode;
if (!idref) {
// eslint-disable-next-line no-alert
@ -561,7 +531,7 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
$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]);
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'},
images: {clientPath: $settings.images.clientPath},
color: {active: colr, alphaSupport: true}
}, function (clr, arg2) {
}, function (clr) {
stopColor = clr.val('hex') ? ('#' + clr.val('hex')) : 'none';
stopOpacity = clr.val('a') !== null ? clr.val('a') / 256 : 1;
colorhandle.setAttribute('fill', stopColor);
@ -1118,7 +1088,7 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
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 sInput = $this.querySelector(data.input);
handle.addEventListener('mousedown', function (evt) {
@ -1190,7 +1160,7 @@ export function jGraduateMethod (elem, options, okCallback, cancelCallback) {
evt.preventDefault();
};
const stopSlider = function (evt) {
const stopSlider = function () {
$win.removeEventListener('mousemove', dragSlider);
$win.removeEventListener('mouseup', stopSlider);
slider = null;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -47,7 +47,7 @@ export const dragmove = function(target, handler, parent, onStart, onEnd, onDrag
});
// On leaving click, stop moving.
document.addEventListener(_isTouch ? "touchend" : "mouseup", function(e) {
document.addEventListener(_isTouch ? "touchend" : "mouseup", function() {
if (onEnd && hasStarted) {
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.
document.addEventListener(_isTouch ? "touchmove" : "mousemove", function(e) {
document.addEventListener(_isTouch ? "touchmove" : "mousemove", function() {
if (onDrag && hasStarted) {
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.
* @module EmbeddedSVGEditDOM
@ -6,8 +5,6 @@
import EmbeddedSVGEdit from './embedapi.js';
import {isChrome} from '../common/browser.js';
const $ = jQuery;
let svgCanvas = null;
/**
@ -110,6 +107,7 @@ iframe.src = frameBase + framePath +
iframe.addEventListener('load', function () {
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
let doc;
try {

View File

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

View File

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

View File

@ -10,6 +10,7 @@
const loadExtensionTranslation = async function (lang) {
let translationModule;
try {
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/${encodeURIComponent(lang)}.js`);
} catch (_error) {
// eslint-disable-next-line no-console
@ -197,7 +198,7 @@ export default {
connections = [];
// 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;
// Grab the ends
const parts = [];
@ -220,7 +221,7 @@ export default {
addThis = false;
// The connected element might be part of a selected group
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)) {
// Pretend this element is selected
addThis = true;
@ -364,7 +365,7 @@ export default {
svgCanvas.setMode('connector');
});
},
/* async */ addLangData({ lang }) { // , importLocale: importLoc
/* async */ addLangData({ _lang }) { // , importLocale: importLoc
return {
data: strings.langList
};
@ -505,7 +506,7 @@ export default {
const connStr = startId + ' ' + endId;
const altStr = endId + ' ' + startId;
// 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');
if (conn === connStr || conn === altStr) { return true; }
return false;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
/* globals jQuery */
const $ = jQuery;
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) {
const { href } = event.currentTarget;
const target = window.parent;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -143,7 +143,6 @@ class LayersPanel {
</div>
`;
this.editor.$svgEditor.append(template.content.cloneNode(true));
this.editor.svgCanvas = this.editor.svgCanvas;
// layer menu added to DOM
const menuMore = document.createElement("se-cmenu-layers");
menuMore.setAttribute("id", "se-cmenu-layers-more");
@ -193,14 +192,14 @@ class LayersPanel {
this.allowmove = true;
}, 20);
});
$id("sidepanel_handle").addEventListener("mouseup", evt => {
$id("sidepanel_handle").addEventListener("mouseup", _evt => {
if (!this.sidedragging) {
this.toggleSidePanel();
}
this.sidedrag = -1;
this.sidedragging = false;
});
window.addEventListener("mouseup", evt => {
window.addEventListener("mouseup", _evt => {
this.sidedrag = -1;
this.sidedragging = false;
$id("svg_editor").removeEventListener(
@ -247,7 +246,7 @@ class LayersPanel {
// 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)
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');
});
document.querySelector('#layerlist tr.layer').classList.add('layersel');
@ -284,7 +283,7 @@ class LayersPanel {
var i = 0;
do {
i++;
} while (el = el.previousElementSibling);
} while (el == el.previousElementSibling);
return i;
}
@ -419,7 +418,7 @@ class LayersPanel {
evt.currentTarget.textContent
);
});
element.addEventListener('mouseout', function(evt) {
element.addEventListener('mouseout', function(_evt) {
self.toggleHighlightLayer(self.editor.svgCanvas);
});
});

View File

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

View File

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

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/**
* Manipulating coordinates.
* @module coords
@ -13,8 +12,6 @@ import {
} from './math.js';
import { getTransformList } from './svgtransformlist.js';
const $ = jQuery;
// this is how we map paths to our preferred relative segment types
const pathMap = [
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
el.childNodes.forEach(function(child, i){
el.childNodes.forEach(function(child){
switch (child.nodeType) {
case 1: // element node
newEl.append(copyElem(child, getNextId));

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/**
* Tools for drawing.
* @module draw
@ -22,8 +21,6 @@ import {
} from './history.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 RandomizeModes = {

View File

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

View File

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

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/**
* Provides tools for the layer concept.
* @module layer
@ -10,7 +9,6 @@
import {NS} from '../common/namespaces.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

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 {
getStrokedBBoxDefaultVisible
} from './utilities.js';
import * as hstry from './history.js';
// Constants
const $ = jQueryPluginSVG(jQuery);
const {
InsertElementCommand, BatchCommand
@ -118,7 +113,7 @@ export const pasteElementsMethod = function (type, x, y) {
dx = [],
dy = [];
pasted.forEach(function(item, i){
pasted.forEach(function(_item){
dx.push(cx);
dy.push(cy);
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,3 @@
/* globals jQuery */
/**
* Tools for selection.
* @module selection
@ -11,7 +10,6 @@ import {
isNullish, getBBox as utilsGetBBox, getStrokedBBoxDefaultVisible
} from './utilities.js';
import { transformPoint, transformListToTransform, rectsIntersect } from './math.js';
import jQueryPluginSVG from './jQuery.attr.js';
import {
getTransformList
} from './svgtransformlist.js';
@ -19,7 +17,6 @@ import * as hstry from './history.js';
import { getClosest } from '../editor/components/jgraduate/Util.js';
const { BatchCommand } = hstry;
const $ = jQueryPluginSVG(jQuery);
let selectionContext_ = null;
/**
@ -243,7 +240,7 @@ export const getVisibleElementsAndBBoxes = function (parent) {
}
const contentElems = [];
const elements = parent.children;
Array.prototype.forEach.call(elements, function (elem, i) {
Array.prototype.forEach.call(elements, function (elem) {
if (elem.getBBox) {
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)
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;
let len = attrs.length;
for (let i = 0; i < len; i++) {
@ -100,7 +100,7 @@ export const svgCanvasToString = function () {
// Rewrap gsvg
if (nakedSvgs.length) {
Array.prototype.forEach.call(nakedSvgs, function (el, i) {
Array.prototype.forEach.call(nakedSvgs, function (el) {
svgContext_.getCanvas().groupSvgElem(el);
});
}
@ -162,7 +162,7 @@ export const svgToString = function (elem, indent) {
const csElements = elem.querySelectorAll('*');
const cElements = Array.prototype.slice.call(csElements);
cElements.push(elem);
Array.prototype.forEach.call(cElements, function (el, i) {
Array.prototype.forEach.call(cElements, function (el) {
// const el = this;
// for some elements have no attribute
const uri = el.namespaceURI;
@ -171,7 +171,7 @@ export const svgToString = function (elem, indent) {
out.push(' xmlns:' + nsMap[uri] + '="' + uri + '"');
}
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;
if (u && !nsuris[u] && nsMap[u] !== 'xmlns' && nsMap[u] !== 'xml') {
nsuris[u] = true;
@ -349,7 +349,7 @@ export const setSvgString = function (xmlString, preventUndo) {
// change image href vals if possible
const elements = content.querySelectorAll('image');
Array.prototype.forEach.call(elements, function (image, i) {
Array.prototype.forEach.call(elements, function (image) {
preventClickDefault(image);
const val = svgContext_.getCanvas().getHref(this);
if (val) {
@ -361,7 +361,7 @@ export const setSvgString = function (xmlString, preventUndo) {
const url = decodeURIComponent(m[1]);
// const url = decodeURIComponent(m.groups.url);
const iimg = new Image();
iimg.addEventListener("load", (e) => {
iimg.addEventListener("load", () => {
image.setAttributeNS(NS.XLINK, 'xlink:href', url);
});
iimg.src = url;
@ -374,7 +374,7 @@ export const setSvgString = function (xmlString, preventUndo) {
// Wrap child SVGs in group elements
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>
if (getClosest(element.parentNode, 'defs')) { return; }
@ -394,7 +394,7 @@ export const setSvgString = function (xmlString, preventUndo) {
if (isGecko()) {
const svgDefs = findDefs();
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);
});
}
@ -421,7 +421,7 @@ export const setSvgString = function (xmlString, preventUndo) {
attrs.height = vb[3];
// handle content that doesn't have a viewBox
} else {
['width', 'height'].forEach(function (dim, i) {
['width', 'height'].forEach(function (dim) {
// Set to 100 if not given
const val = content.getAttribute(dim) || '100%';
if (String(val).substr(-1) === '%') {
@ -438,9 +438,9 @@ export const setSvgString = function (xmlString, preventUndo) {
// Give ID for any visible layer children missing one
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());
Array.prototype.forEach.call(visElems, function (elem, i) {
Array.prototype.forEach.call(visElems, function (elem) {
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
// TODO: Make this properly undo-able.
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);
});
}
@ -653,7 +653,7 @@ export const embedImage = function (src) {
svgContext_.getCanvas().setGoodImage(src);
resolve(svgContext_.getEncodableImages(src));
});
imgI.addEventListener("error", (e) => {
imgI.addEventListener("error", () => {
reject(new Error('Error loading image: '));
});
imgI.setAttribute('src', src);
@ -760,15 +760,15 @@ export const rasterExport = async function (imgType, quality, exportWindowName,
document.body.appendChild(canvasEx);
}
const c = $id('export_canvas');
c.style.width = svgContext_.getCanvas().contentW + "px";;
c.style.height = svgContext_.getCanvas().contentH + "px";;
c.style.width = svgContext_.getCanvas().contentW + "px";
c.style.height = svgContext_.getCanvas().contentH + "px";
const canvg = svgContext_.getcanvg();
const ctx = c.getContext('2d');
const v = canvg.fromString(ctx, svg);
// Render only first frame, ignoring animations.
await v.render();
// 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 datauri = 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
// to other elements
svgContext_.getrefAttrs().forEach(function(attr, i){
svgContext_.getrefAttrs().forEach(function(attr){
const attrnode = n.getAttributeNode(attr);
if (attrnode) {
// 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');
if (!elems.length && isWebkit()) {
// 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'));
});
}
Array.prototype.forEach.call(elems, function (grad, i) {
Array.prototype.forEach.call(elems, function (grad) {
if (grad.getAttribute('gradientUnits') === 'userSpaceOnUse') {
const svgcontent = svgContext_.getSVGContent();
// 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) {
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
@ -632,7 +632,7 @@ class SvgCanvas {
getCurrentZoom,
getRubberBox() { return rubberBox; },
setCurBBoxes(value) { curBBoxes = value; },
getCurBBoxes(value) { return curBBoxes; },
getCurBBoxes(_value) { return curBBoxes; },
getCurrentResizeMode() { return currentResizeMode; },
addCommandToHistory,
getSelector() { return Selector; }
@ -2393,7 +2393,7 @@ class SvgCanvas {
this.convertToPath = function (elem, getBBox) {
if (isNullish(elem)) {
const elems = selectedElements;
elems.forEach(function(el, i){
elems.forEach(function(el){
if (el) { canvas.convertToPath(el); }
});
return undefined;

View File

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

View File

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