move untested components to Archive

This commit is contained in:
JFH
2021-08-04 11:23:05 +02:00
parent f73f6779c3
commit ee6bda3c5c
12 changed files with 4 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
The file below are working with V6 but were not tested with V7
Please open an issue to make them back into the main project.

View File

@@ -0,0 +1,131 @@
/**
* Attaches items to DOM for Embedded SVG support.
* @module EmbeddedSVGEditDOM
*/
import EmbeddedSVGEdit from './embedapi.js';
import { isChrome } from '../common/browser.js';
let svgCanvas = null;
/**
* @param {string} data
* @param {string} error
* @returns {void}
*/
function handleSvgData (data, error) {
if (error) {
// Todo: This should be replaced with a general purpose dialog alert library call
alert('error ' + error);
} else {
// Todo: This should be replaced with a general purpose dialog alert library call
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
}
}
/**
* Set the canvas with an example SVG string.
* @returns {void}
*/
function loadSvg () {
const svgexample = '<svg width="640" height="480" xmlns:xlink="' +
'http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">' +
'<g><title>Layer 1</title><rect stroke-width="5" stroke="#000000" ' +
'fill="#FF0000" id="svg_1" height="35" width="51" y="35" x="32"/>' +
'<ellipse ry="15" rx="24" stroke-width="5" stroke="#000000" ' +
'fill="#0000ff" id="svg_2" cy="60" cx="66"/></g></svg>';
svgCanvas.setSvgString(svgexample);
}
/**
*
* @returns {void}
*/
function saveSvg () {
svgCanvas.getSvgString()(handleSvgData);
}
/**
* Perform a PNG export.
* @returns {void}
*/
function exportPNG () {
svgCanvas.getUIStrings()(function (uiStrings) {
const str = uiStrings.notification.loadingImage;
let exportWindow;
if (!isChrome()) {
exportWindow = window.open(
'data:text/html;charset=utf-8,' + encodeURIComponent('<title>' + str + '</title><h1>' + str + '</h1>'),
'svg-edit-exportWindow'
);
}
svgCanvas.rasterExport('PNG', null, exportWindow && exportWindow.name)();
});
}
/**
* Perform a PDF export.
* @returns {void}
*/
function exportPDF () {
svgCanvas.getUIStrings()(function (uiStrings) {
const str = uiStrings.notification.loadingImage;
/*
// If you want to handle the PDF blob yourself, do as follows
svgCanvas.bind('exportedPDF', function (win, data) {
alert(data.output);
});
svgCanvas.exportPDF(); // Accepts two args: optionalWindowName supplied back to bound exportPDF handler and optional outputType (defaults to dataurlstring)
return;
*/
if (isChrome()) {
// Chrome will open an extra window if we follow the approach below
svgCanvas.exportPDF();
} else {
const exportWindow = window.open(
'data:text/html;charset=utf-8,' + encodeURIComponent('<title>' + str + '</title><h1>' + str + '</h1>'),
'svg-edit-exportWindow'
);
svgCanvas.exportPDF(exportWindow && exportWindow.name);
}
});
}
const frameBase = 'https://raw.githack.com/SVG-Edit/svgedit/master';
// const frameBase = 'http://localhost:8001';
const framePath = '/editor/xdomain-svg-editor-es.html?extensions=ext-xdomain-messaging.js';
const iframe = document.createElement('iframe');
iframe.id = "svgedit";
iframe.style.width = "900px";
iframe.style.width = "600px";
iframe.src = frameBase + framePath +
(location.href.includes('?')
// ? location.href.replace(/\?(?<search>.*)$/, '&$<search>')
? location.href.replace(/\?(.*)$/, '&$1')
: ''); // Append arguments to this file onto the iframe
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 {
doc = frame.contentDocument || frame.contentWindow.document;
} catch (err) {
console.error('Blocked from accessing document', err);
}
if (doc) {
// Todo: Provide a way to get this to occur by `postMessage`
const mainButton = doc.getElementById('main_button');
mainButton.style.display = 'none';
}
// Add event handlers now that `svgCanvas` is ready
$id('load').addEventListener('click', loadSvg);
$id('save').addEventListener('click', saveSvg);
$id('exportPNG').addEventListener('click', exportPNG);
$id('exportPDF').addEventListener('click', exportPDF);
});
document.body.appendChild(iframe);
const frame = document.getElementById('svgedit');

View File

@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Embed API</title>
<link rel="icon" type="image/png" href="images/logo.svg"/>
<script src="jquery.min.js"></script>
<script type="module" src="embedapi-dom.js"></script>
</head>
<body>
<button id="load">Load example</button>
<button id="save">Save data</button>
<button id="exportPNG">Export data to PNG</button>
<button id="exportPDF">Export data to PDF</button>
<br/>
</body>
</html>

View File

