SvgImport: Implement support for onLoad and onError callbacks on string input.

Closes #827
This commit is contained in:
Jürg Lehni 2016-02-14 15:12:52 +01:00
parent 2025bd1a77
commit 75c40babc9

View file

@ -640,22 +640,32 @@ new function() {
return null;
options = typeof options === 'function' ? { onLoad: options }
: options || {};
var node = source,
// Remember current scope so we can restore it in onLoad.
scope = paper;
// Remember current scope so we can restore it in onLoad.
var scope = paper,
item = null;
function onLoad(svg) {
paper = scope;
var item = importSVG(svg, options, true),
onLoad = options.onLoad;
if (onLoad)
onLoad.call(this, item, svg);
try {
var node = typeof svg === 'object' ? svg : new window.DOMParser()
.parseFromString(svg, 'image/svg+xml');
if (!node.nodeName) {
node = null;
throw new Error('Unsupported SVG source: ' + source);
}
paper = scope;
item = importNode(node, options, true);
var onLoad = options.onLoad;
if (onLoad)
onLoad(item, svg);
} catch (e) {
onError(e);
}
}
function onError(message, status) {
var onError = options.onError;
if (onError) {
onError.call(this, message, status);
onError(message, status);
} else {
throw new Error(message);
}
@ -667,15 +677,16 @@ new function() {
if (typeof source === 'string' && !/^.*</.test(source)) {
// First see if we're meant to import an element with the given
// id.
node = document.getElementById(source);
var node = document.getElementById(source);
// Check if the string does not represent SVG data, in which
// case it must be the URL of a SVG to be loaded.
if (node) {
source = null;
onLoad(node);
} else {
Http.request({
url: source, async: true,
onLoad: onLoad, onError: onError
onLoad: onLoad,
onError: onError
});
}
} else if (typeof File !== 'undefined' && source instanceof File) {
@ -688,15 +699,11 @@ new function() {
onError(reader.error);
};
return reader.readAsText(source);
} else {
onLoad(source);
}
if (typeof source === 'string') {
node = new window.DOMParser().parseFromString(source,
'image/svg+xml');
}
if (!node.nodeName)
throw new Error('Unsupported SVG source: ' + source);
return importNode(node, options, true);
return item;
}
// NOTE: Documentation is in Item#importSVG()