Connector extension (#916)

* npm update
* move connector extension back
master
JFH 2023-08-25 23:47:16 +02:00 committed by GitHub
parent ca21e83365
commit 24b8f74c4d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 5345 additions and 21314 deletions

View File

@ -1,5 +1,9 @@
# SVG-Edit CHANGES # SVG-Edit CHANGES
## 7.3.2
- npm packages ugrade
- refactor, fix and and put back the connector extension
## 7.3.1 ## 7.3.1
- npm packages ugrade - npm packages ugrade
- refresh Arabic language - refresh Arabic language

View File

@ -1,659 +0,0 @@
/**
* @file ext-connector.js
*
* @license MIT
*
* @copyright 2010 Alexis Deveria
*
*/
const name = "connector";
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/${lang}.js`);
} catch (_error) {
// eslint-disable-next-line no-console
console.warn(`Missing translation (${lang}) for ${name} - using 'en'`);
// eslint-disable-next-line no-unsanitized/method
translationModule = await import(`./locale/en.js`);
}
svgEditor.i18next.addResourceBundle(lang, name, translationModule.default);
};
export default {
name,
async init(S) {
const svgEditor = this;
const { svgCanvas } = svgEditor;
const { getElem, $id, mergeDeep } = svgCanvas;
const { svgroot } = S;
const addElem = svgCanvas.addSVGElementFromJson;
const selManager = S.selectorManager;
await loadExtensionTranslation(svgEditor);
let startX;
let startY;
let curLine;
let startElem;
let endElem;
let seNs;
let { svgcontent } = S;
let started = false;
let connections = [];
let selElems = [];
/**
*
* @param {Float} x
* @param {Float} y
* @param {module:utilities.BBoxObject} bb
* @param {Float} offset
* @returns {module:math.XYObject}
*/
const getBBintersect = (x, y, bb, offset) => {
if (offset) {
offset -= 0;
bb = mergeDeep({}, bb);
bb.width += offset;
bb.height += offset;
bb.x -= offset / 2;
bb.y -= offset / 2;
}
const midX = bb.x + bb.width / 2;
const midY = bb.y + bb.height / 2;
const lenX = x - midX;
const lenY = y - midY;
const slope = Math.abs(lenY / lenX);
let ratio;
if (slope < bb.height / bb.width) {
ratio = (bb.width / 2) / Math.abs(lenX);
} else {
ratio = lenY
? (bb.height / 2) / Math.abs(lenY)
: 0;
}
return {
x: midX + lenX * ratio,
y: midY + lenY * ratio
};
};
/**
* @param {"start"|"end"} side
* @param {Element} line
* @returns {Float}
*/
const getOffset = (side, line) => {
const giveOffset = line.getAttribute('marker-' + side);
// TODO: Make this number (5) be based on marker width/height
const size = line.getAttribute('stroke-width') * 5;
return giveOffset ? size : 0;
};
/**
* @param {boolean} on
* @returns {void}
*/
const showPanel = (on) => {
let connRules = $id('connector_rules');
if (!connRules) {
connRules = document.createElement('style');
connRules.setAttribute('id', 'connector_rules');
document.getElementsByTagName("head")[0].appendChild(connRules);
}
connRules.textContent = (!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }');
if ($id('connector_panel'))
$id('connector_panel').style.display = (on) ? 'block' : 'none';
};
/**
* @param {Element} elem
* @param {Integer|"end"} pos
* @param {Float} x
* @param {Float} y
* @param {boolean} [setMid]
* @returns {void}
*/
const setPoint = (elem, pos, x, y, setMid) => {
const pts = elem.points;
const pt = svgroot.createSVGPoint();
pt.x = x;
pt.y = y;
if (pos === 'end') { pos = pts.numberOfItems - 1; }
// TODO: Test for this on init, then use alt only if needed
try {
pts.replaceItem(pt, pos);
} catch (err) {
// Should only occur in FF which formats points attr as "n,n n,n", so just split
const ptArr = elem.getAttribute('points').split(' ');
ptArr[pos] = x + ',' + y;
elem.setAttribute('points', ptArr.join(' '));
}
if (setMid) {
// Add center point
const ptStart = pts.getItem(0);
const ptEnd = pts.getItem(pts.numberOfItems - 1);
setPoint(elem, 1, (ptEnd.x + ptStart.x) / 2, (ptEnd.y + ptStart.y) / 2);
}
};
/**
* @param {Float} diffX
* @param {Float} diffY
* @returns {void}
*/
const updateLine = (diffX, diffY) => {
const dataStorage = svgCanvas.getDataStorage();
// Update line with element
let i = connections.length;
while (i--) {
const conn = connections[i];
const line = conn.connector;
// const {elem} = conn;
const pre = conn.is_start ? 'start' : 'end';
// const sw = line.getAttribute('stroke-width') * 5;
// Update bbox for this element
const bb = dataStorage.get(line, pre + '_bb');
bb.x = conn.start_x + diffX;
bb.y = conn.start_y + diffY;
dataStorage.put(line, pre + '_bb', bb);
const altPre = conn.is_start ? 'end' : 'start';
// Get center pt of connected element
const bb2 = dataStorage.get(line, altPre + '_bb');
const srcX = bb2.x + bb2.width / 2;
const srcY = bb2.y + bb2.height / 2;
// Set point of element being moved
const pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line));
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);
// Set point of connected element
const pt2 = getBBintersect(pt.x, pt.y, dataStorage.get(line, altPre + '_bb'), getOffset(altPre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);
}
};
/**
*
* @param {Element[]} [elems=selElems] Array of elements
* @returns {void}
*/
const findConnectors = (elems = selElems) => {
const dataStorage = svgCanvas.getDataStorage();
// const connectors = svgcontent.querySelectorAll('.se_connector');
const connectors = svgcontent.querySelectorAll('.se_connector');
connections = [];
// Loop through connectors to see if one is connected to the element
Array.prototype.forEach.call(connectors, function (ethis) {
let addThis;
// Grab the ends
const parts = [];
[ 'start', 'end' ].forEach( (pos, i) => {
const key = 'c_' + pos;
let part = dataStorage.get(ethis, key);
if (part === null || part === undefined) { // Does this ever return nullish values?
part = document.getElementById(
ethis.attributes['se:connector'].value.split(' ')[i]
);
dataStorage.put(ethis, 'c_' + pos, part.id);
dataStorage.put(ethis, pos + '_bb', svgCanvas.getStrokedBBox([ part ]));
} else part = $id(part);
parts.push(part);
}, ethis);
for (let i = 0; i < 2; i++) {
const cElem = parts[i];
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) {
if (elems.includes(el)) {
// Pretend this element is selected
addThis = true;
}
});
if (!cElem || !cElem.parentNode) {
ethis.remove();
continue;
}
if (elems.includes(cElem) || addThis) {
const bb = svgCanvas.getStrokedBBox([ cElem ]);
connections.push({
elem: cElem,
connector: ethis,
is_start: (i === 0),
start_x: bb.x,
start_y: bb.y
});
}
}
});
};
/**
* @param {Element[]} [elems=selElems]
* @returns {void}
*/
const updateConnectors = (elems) => {
const dataStorage = svgCanvas.getDataStorage();
// Updates connector lines based on selected elements
// Is not used on mousemove, as it runs getStrokedBBox every time,
// which isn't necessary there.
findConnectors(elems);
if (connections.length) {
// Update line with element
let i = connections.length;
while (i--) {
const conn = connections[i];
const line = conn.connector;
const { elem } = conn;
// const sw = line.getAttribute('stroke-width') * 5;
const pre = conn.is_start ? 'start' : 'end';
// Update bbox for this element
const bb = svgCanvas.getStrokedBBox([ elem ]);
bb.x = conn.start_x;
bb.y = conn.start_y;
dataStorage.put(line, pre + '_bb', bb);
/* const addOffset = */ dataStorage.get(line, pre + '_off');
const altPre = conn.is_start ? 'end' : 'start';
// Get center pt of connected element
const bb2 = dataStorage.get(line, altPre + '_bb');
const srcX = bb2.x + bb2.width / 2;
const srcY = bb2.y + bb2.height / 2;
// Set point of element being moved
let pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line));
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);
// Set point of connected element
const pt2 = getBBintersect(pt.x, pt.y, dataStorage.get(line, altPre + '_bb'), getOffset(altPre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);
// Update points attribute manually for webkit
if (navigator.userAgent.includes('AppleWebKit')) {
const pts = line.points;
const len = pts.numberOfItems;
const ptArr = [];
for (let j = 0; j < len; j++) {
pt = pts.getItem(j);
ptArr[j] = pt.x + ',' + pt.y;
}
line.setAttribute('points', ptArr.join(' '));
}
}
}
};
// Do once
(function () {
const gse = svgCanvas.groupSelectedElements;
svgCanvas.groupSelectedElements = function (...args) {
svgCanvas.removeFromSelection(document.querySelectorAll('.se_connector'));
return gse.apply(this, args);
};
const mse = svgCanvas.moveSelectedElements;
svgCanvas.moveSelectedElements = function (...args) {
const cmd = mse.apply(this, args);
updateConnectors();
return cmd;
};
seNs = svgCanvas.getEditorNS();
}());
/**
* Do on reset.
* @returns {void}
*/
const init = () => {
const dataStorage = svgCanvas.getDataStorage();
// Make sure all connectors have data set
const elements = svgcontent.querySelectorAll('*');
elements.forEach(function (curthis) {
const conn = curthis.getAttributeNS(seNs, 'connector');
if (conn) {
curthis.setAttribute('class', 'se_connector');
const connData = conn.split(' ');
const sbb = svgCanvas.getStrokedBBox([ getElem(connData[0]) ]);
const ebb = svgCanvas.getStrokedBBox([ getElem(connData[1]) ]);
dataStorage.put(curthis, 'c_start', connData[0]);
dataStorage.put(curthis, 'c_end', connData[1]);
dataStorage.put(curthis, 'start_bb', sbb);
dataStorage.put(curthis, 'end_bb', ebb);
svgCanvas.getEditorNS(true);
}
});
};
return {
name: svgEditor.i18next.t(`${name}:name`),
callback() {
const btitle = `${name}:langListTitle`;
// eslint-disable-next-line no-unsanitized/property
const buttonTemplate = `
<se-button id="mode_connect" title="${btitle}" src="conn.svg"></se-button>
`;
svgCanvas.insertChildAtIndex($id('tools_left'), buttonTemplate, 13);
$id('mode_connect').addEventListener("click", () => {
if (this.leftPanel.updateLeftPanel("ext-panning")) {
svgCanvas.setMode('connector');
}
});
},
/* async */ addLangData({ _lang }) { // , importLocale: importLoc
return {
data: [
{ id: 'mode_connect', title: svgEditor.i18next.t(`${name}:langListTitle`) }
]
};
},
mouseDown(opts) {
const dataStorage = svgCanvas.getDataStorage();
const e = opts.event;
startX = opts.start_x;
startY = opts.start_y;
const mode = svgCanvas.getMode();
const { curConfig: { initStroke } } = svgEditor.configObj;
if (mode === 'connector') {
if (started) { return undefined; }
const mouseTarget = e.target;
const parents = svgCanvas.getParents(mouseTarget.parentNode);
if (parents.includes(svgcontent)) {
// Connectable element
// If child of foreignObject, use parent
const fo = svgCanvas.getClosest(mouseTarget.parentNode, 'foreignObject');
startElem = fo ? fo : mouseTarget;
// Get center of source element
const bb = svgCanvas.getStrokedBBox([ startElem ]);
const x = bb.x + bb.width / 2;
const y = bb.y + bb.height / 2;
started = true;
curLine = addElem({
element: 'polyline',
attr: {
id: svgCanvas.getNextId(),
points: (x + ',' + y + ' ' + x + ',' + y + ' ' + startX + ',' + startY),
stroke: '#' + initStroke.color,
'stroke-width': (!startElem.stroke_width || startElem.stroke_width === 0)
? initStroke.width
: startElem.stroke_width,
fill: 'none',
opacity: initStroke.opacity,
style: 'pointer-events:none'
}
});
dataStorage.put(curLine, 'start_bb', bb);
}
return {
started: true
};
}
if (mode === 'select') {
findConnectors();
}
return undefined;
},
mouseMove(opts) {
const dataStorage = svgCanvas.getDataStorage();
const zoom = svgCanvas.getZoom();
// const e = opts.event;
const x = opts.mouse_x / zoom;
const y = opts.mouse_y / zoom;
const diffX = x - startX;
const diffY = y - startY;
const mode = svgCanvas.getMode();
if (mode === 'connector' && started) {
// const sw = curLine.getAttribute('stroke-width') * 3;
// Set start point (adjusts based on bb)
const pt = getBBintersect(x, y, dataStorage.get(curLine, 'start_bb'), getOffset('start', curLine));
startX = pt.x;
startY = pt.y;
setPoint(curLine, 0, pt.x, pt.y, true);
// Set end point
setPoint(curLine, 'end', x, y, true);
} else if (mode === 'select') {
let slen = selElems.length;
while (slen--) {
const elem = selElems[slen];
// Look for selected connector elements
if (elem && dataStorage.has(elem, 'c_start')) {
// Remove the "translate" transform given to move
svgCanvas.removeFromSelection([ elem ]);
elem.transform.baseVal.clear();
}
}
if (connections.length) {
updateLine(diffX, diffY);
}
}
},
mouseUp(opts) {
const dataStorage = svgCanvas.getDataStorage();
// const zoom = svgCanvas.getZoom();
const e = opts.event;
// , x = opts.mouse_x / zoom,
// , y = opts.mouse_y / zoom,
let mouseTarget = e.target;
if (svgCanvas.getMode() !== 'connector') {
return undefined;
}
const fo = svgCanvas.getClosest(mouseTarget.parentNode, 'foreignObject');
if (fo) { mouseTarget = fo; }
const parents = svgCanvas.getParents(mouseTarget.parentNode);
if (mouseTarget === startElem) {
// Start line through click
started = true;
return {
keep: true,
element: null,
started
};
}
if (parents.indexOf(svgcontent) === -1) {
// Not a valid target element, so remove line
if (curLine)
curLine.remove();
started = false;
return {
keep: false,
element: null,
started
};
}
// Valid end element
endElem = mouseTarget;
const startId = (startElem) ? startElem.id : '';
const endId = (endElem) ? endElem.id : '';
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) {
const conn = aThis.getAttributeNS(seNs, 'connector');
if (conn === connStr || conn === altStr) { return true; }
return false;
});
if (dupe.length) {
curLine.remove();
return {
keep: false,
element: null,
started: false
};
}
const bb = svgCanvas.getStrokedBBox([ endElem ]);
const pt = getBBintersect(startX, startY, bb, getOffset('start', curLine));
setPoint(curLine, 'end', pt.x, pt.y, true);
dataStorage.put(curLine, 'c_start', startId);
dataStorage.put(curLine, 'c_end', endId);
dataStorage.put(curLine, 'end_bb', bb);
seNs = svgCanvas.getEditorNS(true);
curLine.setAttributeNS(seNs, 'se:connector', connStr);
curLine.setAttribute('class', 'se_connector');
curLine.setAttribute('opacity', 1);
svgCanvas.addToSelection([ curLine ]);
svgCanvas.moveToBottomSelectedElement();
selManager.requestSelector(curLine).showGrips(false);
started = false;
return {
keep: true,
element: curLine,
started
};
},
selectedChanged(opts) {
const dataStorage = svgCanvas.getDataStorage();
// TODO: Find better way to skip operations if no connectors are in use
if (!svgcontent.querySelectorAll('.se_connector').length) { return; }
if (svgCanvas.getMode() === 'connector') {
svgCanvas.setMode('select');
}
// Use this to update the current selected elements
selElems = opts.elems;
let i = selElems.length;
while (i--) {
const elem = selElems[i];
if (elem && dataStorage.has(elem, 'c_start')) {
selManager.requestSelector(elem).showGrips(false);
if (opts.selectedElement && !opts.multiselected) {
// TODO: Set up context tools and hide most regular line tools
showPanel(true);
} else {
showPanel(false);
}
} else {
showPanel(false);
}
}
updateConnectors();
},
elementChanged(opts) {
const dataStorage = svgCanvas.getDataStorage();
let elem = opts.elems[0];
if (!elem) return;
if (elem.tagName === 'svg' && elem.id === 'svgcontent') {
// Update svgcontent (can change on import)
svgcontent = elem;
init();
}
// Has marker, so change offset
if (
elem.getAttribute('marker-start') ||
elem.getAttribute('marker-mid') ||
elem.getAttribute('marker-end')
) {
const start = elem.getAttribute('marker-start');
const mid = elem.getAttribute('marker-mid');
const end = elem.getAttribute('marker-end');
curLine = elem;
dataStorage.put(elem, 'start_off', Boolean(start));
dataStorage.put(elem, 'end_off', Boolean(end));
if (elem.tagName === 'line' && mid) {
// Convert to polyline to accept mid-arrow
const x1 = Number(elem.getAttribute('x1'));
const x2 = Number(elem.getAttribute('x2'));
const y1 = Number(elem.getAttribute('y1'));
const y2 = Number(elem.getAttribute('y2'));
const { id } = elem;
const midPt = (' ' + ((x1 + x2) / 2) + ',' + ((y1 + y2) / 2) + ' ');
const pline = addElem({
element: 'polyline',
attr: {
points: (x1 + ',' + y1 + midPt + x2 + ',' + y2),
stroke: elem.getAttribute('stroke'),
'stroke-width': elem.getAttribute('stroke-width'),
'marker-mid': mid,
fill: 'none',
opacity: elem.getAttribute('opacity') || 1
}
});
elem.insertAdjacentElement('afterend', pline);
elem.remove();
svgCanvas.clearSelection();
pline.id = id;
svgCanvas.addToSelection([ pline ]);
elem = pline;
}
}
// Update line if it's a connector
if (elem.getAttribute('class') === 'se_connector') {
const start = getElem(dataStorage.get(elem, 'c_start'));
updateConnectors([ start ]);
} else {
updateConnectors();
}
},
IDsUpdated(input) {
const remove = [];
input.elems.forEach(function (elem) {
if ('se:connector' in elem.attr) {
elem.attr['se:connector'] = elem.attr['se:connector'].split(' ')
.map(function (oldID) { return input.changes[oldID]; }).join(' ');
// Check validity - the field would be something like 'svg_21 svg_22', but
// if one end is missing, it would be 'svg_21' and therefore fail this test
if (!(/. ./).test(elem.attr['se:connector'])) {
remove.push(elem.attr.id);
}
}
});
return { remove };
},
toolButtonStateUpdate(opts) {
const button = document.getElementById('mode_connect');
if (opts.nostroke && button.pressed === true) {
svgEditor.clickSelect();
}
button.disabled = opts.nostroke;
}
};
}
};

View File

@ -1,5 +1,5 @@
/* eslint-disable max-len, no-console */ /* eslint-disable max-len, no-console */
import SvgCanvas from '../../../packages/svgcanvas/svgcanvas.js' import SvgCanvas from '../../../packages/svgcanvas'
describe('Basic Module', function () { describe('Basic Module', function () {
// helper functions // helper functions

View File

@ -1,4 +1,4 @@
import * as units from '.../../../packages/svgcanvas/core/units.js' import * as units from '../../../packages/svgcanvas/core/units.js'
describe('units', function () { describe('units', function () {
/** /**

25150
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "svgedit", "name": "svgedit",
"version": "7.3.1", "version": "7.3.2",
"description": "Powerful SVG-Editor for your browser ", "description": "Powerful SVG-Editor for your browser ",
"main": "dist/Editor.js", "main": "dist/Editor.js",
"module": "dist/Editor.js", "module": "dist/Editor.js",
@ -19,10 +19,11 @@
"scripts": { "scripts": {
"lint": "standard .", "lint": "standard .",
"test": "NODE_ENV=test start-server-and-test start http://localhost:8000/src/editor/index.html cypress:run", "test": "NODE_ENV=test start-server-and-test start http://localhost:8000/src/editor/index.html cypress:run",
"prebuild": "npm run build --workspace=packages/svgcanvas", "prebuild": "npm run build --workspace=packages/svgcanvas --workspace=packages/react-test",
"build": "rollup -c", "build": "rollup -c",
"build:watch": "rollup -c --watch", "build:watch": "rollup -c --watch",
"start": "web-dev-server --app-index src/editor/index.html --node-resolve", "start": "web-dev-server --app-index src/editor/index.html --node-resolve",
"prestart": "echo svgedit is available at http://localhost:8000/src/editor/index.html",
"start:iife": "web-dev-server --app-index dist/editor/iife-index.html --esbuild-target auto --open", "start:iife": "web-dev-server --app-index dist/editor/iife-index.html --esbuild-target auto --open",
"cypress:run": "rimraf \".nyc_output/*\" && cypress run -q --headless --browser electron && nyc report --reporter text-summary --reporter json-summary", "cypress:run": "rimraf \".nyc_output/*\" && cypress run -q --headless --browser electron && nyc report --reporter text-summary --reporter json-summary",
"cypress:open": "NODE_ENV=test start-server-and-test start http://localhost:8000/src/editor/index.html 'cypress open'", "cypress:open": "NODE_ENV=test start-server-and-test start http://localhost:8000/src/editor/index.html 'cypress open'",
@ -84,26 +85,26 @@
"dependencies": { "dependencies": {
"@svgedit/svgcanvas": "7.2.1", "@svgedit/svgcanvas": "7.2.1",
"browser-fs-access": "0.34.1", "browser-fs-access": "0.34.1",
"core-js": "3.31.1", "core-js": "3.32.1",
"elix": "15.0.1", "elix": "15.0.1",
"html2canvas": "1.4.1", "html2canvas": "1.4.1",
"i18next": "23.2.11", "i18next": "23.4.6",
"jspdf": "2.5.1", "jspdf": "2.5.1",
"pathseg": "1.2.1", "pathseg": "1.2.1",
"regenerator-runtime": "0.13.11", "regenerator-runtime": "0.14.0",
"replace-in-file": "^7.0.1", "replace-in-file": "^7.0.1",
"svg2pdf.js": "2.2.1" "svg2pdf.js": "2.2.2"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "7.22.9", "@babel/core": "7.22.11",
"@babel/preset-env": "7.22.9", "@babel/preset-env": "7.22.10",
"@babel/register": "7.22.5", "@babel/register": "7.22.5",
"@babel/runtime-corejs3": "7.22.6", "@babel/runtime-corejs3": "7.22.11",
"@cypress/code-coverage": "3.11.0", "@cypress/code-coverage": "3.11.0",
"@rollup/plugin-babel": "^6.0.3", "@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-commonjs": "^25", "@rollup/plugin-commonjs": "^25",
"@rollup/plugin-dynamic-import-vars": "2.0.4", "@rollup/plugin-dynamic-import-vars": "2.0.5",
"@rollup/plugin-node-resolve": "15.1.0", "@rollup/plugin-node-resolve": "15.2.1",
"@rollup/plugin-replace": "5.0.2", "@rollup/plugin-replace": "5.0.2",
"@rollup/plugin-url": "8.0.1", "@rollup/plugin-url": "8.0.1",
"@web/dev-server": "0.3.0", "@web/dev-server": "0.3.0",
@ -111,9 +112,9 @@
"@web/dev-server-rollup": "0.5.2", "@web/dev-server-rollup": "0.5.2",
"babel-plugin-istanbul": "^6.1.1", "babel-plugin-istanbul": "^6.1.1",
"babel-plugin-transform-object-rest-spread": "7.0.0-beta.3", "babel-plugin-transform-object-rest-spread": "7.0.0-beta.3",
"core-js-bundle": "3.31.1", "core-js-bundle": "3.32.1",
"cp-cli": "2.0.0", "cp-cli": "2.0.0",
"cypress": "12.17.2", "cypress": "12.17.4",
"cypress-multi-reporters": "1.6.3", "cypress-multi-reporters": "1.6.3",
"jamilih": "0.58.2", "jamilih": "0.58.2",
"jsdoc": "4.0.2", "jsdoc": "4.0.2",
@ -127,7 +128,7 @@
"remark-cli": "11.0.0", "remark-cli": "11.0.0",
"remark-lint-ordered-list-marker-value": "3.1.2", "remark-lint-ordered-list-marker-value": "3.1.2",
"rimraf": "5.0.1", "rimraf": "5.0.1",
"rollup": "3.26.3", "rollup": "3.28.1",
"rollup-plugin-copy": "3.4.0", "rollup-plugin-copy": "3.4.0",
"rollup-plugin-filesize": "10.0.0", "rollup-plugin-filesize": "10.0.0",
"rollup-plugin-html": "0.2.1", "rollup-plugin-html": "0.2.1",

View File

@ -6,7 +6,9 @@ import commonjs from '@rollup/plugin-commonjs'
import replace from '@rollup/plugin-replace' import replace from '@rollup/plugin-replace'
// remove existing distribution // remove existing distribution
rimraf('./dist', () => console.info('recreating dist')) // remove existing distribution
await rimraf('./dist')
console.info('recreating dist')
export default { export default {
input: 'src/index.js', input: 'src/index.js',

View File

@ -5,8 +5,8 @@
* @copyright 2011 Jeff Schiller * @copyright 2011 Jeff Schiller
*/ */
import { jsPDF as JsPDF } from 'jspdf/dist/jspdf.es.min.js' import { jsPDF as JsPDF } from 'jspdf'
import 'svg2pdf.js/dist/svg2pdf.es.js' import 'svg2pdf.js'
import html2canvas from 'html2canvas' import html2canvas from 'html2canvas'
import * as hstry from './history.js' import * as hstry from './history.js'
import { import {
@ -23,7 +23,11 @@ import {
getBBox as utilsGetBBox, getBBox as utilsGetBBox,
hashCode hashCode
} from './utilities.js' } from './utilities.js'
import { transformPoint, transformListToTransform, getTransformList } from './math.js' import {
transformPoint,
transformListToTransform,
getTransformList
} from './math.js'
import { convertUnit, shortFloat, convertToNum } from './units.js' import { convertUnit, shortFloat, convertToNum } from './units.js'
import { isGecko, isChrome, isWebkit } from '../common/browser.js' import { isGecko, isChrome, isWebkit } from '../common/browser.js'
import * as pathModule from './path.js' import * as pathModule from './path.js'
@ -90,7 +94,7 @@ const svgCanvasToString = () => {
// 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 = svgCanvas.getSvgContent().querySelectorAll('g[data-gsvg]') const gsvgElems = svgCanvas.getSvgContent().querySelectorAll('g[data-gsvg]')
Array.prototype.forEach.call(gsvgElems, (element) => { Array.prototype.forEach.call(gsvgElems, 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++) {
@ -109,7 +113,7 @@ const svgCanvasToString = () => {
// Rewrap gsvg // Rewrap gsvg
if (nakedSvgs.length) { if (nakedSvgs.length) {
Array.prototype.forEach.call(nakedSvgs, (el) => { Array.prototype.forEach.call(nakedSvgs, el => {
svgCanvas.groupSvgElem(el) svgCanvas.groupSvgElem(el)
}) })
} }
@ -162,26 +166,14 @@ const svgToString = (elem, indent) => {
// } // }
if (curConfig.dynamicOutput) { if (curConfig.dynamicOutput) {
vb = elem.getAttribute('viewBox') vb = elem.getAttribute('viewBox')
out.push( out.push(' viewBox="' + vb + '" xmlns="' + NS.SVG + '"')
' viewBox="' +
vb +
'" xmlns="' +
NS.SVG +
'"'
)
} else { } else {
if (unit !== 'px') { if (unit !== 'px') {
res.w = convertUnit(res.w, unit) + unit res.w = convertUnit(res.w, unit) + unit
res.h = convertUnit(res.h, unit) + unit res.h = convertUnit(res.h, unit) + unit
} }
out.push( out.push(
' width="' + ' width="' + res.w + '" height="' + res.h + '" xmlns="' + NS.SVG + '"'
res.w +
'" height="' +
res.h +
'" xmlns="' +
NS.SVG +
'"'
) )
} }
@ -191,7 +183,7 @@ const svgToString = (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, (el) => { Array.prototype.forEach.call(cElements, 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
@ -441,7 +433,7 @@ const setSvgString = (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, (image) => { Array.prototype.forEach.call(elements, image => {
preventClickDefault(image) preventClickDefault(image)
const val = svgCanvas.getHref(image) const val = svgCanvas.getHref(image)
if (val) { if (val) {
@ -487,7 +479,7 @@ const setSvgString = (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, (element) => { Array.prototype.forEach.call(svgElements, element => {
// Skip if it's in a <defs> // Skip if it's in a <defs>
if (getClosest(element.parentNode, 'defs')) { if (getClosest(element.parentNode, 'defs')) {
return return
@ -511,7 +503,7 @@ const setSvgString = (xmlString, preventUndo) => {
const findElems = content.querySelectorAll( const findElems = content.querySelectorAll(
'linearGradient, radialGradient, pattern' 'linearGradient, radialGradient, pattern'
) )
Array.prototype.forEach.call(findElems, (ele) => { Array.prototype.forEach.call(findElems, ele => {
svgDefs.appendChild(ele) svgDefs.appendChild(ele)
}) })
} }
@ -538,7 +530,7 @@ const setSvgString = (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((dim) => { ;['width', 'height'].forEach(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) === '%') {
@ -555,9 +547,9 @@ const setSvgString = (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, (chiElem) => { Array.prototype.forEach.call(chiElems, chiElem => {
const visElems = chiElem.querySelectorAll(svgCanvas.getVisElems()) const visElems = chiElem.querySelectorAll(svgCanvas.getVisElems())
Array.prototype.forEach.call(visElems, (elem) => { Array.prototype.forEach.call(visElems, elem => {
if (!elem.id) { if (!elem.id) {
elem.id = svgCanvas.getNextId() elem.id = svgCanvas.getNextId()
} }
@ -696,7 +688,7 @@ const importSvgString = (xmlString, preserveDimension) => {
const elements = svg.querySelectorAll( const elements = svg.querySelectorAll(
'linearGradient, radialGradient, pattern' 'linearGradient, radialGradient, pattern'
) )
Array.prototype.forEach.call(elements, (el) => { Array.prototype.forEach.call(elements, el => {
defs.appendChild(el) defs.appendChild(el)
}) })
} }
@ -766,7 +758,7 @@ const importSvgString = (xmlString, preserveDimension) => {
* @param {string} src - The path/URL of the image * @param {string} src - The path/URL of the image
* @returns {Promise<string|false>} Resolves to a Data URL (string|false) * @returns {Promise<string|false>} Resolves to a Data URL (string|false)
*/ */
const embedImage = (src) => { const embedImage = src => {
// Todo: Remove this Promise in favor of making an async/await `Image.load` utility // Todo: Remove this Promise in favor of making an async/await `Image.load` utility
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// load in the image and once it's loaded, get the dimensions // load in the image and once it's loaded, get the dimensions
@ -1011,7 +1003,7 @@ const exportPDF = async (
* @param {Element} g - The parent element of the tree to give unique IDs * @param {Element} g - The parent element of the tree to give unique IDs
* @returns {void} * @returns {void}
*/ */
const uniquifyElemsMethod = (g) => { const uniquifyElemsMethod = g => {
const ids = {} const ids = {}
// TODO: Handle markers and connectors. These are not yet re-identified properly // TODO: Handle markers and connectors. These are not yet re-identified properly
// as their referring elements do not get remapped. // as their referring elements do not get remapped.
@ -1031,7 +1023,7 @@ const uniquifyElemsMethod = (g) => {
'use' 'use'
] ]
walkTree(g, (n) => { walkTree(g, n => {
// if it's an element node // if it's an element node
if (n.nodeType === 1) { if (n.nodeType === 1) {
// and the element has an ID // and the element has an ID
@ -1046,7 +1038,7 @@ const uniquifyElemsMethod = (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
svgCanvas.getrefAttrs().forEach((attr) => { svgCanvas.getrefAttrs().forEach(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 #
@ -1115,7 +1107,7 @@ const uniquifyElemsMethod = (g) => {
* @param {Element} parent * @param {Element} parent
* @returns {void} * @returns {void}
*/ */
const setUseDataMethod = (parent) => { const setUseDataMethod = parent => {
let elems = parent let elems = parent
if (parent.tagName !== 'use') { if (parent.tagName !== 'use') {
@ -1210,17 +1202,15 @@ const removeUnusedDefElemsMethod = () => {
* @param {Element} elem * @param {Element} elem
* @returns {void} * @returns {void}
*/ */
const convertGradientsMethod = (elem) => { const convertGradientsMethod = 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('*'), ( elems = Array.prototype.filter.call(elem.querySelectorAll('*'), curThis => {
curThis
) => {
return curThis.tagName.includes('Gradient') return curThis.tagName.includes('Gradient')
}) })
} }
Array.prototype.forEach.call(elems, (grad) => { Array.prototype.forEach.call(elems, grad => {
if (grad.getAttribute('gradientUnits') === 'userSpaceOnUse') { if (grad.getAttribute('gradientUnits') === 'userSpaceOnUse') {
const svgContent = svgCanvas.getSvgContent() const svgContent = svgCanvas.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

@ -173,7 +173,7 @@ export default class ConfigObj {
* @type {string[]} * @type {string[]}
*/ */
this.defaultExtensions = [ this.defaultExtensions = [
// 'ext-connector', 'ext-connector',
'ext-eyedropper', 'ext-eyedropper',
'ext-grid', 'ext-grid',
// 'ext-imagelib', // 'ext-imagelib',

View File

@ -0,0 +1,733 @@
/**
* @file ext-connector.js
*
* @license MIT
*
* @copyright 2010 Alexis Deveria
* @copyright 2023 Optimistik SAS
*
*/
const name = 'connector'
const loadExtensionTranslation = async function (svgEditor) {
let translationModule
const lang = svgEditor.configObj.pref('lang')
try {
translationModule = await import(`./locale/${lang}.js`)
} catch (_error) {
// eslint-disable-next-line no-console
console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
translationModule = await import('./locale/en.js')
}
svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}
export default {
name,
async init (S) {
const svgEditor = this
const { svgCanvas } = svgEditor
const { getElement, $id, $click, addSVGElementsFromJson } = svgCanvas
const { svgroot, selectorManager } = S
const seNs = svgCanvas.getEditorNS()
await loadExtensionTranslation(svgEditor)
let startX
let startY
let curLine
let startElem
let endElem
let started = false
let connections = []
// Save the original groupSelectedElements method
const originalGroupSelectedElements = svgCanvas.groupSelectedElements
// Override the original groupSelectedElements to exclude connectors
svgCanvas.groupSelectedElements = function (...args) {
// Remove connectors from selection
svgCanvas.removeFromSelection(document.querySelectorAll('[id^="conn_"]'))
// Call the original method
return originalGroupSelectedElements.apply(this, args)
}
// Save the original moveSelectedElements method
const originalMoveSelectedElements = svgCanvas.moveSelectedElements
// Override the original moveSelectedElements to handle connectors
svgCanvas.moveSelectedElements = function (...args) {
// Call the original method and store its result
const cmd = originalMoveSelectedElements.apply(this, args)
// Update connectors
updateConnectors(svgCanvas.getSelectedElements())
// Return the result of the original method
return cmd
}
/**
* getBBintersect
* @param {Float} x
* @param {Float} y
* @param {module:utilities.BBoxObject} bb
* @param {Float} offset
* @returns {module:math.XYObject}
*/
const getBBintersect = (x, y, bb, offset) => {
// Adjust bounding box if offset is provided
if (offset) {
bb = { ...bb } // Create a shallow copy
bb.width += offset
bb.height += offset
bb.x -= offset / 2
bb.y -= offset / 2
}
// Calculate center of bounding box
const midX = bb.x + bb.width / 2
const midY = bb.y + bb.height / 2
// Calculate lengths from (x, y) to center
const lenX = x - midX
const lenY = y - midY
// Calculate slope of line from (x, y) to center
const slope = Math.abs(lenY / lenX)
// Calculate ratio to find intersection point
let ratio
if (slope < bb.height / bb.width) {
ratio = bb.width / 2 / Math.abs(lenX)
} else {
ratio = lenY ? bb.height / 2 / Math.abs(lenY) : 0
}
// Calculate intersection point
return {
x: midX + lenX * ratio,
y: midY + lenY * ratio
}
}
/**
* getOffset
* @param {"start"|"end"} side - The side of the line ("start" or "end") where the marker may be present.
* @param {Element} line - The line element to check for a marker.
* @returns {Float} - Returns the calculated offset if a marker is present, otherwise returns 0.
*/
const getOffset = (side, line) => {
// Check for marker attribute on the given side ("marker-start" or "marker-end")
const hasMarker = line.getAttribute('marker-' + side)
// Calculate size based on stroke-width, multiplied by a constant factor (here, 5)
// TODO: This factor should ideally be based on the actual size of the marker.
const size = line.getAttribute('stroke-width') * 5
// Return calculated size if marker is present, otherwise return 0.
return hasMarker ? size : 0
}
/**
* showPanel
* @param {boolean} on - Determines whether to show or hide the elements.
* @returns {void}
*/
const showPanel = on => {
// Find the 'connector_rules' or create it if it doesn't exist.
let connRules = $id('connector_rules')
if (!connRules) {
connRules = document.createElement('style')
connRules.setAttribute('id', 'connector_rules')
document.getElementsByTagName('head')[0].appendChild(connRules)
}
// Update the content of <style> element to either hide or show certain elements.
connRules.textContent = !on
? ''
: '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }'
// Update the display property of the <style> element itself based on the 'on' value.
if ($id('connector_rules')) {
$id('connector_rules').style.display = on ? 'block' : 'none'
}
}
/**
* setPoint
* @param {Element} elem - The SVG element.
* @param {Integer|"end"} pos - The position index or "end".
* @param {Float} x - The x-coordinate.
* @param {Float} y - The y-coordinate.
* @param {boolean} [setMid] - Whether to set the midpoint.
* @returns {void}
*/
const setPoint = (elem, pos, x, y, setMid) => {
// Create a new SVG point
const pts = elem.points
const pt = svgroot.createSVGPoint()
pt.x = x
pt.y = y
// If position is "end", set it to the last index
if (pos === 'end') {
pos = pts.numberOfItems - 1
}
// Try replacing the point at the specified position
pts.replaceItem(pt, pos)
// Optionally, set the midpoint
if (setMid) {
const ptStart = pts.getItem(0)
const ptEnd = pts.getItem(pts.numberOfItems - 1)
setPoint(elem, 1, (ptEnd.x + ptStart.x) / 2, (ptEnd.y + ptStart.y) / 2)
}
}
/**
* @param {Float} diffX
* @param {Float} diffY
* @returns {void}
*/
const updatePoints = (line, conn, bb, altBB, pre, altPre) => {
const srcX = altBB.x + altBB.width / 2
const srcY = altBB.y + altBB.height / 2
const pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line))
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true)
const pt2 = getBBintersect(pt.x, pt.y, altBB, getOffset(altPre, line))
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true)
}
const updateLine = (diffX, diffY) => {
const dataStorage = svgCanvas.getDataStorage()
for (const conn of connections) {
const {
connector: line,
is_start: isStart,
start_x: startX,
start_y: startY
} = conn
const pre = isStart ? 'start' : 'end'
const altPre = isStart ? 'end' : 'start'
// Update bbox for this element
const bb = { ...dataStorage.get(line, `${pre}_bb`) }
bb.x = startX + diffX
bb.y = startY + diffY
dataStorage.put(line, `${pre}_bb`, bb)
// Get center point of connected element
const altBB = dataStorage.get(line, `${altPre}_bb`)
updatePoints(line, conn, bb, altBB, pre, altPre)
}
}
// Finds connectors associated with selected elements
const findConnectors = (elems = []) => {
// Fetch data storage object from svgCanvas
const dataStorage = svgCanvas.getDataStorage()
// Query all connector elements (id startss with conn_)
const connectors = document.querySelectorAll('[id^="conn_"]')
// Reset connections array
connections = []
// Loop through each connector
for (const connector of connectors) {
let addThis = false // Flag to indicate whether to add this connector
const parts = [] // To hold the starting and ending elements connected by the connector
// Loop through the connector ends ("start" and "end")
for (const [i, pos] of ['start', 'end'].entries()) {
// Fetch connected element and its bounding box
let part = dataStorage.get(connector, `c_${pos}`)
// If part is null or undefined, fetch it and store it
if (!part) {
part = document.getElementById(
connector.attributes['se:connector'].value.split(' ')[i]
)
dataStorage.put(connector, `c_${pos}`, part.id)
dataStorage.put(
connector,
`${pos}_bb`,
svgCanvas.getStrokedBBox([part])
)
} else {
// If part is already stored, fetch it by ID
part = document.getElementById(part)
}
// Add the part to the parts array
parts.push(part)
}
// Loop through the starting and ending elements connected by the connector
for (let i = 0; i < 2; i++) {
const cElem = parts[i]
const parents = svgCanvas.getParents(cElem?.parentNode)
// Check if the element is part of a selected group
for (const el of parents) {
if (elems.includes(el)) {
addThis = true
break
}
}
// If element is missing or parent is null, remove the connector
if (!cElem || !cElem.parentNode) {
connector.remove()
continue
}
// If element is in the selection or part of a selected group
if (elems.includes(cElem) || addThis) {
const bb = svgCanvas.getStrokedBBox([cElem])
// Add connection information to the connections array
connections.push({
elem: cElem,
connector,
is_start: i === 0,
start_x: bb.x,
start_y: bb.y
})
}
}
}
}
/**
* Updates the connectors based on selected elements.
* @param {Element[]} [elems] - Optional array of selected elements.
* @returns {void}
*/
const updateConnectors = elems => {
const dataStorage = svgCanvas.getDataStorage()
// Find connectors associated with selected elements
findConnectors(elems)
if (connections.length) {
// Iterate through each connection to update its state
for (const conn of connections) {
const {
elem,
connector: line,
is_start: isStart,
start_x: startX,
start_y: startY
} = conn
// Determine whether the connection starts or ends with this element
const pre = isStart ? 'start' : 'end'
// Update the bounding box for this element
const bb = svgCanvas.getStrokedBBox([elem])
bb.x = startX
bb.y = startY
dataStorage.put(line, `${pre}_bb`, bb)
// Determine the opposite end ('start' or 'end') of the connection
const altPre = isStart ? 'end' : 'start'
// Retrieve the bounding box for the connected element at the opposite end
const bb2 = dataStorage.get(line, `${altPre}_bb`)
// Calculate the center point of the connected element
const srcX = bb2?.x + bb2?.width / 2
const srcY = bb2?.y + bb2?.height / 2
// Update the point of the element being moved
const pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line))
setPoint(line, isStart ? 0 : 'end', pt.x, pt.y, true)
// Update the point of the connected element at the opposite end
const pt2 = getBBintersect(
pt.x,
pt.y,
dataStorage.get(line, `${altPre}_bb`),
getOffset(altPre, line)
)
setPoint(line, isStart ? 'end' : 0, pt2.x, pt2.y, true)
}
}
}
/**
* Do on reset.
* @returns {void}
*/
const reset = () => {
const dataStorage = svgCanvas.getDataStorage()
// Make sure all connectors have data set
const svgContent = svgCanvas.getSvgContent()
const elements = svgContent.querySelectorAll('*')
elements.forEach(element => {
const conn = element.getAttributeNS(seNs, 'connector')
if (conn) {
const connData = conn.split(' ')
const sbb = svgCanvas.getStrokedBBox([getElement(connData[0])])
const ebb = svgCanvas.getStrokedBBox([getElement(connData[1])])
dataStorage.put(element, 'c_start', connData[0])
dataStorage.put(element, 'c_end', connData[1])
dataStorage.put(element, 'start_bb', sbb)
dataStorage.put(element, 'end_bb', ebb)
svgCanvas.getEditorNS(true)
}
})
}
reset()
return {
name: svgEditor.i18next.t(`${name}:name`),
callback () {
// Add the button and its handler(s)
const buttonTemplate = document.createElement('template')
const title = `${name}:buttons.0.title`
buttonTemplate.innerHTML = `
<se-button id="tool_connect" title="${title}" src="conn.svg"></se-button>
`
$id('tools_left').append(buttonTemplate.content.cloneNode(true))
$click($id('tool_connect'), () => {
if (this.leftPanel.updateLeftPanel('tool_connect')) {
svgCanvas.setMode('connector')
}
})
},
mouseDown (opts) {
// Retrieve necessary data from the SVG canvas and the event object
const dataStorage = svgCanvas.getDataStorage()
const svgContent = svgCanvas.getSvgContent()
const { event: e, start_x: startX, start_y: startY } = opts
const mode = svgCanvas.getMode()
const {
curConfig: { initStroke }
} = svgEditor.configObj
if (mode === 'connector') {
// Return if the line is already started
if (started) return undefined
const mouseTarget = e.target
const parents = svgCanvas.getParents(mouseTarget.parentNode)
// Check if the target is a child of the main SVG content
if (parents.includes(svgContent)) {
// Identify the connectable element, considering foreignObject elements
const fo = svgCanvas.getClosest(
mouseTarget.parentNode,
'foreignObject'
)
startElem = fo || mouseTarget
// Retrieve the bounding box and calculate the center of the start element
const bb = svgCanvas.getStrokedBBox([startElem])
const x = bb.x + bb.width / 2
const y = bb.y + bb.height / 2
// Set the flag to indicate the line has started
started = true
// Create a new polyline element
curLine = addSVGElementsFromJson({
element: 'polyline',
attr: {
id: 'conn_' + svgCanvas.getNextId(),
points: `${x},${y} ${x},${y} ${startX},${startY}`,
stroke: `#${initStroke.color}`,
'stroke-width':
!startElem.stroke_width || startElem.stroke_width === 0
? initStroke.width
: startElem.stroke_width,
fill: 'none',
opacity: initStroke.opacity,
style: 'pointer-events:none'
}
})
// Store the bounding box of the start element
dataStorage.put(curLine, 'start_bb', bb)
}
return {
started: true
}
}
if (mode === 'select') {
// Find connectors if the mode is 'select'
findConnectors(opts.selectedElements)
}
return undefined
},
mouseMove (opts) {
// Exit early if there are no connectors
if (connections.length === 0) return
const dataStorage = svgCanvas.getDataStorage()
const zoom = svgCanvas.getZoom()
// const e = opts.event;
const x = opts.mouse_x / zoom
const y = opts.mouse_y / zoom
/** @todo We have a concern if startX or startY are undefined */
if (!startX || !startY) return
const diffX = x - startX
const diffY = y - startY
const mode = svgCanvas.getMode()
if (mode === 'connector' && started) {
// const sw = curLine.getAttribute('stroke-width') * 3;
// Set start point (adjusts based on bb)
const pt = getBBintersect(
x,
y,
dataStorage.get(curLine, 'start_bb'),
getOffset('start', curLine)
)
startX = pt.x
startY = pt.y
setPoint(curLine, 0, pt.x, pt.y, true)
// Set end point
setPoint(curLine, 'end', x, y, true)
} else if (mode === 'select') {
for (const elem of svgCanvas.getSelectedElements()) {
if (elem && dataStorage.has(elem, 'c_start')) {
svgCanvas.removeFromSelection([elem])
elem.transform.baseVal.clear()
}
}
if (connections.length) {
updateLine(diffX, diffY)
}
}
},
mouseUp (opts) {
// Get necessary data and initial setups
const dataStorage = svgCanvas.getDataStorage()
const svgContent = svgCanvas.getSvgContent()
const { event: e } = opts
let mouseTarget = e.target
// Early exit if not in connector mode
if (svgCanvas.getMode() !== 'connector') return undefined
// Check for a foreignObject parent and update mouseTarget if found
const fo = svgCanvas.getClosest(mouseTarget.parentNode, 'foreignObject')
if (fo) mouseTarget = fo
// Check if the target is a child of the main SVG content
const parents = svgCanvas.getParents(mouseTarget.parentNode)
const isInSvgContent = parents.includes(svgContent)
if (mouseTarget === startElem) {
// Case: Started drawing line via click
started = true
return {
keep: true,
element: null,
started
}
}
if (!isInSvgContent) {
// Case: Invalid target element; remove the line
curLine?.remove()
started = false
return {
keep: false,
element: null,
started
}
}
// Valid target element for the end of the line
endElem = mouseTarget
const startId = startElem?.id || ''
const endId = endElem?.id || ''
const connStr = `${startId} ${endId}`
const altStr = `${endId} ${startId}`
// Prevent duplicate connectors
const dupe = Array.from(
document.querySelectorAll('[id^="conn_"]')
).filter(
conn =>
conn.getAttributeNS(seNs, 'connector') === connStr ||
conn.getAttributeNS(seNs, 'connector') === altStr
)
if (dupe.length) {
curLine.remove()
return {
keep: false,
element: null,
started: false
}
}
// Update the end point of the connector
const bb = svgCanvas.getStrokedBBox([endElem])
const pt = getBBintersect(
startX,
startY,
bb,
getOffset('start', curLine)
)
setPoint(curLine, 'end', pt.x, pt.y, true)
// Save metadata to the connector
dataStorage.put(curLine, 'c_start', startId)
dataStorage.put(curLine, 'c_end', endId)
dataStorage.put(curLine, 'end_bb', bb)
curLine.setAttributeNS(seNs, 'se:connector', connStr)
curLine.setAttribute('opacity', 1)
// Finalize the connector
svgCanvas.addToSelection([curLine])
svgCanvas.moveToBottomSelectedElement()
selectorManager.requestSelector(curLine).showGrips(false)
started = false
return {
keep: true,
element: curLine,
started
}
},
selectedChanged (opts) {
// Get necessary data storage and SVG content
const dataStorage = svgCanvas.getDataStorage()
const svgContent = svgCanvas.getSvgContent()
// Exit early if there are no connectors
if (!svgContent.querySelectorAll('[id^="conn_"]').length) return
// If the current mode is 'connector', switch to 'select'
if (svgCanvas.getMode() === 'connector') {
svgCanvas.setMode('select')
}
// Get currently selected elements
const { elems: selElems } = opts
// Iterate through selected elements
for (const elem of selElems) {
// If the element has a connector start, handle it
if (elem && dataStorage.has(elem, 'c_start')) {
selectorManager.requestSelector(elem).showGrips(false)
// Show panel depending on selection state
showPanel(opts.selectedElement && !opts.multiselected)
} else {
// Hide panel if no connector start
showPanel(false)
}
}
// Update connectors based on selected elements
updateConnectors(svgCanvas.getSelectedElements())
},
elementChanged (opts) {
// Get the necessary data storage
const dataStorage = svgCanvas.getDataStorage()
// Get the first element from the options; exit early if it's null
let [elem] = opts.elems
if (!elem) return
// Reinitialize if it's the main SVG content
if (elem.tagName === 'svg' && elem.id === 'svgcontent') {
reset()
}
// Check for marker attributes and update offsets
const { markerStart, markerMid, markerEnd } = elem.attributes
if (markerStart || markerMid || markerEnd) {
curLine = elem
dataStorage.put(elem, 'start_off', Boolean(markerStart))
dataStorage.put(elem, 'end_off', Boolean(markerEnd))
// Convert lines to polyline if there's a mid-marker
if (elem.tagName === 'line' && markerMid) {
const { x1, x2, y1, y2, id } = elem.attributes
const midPt = `${(Number(x1.value) + Number(x2.value)) / 2},${
(Number(y1.value) + Number(y2.value)) / 2
}`
const pline = addSVGElementsFromJson({
element: 'polyline',
attr: {
points: `${x1.value},${y1.value} ${midPt} ${x2.value},${y2.value}`,
stroke: elem.getAttribute('stroke'),
'stroke-width': elem.getAttribute('stroke-width'),
'marker-mid': markerMid.value,
fill: 'none',
opacity: elem.getAttribute('opacity') || 1
}
})
elem.insertAdjacentElement('afterend', pline)
elem.remove()
svgCanvas.clearSelection()
pline.id = id.value
svgCanvas.addToSelection([pline])
elem = pline
}
}
// Update connectors based on the current element
if (elem?.id.startsWith('conn_')) {
const start = getElement(dataStorage.get(elem, 'c_start'))
updateConnectors([start])
} else {
updateConnectors(svgCanvas.getSelectedElements())
}
},
IDsUpdated (input) {
const remove = []
input.elems.forEach(function (elem) {
if ('se:connector' in elem.attr) {
elem.attr['se:connector'] = elem.attr['se:connector']
.split(' ')
.map(function (oldID) {
return input.changes[oldID]
})
.join(' ')
// Check validity - the field would be something like 'svg_21 svg_22', but
// if one end is missing, it would be 'svg_21' and therefore fail this test
if (!/. ./.test(elem.attr['se:connector'])) {
remove.push(elem.attr.id)
}
}
})
return { remove }
},
toolButtonStateUpdate (opts) {
const button = document.getElementById('tool_connect')
if (opts.nostroke && button.pressed === true) {
svgEditor.clickSelect()
}
button.disabled = opts.nostroke
}
}
}
}

View File

@ -9,4 +9,4 @@ export default {
title: 'Connect two objects' title: 'Connect two objects'
} }
] ]
}; }

View File

@ -1,5 +1,5 @@
export default { export default {
name: 'Connector', name: 'Connecteur',
langListTitle: 'Connecter deux objets', langListTitle: 'Connecter deux objets',
langList: [ langList: [
{ id: 'mode_connect', title: 'Connecter deux objets' } { id: 'mode_connect', title: 'Connecter deux objets' }
@ -9,4 +9,4 @@ export default {
title: 'Connecter deux objets' title: 'Connecter deux objets'
} }
] ]
}; }

View File

@ -9,4 +9,4 @@ export default {
title: '连接两个对象' title: '连接两个对象'
} }
] ]
}; }