@@ -0,0 +1,395 @@
/**
* Handles underlying communication between the embedding window and the
* editor frame.
* @module EmbeddedSVGEdit
*/
let cbid = 0;
/**
* @callback module:EmbeddedSVGEdit.CallbackSetter
* @param {GenericCallback} newCallback Callback to be stored (signature dependent on function)
* @returns {void}
*/
/**
* @callback module:EmbeddedSVGEdit.CallbackSetGetter
* @param {...any} args Signature dependent on the function
* @returns {module:EmbeddedSVGEdit.CallbackSetter}
*/
/**
* @param {string} funcName
* @returns {module:EmbeddedSVGEdit.CallbackSetGetter}
*/
function getCallbackSetter (funcName) {
return function (...args) {
const that = this; // New callback
const callbackID = this.send(funcName, args, function () { /* empty fn */ }); // The callback (currently it's nothing, but will be set later)
return function (newCallback) {
that.callbacks[callbackID] = newCallback; // Set callback
};
};
}
/**
* Having this separate from messageListener allows us to
* avoid using JSON parsing (and its limitations) in the case
* of same domain control.
* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value
* @param {PlainObject} data
* @param {JSON} data.result
* @param {string} data.error
* @param {Integer} data.id
* @returns {void}
*/
function addCallback (t, { result, error, id: callbackID }) {
if (typeof callbackID === 'number' && t.callbacks[callbackID]) {
// These should be safe both because we check `cbid` is numeric and
// because the calls are from trusted origins
if (result) {
t.callbacks[callbackID](result); // lgtm [js/unvalidated-dynamic-method-call]
} else {
t.callbacks[callbackID](error, 'error'); // lgtm [js/unvalidated-dynamic-method-call]
}
}
}
/**
* @param {Event} e
* @returns {void}
*/
function messageListener (e) {
// We accept and post strings as opposed to objects for the sake of IE9 support; this
// will most likely be changed in the future
if (!e.data || ![ 'string', 'object' ].includes(typeof e.data)) {
return;
}
const { allowedOrigins } = this;
const data = typeof e.data === 'object' ? e.data : JSON.parse(e.data);
if (!data || typeof data !== 'object' || data.namespace !== 'svg-edit' ||
e.source !== this.frame.contentWindow ||
(!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin))
) {
console.error(
`The origin ${e.origin} was not whitelisted as an origin from ` +
`which responses may be received by this ${window.origin} script.`
);
return;
}
addCallback(this, data);
}
/**
* @callback module:EmbeddedSVGEdit.MessageListener
* @param {MessageEvent} e
* @returns {void}
*/
/**
* @param {module:EmbeddedSVGEdit.EmbeddedSVGEdit} t The `this` value
* @returns {module:EmbeddedSVGEdit.MessageListener} Event listener
*/
function getMessageListener (t) {
return function (e) {
messageListener.call(t, e);
};
}
/**
* Embedded SVG-edit API.
* General usage:
* - Have an iframe somewhere pointing to a version of svg-edit > r1000.
* @example
// Initialize the magic with:
const svgCanvas = new EmbeddedSVGEdit(window.frames.svgedit);
// Pass functions in this format:
svgCanvas.setSvgString('string');
// Or if a callback is needed:
svgCanvas.setSvgString('string')(function (data, error) {
if (error) {
// There was an error
throw error
} else {
// Handle data
}
});
// Everything is done with the same API as the real svg-edit,
// and all documentation is unchanged.
// However, this file depends on the postMessage API which
// can only support JSON-serializable arguments and
// return values, so, for example, arguments whose value is
// 'undefined', a function, a non-finite number, or a built-in
// object like Date(), RegExp(), etc. will most likely not behave
// as expected. In such a case one may need to host
// the SVG editor on the same domain and reference the
// JavaScript methods on the frame itself.
// The only other difference is when handling returns:
// the callback notation is used instead.
const blah = new EmbeddedSVGEdit(window.frames.svgedit);
blah.clearSelection('woot', 'blah', 1337, [1, 2, 3, 4, 5, 'moo'], -42, {
a: 'tree', b: 6, c: 9
})(function () { console.log('GET DATA', args); });
*
* @memberof module:EmbeddedSVGEdit
*/
class EmbeddedSVGEdit {
/**
* @param {HTMLIFrameElement} frame
* @param {string[]} [allowedOrigins=[]] Array of origins from which incoming
* messages will be allowed when same origin is not used; defaults to none.
* If supplied, it should probably be the same as svgEditor's allowedOrigins
*/
constructor (frame, allowedOrigins) {
const that = this;
this.allowedOrigins = allowedOrigins || [];
// Initialize communication
this.frame = frame;
this.callbacks = {};
// List of functions extracted with this:
// Run in firebug on http://svg-edit.googlecode.com/svn/trunk/docs/files/svgcanvas-js.html
// for (const i=0,q=[],f = document.querySelectorAll('div.CFunction h3.CTitle a'); i < f.length; i++) { q.push(f[i].name); }; q
// const functions = ['clearSelection', 'addToSelection', 'removeFromSelection', 'open', 'save', 'getSvgString', 'setSvgString',
// 'createLayer', 'deleteCurrentLayer', 'setCurrentLayer', 'renameCurrentLayer', 'setCurrentLayerPosition', 'setLayerVisibility',
// 'moveSelectedToLayer', 'clear'];
// Newer, well, it extracts things that aren't documented as well. All functions accessible through the normal thingy can now be accessed though the API
// const {svgCanvas} = frame.contentWindow;
// const l = [];
// for (const i in svgCanvas) { if (typeof svgCanvas[i] === 'function') { l.push(i);} };
// alert("['" + l.join("', '") + "']");
// Run in svgedit itself
const functions = [
'addExtension',
'addSVGElementFromJson',
'addToSelection',
'alignSelectedElements',
'assignAttributes',
'bind',
'call',
'changeSelectedAttribute',
'cleanupElement',
'clear',
'clearSelection',
'clearSvgContentElement',
'cloneLayer',
'cloneSelectedElements',
'convertGradients',
'convertToGroup',
'convertToNum',
'convertToPath',
'copySelectedElements',
'createLayer',
'cutSelectedElements',
'cycleElement',
'deleteCurrentLayer',
'deleteSelectedElements',
'embedImage',
'exportPDF',
'findDefs',
'getBBox',
'getBlur',
'getBold',
'getColor',
'getContentElem',
'getCurrentDrawing',
'getDocumentTitle',
'getEditorNS',
'getElem',
'getFillOpacity',
'getFontColor',
'getFontFamily',
'getFontSize',
'getHref',
'getId',
'getIntersectionList',
'getItalic',
'getMode',
'getMouseTarget',
'getNextId',
'getOffset',
'getOpacity',
'getPaintOpacity',
'getPrivateMethods',
'getRefElem',
'getResolution',
'getRootElem',
'getRotationAngle',
'getSelectedElems',
'getStrokeOpacity',
'getStrokeWidth',
'getStrokedBBox',
'getStyle',
'getSvgString',
'getText',
'getTitle',
'getTransformList',
'getUIStrings',
'getUrlFromAttr',
'getVersion',
'getVisibleElements',
'getVisibleElementsAndBBoxes',
'getZoom',
'groupSelectedElements',
'groupSvgElem',
'hasMatrixTransform',
'identifyLayers',
'importSvgString',
'leaveContext',
'linkControlPoints',
'makeHyperlink',
'matrixMultiply',
'mergeAllLayers',
'mergeLayer',
'moveSelectedElements',
'moveSelectedToLayer',
'moveToBottomSelectedElement',
'moveToTopSelectedElement',
'moveUpDownSelected',
'open',
'pasteElements',
'prepareSvg',
'pushGroupProperties',
'randomizeIds',
'rasterExport',
'ready',
'recalculateAllSelectedDimensions',
'recalculateDimensions',
'remapElement',
'removeFromSelection',
'removeHyperlink',
'removeUnusedDefElems',
'renameCurrentLayer',
'round',
'runExtensions',
'sanitizeSvg',
'save',
'selectAllInCurrentLayer',
'selectOnly',
'setBBoxZoom',
'setBackground',
'setBlur',
'setBlurNoUndo',
'setBlurOffsets',
'setBold',
'setColor',
'setConfig',
'setContext',
'setCurrentLayer',
'setCurrentLayerPosition',
'setDocumentTitle',
'setFillPaint',
'setFontColor',
'setFontFamily',
'setFontSize',
'setGoodImage',
'setGradient',
'setGroupTitle',
'setHref',
'setIdPrefix',
'setImageURL',
'setItalic',
'setLayerVisibility',
'setLinkURL',
'setMode',
'setOpacity',
'setPaint',
'setPaintOpacity',
'setRectRadius',
'setResolution',
'setRotationAngle',
'setSegType',
'setStrokeAttr',
'setStrokePaint',
'setStrokeWidth',
'setSvgString',
'setTextContent',
'setUiStrings',
'setUseData',
'setZoom',
'svgCanvasToString',
'svgToString',
'transformListToTransform',
'ungroupSelectedElement',
'uniquifyElems',
'updateCanvas',
'zoomChanged'
];
// TODO: rewrite the following, it's pretty scary.
for (const func of functions) {
this[func] = getCallbackSetter(func);
}
// Older IE may need a polyfill for addEventListener, but so it would for SVG
window.addEventListener('message', getMessageListener(this));
window.addEventListener('keydown', (e) => {
const { type, key } = e;
if (key === 'Backspace') {
e.preventDefault();
const keyboardEvent = new KeyboardEvent(type, { key });
that.frame.contentDocument.dispatchEvent(keyboardEvent);
}
});
}
/**
* @param {string} name
* @param {ArgumentsArray} args Signature dependent on function
* @param {GenericCallback} callback (This may be better than a promise in case adding an event.)
* @returns {Integer}
*/
send (name, args, callback) {
const that = this;
cbid++;
this.callbacks[cbid] = callback;
setTimeout((function (callbackID) {
return function () { // Delay for the callback to be set in case its synchronous
/*
* Todo: Handle non-JSON arguments and return values (undefined,
* nonfinite numbers, functions, and built-in objects like Date,
* RegExp), etc.? Allow promises instead of callbacks? Review
* SVG-Edit functions for whether JSON-able parameters can be
* made compatile with all API functionality
*/
// We accept and post strings for the sake of IE9 support
let sameOriginWithGlobal = false;
try {
sameOriginWithGlobal = window.location.origin === that.frame.contentWindow.location.origin &&
that.frame.contentWindow.svgEditor.svgCanvas;
}catch (err) {/* empty */}
if (sameOriginWithGlobal) {
// Although we do not really need this API if we are working same
// domain, it could allow us to write in a way that would work
// cross-domain as well, assuming we stick to the argument limitations
// of the current JSON-based communication API (e.g., not passing
// callbacks). We might be able to address these shortcomings; see
// the todo elsewhere in this file.
const message = { id: callbackID };
const { svgEditor: { canvas: svgCanvas } } = that.frame.contentWindow;
try {
message.result = svgCanvas[name](...args);
} catch (err) {
message.error = err.message;
}
addCallback(that, message);
} else { // Requires the ext-xdomain-messaging.js extension
that.frame.contentWindow.postMessage(JSON.stringify({
namespace: 'svgCanvas', id: callbackID, name, args
}), '*');
}
};
}(cbid)), 0);
return cbid;
}
}
export default EmbeddedSVGEdit;

