Introduce DOMSVGFactory

This patch provides a new unit tested factory for creating SVG
containers and elements. This code is duplicated twice in the
codebase, but with upcoming changes this would need to be duplicated
even more. Moreover, consolidating this code in one factory allows
us to replace it easily for e.g., supporting Node.js. Therefore, move
this to a central place and update/ES6-ify the related code.

Finally, we replace `setAttributeNS` with `setAttribute` because no
namespace is provided.
This commit is contained in:
Tim van der Meij 2017-07-24 00:09:18 +02:00
parent 1c9af00bee
commit f7fd1db52f
No known key found for this signature in database
GPG key ID: 8C3FD2925A5F2762
4 changed files with 128 additions and 54 deletions

View file

@ -14,12 +14,13 @@
*/
import {
CMapCompressionType, createValidAbsoluteUrl, deprecated,
assert, CMapCompressionType, createValidAbsoluteUrl, deprecated,
removeNullCharacters, stringToBytes, warn
} from '../shared/util';
import globalScope from '../shared/global_scope';
var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
const DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
const SVG_NS = 'http://www.w3.org/2000/svg';
class DOMCanvasFactory {
create(width, height) {
@ -109,6 +110,27 @@ class DOMCMapReaderFactory {
}
}
class DOMSVGFactory {
create(width, height) {
assert(width > 0 && height > 0, 'Invalid SVG dimensions');
let svg = document.createElementNS(SVG_NS, 'svg:svg');
svg.setAttribute('version', '1.1');
svg.setAttribute('width', width + 'px');
svg.setAttribute('height', height + 'px');
svg.setAttribute('preserveAspectRatio', 'none');
svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
return svg;
}
createElement(type) {
assert(typeof type === 'string', 'Invalid SVG element type');
return document.createElementNS(SVG_NS, type);
}
}
/**
* Optimised CSS custom property getter/setter.
* @class
@ -330,4 +352,5 @@ export {
DEFAULT_LINK_REL,
DOMCanvasFactory,
DOMCMapReaderFactory,
DOMSVGFactory,
};