View File

@@ -0,0 +1,2 @@
The file below are working with V6 but were not tested with V7
Please open an issue to make them back into the main project.

View File

@@ -0,0 +1,338 @@
/**
* @file ext-arrows.js
*
* @license MIT
*
* @copyright 2010 Alexis Deveria
*
*/
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
console.error(`Missing translation (${lang}) - using 'en'`);
translationModule = await import(`./locale/en.js`);
}
return translationModule.default;
};
export default {
name: 'arrows',
async init (S) {
const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor);
const { svgCanvas } = svgEditor;
const { $id } = svgCanvas;
const
addElem = svgCanvas.addSVGElementFromJson;
const { nonce } = S;
const prefix = 'se_arrow_';
let selElems; let arrowprefix; let randomizeIds = S.randomize_ids;
/**
* @param {Window} win
* @param {!(string|Integer)} n
* @returns {void}
*/
function setArrowNonce (win, n) {
randomizeIds = true;
arrowprefix = prefix + n + '_';
pathdata.fw.id = arrowprefix + 'fw';
pathdata.bk.id = arrowprefix + 'bk';
}
/**
* @param {Window} win
* @returns {void}
*/
function unsetArrowNonce (_win) {
randomizeIds = false;
arrowprefix = prefix;
pathdata.fw.id = arrowprefix + 'fw';
pathdata.bk.id = arrowprefix + 'bk';
}
svgCanvas.bind('setnonce', setArrowNonce);
svgCanvas.bind('unsetnonce', unsetArrowNonce);
arrowprefix = (randomizeIds) ? `${prefix}${nonce}_` : prefix;
const pathdata = {
fw: { d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', refx: 8, id: arrowprefix + 'fw' },
bk: { d: 'm10,0l-10,5l10,5l-5,-5l5,-5z', refx: 2, id: arrowprefix + 'bk' }
};
/**
* Gets linked element.
* @param {Element} elem
* @param {string} attr
* @returns {Element}
*/
function getLinked (elem, attr) {
const str = elem.getAttribute(attr);
if (!str) { return null; }
const m = str.match(/\(#(.*)\)/);
// const m = str.match(/\(#(?<id>.+)\)/);
// if (!m || !m.groups.id) {
if (!m || m.length !== 2) {
return null;
}
return svgCanvas.getElem(m[1]);
}
/**
* @param {boolean} on
* @returns {void}
*/
function showPanel (on) {
$id('arrow_panel').style.display = (on) ? 'block' : 'none';
if (on) {
const el = selElems[0];
const end = el.getAttribute('marker-end');
const start = el.getAttribute('marker-start');
const mid = el.getAttribute('marker-mid');
let val;
if (end && start) {
val = 'both';
} else if (end) {
val = 'end';
} else if (start) {
val = 'start';
} else if (mid) {
val = 'mid';
if (mid.includes('bk')) {
val = 'mid_bk';
}
}
if (!start && !mid && !end) {
val = 'none';
}
$id('arrow_list').value = val;
}
}
/**
*
* @returns {void}
*/
function resetMarker () {
const el = selElems[0];
el.removeAttribute('marker-start');
el.removeAttribute('marker-mid');
el.removeAttribute('marker-end');
}
/**
* @param {"bk"|"fw"} dir
* @param {"both"|"mid"|"end"|"start"} type
* @param {string} id
* @returns {Element}
*/
function addMarker (dir, type, id) {
// TODO: Make marker (or use?) per arrow type, since refX can be different
id = id || arrowprefix + dir;
const data = pathdata[dir];
if (type === 'mid') {
data.refx = 5;
}
let marker = svgCanvas.getElem(id);
if (!marker) {
marker = addElem({
element: 'marker',
attr: {
viewBox: '0 0 10 10',
id,
refY: 5,
markerUnits: 'strokeWidth',
markerWidth: 5,
markerHeight: 5,
orient: 'auto',
style: 'pointer-events:none' // Currently needed for Opera
}
});
const arrow = addElem({
element: 'path',
attr: {
d: data.d,
fill: '#000000'
}
});
marker.append(arrow);
svgCanvas.findDefs().append(marker);
}
marker.setAttribute('refX', data.refx);
return marker;
}
/**
*
* @returns {void}
*/
function setArrow () {
resetMarker();
let type = this.value;
if (type === 'none') {
return;
}
// Set marker on element
let dir = 'fw';
if (type === 'mid_bk') {
type = 'mid';
dir = 'bk';
} else if (type === 'both') {
addMarker('bk', type);
svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')');
type = 'end';
dir = 'fw';
} else if (type === 'start') {
dir = 'bk';
}
addMarker(dir, type);
svgCanvas.changeSelectedAttribute('marker-' + type, 'url(#' + pathdata[dir].id + ')');
svgCanvas.call('changed', selElems);
}
/**
* @param {Element} elem
* @returns {void}
*/
function colorChanged (elem) {
const color = elem.getAttribute('stroke');
const mtypes = [ 'start', 'mid', 'end' ];
const defs = svgCanvas.findDefs();
mtypes.forEach(function(type){
const marker = getLinked(elem, 'marker-' + type);
if (!marker) { return; }
const curColor = marker.children.getAttribute('fill');
const curD = marker.children.getAttribute('d');
if (curColor === color) { return; }
const allMarkers = defs.querySelectorAll('marker');
let newMarker = null;
// Different color, check if already made
Array.from(allMarkers).forEach(function(marker) {
const attrsFill = marker.children.getAttribute('fill');
const attrsD = marker.children.getAttribute('d');
if (attrsFill === color && attrsD === curD) {
// Found another marker with this color and this path
newMarker = marker;
}
});
if (!newMarker) {
// Create a new marker with this color
const lastId = marker.id;
const dir = lastId.includes('_fw') ? 'fw' : 'bk';
newMarker = addMarker(dir, type, arrowprefix + dir + allMarkers.length);
newMarker.children.setAttribute('fill', color);
}
elem.setAttribute('marker-' + type, 'url(#' + newMarker.id + ')');
// 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){
mtypes.forEach(function(mtype){
if (element.getAttribute('marker-' + mtype) === 'url(#' + marker.id + ')') {
remove = false;
return remove;
}
return undefined;
});
if (!remove) { return false; }
return undefined;
});
// Not found, so can safely remove
if (remove) {
marker.remove();
}
});
}
const contextTools = [
{
type: 'select',
panel: 'arrow_panel',
id: 'arrow_list',
defval: 'none',
events: {
change: setArrow
}
}
];
return {
name: strings.name,
context_tools: strings.contextTools.map((contextTool, i) => {
return Object.assign(contextTools[i], contextTool);
}),
callback () {
$id("arrow_panel").style.display = 'none';
// Set ID so it can be translated in locale file
$id('arrow_list option').setAttribute('id', 'connector_no_arrow');
},
async addLangData ({ _lang, importLocale }) {
const { langList } = await importLocale();
return {
data: langList
};
},
selectedChanged (opts) {
// Use this to update the current selected elements
selElems = opts.elems;
const markerElems = [ 'line', 'path', 'polyline', 'polygon' ];
let i = selElems.length;
while (i--) {
const elem = selElems[i];
if (elem && markerElems.includes(elem.tagName)) {
if (opts.selectedElement && !opts.multiselected) {
showPanel(true);
} else {
showPanel(false);
}
} else {
showPanel(false);
}
}
},
elementChanged (opts) {
const elem = opts.elems[0];
if (elem && (
elem.getAttribute('marker-start') ||
elem.getAttribute('marker-mid') ||
elem.getAttribute('marker-end')
)) {
// const start = elem.getAttribute('marker-start');
// const mid = elem.getAttribute('marker-mid');
// const end = elem.getAttribute('marker-end');
// Has marker, so see if it should match color
colorChanged(elem);
}
}
};
}
};

View File

@@ -0,0 +1,19 @@
export default {
name: 'Arrows',
langList: [
{ id: 'arrow_none', textContent: 'No arrow' }
],
contextTools: [
{
title: 'Select arrow type',
options: {
none: 'No arrow',
end: '----&gt;',
start: '&lt;----',
both: '&lt;---&gt;',
mid: '--&gt;--',
mid_bk: '--&lt;--'
}
}
]
};

View File

@@ -0,0 +1,19 @@
export default {
name: 'Arrows',
langList: [
{ id: 'arrow_none', textContent: 'Sans flèche' }
],
contextTools: [
{
title: 'Select arrow type',
options: {
none: 'No arrow',
end: '----&gt;',
start: '&lt;----',
both: '&lt;---&gt;',
mid: '--&gt;--',
mid_bk: '--&lt;--'
}
}
]
};

View File

@@ -0,0 +1,19 @@
export default {
name: '箭头',
langList: [
{ id: 'arrow_none', textContent: '无箭头' }
],
contextTools: [
{
title: '选择箭头类型',
options: {
none: '无箭头',
end: '----&gt;',
start: '&lt;----',
both: '&lt;---&gt;',
mid: '--&gt;--',
mid_bk: '--&lt;--'
}
}
]
};

View File

@@ -0,0 +1,623 @@
/**
* @file ext-markers.js
*
* @license Apache-2.0
*
* @copyright 2010 Will Schleter based on ext-arrows.js by Copyright(c) 2010 Alexis Deveria
*
* This extension provides for the addition of markers to the either end
* or the middle of a line, polyline, path, polygon.
*
* Markers may be either a graphic or arbitary text
*
* to simplify the coding and make the implementation as robust as possible,
* markers are not shared - every object has its own set of markers.
* this relationship is maintained by a naming convention between the
* ids of the markers and the ids of the object
*
* The following restrictions exist for simplicty of use and programming
* objects and their markers to have the same color
* marker size is fixed
* text marker font, size, and attributes are fixed
* an application specific attribute - se_type - is added to each marker element
* to store the type of marker
*
* @todo
* remove some of the restrictions above
* add option for keeping text aligned to horizontal
* add support for dimension extension lines
*
*/
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
console.error(`Missing translation (${lang}) - using 'en'`);
translationModule = await import(`./locale/en.js`);
}
return translationModule.default;
};
export default {
name: 'markers',
async init (S) {
const svgEditor = this;
const strings = await loadExtensionTranslation(svgEditor.configObj.pref('lang'));
const { $ } = S;
const { svgCanvas } = svgEditor;
const { $id } = svgCanvas;
const // {svgcontent} = S,
addElem = svgCanvas.addSVGElementFromJson;
const mtypes = [ 'start', 'mid', 'end' ];
const markerPrefix = 'se_marker_';
const idPrefix = 'mkr_';
// note - to add additional marker types add them below with a unique id
// and add the associated icon(s) to marker-icons.svg
// the geometry is normalized to a 100x100 box with the origin at lower left
// Safari did not like negative values for low left of viewBox
// remember that the coordinate system has +y downward
const markerTypes = {
nomarker: {},
leftarrow:
{ element: 'path', attr: { d: 'M0,50 L100,90 L70,50 L100,10 Z' } },
rightarrow:
{ element: 'path', attr: { d: 'M100,50 L0,90 L30,50 L0,10 Z' } },
textmarker:
{ element: 'text', attr: {
x: 0, y: 0, 'stroke-width': 0, stroke: 'none',
'font-size': 75, 'font-family': 'serif', 'text-anchor': 'left',
'xml:space': 'preserve'
} },
forwardslash:
{ element: 'path', attr: { d: 'M30,100 L70,0' } },
reverseslash:
{ element: 'path', attr: { d: 'M30,0 L70,100' } },
verticalslash:
{ element: 'path', attr: { d: 'M50,0 L50,100' } },
box:
{ element: 'path', attr: { d: 'M20,20 L20,80 L80,80 L80,20 Z' } },
star:
{ element: 'path', attr: { d: 'M10,30 L90,30 L20,90 L50,10 L80,90 Z' } },
xmark:
{ element: 'path', attr: { d: 'M20,80 L80,20 M80,80 L20,20' } },
triangle:
{ element: 'path', attr: { d: 'M10,80 L50,20 L80,80 Z' } },
mcircle:
{ element: 'circle', attr: { r: 30, cx: 50, cy: 50 } }
};
// duplicate shapes to support unfilled (open) marker types with an _o suffix
[ 'leftarrow', 'rightarrow', 'box', 'star', 'mcircle', 'triangle' ].forEach((v) => {
markerTypes[v + '_o'] = markerTypes[v];
});
/**
* @param {Element} elem - A graphic element will have an attribute like marker-start
* @param {"marker-start"|"marker-mid"|"marker-end"} attr
* @returns {Element} The marker element that is linked to the graphic element
*/
function getLinked (elem, attr) {
const str = elem.getAttribute(attr);
if (!str) { return null; }
const m = str.match(/\(#(.*)\)/);
// const m = str.match(/\(#(?<id>.+)\)/);
// if (!m || !m.groups.id) {
if (!m || m.length !== 2) {
return null;
}
return svgCanvas.getElem(m[1]);
// return svgCanvas.getElem(m.groups.id);
}
/**
*
* @param {"start"|"mid"|"end"} pos
* @param {string} id
* @returns {void}
*/
function setIcon (pos, id) {
if (id.substr(0, 1) !== '\\') { id = '\\textmarker'; }
const ci = idPrefix + pos + '_' + id.substr(1);
svgEditor.setIcon('cur_' + pos + '_marker_list', $id(ci).children);
$id(ci).classList.add('current');
const siblings = Array.prototype.filter.call($id(ci).parentNode.children, function(child){
return child !== $id(ci);
});
Array.from(siblings).forEach(function(sibling) {
sibling.classList.remove('current');
});
}
let selElems;
/**
* Toggles context tool panel off/on. Sets the controls with the
* selected element's settings.
* @param {boolean} on
* @returns {void}
*/
function showPanel (on) {
$id('marker_panel').style.display = (on) ? 'block' : 'none';
if (on) {
const el = selElems[0];
let val; let ci;
$.each(mtypes, function (i, pos) {
const m = getLinked(el, 'marker-' + pos);
const txtbox = $id(pos + '_marker');
if (!m) {
val = '\\nomarker';
ci = val;
txtbox.style.display = 'none';
} else {
if (!m.attributes.se_type) { return; } // not created by this extension
val = '\\' + m.attributes.se_type.textContent;
ci = val;
if (val === '\\textmarker') {
val = m.lastChild.textContent;
// txtbox.show(); // show text box
} else {
txtbox.style.display = 'none';
}
}
txtbox.value = val;
setIcon(pos, ci);
});
}
}
/**
* @param {string} id
* @param {""|"\\nomarker"|"nomarker"|"leftarrow"|"rightarrow"|"textmarker"|"forwardslash"|"reverseslash"|"verticalslash"|"box"|"star"|"xmark"|"triangle"|"mcircle"} val
* @returns {SVGMarkerElement}
*/
function addMarker (id, val) {
const txtBoxBg = '#ffffff';
const txtBoxBorder = 'none';
const txtBoxStrokeWidth = 0;
let marker = svgCanvas.getElem(id);
if (marker) { return undefined; }
if (val === '' || val === '\\nomarker') { return undefined; }
const el = selElems[0];
const color = el.getAttribute('stroke');
// NOTE: Safari didn't like a negative value in viewBox
// so we use a standardized 0 0 100 100
// with 50 50 being mapped to the marker position
const strokeWidth = 10;
let refX = 50;
let refY = 50;
let viewBox = '0 0 100 100';
let markerWidth = 5;
let markerHeight = 5;
const seType = (val.substr(0, 1) === '\\') ? val.substr(1) : 'textmarker';
if (!markerTypes[seType]) { return undefined; } // an unknown type!
// create a generic marker
marker = addElem({
element: 'marker',
attr: {
id,
markerUnits: 'strokeWidth',
orient: 'auto',
style: 'pointer-events:none',
se_type: seType
}
});
if (seType !== 'textmarker') {
const mel = addElem(markerTypes[seType]);
const fillcolor = (seType.substr(-2) === '_o')
? 'none'
: color;
mel.setAttribute('fill', fillcolor);
mel.setAttribute('stroke', color);
mel.setAttribute('stroke-width', strokeWidth);
marker.append(mel);
} else {
const text = addElem(markerTypes[seType]);
// have to add text to get bounding box
text.textContent = val;
const tb = text.getBBox();
// alert(tb.x + ' ' + tb.y + ' ' + tb.width + ' ' + tb.height);
const pad = 1;
const bb = tb;
bb.x = 0;
bb.y = 0;
bb.width += pad * 2;
bb.height += pad * 2;
// shift text according to its size
text.setAttribute('x', pad);
text.setAttribute('y', bb.height - pad - tb.height / 4); // kludge?
text.setAttribute('fill', color);
refX = bb.width / 2 + pad;
refY = bb.height / 2 + pad;
viewBox = bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height;
markerWidth = bb.width / 10;
markerHeight = bb.height / 10;
const box = addElem({
element: 'rect',
attr: {
x: bb.x,
y: bb.y,
width: bb.width,
height: bb.height,
fill: txtBoxBg,
stroke: txtBoxBorder,
'stroke-width': txtBoxStrokeWidth
}
});
marker.setAttribute('orient', 0);
marker.append(box, text);
}
marker.setAttribute('viewBox', viewBox);
marker.setAttribute('markerWidth', markerWidth);
marker.setAttribute('markerHeight', markerHeight);
marker.setAttribute('refX', refX);
marker.setAttribute('refY', refY);
svgCanvas.findDefs().append(marker);
return marker;
}
/**
* @param {Element} elem
* @returns {SVGPolylineElement}
*/
function convertline (elem) {
// this routine came from the connectors extension
// it is needed because midpoint markers don't work with line elements
if (elem.tagName !== 'line') { return elem; }
// Convert to polyline to accept mid-arrow
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'),
fill: 'none',
opacity: elem.getAttribute('opacity') || 1
}
});
$.each(mtypes, function (i, pos) { // get any existing marker definitions
const nam = 'marker-' + pos;
const m = elem.getAttribute(nam);
if (m) { pline.setAttribute(nam, elem.getAttribute(nam)); }
});
const batchCmd = new S.BatchCommand();
batchCmd.addSubCommand(new S.RemoveElementCommand(elem, elem.parentNode));
batchCmd.addSubCommand(new S.InsertElementCommand(pline));
elem.insertAdjacentElement('afterend', pline);
elem.remove();
svgCanvas.clearSelection();
pline.id = id;
svgCanvas.addToSelection([ pline ]);
S.addCommandToHistory(batchCmd);
return pline;
}
/**
*
* @returns {void}
*/
function setMarker () {
const poslist = { start_marker: 'start', mid_marker: 'mid', end_marker: 'end' };
const pos = poslist[this.id];
const markerName = 'marker-' + pos;
const el = selElems[0];
const marker = getLinked(el, markerName);
if (marker) { marker.remove(); }
el.removeAttribute(markerName);
let val = this.value;
if (val === '') { val = '\\nomarker'; }
if (val === '\\nomarker') {
setIcon(pos, val);
svgCanvas.call('changed', selElems);
return;
}
// Set marker on element
const id = markerPrefix + pos + '_' + el.id;
addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') {
convertline(el);
}
svgCanvas.call('changed', selElems);
setIcon(pos, val);
}
/**
* Called when the main system modifies an object. This routine changes
* the associated markers to be the same color.
* @param {Element} elem
* @returns {void}
*/
function colorChanged (elem) {
const color = elem.getAttribute('stroke');
$.each(mtypes, function (i, pos) {
const marker = getLinked(elem, 'marker-' + pos);
if (!marker) { return; }
if (!marker.attributes.se_type) { return; } // not created by this extension
const ch = marker.lastElementChild;
if (!ch) { return; }
const curfill = ch.getAttribute('fill');
const curstroke = ch.getAttribute('stroke');
if (curfill && curfill !== 'none') { ch.setAttribute('fill', color); }
if (curstroke && curstroke !== 'none') { ch.setAttribute('stroke', color); }
});
}
/**
* Called when the main system creates or modifies an object.
* Its primary purpose is to create new markers for cloned objects.
* @param {Element} el
* @returns {void}
*/
function updateReferences (el) {
$.each(mtypes, function (i, pos) {
const id = markerPrefix + pos + '_' + el.id;
const markerName = 'marker-' + pos;
const marker = getLinked(el, markerName);
if (!marker || !marker.attributes.se_type) { return; } // not created by this extension
const url = el.getAttribute(markerName);
if (url) {
const len = el.id.length;
const linkid = url.substr(-len - 1, len);
if (el.id !== linkid) {
const val = $id(pos + '_marker').getAttribute('value');
addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') { el = convertline(el); }
svgCanvas.call('changed', selElems);
}
}
});
}
// simulate a change event a text box that stores the current element's marker type
/**
* @param {"start"|"mid"|"end"} pos
* @param {string} val
* @returns {void}
*/
function triggerTextEntry (pos, val) {
$id(pos + '_marker').value = val;
$id(pos + '_marker').change();
}
/**
* @param {"start"|"mid"|"end"} pos
* @returns {void} Resolves to `undefined`
*/
function showTextPrompt (pos) {
let def = $id(pos + '_marker').value;
if (def.substr(0, 1) === '\\') { def = ''; }
// eslint-disable-next-line no-alert
const txt = prompt('Enter text for ' + pos + ' marker', def);
if (txt) {
triggerTextEntry(pos, txt);
}
}
/*
function setMarkerSet(obj) {
const parts = this.id.split('_');
const set = parts[2];
switch (set) {
case 'off':
triggerTextEntry('start','\\nomarker');
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\nomarker');
break;
case 'dimension':
triggerTextEntry('start','\\leftarrow');
triggerTextEntry('end','\\rightarrow');
await showTextPrompt('mid');
break;
case 'label':
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\rightarrow');
await showTextPrompt('start');
break;
}
}
*/
// callback function for a toolbar button click
/**
* @param {Event} ev
* @returns {Promise<void>} Resolves to `undefined`
*/
async function setArrowFromButton () {
const parts = this.id.split('_');
const pos = parts[1];
let val = parts[2];
if (parts[3]) { val += '_' + parts[3]; }
if (val !== 'textmarker') {
triggerTextEntry(pos, '\\' + val);
} else {
await showTextPrompt(pos);
}
}
/**
* @param {"nomarker"|"leftarrow"|"rightarrow"|"textmarker"|"forwardslash"|"reverseslash"|"verticalslash"|"box"|"star"|"xmark"|"triangle"|"mcircle"} id
* @returns {string}
*/
function getTitle (id) {
const { langList } = strings;
const item = langList.find((itm) => {
return itm.id === id;
});
return item ? item.title : id;
}
/**
* Build the toolbar button array from the marker definitions.
* @returns {module:SVGEditor.Button[]}
*/
function buildButtonList () {
const buttons = [];
// const i = 0;
/*
buttons.push({
id: idPrefix + 'markers_off',
title: 'Turn off all markers',
type: 'context',
events: { click: setMarkerSet },
panel: 'marker_panel'
});
buttons.push({
id: idPrefix + 'markers_dimension',
title: 'Dimension',
type: 'context',
events: { click: setMarkerSet },
panel: 'marker_panel'
});
buttons.push({
id: idPrefix + 'markers_label',
title: 'Label',
type: 'context',
events: { click: setMarkerSet },
panel: 'marker_panel'
});
*/
$.each(mtypes, function (k, pos) {
const listname = pos + '_marker_list';
let def = true;
Object.keys(markerTypes).forEach(function (id) {
const title = getTitle(String(id));
buttons.push({
id: idPrefix + pos + '_' + id,
svgicon: id,
icon: id + '.svg',
title,
type: 'context',
events: { click: setArrowFromButton },
panel: 'marker_panel',
list: listname,
isDefault: def
});
def = false;
});
});
return buttons;
}
const contextTools = [
{
type: 'input',
panel: 'marker_panel',
id: 'start_marker',
size: 3,
events: { change: setMarker }
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'start_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
}, {
type: 'input',
panel: 'marker_panel',
id: 'mid_marker',
defval: '',
size: 3,
events: { change: setMarker }
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'mid_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
}, {
type: 'input',
panel: 'marker_panel',
id: 'end_marker',
size: 3,
events: { change: setMarker }
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'end_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
}
];
return {
name: strings.name,
svgicons: '',
callback () {
if($id("marker_panel") !== null) {
$id("marker_panel").classList.add('toolset');
$id("marker_panel").style.display = 'none';
}
},
/* async */ addLangData ({ _importLocale, _lang }) {
return { data: strings.langList };
},
selectedChanged (opts) {
// Use this to update the current selected elements
selElems = opts.elems;
const markerElems = [ 'line', 'path', 'polyline', 'polygon' ];
let i = selElems.length;
while (i--) {
const elem = selElems[i];
if (elem && markerElems.includes(elem.tagName)) {
if (opts.selectedElement && !opts.multiselected) {
showPanel(true);
} else {
showPanel(false);
}
} else {
showPanel(false);
}
}
},
elementChanged (opts) {
const elem = opts.elems[0];
if (elem && (
elem.getAttribute('marker-start') ||
elem.getAttribute('marker-mid') ||
elem.getAttribute('marker-end')
)) {
colorChanged(elem);
updateReferences(elem);
}
// changing_flag = false; // Not apparently in use
},
buttons: buildButtonList(),
context_tools: strings.contextTools.map((contextTool, i) => {
return Object.assign(contextTools[i], contextTool);
})
};
}
};

View File

@@ -0,0 +1,46 @@
export default {
name: 'Markers',
langList: [
{ id: 'nomarker', title: 'No Marker' },
{ id: 'leftarrow', title: 'Left Arrow' },
{ id: 'rightarrow', title: 'Right Arrow' },
{ id: 'textmarker', title: 'Text Marker' },
{ id: 'forwardslash', title: 'Forward Slash' },
{ id: 'reverseslash', title: 'Reverse Slash' },
{ id: 'verticalslash', title: 'Vertical Slash' },
{ id: 'box', title: 'Box' },
{ id: 'star', title: 'Star' },
{ id: 'xmark', title: 'X' },
{ id: 'triangle', title: 'Triangle' },
{ id: 'mcircle', title: 'Circle' },
{ id: 'leftarrow_o', title: 'Open Left Arrow' },
{ id: 'rightarrow_o', title: 'Open Right Arrow' },
{ id: 'box_o', title: 'Open Box' },
{ id: 'star_o', title: 'Open Star' },
{ id: 'triangle_o', title: 'Open Triangle' },
{ id: 'mcircle_o', title: 'Open Circle' }
],
contextTools: [
{
title: 'Start marker',
label: 's'
},
{
title: 'Select start marker type'
},
{
title: 'Middle marker',
label: 'm'
},
{
title: 'Select mid marker type'
},
{
title: 'End marker',
label: 'e'
},
{
title: 'Select end marker type'
}
]
};

View File

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