diff options
49 files changed, 6237 insertions, 5662 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index a4ade76..b1570fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,53 @@ The document follows the conventions described in [“Keep a CHANGELOG”](http: - fixed a bug in clipping and masking where empty nodes persists after removal -> __TODO!__ - fixed a bug in IE11 with `mouseenter` and `mouseleave` -> __TODO!__ -## [2.5.0](https://github.com/svgdotjs/svg.js/releases/tag/2.5.0) - 2017-03-10 + +## [2.6.0] - 2017-04-21 + +### Added +- added `options` object to `SVG.on()` and `el.on()` (#661) + +### Changed +- back to sloppy mode because of problems with plugins (#660) + + +## [2.5.3] - 2017-04-15 + +### Added +- added gitter badge in readme + + +### Fixed +- fixed svg.js.d.ts (#644 #648) +- fixed bug in `el.flip()` which causes an error when calling flip without any argument + +### Removed +- component.json (#652) + + +## [2.5.2] - 2017-04-11 + +### Changed +- SVG.js is now running in strict mode + +### Fixed +- `clear()` does not remove the parser in svg documents anymore +- `len` not declared in FX module, making it a global variable (9737e8a) +- `bbox` not declared in SVG.Box.transform in the Box module (131df0f) +- `namespace` not declared in the Event module (e89c97e) + + +## [2.5.1] - 2017-03-27 + +### Changed +- make svgjs ready to be used on the server + +### Fixed +- fixed `SVG.PathArray.parse` that did not correctly parsed flat arrays +- prevented unnecessary parsing of point or path strings + + +## [2.5.0] - 2017-03-10 ### Added - added a plot and array method to `SVG.TextPath` (#582) @@ -554,6 +600,11 @@ The document follows the conventions described in [“Keep a CHANGELOG”](http: <!-- Headings above link to the releases listed here --> +[2.6.0]: https://github.com/svgdotjs/svg.js/releases/tag/2.6.0 +[2.5.3]: https://github.com/svgdotjs/svg.js/releases/tag/2.5.3 +[2.5.2]: https://github.com/svgdotjs/svg.js/releases/tag/2.5.2 +[2.5.1]: https://github.com/svgdotjs/svg.js/releases/tag/2.5.1 +[2.5.0]: https://github.com/svgdotjs/svg.js/releases/tag/2.5.0 [2.4.0]: https://github.com/svgdotjs/svg.js/releases/tag/2.4.0 [2.3.7]: https://github.com/svgdotjs/svg.js/releases/tag/2.3.7 @@ -3,6 +3,7 @@ [![Build Status](https://travis-ci.org/svgdotjs/svg.js.svg?branch=master)](https://travis-ci.org/svgdotjs/svg.js) [![Coverage Status](https://coveralls.io/repos/github/svgdotjs/svg.js/badge.svg?branch=master)](https://coveralls.io/github/svgdotjs/svg.js?branch=master) [![CDNJS](https://img.shields.io/cdnjs/v/svg.js.svg)](https://cdnjs.com/libraries/svg.js) +[![Join the chat at https://gitter.im/svgdotjs/svg.js](https://badges.gitter.im/svgdotjs/svg.js.svg)](https://gitter.im/svgdotjs/svg.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) __A lightweight library for manipulating and animating SVG, without any dependencies.__ diff --git a/bench/runner.html b/bench/runner.html index a0bc5d9..1a2f727 100644 --- a/bench/runner.html +++ b/bench/runner.html @@ -40,6 +40,7 @@ <script src="../dist/svg.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/snap.svg/0.5.1/snap.svg-min.js"></script> <script src="svg.bench.js"></script> + <!-- <script src="tests/10000-each.js"></script> --> <script src="tests/10000-rects.js"></script> <script src="tests/10000-circles.js"></script> <script src="tests/10000-paths.js"></script> diff --git a/bench/tests/10000-circles.js b/bench/tests/10000-circles.js index da2a3de..f090281 100644 --- a/bench/tests/10000-circles.js +++ b/bench/tests/10000-circles.js @@ -1,5 +1,5 @@ SVG.bench.describe('Generate 10000 circles', function(bench) { - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) bench.draw.circle(100,100) }) @@ -18,7 +18,7 @@ SVG.bench.describe('Generate 10000 circles', function(bench) { }) SVG.bench.describe('Generate 10000 circles with fill', function(bench) { - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) bench.draw.circle(100,100).fill('#f06') }) diff --git a/bench/tests/10000-each.js b/bench/tests/10000-each.js new file mode 100644 index 0000000..c47eb60 --- /dev/null +++ b/bench/tests/10000-each.js @@ -0,0 +1,27 @@ +SVG.bench.describe('each() vs forEach()', function(bench) { + // preparation + var list = [] + + for (var i = 99; i >= 0; i--) + list.push(bench.draw.rect(100, 50)) + + var set = new SVG.Set(list) + + + bench.test('10000 x each()', function() { + for (var i = 0; i < 10000; i++) { + set.each(function() { + this.fill('#f06') + }) + } + }) + + bench.test('10000 x forEach()', function() { + for (var i = 0; i < 10000; i++) { + list.forEach(function(e) { + e.fill('#f06') + }) + } + }) + +})
\ No newline at end of file diff --git a/bench/tests/10000-pathArrays.js b/bench/tests/10000-pathArrays.js index fc34e5f..a4c0fdc 100644 --- a/bench/tests/10000-pathArrays.js +++ b/bench/tests/10000-pathArrays.js @@ -5,17 +5,17 @@ SVG.bench.describe('Generate 10000 pathArrays', function(bench) { var data3 = 'M10 10-45-30.5.5 .89L2e-2.5.5.5-.5C.5.5.5.5.5.5L-3-4z' - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) new SVG.PathArray(data) }) - bench.test('using SVG.js v2.4.0 more data', function() { + bench.test('using SVG.js v2.5.3 more data', function() { for (var i = 0; i < 10000; i++) new SVG.PathArray(data2) }) - bench.test('using SVG.js v2.4.0 complicated data', function() { + bench.test('using SVG.js v2.5.3 complicated data', function() { for (var i = 0; i < 10000; i++) new SVG.PathArray(data3) }) diff --git a/bench/tests/10000-paths.js b/bench/tests/10000-paths.js index 378cb29..cdf1d22 100644 --- a/bench/tests/10000-paths.js +++ b/bench/tests/10000-paths.js @@ -1,7 +1,7 @@ SVG.bench.describe('Generate 10000 paths', function(bench) { var data = 'M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100' - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) bench.draw.path(data) }) diff --git a/bench/tests/10000-rects.js b/bench/tests/10000-rects.js index dee09b4..aea0c79 100644 --- a/bench/tests/10000-rects.js +++ b/bench/tests/10000-rects.js @@ -1,5 +1,5 @@ SVG.bench.describe('Generate 10000 rects', function(bench) { - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) bench.draw.rect(100,100) }) @@ -19,7 +19,7 @@ SVG.bench.describe('Generate 10000 rects', function(bench) { SVG.bench.describe('Generate 10000 rects with fill', function(bench) { - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) bench.draw.rect(100,100).fill('#f06') }) @@ -40,7 +40,7 @@ SVG.bench.describe('Generate 10000 rects with fill', function(bench) { SVG.bench.describe('Generate 10000 rects with position and fill', function(bench) { - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) bench.draw.rect(100,100).move(50,50).fill('#f06') }) @@ -63,7 +63,7 @@ SVG.bench.describe('Generate 10000 rects with position and fill', function(bench SVG.bench.describe('Generate 10000 rects with gradient fill', function(bench) { - bench.test('using SVG.js v2.4.0', function() { + bench.test('using SVG.js v2.5.3', function() { for (var i = 0; i < 10000; i++) { var g = bench.draw.gradient('linear', function(stop) { stop.at(0, '#000') diff --git a/component.json b/component.json deleted file mode 100644 index 3ab91d0..0000000 --- a/component.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "svg.js", - "repo": "svgdotjs/svg.js", - "description": "A lightweight library for manipulating and animating SVG", - "version": "2.5.0", - "keywords": ["svg"], - "author": "Wout Fierens <wout@mick-wout.com>", - "main": "dist/svg.js", - "scripts": ["dist/svg.js"], - "license": "MIT" -}
\ No newline at end of file diff --git a/dist/svg.js b/dist/svg.js index a71d957..35ae5a1 100644 --- a/dist/svg.js +++ b/dist/svg.js @@ -1,5061 +1,5108 @@ /*! * svg.js - A lightweight library for manipulating and animating SVG. -* @version 2.5.0 +* @version 3.0.0 * https://svgdotjs.github.io/ * * @copyright Wout Fierens <wout@mick-wout.com> * @license MIT * -* BUILT: Sun Mar 19 2017 16:34:53 GMT+0100 (Mitteleuropäische Zeit) +* BUILT: Sat Apr 22 2017 20:28:05 GMT+0200 (Mitteleuropäische Sommerzeit) */; -(function(root, factory) { - if (typeof define === 'function' && define.amd) { - define(function(){ - return factory(root, root.document) - }) - } else if (typeof exports === 'object') { - module.exports = root.document ? factory(root, root.document) : function(w){ return factory(w, w.document) } - } else { - root.SVG = factory(root, root.document) - } -}(typeof window !== "undefined" ? window : this, function(window, document) { - -// The main wrapping element -var SVG = this.SVG = function(element) { - if (SVG.supported) { - element = new SVG.Doc(element) - - if(!SVG.parser.draw) - SVG.prepare() - - return element - } -} - -// Default namespaces -SVG.ns = 'http://www.w3.org/2000/svg' -SVG.xmlns = 'http://www.w3.org/2000/xmlns/' -SVG.xlink = 'http://www.w3.org/1999/xlink' -SVG.svgjs = 'http://svgjs.com/svgjs' - -// Svg support test -SVG.supported = (function() { - return !! document.createElementNS && - !! document.createElementNS(SVG.ns,'svg').createSVGRect -})() - -// Don't bother to continue if SVG is not supported -if (!SVG.supported) return false - -// Element id sequence -SVG.did = 1000 - -// Get next named element id -SVG.eid = function(name) { - return 'Svgjs' + capitalize(name) + (SVG.did++) -} - -// Method for element creation -SVG.create = function(name) { - // create element - var element = document.createElementNS(this.ns, name) - - // apply unique id - element.setAttribute('id', this.eid(name)) - - return element -} - -// Method for extending objects -SVG.extend = function() { - var modules, methods, key, i - - // Get list of modules - modules = [].slice.call(arguments) - - // Get object with extensions - methods = modules.pop() - - for (i = modules.length - 1; i >= 0; i--) - if (modules[i]) - for (key in methods) - modules[i].prototype[key] = methods[key] -} - -// Invent new element -SVG.invent = function(config) { - // Create element initializer - var initializer = typeof config.create == 'function' ? - config.create : - function() { - this.constructor.call(this, SVG.create(config.create)) - } - - // Inherit prototype - if (config.inherit) - initializer.prototype = new config.inherit - - // Extend with methods - if (config.extend) - SVG.extend(initializer, config.extend) - - // Attach construct method to parent - if (config.construct) - SVG.extend(config.parent || SVG.Container, config.construct) - - return initializer -} - -// Adopt existing svg elements -SVG.adopt = function(node) { - // check for presence of node - if (!node) return null - - // make sure a node isn't already adopted - if (node.instance) return node.instance - - // initialize variables - var element - - // adopt with element-specific settings - if (node.nodeName == 'svg') - element = node.parentNode instanceof window.SVGElement ? new SVG.Nested : new SVG.Doc - else if (node.nodeName == 'linearGradient') - element = new SVG.Gradient('linear') - else if (node.nodeName == 'radialGradient') - element = new SVG.Gradient('radial') - else if (SVG[capitalize(node.nodeName)]) - element = new SVG[capitalize(node.nodeName)] - else - element = new SVG.Element(node) - - // ensure references - element.type = node.nodeName - element.node = node - node.instance = element - - // SVG.Class specific preparations - if (element instanceof SVG.Doc) - element.namespace().defs() - - // pull svgjs data from the dom (getAttributeNS doesn't work in html5) - element.setData(JSON.parse(node.getAttribute('svgjs:data')) || {}) - - return element -} - -// Initialize parsing element -SVG.prepare = function() { - // Select document body and create invisible svg element - var body = document.getElementsByTagName('body')[0] - , draw = (body ? new SVG.Doc(body) : new SVG.Doc(document.documentElement).nested()).size(2, 0) - - // Create parser object - SVG.parser = { - body: body || document.documentElement - , draw: draw.style({ - opacity:0, - position:'absolute', - left:'-100%', - top:'-100%', - overflow:'hidden' - }) - , poly: draw.polyline().node - , path: draw.path().node - , native: SVG.create('svg') - } -} - -SVG.parser = { - native: SVG.create('svg') -} - -document.addEventListener('DOMContentLoaded', function() { - if(!SVG.parser.draw) - SVG.prepare() -}, false) - -// Storage for regular expressions -SVG.regex = { - // Parse unit value - numberAndUnit: /^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i - - // Parse hex value -, hex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i - - // Parse rgb value -, rgb: /rgb\((\d+),(\d+),(\d+)\)/ - - // Parse reference id -, reference: /#([a-z0-9\-_]+)/i - - // splits a transformation chain -, transforms: /\)\s*,?\s*/ - - // Whitespace -, whitespace: /\s/g - - // Test hex value -, isHex: /^#[a-f0-9]{3,6}$/i - - // Test rgb value -, isRgb: /^rgb\(/ - - // Test css declaration -, isCss: /[^:]+:[^;]+;?/ - - // Test for blank string -, isBlank: /^(\s+)?$/ - - // Test for numeric string -, isNumber: /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i - - // Test for percent value -, isPercent: /^-?[\d\.]+%$/ - - // Test for image url -, isImage: /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i - - // split at whitespace and comma -, delimiter: /[\s,]+/ - - // The following regex are used to parse the d attribute of a path - - // Matches all hyphens which are not after an exponent -, hyphen: /([^e])\-/gi - - // Replaces and tests for all path letters -, pathLetters: /[MLHVCSQTAZ]/gi - - // yes we need this one, too -, isPathLetter: /[MLHVCSQTAZ]/i - - // matches 0.154.23.45 -, numbersWithDots: /((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi - - // matches . -, dots: /\./g -} - -SVG.utils = { - // Map function - map: function(array, block) { - var i - , il = array.length - , result = [] - - for (i = 0; i < il; i++) - result.push(block(array[i])) - - return result - } - - // Filter function -, filter: function(array, block) { - var i - , il = array.length - , result = [] - - for (i = 0; i < il; i++) - if (block(array[i])) - result.push(array[i]) - - return result - } - - // Degrees to radians -, radians: function(d) { - return d % 360 * Math.PI / 180 - } - - // Radians to degrees -, degrees: function(r) { - return r * 180 / Math.PI % 360 - } - -, filterSVGElements: function(nodes) { - return this.filter( nodes, function(el) { return el instanceof window.SVGElement }) - } - -} - -SVG.defaults = { - // Default attribute values - attrs: { - // fill and stroke - 'fill-opacity': 1 - , 'stroke-opacity': 1 - , 'stroke-width': 0 - , 'stroke-linejoin': 'miter' - , 'stroke-linecap': 'butt' - , fill: '#000000' - , stroke: '#000000' - , opacity: 1 - // position - , x: 0 - , y: 0 - , cx: 0 - , cy: 0 - // size - , width: 0 - , height: 0 - // radius - , r: 0 - , rx: 0 - , ry: 0 - // gradient - , offset: 0 - , 'stop-opacity': 1 - , 'stop-color': '#000000' - // text - , 'font-size': 16 - , 'font-family': 'Helvetica, Arial, sans-serif' - , 'text-anchor': 'start' - } - -} -// Module for color convertions -SVG.Color = function(color) { - var match - - // initialize defaults - this.r = 0 - this.g = 0 - this.b = 0 - - if(!color) return - - // parse color - if (typeof color === 'string') { - if (SVG.regex.isRgb.test(color)) { - // get rgb values - match = SVG.regex.rgb.exec(color.replace(SVG.regex.whitespace,'')) - - // parse numeric values - this.r = parseInt(match[1]) - this.g = parseInt(match[2]) - this.b = parseInt(match[3]) - - } else if (SVG.regex.isHex.test(color)) { - // get hex values - match = SVG.regex.hex.exec(fullHex(color)) - - // parse numeric values - this.r = parseInt(match[1], 16) - this.g = parseInt(match[2], 16) - this.b = parseInt(match[3], 16) - - } - - } else if (typeof color === 'object') { - this.r = color.r - this.g = color.g - this.b = color.b - - } - -} - -SVG.extend(SVG.Color, { - // Default to hex conversion - toString: function() { - return this.toHex() - } - // Build hex value -, toHex: function() { - return '#' - + compToHex(this.r) - + compToHex(this.g) - + compToHex(this.b) - } - // Build rgb value -, toRgb: function() { - return 'rgb(' + [this.r, this.g, this.b].join() + ')' - } - // Calculate true brightness -, brightness: function() { - return (this.r / 255 * 0.30) - + (this.g / 255 * 0.59) - + (this.b / 255 * 0.11) - } - // Make color morphable -, morph: function(color) { - this.destination = new SVG.Color(color) - - return this - } - // Get morphed color at given position -, at: function(pos) { - // make sure a destination is defined - if (!this.destination) return this - - // normalise pos - pos = pos < 0 ? 0 : pos > 1 ? 1 : pos - - // generate morphed color - return new SVG.Color({ - r: ~~(this.r + (this.destination.r - this.r) * pos) - , g: ~~(this.g + (this.destination.g - this.g) * pos) - , b: ~~(this.b + (this.destination.b - this.b) * pos) - }) - } - -}) - -// Testers - -// Test if given value is a color string -SVG.Color.test = function(color) { - color += '' - return SVG.regex.isHex.test(color) - || SVG.regex.isRgb.test(color) -} - -// Test if given value is a rgb object -SVG.Color.isRgb = function(color) { - return color && typeof color.r == 'number' - && typeof color.g == 'number' - && typeof color.b == 'number' -} - -// Test if given value is a color -SVG.Color.isColor = function(color) { - return SVG.Color.isRgb(color) || SVG.Color.test(color) -} -// Module for array conversion -SVG.Array = function(array, fallback) { - array = (array || []).valueOf() - - // if array is empty and fallback is provided, use fallback - if (array.length == 0 && fallback) - array = fallback.valueOf() - - // parse array - this.value = this.parse(array) +(function(root, factory) {
+ /* istanbul ignore next */
+ if (typeof define === 'function' && define.amd) {
+ define(function(){
+ return factory(root, root.document)
+ })
+ } else if (typeof exports === 'object') {
+ module.exports = root.document ? factory(root, root.document) : function(w){ return factory(w, w.document) }
+ } else {
+ root.SVG = factory(root, root.document)
+ }
+}(typeof window !== "undefined" ? window : this, function(window, document) {
+
+// The main wrapping element
+var SVG = this.SVG = function(element) {
+ if (SVG.supported) {
+ element = new SVG.Doc(element)
+
+ if(!SVG.parser.draw)
+ SVG.prepare()
+
+ return element
+ }
+}
+
+// Default namespaces
+SVG.ns = 'http://www.w3.org/2000/svg'
+SVG.xmlns = 'http://www.w3.org/2000/xmlns/'
+SVG.xlink = 'http://www.w3.org/1999/xlink'
+SVG.svgjs = 'http://svgjs.com/svgjs'
+
+// Svg support test
+SVG.supported = (function() {
+ return !! document.createElementNS &&
+ !! document.createElementNS(SVG.ns,'svg').createSVGRect
+})()
+
+// Don't bother to continue if SVG is not supported
+if (!SVG.supported) return false
+
+// Element id sequence
+SVG.did = 1000
+
+// Get next named element id
+SVG.eid = function(name) {
+ return 'Svgjs' + capitalize(name) + (SVG.did++)
+}
+
+// Method for element creation
+SVG.create = function(name) {
+ // create element
+ var element = document.createElementNS(this.ns, name)
+
+ // apply unique id
+ element.setAttribute('id', this.eid(name))
+
+ return element
+}
+
+// Method for extending objects
+SVG.extend = function() {
+ var modules, methods, key, i
+
+ // Get list of modules
+ modules = [].slice.call(arguments)
+
+ // Get object with extensions
+ methods = modules.pop()
+
+ for (i = modules.length - 1; i >= 0; i--)
+ if (modules[i])
+ for (key in methods)
+ modules[i].prototype[key] = methods[key]
+}
+
+// Invent new element
+SVG.invent = function(config) {
+ // Create element initializer
+ var initializer = typeof config.create == 'function' ?
+ config.create :
+ function() {
+ this.constructor.call(this, SVG.create(config.create))
+ }
+
+ // Inherit prototype
+ if (config.inherit)
+ initializer.prototype = new config.inherit
+
+ // Extend with methods
+ if (config.extend)
+ SVG.extend(initializer, config.extend)
+
+ // Attach construct method to parent
+ if (config.construct)
+ SVG.extend(config.parent || SVG.Container, config.construct)
+
+ return initializer
+}
+
+// Adopt existing svg elements
+SVG.adopt = function(node) {
+ // check for presence of node
+ if (!node) return null
+
+ // make sure a node isn't already adopted
+ if (node.instance) return node.instance
+
+ // initialize variables
+ var element
+
+ // adopt with element-specific settings
+ if (node.nodeName == 'svg')
+ element = node.parentNode instanceof window.SVGElement ? new SVG.Nested : new SVG.Doc
+ else if (node.nodeName == 'linearGradient')
+ element = new SVG.Gradient('linear')
+ else if (node.nodeName == 'radialGradient')
+ element = new SVG.Gradient('radial')
+ else if (SVG[capitalize(node.nodeName)])
+ element = new SVG[capitalize(node.nodeName)]
+ else
+ element = new SVG.Element(node)
+
+ // ensure references
+ element.type = node.nodeName
+ element.node = node
+ node.instance = element
+
+ // SVG.Class specific preparations
+ if (element instanceof SVG.Doc)
+ element.namespace().defs()
+
+ // pull svgjs data from the dom (getAttributeNS doesn't work in html5)
+ element.setData(JSON.parse(node.getAttribute('svgjs:data')) || {})
+
+ return element
+}
+
+// Initialize parsing element
+SVG.prepare = function() {
+ // Select document body and create invisible svg element
+ var body = document.getElementsByTagName('body')[0]
+ , draw = (body ? new SVG.Doc(body) : SVG.adopt(document.documentElement).nested()).size(2, 0)
+
+ // Create parser object
+ SVG.parser = {
+ body: body || document.documentElement
+ , draw: draw.style({
+ opacity:0,
+ position:'absolute',
+ left:'-100%',
+ top:'-100%',
+ overflow:'hidden'
+ }).node
+ , poly: draw.polyline().node
+ , path: draw.path().node
+ , native: SVG.create('svg')
+ }
+}
+
+SVG.parser = {
+ native: SVG.create('svg')
+}
+
+document.addEventListener('DOMContentLoaded', function() {
+ if(!SVG.parser.draw)
+ SVG.prepare()
+}, false)
+ +// Storage for regular expressions
+SVG.regex = {
+ // Parse unit value
+ numberAndUnit: /^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i
+
+ // Parse hex value
+, hex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
+
+ // Parse rgb value
+, rgb: /rgb\((\d+),(\d+),(\d+)\)/
+
+ // Parse reference id
+, reference: /#([a-z0-9\-_]+)/i
+
+ // splits a transformation chain
+, transforms: /\)\s*,?\s*/
+
+ // Whitespace
+, whitespace: /\s/g
+
+ // Test hex value
+, isHex: /^#[a-f0-9]{3,6}$/i
+
+ // Test rgb value
+, isRgb: /^rgb\(/
+
+ // Test css declaration
+, isCss: /[^:]+:[^;]+;?/
+
+ // Test for blank string
+, isBlank: /^(\s+)?$/
+
+ // Test for numeric string
+, isNumber: /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i
+
+ // Test for percent value
+, isPercent: /^-?[\d\.]+%$/
+
+ // Test for image url
+, isImage: /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i
+
+ // split at whitespace and comma
+, delimiter: /[\s,]+/
+
+ // The following regex are used to parse the d attribute of a path
+
+ // Matches all hyphens which are not after an exponent
+, hyphen: /([^e])\-/gi
+
+ // Replaces and tests for all path letters
+, pathLetters: /[MLHVCSQTAZ]/gi
+
+ // yes we need this one, too
+, isPathLetter: /[MLHVCSQTAZ]/i
+
+ // matches 0.154.23.45
+, numbersWithDots: /((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi
+
+ // matches .
+, dots: /\./g
+}
+ +SVG.utils = {
+ // Map function
+ map: function(array, block) {
+ var i
+ , il = array.length
+ , result = []
+
+ for (i = 0; i < il; i++)
+ result.push(block(array[i]))
+
+ return result
+ }
+
+ // Filter function
+, filter: function(array, block) {
+ var i
+ , il = array.length
+ , result = []
+
+ for (i = 0; i < il; i++)
+ if (block(array[i]))
+ result.push(array[i])
+
+ return result
+ }
+
+ // Degrees to radians
+, radians: function(d) {
+ return d % 360 * Math.PI / 180
+ }
+
+ // Radians to degrees
+, degrees: function(r) {
+ return r * 180 / Math.PI % 360
+ }
+
+, filterSVGElements: function(nodes) {
+ return this.filter( nodes, function(el) { return el instanceof window.SVGElement })
+ }
+
} - -SVG.extend(SVG.Array, { - // Make array morphable - morph: function(array) { - this.destination = this.parse(array) - - // normalize length of arrays - if (this.value.length != this.destination.length) { - var lastValue = this.value[this.value.length - 1] - , lastDestination = this.destination[this.destination.length - 1] - - while(this.value.length > this.destination.length) - this.destination.push(lastDestination) - while(this.value.length < this.destination.length) - this.value.push(lastValue) - } - - return this - } - // Clean up any duplicate points -, settle: function() { - // find all unique values - for (var i = 0, il = this.value.length, seen = []; i < il; i++) - if (seen.indexOf(this.value[i]) == -1) - seen.push(this.value[i]) - - // set new value - return this.value = seen - } - // Get morphed array at given position -, at: function(pos) { - // make sure a destination is defined - if (!this.destination) return this - - // generate morphed array - for (var i = 0, il = this.value.length, array = []; i < il; i++) - array.push(this.value[i] + (this.destination[i] - this.value[i]) * pos) - - return new SVG.Array(array) - } - // Convert array to string -, toString: function() { - return this.value.join(' ') - } - // Real value -, valueOf: function() { - return this.value - } - // Parse whitespace separated string -, parse: function(array) { - array = array.valueOf() - - // if already is an array, no need to parse it - if (Array.isArray(array)) return array - - return array.trim().split(SVG.regex.delimiter).map(parseFloat) - } - // Reverse array -, reverse: function() { - this.value.reverse() - - return this - } -, clone: function() { - var clone = new this.constructor() - clone.value = array_clone(this.value) - return clone - } -}) -// Poly points array -SVG.PointArray = function(array, fallback) { - SVG.Array.call(this, array, fallback || [[0,0]]) -} - -// Inherit from SVG.Array -SVG.PointArray.prototype = new SVG.Array -SVG.PointArray.prototype.constructor = SVG.PointArray - -SVG.extend(SVG.PointArray, { - // Convert array to string - toString: function() { - // convert to a poly point string - for (var i = 0, il = this.value.length, array = []; i < il; i++) - array.push(this.value[i].join(',')) - - return array.join(' ') - } - // Convert array to line object -, toLine: function() { - return { - x1: this.value[0][0] - , y1: this.value[0][1] - , x2: this.value[1][0] - , y2: this.value[1][1] - } - } - // Get morphed array at given position -, at: function(pos) { - // make sure a destination is defined - if (!this.destination) return this - - // generate morphed point string - for (var i = 0, il = this.value.length, array = []; i < il; i++) - array.push([ - this.value[i][0] + (this.destination[i][0] - this.value[i][0]) * pos - , this.value[i][1] + (this.destination[i][1] - this.value[i][1]) * pos - ]) - - return new SVG.PointArray(array) - } - // Parse point string and flat array -, parse: function(array) { - var points = [] - - array = array.valueOf() - - // if it is an array - if (Array.isArray(array)) { - // and it is not flat, there is no need to parse it - if(Array.isArray(array[0])) { - return array - } - } else { // Else, it is considered as a string - // parse points - array = array.trim().split(SVG.regex.delimiter).map(parseFloat) - } - - // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints - // Odd number of coordinates is an error. In such cases, drop the last odd coordinate. - if (array.length % 2 !== 0) array.pop() - - // wrap points in two-tuples and parse points as floats - for(var i = 0, len = array.length; i < len; i = i + 2) - points.push([ array[i], array[i+1] ]) - - return points - } - // Move point string -, move: function(x, y) { - var box = this.bbox() - - // get relative offset - x -= box.x - y -= box.y - - // move every point - if (!isNaN(x) && !isNaN(y)) - for (var i = this.value.length - 1; i >= 0; i--) - this.value[i] = [this.value[i][0] + x, this.value[i][1] + y] - - return this - } - // Resize poly string -, size: function(width, height) { - var i, box = this.bbox() - - // recalculate position of all points according to new size - for (i = this.value.length - 1; i >= 0; i--) { - if(box.width) this.value[i][0] = ((this.value[i][0] - box.x) * width) / box.width + box.x - if(box.height) this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y - } - - return this - } - // Get bounding box of points -, bbox: function() { - SVG.parser.poly.setAttribute('points', this.toString()) - - return SVG.parser.poly.getBBox() - } -}) - -// Path points array -SVG.PathArray = function(array, fallback) { - SVG.Array.call(this, array, fallback || [['M', 0, 0]]) -} - -// Inherit from SVG.Array -SVG.PathArray.prototype = new SVG.Array -SVG.PathArray.prototype.constructor = SVG.PathArray - -SVG.extend(SVG.PathArray, { - // Convert array to string - toString: function() { - return arrayToString(this.value) - } - // Move path string -, move: function(x, y) { - // get bounding box of current situation - var box = this.bbox() - - // get relative offset - x -= box.x - y -= box.y - - if (!isNaN(x) && !isNaN(y)) { - // move every point - for (var l, i = this.value.length - 1; i >= 0; i--) { - l = this.value[i][0] - - if (l == 'M' || l == 'L' || l == 'T') { - this.value[i][1] += x - this.value[i][2] += y - - } else if (l == 'H') { - this.value[i][1] += x - - } else if (l == 'V') { - this.value[i][1] += y - - } else if (l == 'C' || l == 'S' || l == 'Q') { - this.value[i][1] += x - this.value[i][2] += y - this.value[i][3] += x - this.value[i][4] += y - - if (l == 'C') { - this.value[i][5] += x - this.value[i][6] += y - } - - } else if (l == 'A') { - this.value[i][6] += x - this.value[i][7] += y - } - - } - } - - return this - } - // Resize path string -, size: function(width, height) { - // get bounding box of current situation - var i, l, box = this.bbox() - - // recalculate position of all points according to new size - for (i = this.value.length - 1; i >= 0; i--) { - l = this.value[i][0] - - if (l == 'M' || l == 'L' || l == 'T') { - this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x - this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y - - } else if (l == 'H') { - this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x - - } else if (l == 'V') { - this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y - - } else if (l == 'C' || l == 'S' || l == 'Q') { - this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x - this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y - this.value[i][3] = ((this.value[i][3] - box.x) * width) / box.width + box.x - this.value[i][4] = ((this.value[i][4] - box.y) * height) / box.height + box.y - - if (l == 'C') { - this.value[i][5] = ((this.value[i][5] - box.x) * width) / box.width + box.x - this.value[i][6] = ((this.value[i][6] - box.y) * height) / box.height + box.y - } - - } else if (l == 'A') { - // resize radii - this.value[i][1] = (this.value[i][1] * width) / box.width - this.value[i][2] = (this.value[i][2] * height) / box.height - - // move position values - this.value[i][6] = ((this.value[i][6] - box.x) * width) / box.width + box.x - this.value[i][7] = ((this.value[i][7] - box.y) * height) / box.height + box.y - } - - } - - return this - } - // Test if the passed path array use the same path data commands as this path array -, equalCommands: function(pathArray) { - var i, il, equalCommands - - pathArray = new SVG.PathArray(pathArray) - - equalCommands = this.value.length === pathArray.value.length - for(i = 0, il = this.value.length; equalCommands && i < il; i++) { - equalCommands = this.value[i][0] === pathArray.value[i][0] - } - - return equalCommands - } - // Make path array morphable -, morph: function(pathArray) { - pathArray = new SVG.PathArray(pathArray) - - if(this.equalCommands(pathArray)) { - this.destination = pathArray - } else { - this.destination = null - } - - return this - } - // Get morphed path array at given position -, at: function(pos) { - // make sure a destination is defined - if (!this.destination) return this - - var sourceArray = this.value - , destinationArray = this.destination.value - , array = [], pathArray = new SVG.PathArray() - , i, il, j, jl - - // Animate has specified in the SVG spec - // See: https://www.w3.org/TR/SVG11/paths.html#PathElement - for (i = 0, il = sourceArray.length; i < il; i++) { - array[i] = [sourceArray[i][0]] - for(j = 1, jl = sourceArray[i].length; j < jl; j++) { - array[i][j] = sourceArray[i][j] + (destinationArray[i][j] - sourceArray[i][j]) * pos - } - // For the two flags of the elliptical arc command, the SVG spec say: - // Flags and booleans are interpolated as fractions between zero and one, with any non-zero value considered to be a value of one/true - // Elliptical arc command as an array followed by corresponding indexes: - // ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y] - // 0 1 2 3 4 5 6 7 - if(array[i][0] === 'A') { - array[i][4] = +(array[i][4] != 0) - array[i][5] = +(array[i][5] != 0) - } - } - - // Directly modify the value of a path array, this is done this way for performance - pathArray.value = array - return pathArray - } - // Absolutize and parse path to array -, parse: function(array) { - // if it's already a patharray, no need to parse it - if (array instanceof SVG.PathArray) return array.valueOf() - - // prepare for parsing - var i, x0, y0, s, seg, arr - , x = 0 - , y = 0 - , paramCnt = { 'M':2, 'L':2, 'H':1, 'V':1, 'C':6, 'S':4, 'Q':4, 'T':2, 'A':7 } - - if(typeof array == 'string'){ - - array = array - .replace(SVG.regex.numbersWithDots, pathRegReplace) // convert 45.123.123 to 45.123 .123 - .replace(SVG.regex.pathLetters, ' $& ') // put some room between letters and numbers - .replace(SVG.regex.hyphen, '$1 -') // add space before hyphen - .trim() // trim - .split(SVG.regex.delimiter) // split into array - - }else{ - array = array.reduce(function(prev, curr){ - return [].concat.apply(prev, curr) - }, []) - } - - // array now is an array containing all parts of a path e.g. ['M', '0', '0', 'L', '30', '30' ...] - - var arr = [] - - do{ - - // Test if we have a path letter - if(SVG.regex.isPathLetter.test(array[0])){ - s = array[0] - array.shift() - // If last letter was a move command and we got no new, it defaults to [L]ine - }else if(s == 'M'){ - s = 'L' - }else if(s == 'm'){ - s = 'l' - } - - // add path letter as first element - seg = [s.toUpperCase()] - - // push all necessary parameters to segment - for(i = 0; i < paramCnt[seg[0]]; ++i){ - seg.push(parseFloat(array.shift())) - } - - // upper case - if(s == seg[0]){ - - if(s == 'M' || s == 'L' || s == 'C' || s == 'Q' || s == 'S' || s == 'T'){ - x = seg[paramCnt[seg[0]]-1] - y = seg[paramCnt[seg[0]]] - }else if(s == 'V'){ - y = seg[1] - }else if(s == 'H'){ - x = seg[1] - }else if(s == 'A'){ - x = seg[6] - y = seg[7] - } - - // lower case - }else{ - - // convert relative to absolute values - if(s == 'm' || s == 'l' || s == 'c' || s == 's' || s == 'q' || s == 't'){ - - seg[1] += x - seg[2] += y - - if(seg[3] != null){ - seg[3] += x - seg[4] += y - } - - if(seg[5] != null){ - seg[5] += x - seg[6] += y - } - - // move pointer - x = seg[paramCnt[seg[0]]-1] - y = seg[paramCnt[seg[0]]] - - }else if(s == 'v'){ - seg[1] += y - y = seg[1] - }else if(s == 'h'){ - seg[1] += x - x = seg[1] - }else if(s == 'a'){ - seg[6] += x - seg[7] += y - x = seg[6] - y = seg[7] - } - - } - - if(seg[0] == 'M'){ - x0 = x - y0 = y - } - - if(seg[0] == 'Z'){ - x = x0 - y = y0 - } - - arr.push(seg) - - }while(array.length) - - return arr - - } - // Get bounding box of path -, bbox: function() { - SVG.parser.path.setAttribute('d', this.toString()) - - return SVG.parser.path.getBBox() - } - -}) - -// Module for unit convertions -SVG.Number = SVG.invent({ - // Initialize - create: function(value, unit) { - // initialize defaults - this.value = 0 - this.unit = unit || '' - - // parse value - if (typeof value === 'number') { - // ensure a valid numeric value - this.value = isNaN(value) ? 0 : !isFinite(value) ? (value < 0 ? -3.4e+38 : +3.4e+38) : value - - } else if (typeof value === 'string') { - unit = value.match(SVG.regex.numberAndUnit) - - if (unit) { - // make value numeric - this.value = parseFloat(unit[1]) - - // normalize - if (unit[5] == '%') - this.value /= 100 - else if (unit[5] == 's') - this.value *= 1000 - - // store unit - this.unit = unit[5] - } - - } else { - if (value instanceof SVG.Number) { - this.value = value.valueOf() - this.unit = value.unit - } - } - - } - // Add methods -, extend: { - // Stringalize - toString: function() { - return ( - this.unit == '%' ? - ~~(this.value * 1e8) / 1e6: - this.unit == 's' ? - this.value / 1e3 : - this.value - ) + this.unit - } - , toJSON: function() { - return this.toString() - } - , // Convert to primitive - valueOf: function() { - return this.value - } - // Add number - , plus: function(number) { - number = new SVG.Number(number) - return new SVG.Number(this + number, this.unit || number.unit) - } - // Subtract number - , minus: function(number) { - number = new SVG.Number(number) - return new SVG.Number(this - number, this.unit || number.unit) - } - // Multiply number - , times: function(number) { - number = new SVG.Number(number) - return new SVG.Number(this * number, this.unit || number.unit) - } - // Divide number - , divide: function(number) { - number = new SVG.Number(number) - return new SVG.Number(this / number, this.unit || number.unit) - } - // Convert to different unit - , to: function(unit) { - var number = new SVG.Number(this) - - if (typeof unit === 'string') - number.unit = unit - - return number - } - // Make number morphable - , morph: function(number) { - this.destination = new SVG.Number(number) - - if(number.relative) { - this.destination.value += this.value - } - - return this - } - // Get morphed number at given position - , at: function(pos) { - // Make sure a destination is defined - if (!this.destination) return this - - // Generate new morphed number - return new SVG.Number(this.destination) - .minus(this) - .times(pos) - .plus(this) - } - - } -}) - - -SVG.Element = SVG.invent({ - // Initialize node - create: function(node) { - // last fired event on node - this._event = null - - // initialize data object - this.dom = {} - - // create circular reference - if (this.node = node) { - this.type = node.nodeName - this.node.instance = this - } - } - - // Add class methods -, extend: { - // Move over x-axis - x: function(x) { - return this.attr('x', x) - } - // Move over y-axis - , y: function(y) { - return this.attr('y', y) - } - // Move by center over x-axis - , cx: function(x) { - return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2) - } - // Move by center over y-axis - , cy: function(y) { - return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2) - } - // Move element to given x and y values - , move: function(x, y) { - return this.x(x).y(y) - } - // Move element by its center - , center: function(x, y) { - return this.cx(x).cy(y) - } - // Set width of element - , width: function(width) { - return this.attr('width', width) - } - // Set height of element - , height: function(height) { - return this.attr('height', height) - } - // Set element size to given width and height - , size: function(width, height) { - var p = proportionalSize(this, width, height) - - return this - .width(new SVG.Number(p.width)) - .height(new SVG.Number(p.height)) - } - // Clone element - , clone: function(parent, withData) { - // write dom data to the dom so the clone can pickup the data - this.writeDataToDom() - - // clone element and assign new id - var clone = assignNewId(this.node.cloneNode(true)) - - // insert the clone in the given parent or after myself - if(parent) parent.add(clone) - else this.after(clone) - - return clone - } - // Remove element - , remove: function() { - if (this.parent()) - this.parent().removeElement(this) - - return this - } - // Replace element - , replace: function(element) { - this.after(element).remove() - - return element - } - // Add element to given container and return self - , addTo: function(parent) { - return parent.put(this) - } - // Add element to given container and return container - , putIn: function(parent) { - return parent.add(this) - } - // Get / set id - , id: function(id) { - return this.attr('id', id) - } - // Checks whether the given point inside the bounding box of the element - , inside: function(x, y) { - var box = this.bbox() - - return x > box.x - && y > box.y - && x < box.x + box.width - && y < box.y + box.height - } - // Show element - , show: function() { - return this.style('display', '') - } - // Hide element - , hide: function() { - return this.style('display', 'none') - } - // Is element visible? - , visible: function() { - return this.style('display') != 'none' - } - // Return id on string conversion - , toString: function() { - return this.attr('id') - } - // Return array of classes on the node - , classes: function() { - var attr = this.attr('class') - - return attr == null ? [] : attr.trim().split(SVG.regex.delimiter) - } - // Return true if class exists on the node, false otherwise - , hasClass: function(name) { - return this.classes().indexOf(name) != -1 - } - // Add class to the node - , addClass: function(name) { - if (!this.hasClass(name)) { - var array = this.classes() - array.push(name) - this.attr('class', array.join(' ')) - } - - return this - } - // Remove class from the node - , removeClass: function(name) { - if (this.hasClass(name)) { - this.attr('class', this.classes().filter(function(c) { - return c != name - }).join(' ')) - } - - return this - } - // Toggle the presence of a class on the node - , toggleClass: function(name) { - return this.hasClass(name) ? this.removeClass(name) : this.addClass(name) - } - // Get referenced element form attribute value - , reference: function(attr) { - return SVG.get(this.attr(attr)) - } - // Returns the parent element instance - , parent: function(type) { - var parent = this - - // check for parent - if(!parent.node.parentNode) return null - - // get parent element - parent = SVG.adopt(parent.node.parentNode) - - if(!type) return parent - - // loop trough ancestors if type is given - while(parent && parent.node instanceof window.SVGElement){ - if(typeof type === 'string' ? parent.matches(type) : parent instanceof type) return parent - parent = SVG.adopt(parent.node.parentNode) - } - } - // Get parent document - , doc: function() { - return this instanceof SVG.Doc ? this : this.parent(SVG.Doc) - } - // return array of all ancestors of given type up to the root svg - , parents: function(type) { - var parents = [], parent = this - - do{ - parent = parent.parent(type) - if(!parent || !parent.node) break - - parents.push(parent) - } while(parent.parent) - - return parents - } - // matches the element vs a css selector - , matches: function(selector){ - return matches(this.node, selector) - } - // Returns the svg node to call native svg methods on it - , native: function() { - return this.node - } - // Import raw svg - , svg: function(svg) { - var well, len - - // act as a setter if svg is given - if (svg && this instanceof SVG.Parent) { - - // create temporary holder - well = document.createElementNS(SVG.ns, 'svg') - // dump raw svg - well.innerHTML = svg - - // transplant nodes - for (len = well.childNodes.length;len--;) - if(well.firstChild.nodeType != 1) - well.removeChild(well.firstChild) - else - this.node.appendChild(well.firstChild) - - // otherwise act as a getter - } else { - return this.node.outerHTML - } - - return this - } - // write svgjs data to the dom - , writeDataToDom: function() { - - // dump variables recursively - if(this.is(SVG.Parent)){ - this.each(function(){ - this.writeDataToDom() - }) - } - - // remove previously set data - this.node.removeAttribute('svgjs:data') - - if(Object.keys(this.dom).length) - this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)) // see #428 - - return this - } - // set given data to the elements data property - , setData: function(o){ - this.dom = o - return this - } - , is: function(obj){ - return is(this, obj) - } - } -}) - -SVG.easing = { - '-': function(pos){return pos} -, '<>':function(pos){return -Math.cos(pos * Math.PI) / 2 + 0.5} -, '>': function(pos){return Math.sin(pos * Math.PI / 2)} -, '<': function(pos){return -Math.cos(pos * Math.PI / 2) + 1} -} - -SVG.morph = function(pos){ - return function(from, to) { - return new SVG.MorphObj(from, to).at(pos) - } -} - -SVG.Situation = SVG.invent({ - - create: function(o){ - this.init = false - this.reversed = false - this.reversing = false - - this.duration = new SVG.Number(o.duration).valueOf() - this.delay = new SVG.Number(o.delay).valueOf() - - this.start = +new Date() + this.delay - this.finish = this.start + this.duration - this.ease = o.ease - - // this.loop is incremented from 0 to this.loops - // it is also incremented when in an infinite loop (when this.loops is true) - this.loop = 0 - this.loops = false - - this.animations = { - // functionToCall: [list of morphable objects] - // e.g. move: [SVG.Number, SVG.Number] - } - - this.attrs = { - // holds all attributes which are not represented from a function svg.js provides - // e.g. someAttr: SVG.Number - } - - this.styles = { - // holds all styles which should be animated - // e.g. fill-color: SVG.Color - } - - this.transforms = [ - // holds all transformations as transformation objects - // e.g. [SVG.Rotate, SVG.Translate, SVG.Matrix] - ] - - this.once = { - // functions to fire at a specific position - // e.g. "0.5": function foo(){} - } - - } - -}) - - -SVG.FX = SVG.invent({ - - create: function(element) { - this._target = element - this.situations = [] - this.active = false - this.situation = null - this.paused = false - this.lastPos = 0 - this.pos = 0 - // The absolute position of an animation is its position in the context of its complete duration (including delay and loops) - // When performing a delay, absPos is below 0 and when performing a loop, its value is above 1 - this.absPos = 0 - this._speed = 1 - } - -, extend: { - - /** - * sets or returns the target of this animation - * @param o object || number In case of Object it holds all parameters. In case of number its the duration of the animation - * @param ease function || string Function which should be used for easing or easing keyword - * @param delay Number indicating the delay before the animation starts - * @return target || this - */ - animate: function(o, ease, delay){ - - if(typeof o == 'object'){ - ease = o.ease - delay = o.delay - o = o.duration - } - - var situation = new SVG.Situation({ - duration: o || 1000, - delay: delay || 0, - ease: SVG.easing[ease || '-'] || ease - }) - - this.queue(situation) - - return this - } - - /** - * sets a delay before the next element of the queue is called - * @param delay Duration of delay in milliseconds - * @return this.target() - */ - , delay: function(delay){ - // The delay is performed by an empty situation with its duration - // attribute set to the duration of the delay - var situation = new SVG.Situation({ - duration: delay, - delay: 0, - ease: SVG.easing['-'] - }) - - return this.queue(situation) - } - - /** - * sets or returns the target of this animation - * @param null || target SVG.Element which should be set as new target - * @return target || this - */ - , target: function(target){ - if(target && target instanceof SVG.Element){ - this._target = target - return this - } - - return this._target - } - - // returns the absolute position at a given time - , timeToAbsPos: function(timestamp){ - return (timestamp - this.situation.start) / (this.situation.duration/this._speed) - } - - // returns the timestamp from a given absolute positon - , absPosToTime: function(absPos){ - return this.situation.duration/this._speed * absPos + this.situation.start - } - - // starts the animationloop - , startAnimFrame: function(){ - this.stopAnimFrame() - this.animationFrame = requestAnimationFrame(function(){ this.step() }.bind(this)) - } - - // cancels the animationframe - , stopAnimFrame: function(){ - cancelAnimationFrame(this.animationFrame) - } - - // kicks off the animation - only does something when the queue is currently not active and at least one situation is set - , start: function(){ - // dont start if already started - if(!this.active && this.situation){ - this.active = true - this.startCurrent() - } - - return this - } - - // start the current situation - , startCurrent: function(){ - this.situation.start = +new Date + this.situation.delay/this._speed - this.situation.finish = this.situation.start + this.situation.duration/this._speed - return this.initAnimations().step() - } - - /** - * adds a function / Situation to the animation queue - * @param fn function / situation to add - * @return this - */ - , queue: function(fn){ - if(typeof fn == 'function' || fn instanceof SVG.Situation) - this.situations.push(fn) - - if(!this.situation) this.situation = this.situations.shift() - - return this - } - - /** - * pulls next element from the queue and execute it - * @return this - */ - , dequeue: function(){ - // stop current animation - this.stop() - - // get next animation from queue - this.situation = this.situations.shift() - - if(this.situation){ - if(this.situation instanceof SVG.Situation) { - this.start() - } else { - // If it is not a SVG.Situation, then it is a function, we execute it - this.situation.call(this) - } - } - - return this - } - - // updates all animations to the current state of the element - // this is important when one property could be changed from another property - , initAnimations: function() { - var i, source - var s = this.situation - - if(s.init) return this - - for(i in s.animations){ - source = this.target()[i]() - - // The condition is because some methods return a normal number instead - // of a SVG.Number - if(s.animations[i] instanceof SVG.Number) - source = new SVG.Number(source) - - s.animations[i] = source.morph(s.animations[i]) - } - - for(i in s.attrs){ - s.attrs[i] = new SVG.MorphObj(this.target().attr(i), s.attrs[i]) - } - - for(i in s.styles){ - s.styles[i] = new SVG.MorphObj(this.target().style(i), s.styles[i]) - } - - s.initialTransformation = this.target().matrixify() - - s.init = true - return this - } - , clearQueue: function(){ - this.situations = [] - return this - } - , clearCurrent: function(){ - this.situation = null - return this - } - /** stops the animation immediately - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. - * @param clearQueue A Boolean indicating whether to remove queued animation as well. - * @return this - */ - , stop: function(jumpToEnd, clearQueue){ - var active = this.active - this.active = false - - if(clearQueue){ - this.clearQueue() - } - - if(jumpToEnd && this.situation){ - // initialize the situation if it was not - !active && this.startCurrent() - this.atEnd() - } - - this.stopAnimFrame() - - return this.clearCurrent() - } - - /** resets the element to the state where the current element has started - * @return this - */ - , reset: function(){ - if(this.situation){ - var temp = this.situation - this.stop() - this.situation = temp - this.atStart() - } - return this - } - - // Stop the currently-running animation, remove all queued animations, and complete all animations for the element. - , finish: function(){ - - this.stop(true, false) - - while(this.dequeue().situation && this.stop(true, false)); - - this.clearQueue().clearCurrent() - - return this - } - - // set the internal animation pointer at the start position, before any loops, and updates the visualisation - , atStart: function() { - return this.at(0, true) - } - - // set the internal animation pointer at the end position, after all the loops, and updates the visualisation - , atEnd: function() { - if (this.situation.loops === true) { - // If in a infinite loop, we end the current iteration - this.situation.loops = this.situation.loop + 1 - } - - if(typeof this.situation.loops == 'number') { - // If performing a finite number of loops, we go after all the loops - return this.at(this.situation.loops, true) - } else { - // If no loops, we just go at the end - return this.at(1, true) - } - } - - // set the internal animation pointer to the specified position and updates the visualisation - // if isAbsPos is true, pos is treated as an absolute position - , at: function(pos, isAbsPos){ - var durDivSpd = this.situation.duration/this._speed - - this.absPos = pos - // If pos is not an absolute position, we convert it into one - if (!isAbsPos) { - if (this.situation.reversed) this.absPos = 1 - this.absPos - this.absPos += this.situation.loop - } - - this.situation.start = +new Date - this.absPos * durDivSpd - this.situation.finish = this.situation.start + durDivSpd - - return this.step(true) - } - - /** - * sets or returns the speed of the animations - * @param speed null || Number The new speed of the animations - * @return Number || this - */ - , speed: function(speed){ - if (speed === 0) return this.pause() - - if (speed) { - this._speed = speed - // We use an absolute position here so that speed can affect the delay before the animation - return this.at(this.absPos, true) - } else return this._speed - } - - // Make loopable - , loop: function(times, reverse) { - var c = this.last() - - // store total loops - c.loops = (times != null) ? times : true - c.loop = 0 - - if(reverse) c.reversing = true - return this - } - - // pauses the animation - , pause: function(){ - this.paused = true - this.stopAnimFrame() - - return this - } - - // unpause the animation - , play: function(){ - if(!this.paused) return this - this.paused = false - // We use an absolute position here so that the delay before the animation can be paused - return this.at(this.absPos, true) - } - - /** - * toggle or set the direction of the animation - * true sets direction to backwards while false sets it to forwards - * @param reversed Boolean indicating whether to reverse the animation or not (default: toggle the reverse status) - * @return this - */ - , reverse: function(reversed){ - var c = this.last() - - if(typeof reversed == 'undefined') c.reversed = !c.reversed - else c.reversed = reversed - - return this - } - - - /** - * returns a float from 0-1 indicating the progress of the current animation - * @param eased Boolean indicating whether the returned position should be eased or not - * @return number - */ - , progress: function(easeIt){ - return easeIt ? this.situation.ease(this.pos) : this.pos - } - - /** - * adds a callback function which is called when the current animation is finished - * @param fn Function which should be executed as callback - * @return number - */ - , after: function(fn){ - var c = this.last() - , wrapper = function wrapper(e){ - if(e.detail.situation == c){ - fn.call(this, c) - this.off('finished.fx', wrapper) // prevent memory leak - } - } - - this.target().on('finished.fx', wrapper) - - return this._callStart() - } - - // adds a callback which is called whenever one animation step is performed - , during: function(fn){ - var c = this.last() - , wrapper = function(e){ - if(e.detail.situation == c){ - fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, c) - } - } - - // see above - this.target().off('during.fx', wrapper).on('during.fx', wrapper) - - this.after(function(){ - this.off('during.fx', wrapper) - }) - - return this._callStart() - } - - // calls after ALL animations in the queue are finished - , afterAll: function(fn){ - var wrapper = function wrapper(e){ - fn.call(this) - this.off('allfinished.fx', wrapper) - } - - // see above - this.target().off('allfinished.fx', wrapper).on('allfinished.fx', wrapper) - - return this._callStart() - } - - // calls on every animation step for all animations - , duringAll: function(fn){ - var wrapper = function(e){ - fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, e.detail.situation) - } - - this.target().off('during.fx', wrapper).on('during.fx', wrapper) - - this.afterAll(function(){ - this.off('during.fx', wrapper) - }) - - return this._callStart() - } - - , last: function(){ - return this.situations.length ? this.situations[this.situations.length-1] : this.situation - } - - // adds one property to the animations - , add: function(method, args, type){ - this.last()[type || 'animations'][method] = args - return this._callStart() - } - - /** perform one step of the animation - * @param ignoreTime Boolean indicating whether to ignore time and use position directly or recalculate position based on time - * @return this - */ - , step: function(ignoreTime){ - - // convert current time to an absolute position - if(!ignoreTime) this.absPos = this.timeToAbsPos(+new Date) - - // This part convert an absolute position to a position - if(this.situation.loops !== false) { - var absPos, absPosInt, lastLoop - - // If the absolute position is below 0, we just treat it as if it was 0 - absPos = Math.max(this.absPos, 0) - absPosInt = Math.floor(absPos) - - if(this.situation.loops === true || absPosInt < this.situation.loops) { - this.pos = absPos - absPosInt - lastLoop = this.situation.loop - this.situation.loop = absPosInt - } else { - this.absPos = this.situation.loops - this.pos = 1 - // The -1 here is because we don't want to toggle reversed when all the loops have been completed - lastLoop = this.situation.loop - 1 - this.situation.loop = this.situation.loops - } - - if(this.situation.reversing) { - // Toggle reversed if an odd number of loops as occured since the last call of step - this.situation.reversed = this.situation.reversed != Boolean((this.situation.loop - lastLoop) % 2) - } - - } else { - // If there are no loop, the absolute position must not be above 1 - this.absPos = Math.min(this.absPos, 1) - this.pos = this.absPos - } - - // while the absolute position can be below 0, the position must not be below 0 - if(this.pos < 0) this.pos = 0 - - if(this.situation.reversed) this.pos = 1 - this.pos - - - // apply easing - var eased = this.situation.ease(this.pos) - - // call once-callbacks - for(var i in this.situation.once){ - if(i > this.lastPos && i <= eased){ - this.situation.once[i].call(this.target(), this.pos, eased) - delete this.situation.once[i] - } - } - - // fire during callback with position, eased position and current situation as parameter - if(this.active) this.target().fire('during', {pos: this.pos, eased: eased, fx: this, situation: this.situation}) - - // the user may call stop or finish in the during callback - // so make sure that we still have a valid situation - if(!this.situation){ - return this - } - - // apply the actual animation to every property - this.eachAt() - - // do final code when situation is finished - if((this.pos == 1 && !this.situation.reversed) || (this.situation.reversed && this.pos == 0)){ - - // stop animation callback - this.stopAnimFrame() - - // fire finished callback with current situation as parameter - this.target().fire('finished', {fx:this, situation: this.situation}) - - if(!this.situations.length){ - this.target().fire('allfinished') - this.target().off('.fx') // there shouldnt be any binding left, but to make sure... - this.active = false - } - - // start next animation - if(this.active) this.dequeue() - else this.clearCurrent() - - }else if(!this.paused && this.active){ - // we continue animating when we are not at the end - this.startAnimFrame() - } - - // save last eased position for once callback triggering - this.lastPos = eased - return this - - } - - // calculates the step for every property and calls block with it - , eachAt: function(){ - var i, at, self = this, target = this.target(), s = this.situation - - // apply animations which can be called trough a method - for(i in s.animations){ - - at = [].concat(s.animations[i]).map(function(el){ - return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el - }) - - target[i].apply(target, at) - - } - - // apply animation which has to be applied with attr() - for(i in s.attrs){ - - at = [i].concat(s.attrs[i]).map(function(el){ - return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el - }) - - target.attr.apply(target, at) - - } - - // apply animation which has to be applied with style() - for(i in s.styles){ - - at = [i].concat(s.styles[i]).map(function(el){ - return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el - }) - - target.style.apply(target, at) - - } - - // animate initialTransformation which has to be chained - if(s.transforms.length){ - - // get initial initialTransformation - at = s.initialTransformation - for(i = 0, len = s.transforms.length; i < len; i++){ - - // get next transformation in chain - var a = s.transforms[i] - - // multiply matrix directly - if(a instanceof SVG.Matrix){ - - if(a.relative){ - at = at.multiply(new SVG.Matrix().morph(a).at(s.ease(this.pos))) - }else{ - at = at.morph(a).at(s.ease(this.pos)) - } - continue - } - - // when transformation is absolute we have to reset the needed transformation first - if(!a.relative) - a.undo(at.extract()) - - // and reapply it after - at = at.multiply(a.at(s.ease(this.pos))) - - } - - // set new matrix on element - target.matrix(at) - } - - return this - - } - - - // adds an once-callback which is called at a specific position and never again - , once: function(pos, fn, isEased){ - - if(!isEased)pos = this.situation.ease(pos) - - this.situation.once[pos] = fn - - return this - } - - , _callStart: function() { - setTimeout(function(){this.start()}.bind(this), 0) - return this - } - - } - -, parent: SVG.Element - - // Add method to parent elements -, construct: { - // Get fx module or create a new one, then animate with given duration and ease - animate: function(o, ease, delay) { - return (this.fx || (this.fx = new SVG.FX(this))).animate(o, ease, delay) - } - , delay: function(delay){ - return (this.fx || (this.fx = new SVG.FX(this))).delay(delay) - } - , stop: function(jumpToEnd, clearQueue) { - if (this.fx) - this.fx.stop(jumpToEnd, clearQueue) - - return this - } - , finish: function() { - if (this.fx) - this.fx.finish() - - return this - } - // Pause current animation - , pause: function() { - if (this.fx) - this.fx.pause() - - return this - } - // Play paused current animation - , play: function() { - if (this.fx) - this.fx.play() - - return this - } - // Set/Get the speed of the animations - , speed: function(speed) { - if (this.fx) - if (speed == null) - return this.fx.speed() - else - this.fx.speed(speed) - - return this - } - } - -}) - -// MorphObj is used whenever no morphable object is given -SVG.MorphObj = SVG.invent({ - - create: function(from, to){ - // prepare color for morphing - if(SVG.Color.isColor(to)) return new SVG.Color(from).morph(to) - // prepare number for morphing - if(SVG.regex.numberAndUnit.test(to)) return new SVG.Number(from).morph(to) - - // prepare for plain morphing - this.value = from - this.destination = to - } - -, extend: { - at: function(pos, real){ - return real < 1 ? this.value : this.destination - }, - - valueOf: function(){ - return this.value - } - } - -}) - -SVG.extend(SVG.FX, { - // Add animatable attributes - attr: function(a, v, relative) { - // apply attributes individually - if (typeof a == 'object') { - for (var key in a) - this.attr(key, a[key]) - - } else { - this.add(a, v, 'attrs') - } - - return this - } - // Add animatable styles -, style: function(s, v) { - if (typeof s == 'object') - for (var key in s) - this.style(key, s[key]) - - else - this.add(s, v, 'styles') - - return this - } - // Animatable x-axis -, x: function(x, relative) { - if(this.target() instanceof SVG.G){ - this.transform({x:x}, relative) - return this - } - - var num = new SVG.Number(x) - num.relative = relative - return this.add('x', num) - } - // Animatable y-axis -, y: function(y, relative) { - if(this.target() instanceof SVG.G){ - this.transform({y:y}, relative) - return this - } - - var num = new SVG.Number(y) - num.relative = relative - return this.add('y', num) - } - // Animatable center x-axis -, cx: function(x) { - return this.add('cx', new SVG.Number(x)) - } - // Animatable center y-axis -, cy: function(y) { - return this.add('cy', new SVG.Number(y)) - } - // Add animatable move -, move: function(x, y) { - return this.x(x).y(y) - } - // Add animatable center -, center: function(x, y) { - return this.cx(x).cy(y) - } - // Add animatable size -, size: function(width, height) { - if (this.target() instanceof SVG.Text) { - // animate font size for Text elements - this.attr('font-size', width) - - } else { - // animate bbox based size for all other elements - var box - - if(!width || !height){ - box = this.target().bbox() - } - - if(!width){ - width = box.width / box.height * height - } - - if(!height){ - height = box.height / box.width * width - } - - this.add('width' , new SVG.Number(width)) - .add('height', new SVG.Number(height)) - - } - - return this - } - // Add animatable plot -, plot: function() { - // We use arguments here since SVG.Line's plot method can be passed 4 parameters - return this.add('plot', arguments.length > 1 ? [].slice.call(arguments) : arguments[0]) - } - // Add leading method -, leading: function(value) { - return this.target().leading ? - this.add('leading', new SVG.Number(value)) : - this - } - // Add animatable viewbox -, viewbox: function(x, y, width, height) { - if (this.target() instanceof SVG.Container) { - this.add('viewbox', new SVG.Box(x, y, width, height)) - } - - return this - } -, update: function(o) { - if (this.target() instanceof SVG.Stop) { - if (typeof o == 'number' || o instanceof SVG.Number) { - return this.update({ - offset: arguments[0] - , color: arguments[1] - , opacity: arguments[2] - }) - } - - if (o.opacity != null) this.attr('stop-opacity', o.opacity) - if (o.color != null) this.attr('stop-color', o.color) - if (o.offset != null) this.attr('offset', o.offset) - } - - return this - } -}) - -SVG.Matrix = SVG.invent({ - // Initialize - create: function(source) { - var i, base = arrayToMatrix([1, 0, 0, 1, 0, 0]) - - // ensure source as object - source = source instanceof SVG.Element ? - source.matrixify() : - typeof source === 'string' ? - arrayToMatrix(source.split(SVG.regex.delimiter).map(parseFloat)) : - arguments.length == 6 ? - arrayToMatrix([].slice.call(arguments)) : - Array.isArray(source) ? - arrayToMatrix(source) : - typeof source === 'object' ? - source : base - - // merge source - for (i = abcdef.length - 1; i >= 0; --i) - this[abcdef[i]] = source && typeof source[abcdef[i]] === 'number' ? - source[abcdef[i]] : base[abcdef[i]] - } - - // Add methods -, extend: { - // Extract individual transformations - extract: function() { - // find delta transform points - var px = deltaTransformPoint(this, 0, 1) - , py = deltaTransformPoint(this, 1, 0) - , skewX = 180 / Math.PI * Math.atan2(px.y, px.x) - 90 - - return { - // translation - x: this.e - , y: this.f - , transformedX:(this.e * Math.cos(skewX * Math.PI / 180) + this.f * Math.sin(skewX * Math.PI / 180)) / Math.sqrt(this.a * this.a + this.b * this.b) - , transformedY:(this.f * Math.cos(skewX * Math.PI / 180) + this.e * Math.sin(-skewX * Math.PI / 180)) / Math.sqrt(this.c * this.c + this.d * this.d) - // skew - , skewX: -skewX - , skewY: 180 / Math.PI * Math.atan2(py.y, py.x) - // scale - , scaleX: Math.sqrt(this.a * this.a + this.b * this.b) - , scaleY: Math.sqrt(this.c * this.c + this.d * this.d) - // rotation - , rotation: skewX - , a: this.a - , b: this.b - , c: this.c - , d: this.d - , e: this.e - , f: this.f - , matrix: new SVG.Matrix(this) - } - } - // Clone matrix - , clone: function() { - return new SVG.Matrix(this) - } - // Morph one matrix into another - , morph: function(matrix) { - // store new destination - this.destination = new SVG.Matrix(matrix) - - return this - } - // Get morphed matrix at a given position - , at: function(pos) { - // make sure a destination is defined - if (!this.destination) return this - - // calculate morphed matrix at a given position - var matrix = new SVG.Matrix({ - a: this.a + (this.destination.a - this.a) * pos - , b: this.b + (this.destination.b - this.b) * pos - , c: this.c + (this.destination.c - this.c) * pos - , d: this.d + (this.destination.d - this.d) * pos - , e: this.e + (this.destination.e - this.e) * pos - , f: this.f + (this.destination.f - this.f) * pos - }) - - return matrix - } - // Multiplies by given matrix - , multiply: function(matrix) { - return new SVG.Matrix(this.native().multiply(parseMatrix(matrix).native())) - } - // Inverses matrix - , inverse: function() { - return new SVG.Matrix(this.native().inverse()) - } - // Translate matrix - , translate: function(x, y) { - return new SVG.Matrix(this.native().translate(x || 0, y || 0)) - } - // Scale matrix - , scale: function(x, y, cx, cy) { - // support uniformal scale - if (arguments.length == 1) { - y = x - } else if (arguments.length == 3) { - cy = cx - cx = y - y = x - } - - return this.around(cx, cy, new SVG.Matrix(x, 0, 0, y, 0, 0)) - } - // Rotate matrix - , rotate: function(r, cx, cy) { - // convert degrees to radians - r = SVG.utils.radians(r) - - return this.around(cx, cy, new SVG.Matrix(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0)) - } - // Flip matrix on x or y, at a given offset - , flip: function(a, o) { - o = typeof a == 'number' ? a : o - return a == 'x' ? - this.scale(-1, 1, o, 0) : - a == 'y' ? - this.scale(1, -1, 0, o) : - this.scale(-1, -1, o, o) - } - // Skew - , skew: function(x, y, cx, cy) { - // support uniformal skew - if (arguments.length == 1) { - y = x - } else if (arguments.length == 3) { - cy = cx - cx = y - y = x - } - - // convert degrees to radians - x = SVG.utils.radians(x) - y = SVG.utils.radians(y) - - return this.around(cx, cy, new SVG.Matrix(1, Math.tan(y), Math.tan(x), 1, 0, 0)) - } - // SkewX - , skewX: function(x, cx, cy) { - return this.skew(x, 0, cx, cy) - } - // SkewY - , skewY: function(y, cx, cy) { - return this.skew(0, y, cx, cy) - } - // Transform around a center point - , around: function(cx, cy, matrix) { - return this - .multiply(new SVG.Matrix(1, 0, 0, 1, cx || 0, cy || 0)) - .multiply(matrix) - .multiply(new SVG.Matrix(1, 0, 0, 1, -cx || 0, -cy || 0)) - } - // Convert to native SVGMatrix - , native: function() { - // create new matrix - var matrix = SVG.parser.native.createSVGMatrix() - - // update with current values - for (var i = abcdef.length - 1; i >= 0; i--) - matrix[abcdef[i]] = this[abcdef[i]] - - return matrix - } - // Convert matrix to string - , toString: function() { - return 'matrix(' + this.a + ',' + this.b + ',' + this.c + ',' + this.d + ',' + this.e + ',' + this.f + ')' - } - } - - // Define parent -, parent: SVG.Element - - // Add parent method -, construct: { - // Get current matrix - ctm: function() { - return new SVG.Matrix(this.node.getCTM()) - }, - // Get current screen matrix - screenCTM: function() { - /* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537 - This is needed because FF does not return the transformation matrix - for the inner coordinate system when getScreenCTM() is called on nested svgs. - However all other Browsers do that */ - if(this instanceof SVG.Nested) { - var rect = this.rect(1,1) - var m = rect.node.getScreenCTM() - rect.remove() - return new SVG.Matrix(m) - } - return new SVG.Matrix(this.node.getScreenCTM()) - } - - } - -}) - -SVG.Point = SVG.invent({ - // Initialize - create: function(x,y) { - var i, source, base = {x:0, y:0} - - // ensure source as object - source = Array.isArray(x) ? - {x:x[0], y:x[1]} : - typeof x === 'object' ? - {x:x.x, y:x.y} : - x != null ? - {x:x, y:(y != null ? y : x)} : base // If y has no value, then x is used has its value - - // merge source - this.x = source.x - this.y = source.y - } - - // Add methods -, extend: { - // Clone point - clone: function() { - return new SVG.Point(this) - } - // Morph one point into another - , morph: function(x, y) { - // store new destination - this.destination = new SVG.Point(x, y) - - return this - } - // Get morphed point at a given position - , at: function(pos) { - // make sure a destination is defined - if (!this.destination) return this - - // calculate morphed matrix at a given position - var point = new SVG.Point({ - x: this.x + (this.destination.x - this.x) * pos - , y: this.y + (this.destination.y - this.y) * pos - }) - - return point - } - // Convert to native SVGPoint - , native: function() { - // create new point - var point = SVG.parser.native.createSVGPoint() - - // update with current values - point.x = this.x - point.y = this.y - - return point - } - // transform point with matrix - , transform: function(matrix) { - return new SVG.Point(this.native().matrixTransform(matrix.native())) - } - - } - -}) - -SVG.extend(SVG.Element, { - - // Get point - point: function(x, y) { - return new SVG.Point(x,y).transform(this.screenCTM().inverse()); - } - -}) - -SVG.extend(SVG.Element, { - // Set svg element attribute - attr: function(a, v, n) { - // act as full getter - if (a == null) { - // get an object of attributes - a = {} - v = this.node.attributes - for (n = v.length - 1; n >= 0; n--) - a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue) ? parseFloat(v[n].nodeValue) : v[n].nodeValue - - return a - - } else if (typeof a == 'object') { - // apply every attribute individually if an object is passed - for (v in a) this.attr(v, a[v]) - - } else if (v === null) { - // remove value - this.node.removeAttribute(a) - - } else if (v == null) { - // act as a getter if the first and only argument is not an object - v = this.node.getAttribute(a) - return v == null ? - SVG.defaults.attrs[a] : - SVG.regex.isNumber.test(v) ? - parseFloat(v) : v - - } else { - - // convert image fill and stroke to patterns - if (a == 'fill' || a == 'stroke') { - if (SVG.regex.isImage.test(v)) - v = this.doc().defs().image(v) - - if (v instanceof SVG.Image) - v = this.doc().defs().pattern(0, 0, function() { - this.add(v) - }) - } - - // ensure correct numeric values (also accepts NaN and Infinity) - if (typeof v === 'number') - v = new SVG.Number(v) - - // ensure full hex color - else if (SVG.Color.isColor(v)) - v = new SVG.Color(v) - - // parse array values - else if (Array.isArray(v)) - v = new SVG.Array(v) - - // if the passed attribute is leading... - if (a == 'leading') { - // ... call the leading method instead - if (this.leading) - this.leading(v) - } else { - // set given attribute on node - typeof n === 'string' ? - this.node.setAttributeNS(n, a, v.toString()) : - this.node.setAttribute(a, v.toString()) - } - - // rebuild if required - if (this.rebuild && (a == 'font-size' || a == 'x')) - this.rebuild(a, v) - } - - return this - } -}) -SVG.extend(SVG.Element, { - // Add transformations - transform: function(o, relative) { - // get target in case of the fx module, otherwise reference this - var target = this - , matrix - - // act as a getter - if (typeof o !== 'object') { - // get current matrix - matrix = new SVG.Matrix(target).extract() - - return typeof o === 'string' ? matrix[o] : matrix - } - - // get current matrix - matrix = new SVG.Matrix(target) - - // ensure relative flag - relative = !!relative || !!o.relative - - // act on matrix - if (o.a != null) { - matrix = relative ? - // relative - matrix.multiply(new SVG.Matrix(o)) : - // absolute - new SVG.Matrix(o) - - // act on rotation - } else if (o.rotation != null) { - // ensure centre point - ensureCentre(o, target) - - // apply transformation - matrix = relative ? - // relative - matrix.rotate(o.rotation, o.cx, o.cy) : - // absolute - matrix.rotate(o.rotation - matrix.extract().rotation, o.cx, o.cy) - - // act on scale - } else if (o.scale != null || o.scaleX != null || o.scaleY != null) { - // ensure centre point - ensureCentre(o, target) - - // ensure scale values on both axes - o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1 - o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1 - - if (!relative) { - // absolute; multiply inversed values - var e = matrix.extract() - o.scaleX = o.scaleX * 1 / e.scaleX - o.scaleY = o.scaleY * 1 / e.scaleY - } - - matrix = matrix.scale(o.scaleX, o.scaleY, o.cx, o.cy) - - // act on skew - } else if (o.skew != null || o.skewX != null || o.skewY != null) { - // ensure centre point - ensureCentre(o, target) - - // ensure skew values on both axes - o.skewX = o.skew != null ? o.skew : o.skewX != null ? o.skewX : 0 - o.skewY = o.skew != null ? o.skew : o.skewY != null ? o.skewY : 0 - - if (!relative) { - // absolute; reset skew values - var e = matrix.extract() - matrix = matrix.multiply(new SVG.Matrix().skew(e.skewX, e.skewY, o.cx, o.cy).inverse()) - } - - matrix = matrix.skew(o.skewX, o.skewY, o.cx, o.cy) - - // act on flip - } else if (o.flip) { - matrix = matrix.flip( - o.flip - , o.offset == null ? target.bbox()['c' + o.flip] : o.offset - ) - - // act on translate - } else if (o.x != null || o.y != null) { - if (relative) { - // relative - matrix = matrix.translate(o.x, o.y) - } else { - // absolute - if (o.x != null) matrix.e = o.x - if (o.y != null) matrix.f = o.y - } - } - - return this.attr('transform', matrix) - } -}) - -SVG.extend(SVG.FX, { - transform: function(o, relative) { - // get target in case of the fx module, otherwise reference this - var target = this.target() - , matrix - - // act as a getter - if (typeof o !== 'object') { - // get current matrix - matrix = new SVG.Matrix(target).extract() - - return typeof o === 'string' ? matrix[o] : matrix - } - - // ensure relative flag - relative = !!relative || !!o.relative - - // act on matrix - if (o.a != null) { - matrix = new SVG.Matrix(o) - - // act on rotation - } else if (o.rotation != null) { - // ensure centre point - ensureCentre(o, target) - - // apply transformation - matrix = new SVG.Rotate(o.rotation, o.cx, o.cy) - - // act on scale - } else if (o.scale != null || o.scaleX != null || o.scaleY != null) { - // ensure centre point - ensureCentre(o, target) - - // ensure scale values on both axes - o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1 - o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1 - - matrix = new SVG.Scale(o.scaleX, o.scaleY, o.cx, o.cy) - - // act on skew - } else if (o.skewX != null || o.skewY != null) { - // ensure centre point - ensureCentre(o, target) - - // ensure skew values on both axes - o.skewX = o.skewX != null ? o.skewX : 0 - o.skewY = o.skewY != null ? o.skewY : 0 - - matrix = new SVG.Skew(o.skewX, o.skewY, o.cx, o.cy) - - // act on flip - } else if (o.flip) { - matrix = new SVG.Matrix().flip( - o.flip - , o.offset == null ? target.bbox()['c' + o.flip] : o.offset - ) - - // act on translate - } else if (o.x != null || o.y != null) { - matrix = new SVG.Translate(o.x, o.y) - } - - if(!matrix) return this - - matrix.relative = relative - - this.last().transforms.push(matrix) - - return this._callStart() - } -}) - -SVG.extend(SVG.Element, { - // Reset all transformations - untransform: function() { - return this.attr('transform', null) - }, - // merge the whole transformation chain into one matrix and returns it - matrixify: function() { - - var matrix = (this.attr('transform') || '') - // split transformations - .split(SVG.regex.transforms).slice(0,-1).map(function(str){ - // generate key => value pairs - var kv = str.trim().split('(') - return [kv[0], kv[1].split(SVG.regex.delimiter).map(function(str){ return parseFloat(str) })] - }) - // merge every transformation into one matrix - .reduce(function(matrix, transform){ - - if(transform[0] == 'matrix') return matrix.multiply(arrayToMatrix(transform[1])) - return matrix[transform[0]].apply(matrix, transform[1]) - - }, new SVG.Matrix()) - - return matrix - }, - // add an element to another parent without changing the visual representation on the screen - toParent: function(parent) { - if(this == parent) return this - var ctm = this.screenCTM() - var pCtm = parent.screenCTM().inverse() - - this.addTo(parent).untransform().transform(pCtm.multiply(ctm)) - - return this - }, - // same as above with parent equals root-svg - toDoc: function() { - return this.toParent(this.doc()) - } - -}) - -SVG.Transformation = SVG.invent({ - - create: function(source, inversed){ - - if(arguments.length > 1 && typeof inversed != 'boolean'){ - return this.constructor.call(this, [].slice.call(arguments)) - } - - if(Array.isArray(source)){ - for(var i = 0, len = this.arguments.length; i < len; ++i){ - this[this.arguments[i]] = source[i] - } - } else if(typeof source == 'object'){ - for(var i = 0, len = this.arguments.length; i < len; ++i){ - this[this.arguments[i]] = source[this.arguments[i]] - } - } - - this.inversed = false - - if(inversed === true){ - this.inversed = true - } - - } - -, extend: { - - arguments: [] - , method: '' - - , at: function(pos){ - - var params = [] - - for(var i = 0, len = this.arguments.length; i < len; ++i){ - params.push(this[this.arguments[i]]) - } - - var m = this._undo || new SVG.Matrix() - - m = new SVG.Matrix().morph(SVG.Matrix.prototype[this.method].apply(m, params)).at(pos) - - return this.inversed ? m.inverse() : m - - } - - , undo: function(o){ - for(var i = 0, len = this.arguments.length; i < len; ++i){ - o[this.arguments[i]] = typeof this[this.arguments[i]] == 'undefined' ? 0 : o[this.arguments[i]] - } - - // The method SVG.Matrix.extract which was used before calling this - // method to obtain a value for the parameter o doesn't return a cx and - // a cy so we use the ones that were provided to this object at its creation - o.cx = this.cx - o.cy = this.cy - - this._undo = new SVG[capitalize(this.method)](o, true).at(1) - - return this - } - - } - -}) - -SVG.Translate = SVG.invent({ - - parent: SVG.Matrix -, inherit: SVG.Transformation - -, create: function(source, inversed){ - this.constructor.apply(this, [].slice.call(arguments)) - } - -, extend: { - arguments: ['transformedX', 'transformedY'] - , method: 'translate' - } - -}) - -SVG.Rotate = SVG.invent({ - - parent: SVG.Matrix -, inherit: SVG.Transformation - -, create: function(source, inversed){ - this.constructor.apply(this, [].slice.call(arguments)) - } - -, extend: { - arguments: ['rotation', 'cx', 'cy'] - , method: 'rotate' - , at: function(pos){ - var m = new SVG.Matrix().rotate(new SVG.Number().morph(this.rotation - (this._undo ? this._undo.rotation : 0)).at(pos), this.cx, this.cy) - return this.inversed ? m.inverse() : m - } - , undo: function(o){ - this._undo = o - } - } - -}) - -SVG.Scale = SVG.invent({ - - parent: SVG.Matrix -, inherit: SVG.Transformation - -, create: function(source, inversed){ - this.constructor.apply(this, [].slice.call(arguments)) - } - -, extend: { - arguments: ['scaleX', 'scaleY', 'cx', 'cy'] - , method: 'scale' - } - -}) - -SVG.Skew = SVG.invent({ - - parent: SVG.Matrix -, inherit: SVG.Transformation - -, create: function(source, inversed){ - this.constructor.apply(this, [].slice.call(arguments)) - } - -, extend: { - arguments: ['skewX', 'skewY', 'cx', 'cy'] - , method: 'skew' - } - -}) - -SVG.extend(SVG.Element, { - // Dynamic style generator - style: function(s, v) { - if (arguments.length == 0) { - // get full style - return this.node.style.cssText || '' - - } else if (arguments.length < 2) { - // apply every style individually if an object is passed - if (typeof s == 'object') { - for (v in s) this.style(v, s[v]) - - } else { - // act as a getter if the first and only argument is not an object - return this.node.style[camelCase(s)] - } - - } else { - this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v - } - - return this - } -}) - -SVG.Parent = SVG.invent({ - // Initialize node - create: function(element) { - this.constructor.call(this, element) - } - - // Inherit from -, inherit: SVG.Element - - // Add class methods -, extend: { - // Returns all child elements - children: function() { - return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) { - return SVG.adopt(node) - }) - } - // Add given element at a position - , add: function(element, i) { - if (i == null) - this.node.appendChild(element.node) - else if (element.node != this.node.childNodes[i]) - this.node.insertBefore(element.node, this.node.childNodes[i]) - - return this - } - // Basically does the same as `add()` but returns the added element instead - , put: function(element, i) { - this.add(element, i) - return element - } - // Checks if the given element is a child - , has: function(element) { - return this.index(element) >= 0 - } - // Gets index of given element - , index: function(element) { - return [].slice.call(this.node.childNodes).indexOf(element.node) - } - // Get a element at the given index - , get: function(i) { - return SVG.adopt(this.node.childNodes[i]) - } - // Get first child - , first: function() { - return this.get(0) - } - // Get the last child - , last: function() { - return this.get(this.node.childNodes.length - 1) - } - // Iterates over all children and invokes a given block - , each: function(block, deep) { - var i, il - , children = this.children() - - for (i = 0, il = children.length; i < il; i++) { - if (children[i] instanceof SVG.Element) - block.apply(children[i], [i, children]) - - if (deep && (children[i] instanceof SVG.Container)) - children[i].each(block, deep) - } - - return this - } - // Remove a given child - , removeElement: function(element) { - this.node.removeChild(element.node) - - return this - } - // Remove all elements in this container - , clear: function() { - // remove children - while(this.node.hasChildNodes()) - this.node.removeChild(this.node.lastChild) - - // remove defs reference - delete this._defs - - return this - } - , // Get defs - defs: function() { - return this.doc().defs() - } - } - -}) - -SVG.extend(SVG.Parent, { - flatten: function(parent) { - if(this instanceof SVG.Defs) return this - - parent = parent || (this instanceof SVG.Doc ? this : this.parent(SVG.Parent)) - - this.each(function(){ - if(this instanceof SVG.Defs) return this - if(this instanceof SVG.Parent) return this.flatten(parent) - return this.toParent(parent) - }) - - // we need this so that SVG.Doc does not get removed - this.node.firstChild || this.remove() - - return this - } -}) - -SVG.Container = SVG.invent({ - // Initialize node - create: function(element) { - this.constructor.call(this, element) - } - - // Inherit from -, inherit: SVG.Parent - -}) -// Add events to elements -;[ 'click' - , 'dblclick' - , 'mousedown' - , 'mouseup' - , 'mouseover' - , 'mouseout' - , 'mousemove' - // , 'mouseenter' -> not supported by IE - // , 'mouseleave' -> not supported by IE - , 'touchstart' - , 'touchmove' - , 'touchleave' - , 'touchend' - , 'touchcancel' ].forEach(function(event) { - - // add event to SVG.Element - SVG.Element.prototype[event] = function(f) { - var self = this - - // bind event to element rather than element node - this.node['on' + event] = typeof f == 'function' ? - function() { return f.apply(self, arguments) } : null - - return this - } - -}) - -// Initialize listeners stack -SVG.listeners = [] -SVG.handlerMap = [] -SVG.listenerId = 0 - -// Add event binder in the SVG namespace -SVG.on = function(node, event, listener, binding) { - // create listener, get object-index - var l = listener.bind(binding || node.instance || node) - , index = (SVG.handlerMap.indexOf(node) + 1 || SVG.handlerMap.push(node)) - 1 - , ev = event.split('.')[0] - , ns = event.split('.')[1] || '*' - - - // ensure valid object - SVG.listeners[index] = SVG.listeners[index] || {} - SVG.listeners[index][ev] = SVG.listeners[index][ev] || {} - SVG.listeners[index][ev][ns] = SVG.listeners[index][ev][ns] || {} - - if(!listener._svgjsListenerId) - listener._svgjsListenerId = ++SVG.listenerId - - // reference listener - SVG.listeners[index][ev][ns][listener._svgjsListenerId] = l - - // add listener - node.addEventListener(ev, l, false) +
+SVG.defaults = {
+ // Default attribute values
+ attrs: {
+ // fill and stroke
+ 'fill-opacity': 1
+ , 'stroke-opacity': 1
+ , 'stroke-width': 0
+ , 'stroke-linejoin': 'miter'
+ , 'stroke-linecap': 'butt'
+ , fill: '#000000'
+ , stroke: '#000000'
+ , opacity: 1
+ // position
+ , x: 0
+ , y: 0
+ , cx: 0
+ , cy: 0
+ // size
+ , width: 0
+ , height: 0
+ // radius
+ , r: 0
+ , rx: 0
+ , ry: 0
+ // gradient
+ , offset: 0
+ , 'stop-opacity': 1
+ , 'stop-color': '#000000'
+ // text
+ , 'font-size': 16
+ , 'font-family': 'Helvetica, Arial, sans-serif'
+ , 'text-anchor': 'start'
+ }
+
} - -// Add event unbinder in the SVG namespace -SVG.off = function(node, event, listener) { - var index = SVG.handlerMap.indexOf(node) - , ev = event && event.split('.')[0] - , ns = event && event.split('.')[1] - - if(index == -1) return - - if (listener) { - if(typeof listener == 'function') listener = listener._svgjsListenerId - if(!listener) return - - // remove listener reference - if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns || '*']) { - // remove listener - node.removeEventListener(ev, SVG.listeners[index][ev][ns || '*'][listener], false) - - delete SVG.listeners[index][ev][ns || '*'][listener] - } - - } else if (ns && ev) { - // remove all listeners for a namespaced event - if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns]) { - for (listener in SVG.listeners[index][ev][ns]) - SVG.off(node, [ev, ns].join('.'), listener) - - delete SVG.listeners[index][ev][ns] - } - - } else if (ns){ - // remove all listeners for a specific namespace - for(event in SVG.listeners[index]){ - for(namespace in SVG.listeners[index][event]){ - if(ns === namespace){ - SVG.off(node, [event, ns].join('.')) - } - } - } - - } else if (ev) { - // remove all listeners for the event - if (SVG.listeners[index][ev]) { - for (namespace in SVG.listeners[index][ev]) - SVG.off(node, [ev, namespace].join('.')) - - delete SVG.listeners[index][ev] - } - - } else { - // remove all listeners on a given node - for (event in SVG.listeners[index]) - SVG.off(node, event) - - delete SVG.listeners[index] - delete SVG.handlerMap[index] - - } +// Module for color convertions
+SVG.Color = function(color) {
+ var match
+
+ // initialize defaults
+ this.r = 0
+ this.g = 0
+ this.b = 0
+
+ if(!color) return
+
+ // parse color
+ if (typeof color === 'string') {
+ if (SVG.regex.isRgb.test(color)) {
+ // get rgb values
+ match = SVG.regex.rgb.exec(color.replace(SVG.regex.whitespace,''))
+
+ // parse numeric values
+ this.r = parseInt(match[1])
+ this.g = parseInt(match[2])
+ this.b = parseInt(match[3])
+
+ } else if (SVG.regex.isHex.test(color)) {
+ // get hex values
+ match = SVG.regex.hex.exec(fullHex(color))
+
+ // parse numeric values
+ this.r = parseInt(match[1], 16)
+ this.g = parseInt(match[2], 16)
+ this.b = parseInt(match[3], 16)
+
+ }
+
+ } else if (typeof color === 'object') {
+ this.r = color.r
+ this.g = color.g
+ this.b = color.b
+
+ }
+
+}
+
+SVG.extend(SVG.Color, {
+ // Default to hex conversion
+ toString: function() {
+ return this.toHex()
+ }
+ // Build hex value
+, toHex: function() {
+ return '#'
+ + compToHex(this.r)
+ + compToHex(this.g)
+ + compToHex(this.b)
+ }
+ // Build rgb value
+, toRgb: function() {
+ return 'rgb(' + [this.r, this.g, this.b].join() + ')'
+ }
+ // Calculate true brightness
+, brightness: function() {
+ return (this.r / 255 * 0.30)
+ + (this.g / 255 * 0.59)
+ + (this.b / 255 * 0.11)
+ }
+ // Make color morphable
+, morph: function(color) {
+ this.destination = new SVG.Color(color)
+
+ return this
+ }
+ // Get morphed color at given position
+, at: function(pos) {
+ // make sure a destination is defined
+ if (!this.destination) return this
+
+ // normalise pos
+ pos = pos < 0 ? 0 : pos > 1 ? 1 : pos
+
+ // generate morphed color
+ return new SVG.Color({
+ r: ~~(this.r + (this.destination.r - this.r) * pos)
+ , g: ~~(this.g + (this.destination.g - this.g) * pos)
+ , b: ~~(this.b + (this.destination.b - this.b) * pos)
+ })
+ }
+
+})
+
+// Testers
+
+// Test if given value is a color string
+SVG.Color.test = function(color) {
+ color += ''
+ return SVG.regex.isHex.test(color)
+ || SVG.regex.isRgb.test(color)
+}
+
+// Test if given value is a rgb object
+SVG.Color.isRgb = function(color) {
+ return color && typeof color.r == 'number'
+ && typeof color.g == 'number'
+ && typeof color.b == 'number'
+}
+
+// Test if given value is a color
+SVG.Color.isColor = function(color) {
+ return SVG.Color.isRgb(color) || SVG.Color.test(color)
} - -// -SVG.extend(SVG.Element, { - // Bind given event to listener - on: function(event, listener, binding) { - SVG.on(this.node, event, listener, binding) - - return this - } - // Unbind event from listener -, off: function(event, listener) { - SVG.off(this.node, event, listener) - - return this - } - // Fire given event -, fire: function(event, data) { - - // Dispatch event - if(event instanceof window.Event){ - this.node.dispatchEvent(event) - }else{ - this.node.dispatchEvent(event = new window.CustomEvent(event, {detail:data, cancelable: true})) - } - - this._event = event - return this - } -, event: function() { - return this._event - } -}) - -SVG.Defs = SVG.invent({ - // Initialize node - create: 'defs' - - // Inherit from -, inherit: SVG.Container - -}) -SVG.G = SVG.invent({ - // Initialize node - create: 'g' - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Move over x-axis - x: function(x) { - return x == null ? this.transform('x') : this.transform({ x: x - this.x() }, true) - } - // Move over y-axis - , y: function(y) { - return y == null ? this.transform('y') : this.transform({ y: y - this.y() }, true) - } - // Move by center over x-axis - , cx: function(x) { - return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2) - } - // Move by center over y-axis - , cy: function(y) { - return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2) - } - , gbox: function() { - - var bbox = this.bbox() - , trans = this.transform() - - bbox.x += trans.x - bbox.x2 += trans.x - bbox.cx += trans.x - - bbox.y += trans.y - bbox.y2 += trans.y - bbox.cy += trans.y - - return bbox - } - } - - // Add parent method -, construct: { - // Create a group element - group: function() { - return this.put(new SVG.G) - } - } -}) - -// ### This module adds backward / forward functionality to elements. - -// -SVG.extend(SVG.Element, { - // Get all siblings, including myself - siblings: function() { - return this.parent().children() - } - // Get the curent position siblings -, position: function() { - return this.parent().index(this) - } - // Get the next element (will return null if there is none) -, next: function() { - return this.siblings()[this.position() + 1] - } - // Get the next element (will return null if there is none) -, previous: function() { - return this.siblings()[this.position() - 1] - } - // Send given element one step forward -, forward: function() { - var i = this.position() + 1 - , p = this.parent() - - // move node one step forward - p.removeElement(this).add(this, i) - - // make sure defs node is always at the top - if (p instanceof SVG.Doc) - p.node.appendChild(p.defs().node) - - return this - } - // Send given element one step backward -, backward: function() { - var i = this.position() - - if (i > 0) - this.parent().removeElement(this).add(this, i - 1) - - return this - } - // Send given element all the way to the front -, front: function() { - var p = this.parent() - - // Move node forward - p.node.appendChild(this.node) - - // Make sure defs node is always at the top - if (p instanceof SVG.Doc) - p.node.appendChild(p.defs().node) - - return this - } - // Send given element all the way to the back -, back: function() { - if (this.position() > 0) - this.parent().removeElement(this).add(this, 0) - - return this - } - // Inserts a given element before the targeted element -, before: function(element) { - element.remove() - - var i = this.position() - - this.parent().add(element, i) - - return this - } - // Insters a given element after the targeted element -, after: function(element) { - element.remove() - - var i = this.position() - - this.parent().add(element, i + 1) - - return this - } - -}) -SVG.Mask = SVG.invent({ - // Initialize node - create: 'mask' - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Unmask all masked elements and remove itself - remove: function() { - // unmask all targets - this.targets().forEach(function(el) { - el.unmask() - }) - - // remove mask from parent - return SVG.Element.prototype.remove.call(this) - } - - , targets: function() { - return SVG.select('svg [mask*="' +this.id() +'"]') - } - } - - // Add parent method -, construct: { - // Create masking element - mask: function() { - return this.defs().put(new SVG.Mask) - } - } -}) - - -SVG.extend(SVG.Element, { - // Distribute mask to svg element - maskWith: function(element) { - // use given mask or create a new one - var masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element) - - // apply mask - return this.attr('mask', 'url("#' + masker.attr('id') + '")') - } - // Unmask element -, unmask: function() { - return this.attr('mask', null) - } -, masker: function() { - return this.reference('mask') - } -}) - -SVG.ClipPath = SVG.invent({ - // Initialize node - create: 'clipPath' - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Unclip all clipped elements and remove itself - remove: function() { - // unclip all targets - this.targets().forEach(function(el) { - el.unclip() - }) - - // remove clipPath from parent - return SVG.Element.prototype.remove.call(this) - } - - , targets: function() { - return SVG.select('svg [clip-path*="' +this.id() +'"]') - } - } - - // Add parent method -, construct: { - // Create clipping element - clip: function() { - return this.defs().put(new SVG.ClipPath) - } - } -}) - -// -SVG.extend(SVG.Element, { - // Distribute clipPath to svg element - clipWith: function(element) { - // use given clip or create a new one - var clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element) - - // apply mask - return this.attr('clip-path', 'url("#' + clipper.attr('id') + '")') - } - // Unclip element -, unclip: function() { - return this.attr('clip-path', null) - } -, clipper: function() { - return this.reference('clip-path') - } - -}) -SVG.Gradient = SVG.invent({ - // Initialize node - create: function(type) { - this.constructor.call(this, SVG.create(type + 'Gradient')) - } - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Add a color stop - at: function(offset, color, opacity) { - return this.put(new SVG.Stop).update(offset, color, opacity) - } - // Update gradient - , update: function(block) { - // remove all stops - this.clear() - - // invoke passed block - if (typeof block == 'function') - block.call(this, this) - - return this - } - // Return the fill id - , fill: function() { - return 'url(#' + this.id() + ')' - } - // Alias string convertion to fill - , toString: function() { - return this.fill() - } - // custom attr to handle transform - , attr: function(a, b, c) { - if(a == 'transform') a = 'gradientTransform' - return SVG.Container.prototype.attr.call(this, a, b, c) - } - } - - // Add parent method -, construct: { - // Create gradient element in defs - gradient: function(type, block) { - return this.defs().gradient(type, block) - } - } -}) - -// Add animatable methods to both gradient and fx module -SVG.extend(SVG.Gradient, SVG.FX, { - // From position - from: function(x, y) { - return (this._target || this).type == 'radialGradient' ? - this.attr({ fx: new SVG.Number(x), fy: new SVG.Number(y) }) : - this.attr({ x1: new SVG.Number(x), y1: new SVG.Number(y) }) - } - // To position -, to: function(x, y) { - return (this._target || this).type == 'radialGradient' ? - this.attr({ cx: new SVG.Number(x), cy: new SVG.Number(y) }) : - this.attr({ x2: new SVG.Number(x), y2: new SVG.Number(y) }) - } -}) - -// Base gradient generation -SVG.extend(SVG.Defs, { - // define gradient - gradient: function(type, block) { - return this.put(new SVG.Gradient(type)).update(block) - } - -}) - -SVG.Stop = SVG.invent({ - // Initialize node - create: 'stop' - - // Inherit from -, inherit: SVG.Element - - // Add class methods -, extend: { - // add color stops - update: function(o) { - if (typeof o == 'number' || o instanceof SVG.Number) { - o = { - offset: arguments[0] - , color: arguments[1] - , opacity: arguments[2] - } - } - - // set attributes - if (o.opacity != null) this.attr('stop-opacity', o.opacity) - if (o.color != null) this.attr('stop-color', o.color) - if (o.offset != null) this.attr('offset', new SVG.Number(o.offset)) - - return this - } - } - -}) - -SVG.Pattern = SVG.invent({ - // Initialize node - create: 'pattern' - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Return the fill id - fill: function() { - return 'url(#' + this.id() + ')' - } - // Update pattern by rebuilding - , update: function(block) { - // remove content - this.clear() - - // invoke passed block - if (typeof block == 'function') - block.call(this, this) - - return this - } - // Alias string convertion to fill - , toString: function() { - return this.fill() - } - // custom attr to handle transform - , attr: function(a, b, c) { - if(a == 'transform') a = 'patternTransform' - return SVG.Container.prototype.attr.call(this, a, b, c) - } - - } - - // Add parent method -, construct: { - // Create pattern element in defs - pattern: function(width, height, block) { - return this.defs().pattern(width, height, block) - } - } -}) - -SVG.extend(SVG.Defs, { - // Define gradient - pattern: function(width, height, block) { - return this.put(new SVG.Pattern).update(block).attr({ - x: 0 - , y: 0 - , width: width - , height: height - , patternUnits: 'userSpaceOnUse' - }) - } - -}) -SVG.Doc = SVG.invent({ - // Initialize node - create: function(element) { - if (element) { - // ensure the presence of a dom element - element = typeof element == 'string' ? - document.getElementById(element) : - element - - // If the target is an svg element, use that element as the main wrapper. - // This allows svg.js to work with svg documents as well. - if (element.nodeName == 'svg') { - this.constructor.call(this, element) - } else { - this.constructor.call(this, SVG.create('svg')) - element.appendChild(this.node) - this.size('100%', '100%') - } - - // set svg element attributes and ensure defs node - this.namespace().defs() - } - } - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Add namespaces - namespace: function() { - return this - .attr({ xmlns: SVG.ns, version: '1.1' }) - .attr('xmlns:xlink', SVG.xlink, SVG.xmlns) - .attr('xmlns:svgjs', SVG.svgjs, SVG.xmlns) - } - // Creates and returns defs element - , defs: function() { - if (!this._defs) { - var defs - - // Find or create a defs element in this instance - if (defs = this.node.getElementsByTagName('defs')[0]) - this._defs = SVG.adopt(defs) - else - this._defs = new SVG.Defs - - // Make sure the defs node is at the end of the stack - this.node.appendChild(this._defs.node) - } - - return this._defs - } - // custom parent method - , parent: function() { - return this.node.parentNode.nodeName == '#document' ? null : this.node.parentNode - } - // Fix for possible sub-pixel offset. See: - // https://bugzilla.mozilla.org/show_bug.cgi?id=608812 - , spof: function(spof) { - var pos = this.node.getScreenCTM() - - if (pos) - this - .style('left', (-pos.e % 1) + 'px') - .style('top', (-pos.f % 1) + 'px') - - return this - } - - // Removes the doc from the DOM - , remove: function() { - if(this.parent()) { - this.parent().removeChild(this.node); - } - - return this; - } - } - -}) - -SVG.Shape = SVG.invent({ - // Initialize node - create: function(element) { - this.constructor.call(this, element) - } - - // Inherit from -, inherit: SVG.Element - -}) - -SVG.Bare = SVG.invent({ - // Initialize - create: function(element, inherit) { - // construct element - this.constructor.call(this, SVG.create(element)) - - // inherit custom methods - if (inherit) - for (var method in inherit.prototype) - if (typeof inherit.prototype[method] === 'function') - this[method] = inherit.prototype[method] - } - - // Inherit from -, inherit: SVG.Element - - // Add methods -, extend: { - // Insert some plain text - words: function(text) { - // remove contents - while (this.node.hasChildNodes()) - this.node.removeChild(this.node.lastChild) - - // create text node - this.node.appendChild(document.createTextNode(text)) - - return this - } - } -}) - - -SVG.extend(SVG.Parent, { - // Create an element that is not described by SVG.js - element: function(element, inherit) { - return this.put(new SVG.Bare(element, inherit)) - } -}) - -SVG.Symbol = SVG.invent({ - // Initialize node - create: 'symbol' - - // Inherit from -, inherit: SVG.Container - -, construct: { - // create symbol - symbol: function() { - return this.put(new SVG.Symbol) - } - } -}) - -SVG.Use = SVG.invent({ - // Initialize node - create: 'use' - - // Inherit from -, inherit: SVG.Shape - - // Add class methods -, extend: { - // Use element as a reference - element: function(element, file) { - // Set lined element - return this.attr('href', (file || '') + '#' + element, SVG.xlink) - } - } - - // Add parent method -, construct: { - // Create a use element - use: function(element, file) { - return this.put(new SVG.Use).element(element, file) - } - } -}) -SVG.Rect = SVG.invent({ - // Initialize node - create: 'rect' - - // Inherit from -, inherit: SVG.Shape - - // Add parent method -, construct: { - // Create a rect element - rect: function(width, height) { - return this.put(new SVG.Rect()).size(width, height) - } - } -}) -SVG.Circle = SVG.invent({ - // Initialize node - create: 'circle' - - // Inherit from -, inherit: SVG.Shape - - // Add parent method -, construct: { - // Create circle element, based on ellipse - circle: function(size) { - return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0) - } - } -}) - -SVG.extend(SVG.Circle, SVG.FX, { - // Radius x value - rx: function(rx) { - return this.attr('r', rx) - } - // Alias radius x value -, ry: function(ry) { - return this.rx(ry) - } +// Module for array conversion
+SVG.Array = function(array, fallback) {
+ array = (array || []).valueOf()
+
+ // if array is empty and fallback is provided, use fallback
+ if (array.length == 0 && fallback)
+ array = fallback.valueOf()
+
+ // parse array
+ this.value = this.parse(array)
+}
+
+SVG.extend(SVG.Array, {
+ // Make array morphable
+ morph: function(array) {
+ this.destination = this.parse(array)
+
+ // normalize length of arrays
+ if (this.value.length != this.destination.length) {
+ var lastValue = this.value[this.value.length - 1]
+ , lastDestination = this.destination[this.destination.length - 1]
+
+ while(this.value.length > this.destination.length)
+ this.destination.push(lastDestination)
+ while(this.value.length < this.destination.length)
+ this.value.push(lastValue)
+ }
+
+ return this
+ }
+ // Clean up any duplicate points
+, settle: function() {
+ // find all unique values
+ for (var i = 0, il = this.value.length, seen = []; i < il; i++)
+ if (seen.indexOf(this.value[i]) == -1)
+ seen.push(this.value[i])
+
+ // set new value
+ return this.value = seen
+ }
+ // Get morphed array at given position
+, at: function(pos) {
+ // make sure a destination is defined
+ if (!this.destination) return this
+
+ // generate morphed array
+ for (var i = 0, il = this.value.length, array = []; i < il; i++)
+ array.push(this.value[i] + (this.destination[i] - this.value[i]) * pos)
+
+ return new SVG.Array(array)
+ }
+ // Convert array to string
+, toString: function() {
+ return this.value.join(' ')
+ }
+ // Real value
+, valueOf: function() {
+ return this.value
+ }
+ // Parse whitespace separated string
+, parse: function(array) {
+ array = array.valueOf()
+
+ // if already is an array, no need to parse it
+ if (Array.isArray(array)) return array
+
+ return array.trim().split(SVG.regex.delimiter).map(parseFloat)
+ }
+ // Reverse array
+, reverse: function() {
+ this.value.reverse()
+
+ return this
+ }
+, clone: function() {
+ var clone = new this.constructor()
+ clone.value = array_clone(this.value)
+ return clone
+ }
}) - -SVG.Ellipse = SVG.invent({ - // Initialize node - create: 'ellipse' - - // Inherit from -, inherit: SVG.Shape - - // Add parent method -, construct: { - // Create an ellipse - ellipse: function(width, height) { - return this.put(new SVG.Ellipse).size(width, height).move(0, 0) - } - } +// Poly points array
+SVG.PointArray = function(array, fallback) {
+ SVG.Array.call(this, array, fallback || [[0,0]])
+}
+
+// Inherit from SVG.Array
+SVG.PointArray.prototype = new SVG.Array
+SVG.PointArray.prototype.constructor = SVG.PointArray
+
+SVG.extend(SVG.PointArray, {
+ // Convert array to string
+ toString: function() {
+ // convert to a poly point string
+ for (var i = 0, il = this.value.length, array = []; i < il; i++)
+ array.push(this.value[i].join(','))
+
+ return array.join(' ')
+ }
+ // Convert array to line object
+, toLine: function() {
+ return {
+ x1: this.value[0][0]
+ , y1: this.value[0][1]
+ , x2: this.value[1][0]
+ , y2: this.value[1][1]
+ }
+ }
+ // Get morphed array at given position
+, at: function(pos) {
+ // make sure a destination is defined
+ if (!this.destination) return this
+
+ // generate morphed point string
+ for (var i = 0, il = this.value.length, array = []; i < il; i++)
+ array.push([
+ this.value[i][0] + (this.destination[i][0] - this.value[i][0]) * pos
+ , this.value[i][1] + (this.destination[i][1] - this.value[i][1]) * pos
+ ])
+
+ return new SVG.PointArray(array)
+ }
+ // Parse point string and flat array
+, parse: function(array) {
+ var points = []
+
+ array = array.valueOf()
+
+ // if it is an array
+ if (Array.isArray(array)) {
+ // and it is not flat, there is no need to parse it
+ if(Array.isArray(array[0])) {
+ return array
+ }
+ } else { // Else, it is considered as a string
+ // parse points
+ array = array.trim().split(SVG.regex.delimiter).map(parseFloat)
+ }
+
+ // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints
+ // Odd number of coordinates is an error. In such cases, drop the last odd coordinate.
+ if (array.length % 2 !== 0) array.pop()
+
+ // wrap points in two-tuples and parse points as floats
+ for(var i = 0, len = array.length; i < len; i = i + 2)
+ points.push([ array[i], array[i+1] ])
+
+ return points
+ }
+ // Move point string
+, move: function(x, y) {
+ var box = this.bbox()
+
+ // get relative offset
+ x -= box.x
+ y -= box.y
+
+ // move every point
+ if (!isNaN(x) && !isNaN(y))
+ for (var i = this.value.length - 1; i >= 0; i--)
+ this.value[i] = [this.value[i][0] + x, this.value[i][1] + y]
+
+ return this
+ }
+ // Resize poly string
+, size: function(width, height) {
+ var i, box = this.bbox()
+
+ // recalculate position of all points according to new size
+ for (i = this.value.length - 1; i >= 0; i--) {
+ if(box.width) this.value[i][0] = ((this.value[i][0] - box.x) * width) / box.width + box.x
+ if(box.height) this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
+ }
+
+ return this
+ }
+ // Get bounding box of points
+, bbox: function() {
+ SVG.parser.poly.setAttribute('points', this.toString())
+
+ return SVG.parser.poly.getBBox()
+ }
+})
+ +var pathHandlers = {
+ M: function(c, p, p0) {
+ p.x = p0.x = c[0]
+ p.y = p0.y = c[1]
+
+ return ['M', p.x, p.y]
+ },
+ L: function(c, p) {
+ p.x = c[0]
+ p.y = c[1]
+ return ['L', c[0], c[1]]
+ },
+ H: function(c, p) {
+ p.x = c[0]
+ return ['H', c[0]]
+ },
+ V: function(c, p) {
+ p.y = c[0]
+ return ['V', c[0]]
+ },
+ C: function(c, p) {
+ p.x = c[4]
+ p.y = c[5]
+ return ['C', c[0], c[1], c[2], c[3], c[4], c[5]]
+ },
+ S: function(c, p) {
+ p.x = c[2]
+ p.y = c[3]
+ return ['S', c[0], c[1], c[2], c[3]]
+ },
+ Q: function(c, p) {
+ p.x = c[2]
+ p.y = c[3]
+ return ['Q', c[0], c[1], c[2], c[3]]
+ },
+ T: function(c, p) {
+ p.x = c[0]
+ p.y = c[1]
+ return ['T', c[0], c[1]]
+ },
+ Z: function(c, p, p0) {
+ p.x = p0.x
+ p.y = p0.y
+ return ['Z']
+ },
+ A: function(c, p) {
+ p.x = c[5]
+ p.y = c[6]
+ return ['A', c[0], c[1], c[2], c[3], c[4], c[5], c[6]]
+ }
+}
+
+var mlhvqtcsa = 'mlhvqtcsaz'.split('')
+
+for(var i = 0, il = mlhvqtcsa.length; i < il; ++i){
+ pathHandlers[mlhvqtcsa[i]] = (function(i){
+ return function(c, p, p0) {
+ if(i == 'H') c[0] = c[0] + p.x
+ else if(i == 'V') c[0] = c[0] + p.y
+ else if(i == 'A'){
+ c[5] = c[5] + p.x,
+ c[6] = c[6] + p.y
+ }
+ else
+ for(var j = 0, jl = c.length; j < jl; ++j) {
+ c[j] = c[j] + (j%2 ? p.y : p.x)
+ }
+
+ return pathHandlers[i](c, p, p0)
+ }
+ })(mlhvqtcsa[i].toUpperCase())
+}
+
+// Path points array
+SVG.PathArray = function(array, fallback) {
+ SVG.Array.call(this, array, fallback || [['M', 0, 0]])
+}
+
+// Inherit from SVG.Array
+SVG.PathArray.prototype = new SVG.Array
+SVG.PathArray.prototype.constructor = SVG.PathArray
+
+SVG.extend(SVG.PathArray, {
+ // Convert array to string
+ toString: function() {
+ return arrayToString(this.value)
+ }
+ // Move path string
+, move: function(x, y) {
+ // get bounding box of current situation
+ var box = this.bbox()
+
+ // get relative offset
+ x -= box.x
+ y -= box.y
+
+ if (!isNaN(x) && !isNaN(y)) {
+ // move every point
+ for (var l, i = this.value.length - 1; i >= 0; i--) {
+ l = this.value[i][0]
+
+ if (l == 'M' || l == 'L' || l == 'T') {
+ this.value[i][1] += x
+ this.value[i][2] += y
+
+ } else if (l == 'H') {
+ this.value[i][1] += x
+
+ } else if (l == 'V') {
+ this.value[i][1] += y
+
+ } else if (l == 'C' || l == 'S' || l == 'Q') {
+ this.value[i][1] += x
+ this.value[i][2] += y
+ this.value[i][3] += x
+ this.value[i][4] += y
+
+ if (l == 'C') {
+ this.value[i][5] += x
+ this.value[i][6] += y
+ }
+
+ } else if (l == 'A') {
+ this.value[i][6] += x
+ this.value[i][7] += y
+ }
+
+ }
+ }
+
+ return this
+ }
+ // Resize path string
+, size: function(width, height) {
+ // get bounding box of current situation
+ var i, l, box = this.bbox()
+
+ // recalculate position of all points according to new size
+ for (i = this.value.length - 1; i >= 0; i--) {
+ l = this.value[i][0]
+
+ if (l == 'M' || l == 'L' || l == 'T') {
+ this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
+ this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
+
+ } else if (l == 'H') {
+ this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
+
+ } else if (l == 'V') {
+ this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
+
+ } else if (l == 'C' || l == 'S' || l == 'Q') {
+ this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
+ this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
+ this.value[i][3] = ((this.value[i][3] - box.x) * width) / box.width + box.x
+ this.value[i][4] = ((this.value[i][4] - box.y) * height) / box.height + box.y
+
+ if (l == 'C') {
+ this.value[i][5] = ((this.value[i][5] - box.x) * width) / box.width + box.x
+ this.value[i][6] = ((this.value[i][6] - box.y) * height) / box.height + box.y
+ }
+
+ } else if (l == 'A') {
+ // resize radii
+ this.value[i][1] = (this.value[i][1] * width) / box.width
+ this.value[i][2] = (this.value[i][2] * height) / box.height
+
+ // move position values
+ this.value[i][6] = ((this.value[i][6] - box.x) * width) / box.width + box.x
+ this.value[i][7] = ((this.value[i][7] - box.y) * height) / box.height + box.y
+ }
+
+ }
+
+ return this
+ }
+ // Test if the passed path array use the same path data commands as this path array
+, equalCommands: function(pathArray) {
+ var i, il, equalCommands
+
+ pathArray = new SVG.PathArray(pathArray)
+
+ equalCommands = this.value.length === pathArray.value.length
+ for(i = 0, il = this.value.length; equalCommands && i < il; i++) {
+ equalCommands = this.value[i][0] === pathArray.value[i][0]
+ }
+
+ return equalCommands
+ }
+ // Make path array morphable
+, morph: function(pathArray) {
+ pathArray = new SVG.PathArray(pathArray)
+
+ if(this.equalCommands(pathArray)) {
+ this.destination = pathArray
+ } else {
+ this.destination = null
+ }
+
+ return this
+ }
+ // Get morphed path array at given position
+, at: function(pos) {
+ // make sure a destination is defined
+ if (!this.destination) return this
+
+ var sourceArray = this.value
+ , destinationArray = this.destination.value
+ , array = [], pathArray = new SVG.PathArray()
+ , i, il, j, jl
+
+ // Animate has specified in the SVG spec
+ // See: https://www.w3.org/TR/SVG11/paths.html#PathElement
+ for (i = 0, il = sourceArray.length; i < il; i++) {
+ array[i] = [sourceArray[i][0]]
+ for(j = 1, jl = sourceArray[i].length; j < jl; j++) {
+ array[i][j] = sourceArray[i][j] + (destinationArray[i][j] - sourceArray[i][j]) * pos
+ }
+ // For the two flags of the elliptical arc command, the SVG spec say:
+ // Flags and booleans are interpolated as fractions between zero and one, with any non-zero value considered to be a value of one/true
+ // Elliptical arc command as an array followed by corresponding indexes:
+ // ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y]
+ // 0 1 2 3 4 5 6 7
+ if(array[i][0] === 'A') {
+ array[i][4] = +(array[i][4] != 0)
+ array[i][5] = +(array[i][5] != 0)
+ }
+ }
+
+ // Directly modify the value of a path array, this is done this way for performance
+ pathArray.value = array
+ return pathArray
+ }
+ // Absolutize and parse path to array
+, parse: function(array) {
+ // if it's already a patharray, no need to parse it
+ if (array instanceof SVG.PathArray) return array.valueOf()
+
+ // prepare for parsing
+ var i, x0, y0, s, seg, arr
+ , x = 0
+ , y = 0
+ , paramCnt = { 'M':2, 'L':2, 'H':1, 'V':1, 'C':6, 'S':4, 'Q':4, 'T':2, 'A':7 }
+
+ if(typeof array == 'string'){
+
+ array = array
+ .replace(SVG.regex.numbersWithDots, pathRegReplace) // convert 45.123.123 to 45.123 .123
+ .replace(SVG.regex.pathLetters, ' $& ') // put some room between letters and numbers
+ .replace(SVG.regex.hyphen, '$1 -') // add space before hyphen
+ .trim() // trim
+ .split(SVG.regex.delimiter) // split into array
+
+ }else{
+ array = array.reduce(function(prev, curr){
+ return [].concat.call(prev, curr)
+ }, [])
+ }
+
+ // array now is an array containing all parts of a path e.g. ['M', '0', '0', 'L', '30', '30' ...]
+ var arr = []
+ , p = new SVG.Point()
+ , p0 = new SVG.Point()
+ , index = 0
+ , len = array.length
+
+ do{
+ // Test if we have a path letter
+ if(SVG.regex.isPathLetter.test(array[index])){
+ s = array[index]
+ ++index
+ // If last letter was a move command and we got no new, it defaults to [L]ine
+ }else if(s == 'M'){
+ s = 'L'
+ }else if(s == 'm'){
+ s = 'l'
+ }
+
+ arr.push(pathHandlers[s].call(null,
+ array.slice(index, (index = index + paramCnt[s.toUpperCase()])).map(parseFloat),
+ p, p0
+ )
+ )
+
+ }while(len > index)
+
+ return arr
+
+ }
+ // Get bounding box of path
+, bbox: function() {
+ SVG.parser.path.setAttribute('d', this.toString())
+
+ return SVG.parser.path.getBBox()
+ }
+
+})
+ +// Module for unit convertions
+SVG.Number = SVG.invent({
+ // Initialize
+ create: function(value, unit) {
+ // initialize defaults
+ this.value = 0
+ this.unit = unit || ''
+
+ // parse value
+ if (typeof value === 'number') {
+ // ensure a valid numeric value
+ this.value = isNaN(value) ? 0 : !isFinite(value) ? (value < 0 ? -3.4e+38 : +3.4e+38) : value
+
+ } else if (typeof value === 'string') {
+ unit = value.match(SVG.regex.numberAndUnit)
+
+ if (unit) {
+ // make value numeric
+ this.value = parseFloat(unit[1])
+
+ // normalize
+ if (unit[5] == '%')
+ this.value /= 100
+ else if (unit[5] == 's')
+ this.value *= 1000
+
+ // store unit
+ this.unit = unit[5]
+ }
+
+ } else {
+ if (value instanceof SVG.Number) {
+ this.value = value.valueOf()
+ this.unit = value.unit
+ }
+ }
+
+ }
+ // Add methods
+, extend: {
+ // Stringalize
+ toString: function() {
+ return (
+ this.unit == '%' ?
+ ~~(this.value * 1e8) / 1e6:
+ this.unit == 's' ?
+ this.value / 1e3 :
+ this.value
+ ) + this.unit
+ }
+ , toJSON: function() {
+ return this.toString()
+ }
+ , // Convert to primitive
+ valueOf: function() {
+ return this.value
+ }
+ // Add number
+ , plus: function(number) {
+ number = new SVG.Number(number)
+ return new SVG.Number(this + number, this.unit || number.unit)
+ }
+ // Subtract number
+ , minus: function(number) {
+ number = new SVG.Number(number)
+ return new SVG.Number(this - number, this.unit || number.unit)
+ }
+ // Multiply number
+ , times: function(number) {
+ number = new SVG.Number(number)
+ return new SVG.Number(this * number, this.unit || number.unit)
+ }
+ // Divide number
+ , divide: function(number) {
+ number = new SVG.Number(number)
+ return new SVG.Number(this / number, this.unit || number.unit)
+ }
+ // Convert to different unit
+ , to: function(unit) {
+ var number = new SVG.Number(this)
+
+ if (typeof unit === 'string')
+ number.unit = unit
+
+ return number
+ }
+ // Make number morphable
+ , morph: function(number) {
+ this.destination = new SVG.Number(number)
+
+ if(number.relative) {
+ this.destination.value += this.value
+ }
+
+ return this
+ }
+ // Get morphed number at given position
+ , at: function(pos) {
+ // Make sure a destination is defined
+ if (!this.destination) return this
+
+ // Generate new morphed number
+ return new SVG.Number(this.destination)
+ .minus(this)
+ .times(pos)
+ .plus(this)
+ }
+
+ }
+})
+ +
+SVG.Element = SVG.invent({
+ // Initialize node
+ create: function(node) {
+ // last fired event on node
+ this._event = null
+
+ // initialize data object
+ this.dom = {}
+
+ // create circular reference
+ if (this.node = node) {
+ this.type = node.nodeName
+ this.node.instance = this
+ }
+ }
+
+ // Add class methods
+, extend: {
+ // Move over x-axis
+ x: function(x) {
+ return this.attr('x', x)
+ }
+ // Move over y-axis
+ , y: function(y) {
+ return this.attr('y', y)
+ }
+ // Move by center over x-axis
+ , cx: function(x) {
+ return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2)
+ }
+ // Move by center over y-axis
+ , cy: function(y) {
+ return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2)
+ }
+ // Move element to given x and y values
+ , move: function(x, y) {
+ return this.x(x).y(y)
+ }
+ // Move element by its center
+ , center: function(x, y) {
+ return this.cx(x).cy(y)
+ }
+ // Set width of element
+ , width: function(width) {
+ return this.attr('width', width)
+ }
+ // Set height of element
+ , height: function(height) {
+ return this.attr('height', height)
+ }
+ // Set element size to given width and height
+ , size: function(width, height) {
+ var p = proportionalSize(this, width, height)
+
+ return this
+ .width(new SVG.Number(p.width))
+ .height(new SVG.Number(p.height))
+ }
+ // Clone element
+ , clone: function(parent, withData) {
+ // write dom data to the dom so the clone can pickup the data
+ this.writeDataToDom()
+
+ // clone element and assign new id
+ var clone = assignNewId(this.node.cloneNode(true))
+
+ // insert the clone in the given parent or after myself
+ if(parent) parent.add(clone)
+ else this.after(clone)
+
+ return clone
+ }
+ // Remove element
+ , remove: function() {
+ if (this.parent())
+ this.parent().removeElement(this)
+
+ return this
+ }
+ // Replace element
+ , replace: function(element) {
+ this.after(element).remove()
+
+ return element
+ }
+ // Add element to given container and return self
+ , addTo: function(parent) {
+ return parent.put(this)
+ }
+ // Add element to given container and return container
+ , putIn: function(parent) {
+ return parent.add(this)
+ }
+ // Get / set id
+ , id: function(id) {
+ return this.attr('id', id)
+ }
+ // Checks whether the given point inside the bounding box of the element
+ , inside: function(x, y) {
+ var box = this.bbox()
+
+ return x > box.x
+ && y > box.y
+ && x < box.x + box.width
+ && y < box.y + box.height
+ }
+ // Show element
+ , show: function() {
+ return this.style('display', '')
+ }
+ // Hide element
+ , hide: function() {
+ return this.style('display', 'none')
+ }
+ // Is element visible?
+ , visible: function() {
+ return this.style('display') != 'none'
+ }
+ // Return id on string conversion
+ , toString: function() {
+ return this.attr('id')
+ }
+ // Return array of classes on the node
+ , classes: function() {
+ var attr = this.attr('class')
+
+ return attr == null ? [] : attr.trim().split(SVG.regex.delimiter)
+ }
+ // Return true if class exists on the node, false otherwise
+ , hasClass: function(name) {
+ return this.classes().indexOf(name) != -1
+ }
+ // Add class to the node
+ , addClass: function(name) {
+ if (!this.hasClass(name)) {
+ var array = this.classes()
+ array.push(name)
+ this.attr('class', array.join(' '))
+ }
+
+ return this
+ }
+ // Remove class from the node
+ , removeClass: function(name) {
+ if (this.hasClass(name)) {
+ this.attr('class', this.classes().filter(function(c) {
+ return c != name
+ }).join(' '))
+ }
+
+ return this
+ }
+ // Toggle the presence of a class on the node
+ , toggleClass: function(name) {
+ return this.hasClass(name) ? this.removeClass(name) : this.addClass(name)
+ }
+ // Get referenced element form attribute value
+ , reference: function(attr) {
+ return SVG.get(this.attr(attr))
+ }
+ // Returns the parent element instance
+ , parent: function(type) {
+ var parent = this
+
+ // check for parent
+ if(!parent.node.parentNode) return null
+
+ // get parent element
+ parent = SVG.adopt(parent.node.parentNode)
+
+ if(!type) return parent
+
+ // loop trough ancestors if type is given
+ while(parent && parent.node instanceof window.SVGElement){
+ if(typeof type === 'string' ? parent.matches(type) : parent instanceof type) return parent
+ parent = SVG.adopt(parent.node.parentNode)
+ }
+ }
+ // Get parent document
+ , doc: function() {
+ return this instanceof SVG.Doc ? this : this.parent(SVG.Doc)
+ }
+ // return array of all ancestors of given type up to the root svg
+ , parents: function(type) {
+ var parents = [], parent = this
+
+ do{
+ parent = parent.parent(type)
+ if(!parent || !parent.node) break
+
+ parents.push(parent)
+ } while(parent.parent)
+
+ return parents
+ }
+ // matches the element vs a css selector
+ , matches: function(selector){
+ return matches(this.node, selector)
+ }
+ // Returns the svg node to call native svg methods on it
+ , native: function() {
+ return this.node
+ }
+ // Import raw svg
+ , svg: function(svg) {
+ var well, len
+
+ // act as a setter if svg is given
+ if (svg && this instanceof SVG.Parent) {
+
+ // create temporary holder
+ well = document.createElementNS(SVG.ns, 'svg')
+ // dump raw svg
+ well.innerHTML = svg
+
+ // transplant nodes
+ for (len = well.childNodes.length;len--;)
+ if(well.firstChild.nodeType != 1)
+ well.removeChild(well.firstChild)
+ else
+ this.node.appendChild(well.firstChild)
+
+ // otherwise act as a getter
+ } else {
+ return this.node.outerHTML
+ }
+
+ return this
+ }
+ // write svgjs data to the dom
+ , writeDataToDom: function() {
+
+ // dump variables recursively
+ if(this.is(SVG.Parent)){
+ this.each(function(){
+ this.writeDataToDom()
+ })
+ }
+
+ // remove previously set data
+ this.node.removeAttribute('svgjs:data')
+
+ if(Object.keys(this.dom).length)
+ this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)) // see #428
+
+ return this
+ }
+ // set given data to the elements data property
+ , setData: function(o){
+ this.dom = o
+ return this
+ }
+ , is: function(obj){
+ return is(this, obj)
+ }
+ }
+})
+ +SVG.easing = {
+ '-': function(pos){return pos}
+, '<>':function(pos){return -Math.cos(pos * Math.PI) / 2 + 0.5}
+, '>': function(pos){return Math.sin(pos * Math.PI / 2)}
+, '<': function(pos){return -Math.cos(pos * Math.PI / 2) + 1}
+}
+
+SVG.morph = function(pos){
+ return function(from, to) {
+ return new SVG.MorphObj(from, to).at(pos)
+ }
+}
+
+SVG.Situation = SVG.invent({
+
+ create: function(o){
+ this.init = false
+ this.reversed = false
+ this.reversing = false
+
+ this.duration = new SVG.Number(o.duration).valueOf()
+ this.delay = new SVG.Number(o.delay).valueOf()
+
+ this.start = +new Date() + this.delay
+ this.finish = this.start + this.duration
+ this.ease = o.ease
+
+ // this.loop is incremented from 0 to this.loops
+ // it is also incremented when in an infinite loop (when this.loops is true)
+ this.loop = 0
+ this.loops = false
+
+ this.animations = {
+ // functionToCall: [list of morphable objects]
+ // e.g. move: [SVG.Number, SVG.Number]
+ }
+
+ this.attrs = {
+ // holds all attributes which are not represented from a function svg.js provides
+ // e.g. someAttr: SVG.Number
+ }
+
+ this.styles = {
+ // holds all styles which should be animated
+ // e.g. fill-color: SVG.Color
+ }
+
+ this.transforms = [
+ // holds all transformations as transformation objects
+ // e.g. [SVG.Rotate, SVG.Translate, SVG.Matrix]
+ ]
+
+ this.once = {
+ // functions to fire at a specific position
+ // e.g. "0.5": function foo(){}
+ }
+
+ }
+
+})
+
+
+SVG.FX = SVG.invent({
+
+ create: function(element) {
+ this._target = element
+ this.situations = []
+ this.active = false
+ this.situation = null
+ this.paused = false
+ this.lastPos = 0
+ this.pos = 0
+ // The absolute position of an animation is its position in the context of its complete duration (including delay and loops)
+ // When performing a delay, absPos is below 0 and when performing a loop, its value is above 1
+ this.absPos = 0
+ this._speed = 1
+ }
+
+, extend: {
+
+ /**
+ * sets or returns the target of this animation
+ * @param o object || number In case of Object it holds all parameters. In case of number its the duration of the animation
+ * @param ease function || string Function which should be used for easing or easing keyword
+ * @param delay Number indicating the delay before the animation starts
+ * @return target || this
+ */
+ animate: function(o, ease, delay){
+
+ if(typeof o == 'object'){
+ ease = o.ease
+ delay = o.delay
+ o = o.duration
+ }
+
+ var situation = new SVG.Situation({
+ duration: o || 1000,
+ delay: delay || 0,
+ ease: SVG.easing[ease || '-'] || ease
+ })
+
+ this.queue(situation)
+
+ return this
+ }
+
+ /**
+ * sets a delay before the next element of the queue is called
+ * @param delay Duration of delay in milliseconds
+ * @return this.target()
+ */
+ , delay: function(delay){
+ // The delay is performed by an empty situation with its duration
+ // attribute set to the duration of the delay
+ var situation = new SVG.Situation({
+ duration: delay,
+ delay: 0,
+ ease: SVG.easing['-']
+ })
+
+ return this.queue(situation)
+ }
+
+ /**
+ * sets or returns the target of this animation
+ * @param null || target SVG.Element which should be set as new target
+ * @return target || this
+ */
+ , target: function(target){
+ if(target && target instanceof SVG.Element){
+ this._target = target
+ return this
+ }
+
+ return this._target
+ }
+
+ // returns the absolute position at a given time
+ , timeToAbsPos: function(timestamp){
+ return (timestamp - this.situation.start) / (this.situation.duration/this._speed)
+ }
+
+ // returns the timestamp from a given absolute positon
+ , absPosToTime: function(absPos){
+ return this.situation.duration/this._speed * absPos + this.situation.start
+ }
+
+ // starts the animationloop
+ , startAnimFrame: function(){
+ this.stopAnimFrame()
+ this.animationFrame = window.requestAnimationFrame(function(){ this.step() }.bind(this))
+ }
+
+ // cancels the animationframe
+ , stopAnimFrame: function(){
+ window.cancelAnimationFrame(this.animationFrame)
+ }
+
+ // kicks off the animation - only does something when the queue is currently not active and at least one situation is set
+ , start: function(){
+ // dont start if already started
+ if(!this.active && this.situation){
+ this.active = true
+ this.startCurrent()
+ }
+
+ return this
+ }
+
+ // start the current situation
+ , startCurrent: function(){
+ this.situation.start = +new Date + this.situation.delay/this._speed
+ this.situation.finish = this.situation.start + this.situation.duration/this._speed
+ return this.initAnimations().step()
+ }
+
+ /**
+ * adds a function / Situation to the animation queue
+ * @param fn function / situation to add
+ * @return this
+ */
+ , queue: function(fn){
+ if(typeof fn == 'function' || fn instanceof SVG.Situation)
+ this.situations.push(fn)
+
+ if(!this.situation) this.situation = this.situations.shift()
+
+ return this
+ }
+
+ /**
+ * pulls next element from the queue and execute it
+ * @return this
+ */
+ , dequeue: function(){
+ // stop current animation
+ this.stop()
+
+ // get next animation from queue
+ this.situation = this.situations.shift()
+
+ if(this.situation){
+ if(this.situation instanceof SVG.Situation) {
+ this.start()
+ } else {
+ // If it is not a SVG.Situation, then it is a function, we execute it
+ this.situation.call(this)
+ }
+ }
+
+ return this
+ }
+
+ // updates all animations to the current state of the element
+ // this is important when one property could be changed from another property
+ , initAnimations: function() {
+ var i, source
+ var s = this.situation
+
+ if(s.init) return this
+
+ for(i in s.animations){
+ source = this.target()[i]()
+
+ // The condition is because some methods return a normal number instead
+ // of a SVG.Number
+ if(s.animations[i] instanceof SVG.Number)
+ source = new SVG.Number(source)
+
+ s.animations[i] = source.morph(s.animations[i])
+ }
+
+ for(i in s.attrs){
+ s.attrs[i] = new SVG.MorphObj(this.target().attr(i), s.attrs[i])
+ }
+
+ for(i in s.styles){
+ s.styles[i] = new SVG.MorphObj(this.target().style(i), s.styles[i])
+ }
+
+ s.initialTransformation = this.target().matrixify()
+
+ s.init = true
+ return this
+ }
+ , clearQueue: function(){
+ this.situations = []
+ return this
+ }
+ , clearCurrent: function(){
+ this.situation = null
+ return this
+ }
+ /** stops the animation immediately
+ * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately.
+ * @param clearQueue A Boolean indicating whether to remove queued animation as well.
+ * @return this
+ */
+ , stop: function(jumpToEnd, clearQueue){
+ var active = this.active
+ this.active = false
+
+ if(clearQueue){
+ this.clearQueue()
+ }
+
+ if(jumpToEnd && this.situation){
+ // initialize the situation if it was not
+ !active && this.startCurrent()
+ this.atEnd()
+ }
+
+ this.stopAnimFrame()
+
+ return this.clearCurrent()
+ }
+
+ /** resets the element to the state where the current element has started
+ * @return this
+ */
+ , reset: function(){
+ if(this.situation){
+ var temp = this.situation
+ this.stop()
+ this.situation = temp
+ this.atStart()
+ }
+ return this
+ }
+
+ // Stop the currently-running animation, remove all queued animations, and complete all animations for the element.
+ , finish: function(){
+
+ this.stop(true, false)
+
+ while(this.dequeue().situation && this.stop(true, false));
+
+ this.clearQueue().clearCurrent()
+
+ return this
+ }
+
+ // set the internal animation pointer at the start position, before any loops, and updates the visualisation
+ , atStart: function() {
+ return this.at(0, true)
+ }
+
+ // set the internal animation pointer at the end position, after all the loops, and updates the visualisation
+ , atEnd: function() {
+ if (this.situation.loops === true) {
+ // If in a infinite loop, we end the current iteration
+ this.situation.loops = this.situation.loop + 1
+ }
+
+ if(typeof this.situation.loops == 'number') {
+ // If performing a finite number of loops, we go after all the loops
+ return this.at(this.situation.loops, true)
+ } else {
+ // If no loops, we just go at the end
+ return this.at(1, true)
+ }
+ }
+
+ // set the internal animation pointer to the specified position and updates the visualisation
+ // if isAbsPos is true, pos is treated as an absolute position
+ , at: function(pos, isAbsPos){
+ var durDivSpd = this.situation.duration/this._speed
+
+ this.absPos = pos
+ // If pos is not an absolute position, we convert it into one
+ if (!isAbsPos) {
+ if (this.situation.reversed) this.absPos = 1 - this.absPos
+ this.absPos += this.situation.loop
+ }
+
+ this.situation.start = +new Date - this.absPos * durDivSpd
+ this.situation.finish = this.situation.start + durDivSpd
+
+ return this.step(true)
+ }
+
+ /**
+ * sets or returns the speed of the animations
+ * @param speed null || Number The new speed of the animations
+ * @return Number || this
+ */
+ , speed: function(speed){
+ if (speed === 0) return this.pause()
+
+ if (speed) {
+ this._speed = speed
+ // We use an absolute position here so that speed can affect the delay before the animation
+ return this.at(this.absPos, true)
+ } else return this._speed
+ }
+
+ // Make loopable
+ , loop: function(times, reverse) {
+ var c = this.last()
+
+ // store total loops
+ c.loops = (times != null) ? times : true
+ c.loop = 0
+
+ if(reverse) c.reversing = true
+ return this
+ }
+
+ // pauses the animation
+ , pause: function(){
+ this.paused = true
+ this.stopAnimFrame()
+
+ return this
+ }
+
+ // unpause the animation
+ , play: function(){
+ if(!this.paused) return this
+ this.paused = false
+ // We use an absolute position here so that the delay before the animation can be paused
+ return this.at(this.absPos, true)
+ }
+
+ /**
+ * toggle or set the direction of the animation
+ * true sets direction to backwards while false sets it to forwards
+ * @param reversed Boolean indicating whether to reverse the animation or not (default: toggle the reverse status)
+ * @return this
+ */
+ , reverse: function(reversed){
+ var c = this.last()
+
+ if(typeof reversed == 'undefined') c.reversed = !c.reversed
+ else c.reversed = reversed
+
+ return this
+ }
+
+
+ /**
+ * returns a float from 0-1 indicating the progress of the current animation
+ * @param eased Boolean indicating whether the returned position should be eased or not
+ * @return number
+ */
+ , progress: function(easeIt){
+ return easeIt ? this.situation.ease(this.pos) : this.pos
+ }
+
+ /**
+ * adds a callback function which is called when the current animation is finished
+ * @param fn Function which should be executed as callback
+ * @return number
+ */
+ , after: function(fn){
+ var c = this.last()
+ , wrapper = function wrapper(e){
+ if(e.detail.situation == c){
+ fn.call(this, c)
+ this.off('finished.fx', wrapper) // prevent memory leak
+ }
+ }
+
+ this.target().on('finished.fx', wrapper)
+
+ return this._callStart()
+ }
+
+ // adds a callback which is called whenever one animation step is performed
+ , during: function(fn){
+ var c = this.last()
+ , wrapper = function(e){
+ if(e.detail.situation == c){
+ fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, c)
+ }
+ }
+
+ // see above
+ this.target().off('during.fx', wrapper).on('during.fx', wrapper)
+
+ this.after(function(){
+ this.off('during.fx', wrapper)
+ })
+
+ return this._callStart()
+ }
+
+ // calls after ALL animations in the queue are finished
+ , afterAll: function(fn){
+ var wrapper = function wrapper(e){
+ fn.call(this)
+ this.off('allfinished.fx', wrapper)
+ }
+
+ // see above
+ this.target().off('allfinished.fx', wrapper).on('allfinished.fx', wrapper)
+
+ return this._callStart()
+ }
+
+ // calls on every animation step for all animations
+ , duringAll: function(fn){
+ var wrapper = function(e){
+ fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, e.detail.situation)
+ }
+
+ this.target().off('during.fx', wrapper).on('during.fx', wrapper)
+
+ this.afterAll(function(){
+ this.off('during.fx', wrapper)
+ })
+
+ return this._callStart()
+ }
+
+ , last: function(){
+ return this.situations.length ? this.situations[this.situations.length-1] : this.situation
+ }
+
+ // adds one property to the animations
+ , add: function(method, args, type){
+ this.last()[type || 'animations'][method] = args
+ return this._callStart()
+ }
+
+ /** perform one step of the animation
+ * @param ignoreTime Boolean indicating whether to ignore time and use position directly or recalculate position based on time
+ * @return this
+ */
+ , step: function(ignoreTime){
+
+ // convert current time to an absolute position
+ if(!ignoreTime) this.absPos = this.timeToAbsPos(+new Date)
+
+ // This part convert an absolute position to a position
+ if(this.situation.loops !== false) {
+ var absPos, absPosInt, lastLoop
+
+ // If the absolute position is below 0, we just treat it as if it was 0
+ absPos = Math.max(this.absPos, 0)
+ absPosInt = Math.floor(absPos)
+
+ if(this.situation.loops === true || absPosInt < this.situation.loops) {
+ this.pos = absPos - absPosInt
+ lastLoop = this.situation.loop
+ this.situation.loop = absPosInt
+ } else {
+ this.absPos = this.situation.loops
+ this.pos = 1
+ // The -1 here is because we don't want to toggle reversed when all the loops have been completed
+ lastLoop = this.situation.loop - 1
+ this.situation.loop = this.situation.loops
+ }
+
+ if(this.situation.reversing) {
+ // Toggle reversed if an odd number of loops as occured since the last call of step
+ this.situation.reversed = this.situation.reversed != Boolean((this.situation.loop - lastLoop) % 2)
+ }
+
+ } else {
+ // If there are no loop, the absolute position must not be above 1
+ this.absPos = Math.min(this.absPos, 1)
+ this.pos = this.absPos
+ }
+
+ // while the absolute position can be below 0, the position must not be below 0
+ if(this.pos < 0) this.pos = 0
+
+ if(this.situation.reversed) this.pos = 1 - this.pos
+
+
+ // apply easing
+ var eased = this.situation.ease(this.pos)
+
+ // call once-callbacks
+ for(var i in this.situation.once){
+ if(i > this.lastPos && i <= eased){
+ this.situation.once[i].call(this.target(), this.pos, eased)
+ delete this.situation.once[i]
+ }
+ }
+
+ // fire during callback with position, eased position and current situation as parameter
+ if(this.active) this.target().fire('during', {pos: this.pos, eased: eased, fx: this, situation: this.situation})
+
+ // the user may call stop or finish in the during callback
+ // so make sure that we still have a valid situation
+ if(!this.situation){
+ return this
+ }
+
+ // apply the actual animation to every property
+ this.eachAt()
+
+ // do final code when situation is finished
+ if((this.pos == 1 && !this.situation.reversed) || (this.situation.reversed && this.pos == 0)){
+
+ // stop animation callback
+ this.stopAnimFrame()
+
+ // fire finished callback with current situation as parameter
+ this.target().fire('finished', {fx:this, situation: this.situation})
+
+ if(!this.situations.length){
+ this.target().fire('allfinished')
+ this.target().off('.fx') // there shouldnt be any binding left, but to make sure...
+ this.active = false
+ }
+
+ // start next animation
+ if(this.active) this.dequeue()
+ else this.clearCurrent()
+
+ }else if(!this.paused && this.active){
+ // we continue animating when we are not at the end
+ this.startAnimFrame()
+ }
+
+ // save last eased position for once callback triggering
+ this.lastPos = eased
+ return this
+
+ }
+
+ // calculates the step for every property and calls block with it
+ , eachAt: function(){
+ var i, len, at, self = this, target = this.target(), s = this.situation
+
+ // apply animations which can be called trough a method
+ for(i in s.animations){
+
+ at = [].concat(s.animations[i]).map(function(el){
+ return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
+ })
+
+ target[i].apply(target, at)
+
+ }
+
+ // apply animation which has to be applied with attr()
+ for(i in s.attrs){
+
+ at = [i].concat(s.attrs[i]).map(function(el){
+ return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
+ })
+
+ target.attr.apply(target, at)
+
+ }
+
+ // apply animation which has to be applied with style()
+ for(i in s.styles){
+
+ at = [i].concat(s.styles[i]).map(function(el){
+ return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
+ })
+
+ target.style.apply(target, at)
+
+ }
+
+ // animate initialTransformation which has to be chained
+ if(s.transforms.length){
+
+ // get initial initialTransformation
+ at = s.initialTransformation
+ for(i = 0, len = s.transforms.length; i < len; i++){
+
+ // get next transformation in chain
+ var a = s.transforms[i]
+
+ // multiply matrix directly
+ if(a instanceof SVG.Matrix){
+
+ if(a.relative){
+ at = at.multiply(new SVG.Matrix().morph(a).at(s.ease(this.pos)))
+ }else{
+ at = at.morph(a).at(s.ease(this.pos))
+ }
+ continue
+ }
+
+ // when transformation is absolute we have to reset the needed transformation first
+ if(!a.relative)
+ a.undo(at.extract())
+
+ // and reapply it after
+ at = at.multiply(a.at(s.ease(this.pos)))
+
+ }
+
+ // set new matrix on element
+ target.matrix(at)
+ }
+
+ return this
+
+ }
+
+
+ // adds an once-callback which is called at a specific position and never again
+ , once: function(pos, fn, isEased){
+
+ if(!isEased)pos = this.situation.ease(pos)
+
+ this.situation.once[pos] = fn
+
+ return this
+ }
+
+ , _callStart: function() {
+ setTimeout(function(){this.start()}.bind(this), 0)
+ return this
+ }
+
+ }
+
+, parent: SVG.Element
+
+ // Add method to parent elements
+, construct: {
+ // Get fx module or create a new one, then animate with given duration and ease
+ animate: function(o, ease, delay) {
+ return (this.fx || (this.fx = new SVG.FX(this))).animate(o, ease, delay)
+ }
+ , delay: function(delay){
+ return (this.fx || (this.fx = new SVG.FX(this))).delay(delay)
+ }
+ , stop: function(jumpToEnd, clearQueue) {
+ if (this.fx)
+ this.fx.stop(jumpToEnd, clearQueue)
+
+ return this
+ }
+ , finish: function() {
+ if (this.fx)
+ this.fx.finish()
+
+ return this
+ }
+ // Pause current animation
+ , pause: function() {
+ if (this.fx)
+ this.fx.pause()
+
+ return this
+ }
+ // Play paused current animation
+ , play: function() {
+ if (this.fx)
+ this.fx.play()
+
+ return this
+ }
+ // Set/Get the speed of the animations
+ , speed: function(speed) {
+ if (this.fx)
+ if (speed == null)
+ return this.fx.speed()
+ else
+ this.fx.speed(speed)
+
+ return this
+ }
+ }
+
+})
+
+// MorphObj is used whenever no morphable object is given
+SVG.MorphObj = SVG.invent({
+
+ create: function(from, to){
+ // prepare color for morphing
+ if(SVG.Color.isColor(to)) return new SVG.Color(from).morph(to)
+ // prepare number for morphing
+ if(SVG.regex.numberAndUnit.test(to)) return new SVG.Number(from).morph(to)
+
+ // prepare for plain morphing
+ this.value = from
+ this.destination = to
+ }
+
+, extend: {
+ at: function(pos, real){
+ return real < 1 ? this.value : this.destination
+ },
+
+ valueOf: function(){
+ return this.value
+ }
+ }
+
+})
+
+SVG.extend(SVG.FX, {
+ // Add animatable attributes
+ attr: function(a, v, relative) {
+ // apply attributes individually
+ if (typeof a == 'object') {
+ for (var key in a)
+ this.attr(key, a[key])
+
+ } else {
+ this.add(a, v, 'attrs')
+ }
+
+ return this
+ }
+ // Add animatable styles
+, style: function(s, v) {
+ if (typeof s == 'object')
+ for (var key in s)
+ this.style(key, s[key])
+
+ else
+ this.add(s, v, 'styles')
+
+ return this
+ }
+ // Animatable x-axis
+, x: function(x, relative) {
+ if(this.target() instanceof SVG.G){
+ this.transform({x:x}, relative)
+ return this
+ }
+
+ var num = new SVG.Number(x)
+ num.relative = relative
+ return this.add('x', num)
+ }
+ // Animatable y-axis
+, y: function(y, relative) {
+ if(this.target() instanceof SVG.G){
+ this.transform({y:y}, relative)
+ return this
+ }
+
+ var num = new SVG.Number(y)
+ num.relative = relative
+ return this.add('y', num)
+ }
+ // Animatable center x-axis
+, cx: function(x) {
+ return this.add('cx', new SVG.Number(x))
+ }
+ // Animatable center y-axis
+, cy: function(y) {
+ return this.add('cy', new SVG.Number(y))
+ }
+ // Add animatable move
+, move: function(x, y) {
+ return this.x(x).y(y)
+ }
+ // Add animatable center
+, center: function(x, y) {
+ return this.cx(x).cy(y)
+ }
+ // Add animatable size
+, size: function(width, height) {
+ if (this.target() instanceof SVG.Text) {
+ // animate font size for Text elements
+ this.attr('font-size', width)
+
+ } else {
+ // animate bbox based size for all other elements
+ var box
+
+ if(!width || !height){
+ box = this.target().bbox()
+ }
+
+ if(!width){
+ width = box.width / box.height * height
+ }
+
+ if(!height){
+ height = box.height / box.width * width
+ }
+
+ this.add('width' , new SVG.Number(width))
+ .add('height', new SVG.Number(height))
+
+ }
+
+ return this
+ }
+ // Add animatable plot
+, plot: function() {
+ // We use arguments here since SVG.Line's plot method can be passed 4 parameters
+ return this.add('plot', arguments.length > 1 ? [].slice.call(arguments) : arguments[0])
+ }
+ // Add leading method
+, leading: function(value) {
+ return this.target().leading ?
+ this.add('leading', new SVG.Number(value)) :
+ this
+ }
+ // Add animatable viewbox
+, viewbox: function(x, y, width, height) {
+ if (this.target() instanceof SVG.Container) {
+ this.add('viewbox', new SVG.Box(x, y, width, height))
+ }
+
+ return this
+ }
+, update: function(o) {
+ if (this.target() instanceof SVG.Stop) {
+ if (typeof o == 'number' || o instanceof SVG.Number) {
+ return this.update({
+ offset: arguments[0]
+ , color: arguments[1]
+ , opacity: arguments[2]
+ })
+ }
+
+ if (o.opacity != null) this.attr('stop-opacity', o.opacity)
+ if (o.color != null) this.attr('stop-color', o.color)
+ if (o.offset != null) this.attr('offset', o.offset)
+ }
+
+ return this
+ }
+})
+ +SVG.Matrix = SVG.invent({
+ // Initialize
+ create: function(source) {
+ var i, base = arrayToMatrix([1, 0, 0, 1, 0, 0])
+
+ // ensure source as object
+ source = source instanceof SVG.Element ?
+ source.matrixify() :
+ typeof source === 'string' ?
+ arrayToMatrix(source.split(SVG.regex.delimiter).map(parseFloat)) :
+ arguments.length == 6 ?
+ arrayToMatrix([].slice.call(arguments)) :
+ Array.isArray(source) ?
+ arrayToMatrix(source) :
+ typeof source === 'object' ?
+ source : base
+
+ // merge source
+ for (i = abcdef.length - 1; i >= 0; --i)
+ this[abcdef[i]] = source && typeof source[abcdef[i]] === 'number' ?
+ source[abcdef[i]] : base[abcdef[i]]
+ }
+
+ // Add methods
+, extend: {
+ // Extract individual transformations
+ extract: function() {
+ // find delta transform points
+ var px = deltaTransformPoint(this, 0, 1)
+ , py = deltaTransformPoint(this, 1, 0)
+ , skewX = 180 / Math.PI * Math.atan2(px.y, px.x) - 90
+
+ return {
+ // translation
+ x: this.e
+ , y: this.f
+ , transformedX:(this.e * Math.cos(skewX * Math.PI / 180) + this.f * Math.sin(skewX * Math.PI / 180)) / Math.sqrt(this.a * this.a + this.b * this.b)
+ , transformedY:(this.f * Math.cos(skewX * Math.PI / 180) + this.e * Math.sin(-skewX * Math.PI / 180)) / Math.sqrt(this.c * this.c + this.d * this.d)
+ // skew
+ , skewX: -skewX
+ , skewY: 180 / Math.PI * Math.atan2(py.y, py.x)
+ // scale
+ , scaleX: Math.sqrt(this.a * this.a + this.b * this.b)
+ , scaleY: Math.sqrt(this.c * this.c + this.d * this.d)
+ // rotation
+ , rotation: skewX
+ , a: this.a
+ , b: this.b
+ , c: this.c
+ , d: this.d
+ , e: this.e
+ , f: this.f
+ , matrix: new SVG.Matrix(this)
+ }
+ }
+ // Clone matrix
+ , clone: function() {
+ return new SVG.Matrix(this)
+ }
+ // Morph one matrix into another
+ , morph: function(matrix) {
+ // store new destination
+ this.destination = new SVG.Matrix(matrix)
+
+ return this
+ }
+ // Get morphed matrix at a given position
+ , at: function(pos) {
+ // make sure a destination is defined
+ if (!this.destination) return this
+
+ // calculate morphed matrix at a given position
+ var matrix = new SVG.Matrix({
+ a: this.a + (this.destination.a - this.a) * pos
+ , b: this.b + (this.destination.b - this.b) * pos
+ , c: this.c + (this.destination.c - this.c) * pos
+ , d: this.d + (this.destination.d - this.d) * pos
+ , e: this.e + (this.destination.e - this.e) * pos
+ , f: this.f + (this.destination.f - this.f) * pos
+ })
+
+ return matrix
+ }
+ // Multiplies by given matrix
+ , multiply: function(matrix) {
+ return new SVG.Matrix(this.native().multiply(parseMatrix(matrix).native()))
+ }
+ // Inverses matrix
+ , inverse: function() {
+ return new SVG.Matrix(this.native().inverse())
+ }
+ // Translate matrix
+ , translate: function(x, y) {
+ return new SVG.Matrix(this.native().translate(x || 0, y || 0))
+ }
+ // Scale matrix
+ , scale: function(x, y, cx, cy) {
+ // support uniformal scale
+ if (arguments.length == 1) {
+ y = x
+ } else if (arguments.length == 3) {
+ cy = cx
+ cx = y
+ y = x
+ }
+
+ return this.around(cx, cy, new SVG.Matrix(x, 0, 0, y, 0, 0))
+ }
+ // Rotate matrix
+ , rotate: function(r, cx, cy) {
+ // convert degrees to radians
+ r = SVG.utils.radians(r)
+
+ return this.around(cx, cy, new SVG.Matrix(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0))
+ }
+ // Flip matrix on x or y, at a given offset
+ , flip: function(a, o) {
+ return a == 'x' ?
+ this.scale(-1, 1, o, 0) :
+ a == 'y' ?
+ this.scale(1, -1, 0, o) :
+ this.scale(-1, -1, a, o != null ? o : a)
+ }
+ // Skew
+ , skew: function(x, y, cx, cy) {
+ // support uniformal skew
+ if (arguments.length == 1) {
+ y = x
+ } else if (arguments.length == 3) {
+ cy = cx
+ cx = y
+ y = x
+ }
+
+ // convert degrees to radians
+ x = SVG.utils.radians(x)
+ y = SVG.utils.radians(y)
+
+ return this.around(cx, cy, new SVG.Matrix(1, Math.tan(y), Math.tan(x), 1, 0, 0))
+ }
+ // SkewX
+ , skewX: function(x, cx, cy) {
+ return this.skew(x, 0, cx, cy)
+ }
+ // SkewY
+ , skewY: function(y, cx, cy) {
+ return this.skew(0, y, cx, cy)
+ }
+ // Transform around a center point
+ , around: function(cx, cy, matrix) {
+ return this
+ .multiply(new SVG.Matrix(1, 0, 0, 1, cx || 0, cy || 0))
+ .multiply(matrix)
+ .multiply(new SVG.Matrix(1, 0, 0, 1, -cx || 0, -cy || 0))
+ }
+ // Convert to native SVGMatrix
+ , native: function() {
+ // create new matrix
+ var matrix = SVG.parser.native.createSVGMatrix()
+
+ // update with current values
+ for (var i = abcdef.length - 1; i >= 0; i--)
+ matrix[abcdef[i]] = this[abcdef[i]]
+
+ return matrix
+ }
+ // Convert matrix to string
+ , toString: function() {
+ return 'matrix(' + this.a + ',' + this.b + ',' + this.c + ',' + this.d + ',' + this.e + ',' + this.f + ')'
+ }
+ }
+
+ // Define parent
+, parent: SVG.Element
+
+ // Add parent method
+, construct: {
+ // Get current matrix
+ ctm: function() {
+ return new SVG.Matrix(this.node.getCTM())
+ },
+ // Get current screen matrix
+ screenCTM: function() {
+ /* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537
+ This is needed because FF does not return the transformation matrix
+ for the inner coordinate system when getScreenCTM() is called on nested svgs.
+ However all other Browsers do that */
+ if(this instanceof SVG.Nested) {
+ var rect = this.rect(1,1)
+ var m = rect.node.getScreenCTM()
+ rect.remove()
+ return new SVG.Matrix(m)
+ }
+ return new SVG.Matrix(this.node.getScreenCTM())
+ }
+
+ }
+
+})
+ +SVG.Point = SVG.invent({
+ // Initialize
+ create: function(x,y) {
+ var i, source, base = {x:0, y:0}
+
+ // ensure source as object
+ source = Array.isArray(x) ?
+ {x:x[0], y:x[1]} :
+ typeof x === 'object' ?
+ {x:x.x, y:x.y} :
+ x != null ?
+ {x:x, y:(y != null ? y : x)} : base // If y has no value, then x is used has its value
+
+ // merge source
+ this.x = source.x
+ this.y = source.y
+ }
+
+ // Add methods
+, extend: {
+ // Clone point
+ clone: function() {
+ return new SVG.Point(this)
+ }
+ // Morph one point into another
+ , morph: function(x, y) {
+ // store new destination
+ this.destination = new SVG.Point(x, y)
+
+ return this
+ }
+ // Get morphed point at a given position
+ , at: function(pos) {
+ // make sure a destination is defined
+ if (!this.destination) return this
+
+ // calculate morphed matrix at a given position
+ var point = new SVG.Point({
+ x: this.x + (this.destination.x - this.x) * pos
+ , y: this.y + (this.destination.y - this.y) * pos
+ })
+
+ return point
+ }
+ // Convert to native SVGPoint
+ , native: function() {
+ // create new point
+ var point = SVG.parser.native.createSVGPoint()
+
+ // update with current values
+ point.x = this.x
+ point.y = this.y
+
+ return point
+ }
+ // transform point with matrix
+ , transform: function(matrix) {
+ return new SVG.Point(this.native().matrixTransform(matrix.native()))
+ }
+
+ }
+
+})
+
+SVG.extend(SVG.Element, {
+
+ // Get point
+ point: function(x, y) {
+ return new SVG.Point(x,y).transform(this.screenCTM().inverse());
+ }
+
+})
+ +SVG.extend(SVG.Element, {
+ // Set svg element attribute
+ attr: function(a, v, n) {
+ // act as full getter
+ if (a == null) {
+ // get an object of attributes
+ a = {}
+ v = this.node.attributes
+ for (n = v.length - 1; n >= 0; n--)
+ a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue) ? parseFloat(v[n].nodeValue) : v[n].nodeValue
+
+ return a
+
+ } else if (typeof a == 'object') {
+ // apply every attribute individually if an object is passed
+ for (v in a) this.attr(v, a[v])
+
+ } else if (v === null) {
+ // remove value
+ this.node.removeAttribute(a)
+
+ } else if (v == null) {
+ // act as a getter if the first and only argument is not an object
+ v = this.node.getAttribute(a)
+ return v == null ?
+ SVG.defaults.attrs[a] :
+ SVG.regex.isNumber.test(v) ?
+ parseFloat(v) : v
+
+ } else {
+
+ // convert image fill and stroke to patterns
+ if (a == 'fill' || a == 'stroke') {
+ if (SVG.regex.isImage.test(v))
+ v = this.doc().defs().image(v)
+
+ if (v instanceof SVG.Image)
+ v = this.doc().defs().pattern(0, 0, function() {
+ this.add(v)
+ })
+ }
+
+ // ensure correct numeric values (also accepts NaN and Infinity)
+ if (typeof v === 'number')
+ v = new SVG.Number(v)
+
+ // ensure full hex color
+ else if (SVG.Color.isColor(v))
+ v = new SVG.Color(v)
+
+ // parse array values
+ else if (Array.isArray(v))
+ v = new SVG.Array(v)
+
+ // if the passed attribute is leading...
+ if (a == 'leading') {
+ // ... call the leading method instead
+ if (this.leading)
+ this.leading(v)
+ } else {
+ // set given attribute on node
+ typeof n === 'string' ?
+ this.node.setAttributeNS(n, a, v.toString()) :
+ this.node.setAttribute(a, v.toString())
+ }
+
+ // rebuild if required
+ if (this.rebuild && (a == 'font-size' || a == 'x'))
+ this.rebuild(a, v)
+ }
+
+ return this
+ }
}) - -SVG.extend(SVG.Ellipse, SVG.Rect, SVG.FX, { - // Radius x value - rx: function(rx) { - return this.attr('rx', rx) - } - // Radius y value -, ry: function(ry) { - return this.attr('ry', ry) - } +SVG.extend(SVG.Element, {
+ // Add transformations
+ transform: function(o, relative) {
+ // get target in case of the fx module, otherwise reference this
+ var target = this
+ , matrix, bbox
+
+ // act as a getter
+ if (typeof o !== 'object') {
+ // get current matrix
+ matrix = new SVG.Matrix(target).extract()
+
+ return typeof o === 'string' ? matrix[o] : matrix
+ }
+
+ // get current matrix
+ matrix = new SVG.Matrix(target)
+
+ // ensure relative flag
+ relative = !!relative || !!o.relative
+
+ // act on matrix
+ if (o.a != null) {
+ matrix = relative ?
+ // relative
+ matrix.multiply(new SVG.Matrix(o)) :
+ // absolute
+ new SVG.Matrix(o)
+
+ // act on rotation
+ } else if (o.rotation != null) {
+ // ensure centre point
+ ensureCentre(o, target)
+
+ // apply transformation
+ matrix = relative ?
+ // relative
+ matrix.rotate(o.rotation, o.cx, o.cy) :
+ // absolute
+ matrix.rotate(o.rotation - matrix.extract().rotation, o.cx, o.cy)
+
+ // act on scale
+ } else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
+ // ensure centre point
+ ensureCentre(o, target)
+
+ // ensure scale values on both axes
+ o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
+ o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
+
+ if (!relative) {
+ // absolute; multiply inversed values
+ var e = matrix.extract()
+ o.scaleX = o.scaleX * 1 / e.scaleX
+ o.scaleY = o.scaleY * 1 / e.scaleY
+ }
+
+ matrix = matrix.scale(o.scaleX, o.scaleY, o.cx, o.cy)
+
+ // act on skew
+ } else if (o.skew != null || o.skewX != null || o.skewY != null) {
+ // ensure centre point
+ ensureCentre(o, target)
+
+ // ensure skew values on both axes
+ o.skewX = o.skew != null ? o.skew : o.skewX != null ? o.skewX : 0
+ o.skewY = o.skew != null ? o.skew : o.skewY != null ? o.skewY : 0
+
+ if (!relative) {
+ // absolute; reset skew values
+ var e = matrix.extract()
+ matrix = matrix.multiply(new SVG.Matrix().skew(e.skewX, e.skewY, o.cx, o.cy).inverse())
+ }
+
+ matrix = matrix.skew(o.skewX, o.skewY, o.cx, o.cy)
+
+ // act on flip
+ } else if (o.flip) {
+ if(o.flip == 'x' || o.flip == 'y') {
+ o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
+ } else {
+ if(o.offset == null) {
+ bbox = target.bbox()
+ o.flip = bbox.cx
+ o.offset = bbox.cy
+ } else {
+ o.flip = o.offset
+ }
+ }
+
+ matrix = new SVG.Matrix().flip(o.flip, o.offset)
+
+ // act on translate
+ } else if (o.x != null || o.y != null) {
+ if (relative) {
+ // relative
+ matrix = matrix.translate(o.x, o.y)
+ } else {
+ // absolute
+ if (o.x != null) matrix.e = o.x
+ if (o.y != null) matrix.f = o.y
+ }
+ }
+
+ return this.attr('transform', matrix)
+ }
+})
+
+SVG.extend(SVG.FX, {
+ transform: function(o, relative) {
+ // get target in case of the fx module, otherwise reference this
+ var target = this.target()
+ , matrix, bbox
+
+ // act as a getter
+ if (typeof o !== 'object') {
+ // get current matrix
+ matrix = new SVG.Matrix(target).extract()
+
+ return typeof o === 'string' ? matrix[o] : matrix
+ }
+
+ // ensure relative flag
+ relative = !!relative || !!o.relative
+
+ // act on matrix
+ if (o.a != null) {
+ matrix = new SVG.Matrix(o)
+
+ // act on rotation
+ } else if (o.rotation != null) {
+ // ensure centre point
+ ensureCentre(o, target)
+
+ // apply transformation
+ matrix = new SVG.Rotate(o.rotation, o.cx, o.cy)
+
+ // act on scale
+ } else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
+ // ensure centre point
+ ensureCentre(o, target)
+
+ // ensure scale values on both axes
+ o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
+ o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
+
+ matrix = new SVG.Scale(o.scaleX, o.scaleY, o.cx, o.cy)
+
+ // act on skew
+ } else if (o.skewX != null || o.skewY != null) {
+ // ensure centre point
+ ensureCentre(o, target)
+
+ // ensure skew values on both axes
+ o.skewX = o.skewX != null ? o.skewX : 0
+ o.skewY = o.skewY != null ? o.skewY : 0
+
+ matrix = new SVG.Skew(o.skewX, o.skewY, o.cx, o.cy)
+
+ // act on flip
+ } else if (o.flip) {
+ if(o.flip == 'x' || o.flip == 'y') {
+ o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
+ } else {
+ if(o.offset == null) {
+ bbox = target.bbox()
+ o.flip = bbox.cx
+ o.offset = bbox.cy
+ } else {
+ o.flip = o.offset
+ }
+ }
+
+ matrix = new SVG.Matrix().flip(o.flip, o.offset)
+
+ // act on translate
+ } else if (o.x != null || o.y != null) {
+ matrix = new SVG.Translate(o.x, o.y)
+ }
+
+ if(!matrix) return this
+
+ matrix.relative = relative
+
+ this.last().transforms.push(matrix)
+
+ return this._callStart()
+ }
+})
+
+SVG.extend(SVG.Element, {
+ // Reset all transformations
+ untransform: function() {
+ return this.attr('transform', null)
+ },
+ // merge the whole transformation chain into one matrix and returns it
+ matrixify: function() {
+
+ var matrix = (this.attr('transform') || '')
+ // split transformations
+ .split(SVG.regex.transforms).slice(0,-1).map(function(str){
+ // generate key => value pairs
+ var kv = str.trim().split('(')
+ return [kv[0], kv[1].split(SVG.regex.delimiter).map(function(str){ return parseFloat(str) })]
+ })
+ // merge every transformation into one matrix
+ .reduce(function(matrix, transform){
+
+ if(transform[0] == 'matrix') return matrix.multiply(arrayToMatrix(transform[1]))
+ return matrix[transform[0]].apply(matrix, transform[1])
+
+ }, new SVG.Matrix())
+
+ return matrix
+ },
+ // add an element to another parent without changing the visual representation on the screen
+ toParent: function(parent) {
+ if(this == parent) return this
+ var ctm = this.screenCTM()
+ var pCtm = parent.screenCTM().inverse()
+
+ this.addTo(parent).untransform().transform(pCtm.multiply(ctm))
+
+ return this
+ },
+ // same as above with parent equals root-svg
+ toDoc: function() {
+ return this.toParent(this.doc())
+ }
+
+})
+
+SVG.Transformation = SVG.invent({
+
+ create: function(source, inversed){
+
+ if(arguments.length > 1 && typeof inversed != 'boolean'){
+ return this.constructor.call(this, [].slice.call(arguments))
+ }
+
+ if(Array.isArray(source)){
+ for(var i = 0, len = this.arguments.length; i < len; ++i){
+ this[this.arguments[i]] = source[i]
+ }
+ } else if(typeof source == 'object'){
+ for(var i = 0, len = this.arguments.length; i < len; ++i){
+ this[this.arguments[i]] = source[this.arguments[i]]
+ }
+ }
+
+ this.inversed = false
+
+ if(inversed === true){
+ this.inversed = true
+ }
+
+ }
+
+, extend: {
+
+ arguments: []
+ , method: ''
+
+ , at: function(pos){
+
+ var params = []
+
+ for(var i = 0, len = this.arguments.length; i < len; ++i){
+ params.push(this[this.arguments[i]])
+ }
+
+ var m = this._undo || new SVG.Matrix()
+
+ m = new SVG.Matrix().morph(SVG.Matrix.prototype[this.method].apply(m, params)).at(pos)
+
+ return this.inversed ? m.inverse() : m
+
+ }
+
+ , undo: function(o){
+ for(var i = 0, len = this.arguments.length; i < len; ++i){
+ o[this.arguments[i]] = typeof this[this.arguments[i]] == 'undefined' ? 0 : o[this.arguments[i]]
+ }
+
+ // The method SVG.Matrix.extract which was used before calling this
+ // method to obtain a value for the parameter o doesn't return a cx and
+ // a cy so we use the ones that were provided to this object at its creation
+ o.cx = this.cx
+ o.cy = this.cy
+
+ this._undo = new SVG[capitalize(this.method)](o, true).at(1)
+
+ return this
+ }
+
+ }
+
+})
+
+SVG.Translate = SVG.invent({
+
+ parent: SVG.Matrix
+, inherit: SVG.Transformation
+
+, create: function(source, inversed){
+ this.constructor.apply(this, [].slice.call(arguments))
+ }
+
+, extend: {
+ arguments: ['transformedX', 'transformedY']
+ , method: 'translate'
+ }
+
+})
+
+SVG.Rotate = SVG.invent({
+
+ parent: SVG.Matrix
+, inherit: SVG.Transformation
+
+, create: function(source, inversed){
+ this.constructor.apply(this, [].slice.call(arguments))
+ }
+
+, extend: {
+ arguments: ['rotation', 'cx', 'cy']
+ , method: 'rotate'
+ , at: function(pos){
+ var m = new SVG.Matrix().rotate(new SVG.Number().morph(this.rotation - (this._undo ? this._undo.rotation : 0)).at(pos), this.cx, this.cy)
+ return this.inversed ? m.inverse() : m
+ }
+ , undo: function(o){
+ this._undo = o
+ return this
+ }
+ }
+
+})
+
+SVG.Scale = SVG.invent({
+
+ parent: SVG.Matrix
+, inherit: SVG.Transformation
+
+, create: function(source, inversed){
+ this.constructor.apply(this, [].slice.call(arguments))
+ }
+
+, extend: {
+ arguments: ['scaleX', 'scaleY', 'cx', 'cy']
+ , method: 'scale'
+ }
+
+})
+
+SVG.Skew = SVG.invent({
+
+ parent: SVG.Matrix
+, inherit: SVG.Transformation
+
+, create: function(source, inversed){
+ this.constructor.apply(this, [].slice.call(arguments))
+ }
+
+, extend: {
+ arguments: ['skewX', 'skewY', 'cx', 'cy']
+ , method: 'skew'
+ }
+
+})
+ +SVG.extend(SVG.Element, {
+ // Dynamic style generator
+ style: function(s, v) {
+ if (arguments.length == 0) {
+ // get full style
+ return this.node.style.cssText || ''
+
+ } else if (arguments.length < 2) {
+ // apply every style individually if an object is passed
+ if (typeof s == 'object') {
+ for (v in s) this.style(v, s[v])
+
+ } else {
+ // act as a getter if the first and only argument is not an object
+ return this.node.style[camelCase(s)]
+ }
+
+ } else {
+ this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v
+ }
+
+ return this
+ }
+})
+ +SVG.Parent = SVG.invent({
+ // Initialize node
+ create: function(element) {
+ this.constructor.call(this, element)
+ }
+
+ // Inherit from
+, inherit: SVG.Element
+
+ // Add class methods
+, extend: {
+ // Returns all child elements
+ children: function() {
+ return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) {
+ return SVG.adopt(node)
+ })
+ }
+ // Add given element at a position
+ , add: function(element, i) {
+ if (i == null)
+ this.node.appendChild(element.node)
+ else if (element.node != this.node.childNodes[i])
+ this.node.insertBefore(element.node, this.node.childNodes[i])
+
+ return this
+ }
+ // Basically does the same as `add()` but returns the added element instead
+ , put: function(element, i) {
+ this.add(element, i)
+ return element
+ }
+ // Checks if the given element is a child
+ , has: function(element) {
+ return this.index(element) >= 0
+ }
+ // Gets index of given element
+ , index: function(element) {
+ return [].slice.call(this.node.childNodes).indexOf(element.node)
+ }
+ // Get a element at the given index
+ , get: function(i) {
+ return SVG.adopt(this.node.childNodes[i])
+ }
+ // Get first child
+ , first: function() {
+ return this.get(0)
+ }
+ // Get the last child
+ , last: function() {
+ return this.get(this.node.childNodes.length - 1)
+ }
+ // Iterates over all children and invokes a given block
+ , each: function(block, deep) {
+ var i, il
+ , children = this.children()
+
+ for (i = 0, il = children.length; i < il; i++) {
+ if (children[i] instanceof SVG.Element)
+ block.apply(children[i], [i, children])
+
+ if (deep && (children[i] instanceof SVG.Container))
+ children[i].each(block, deep)
+ }
+
+ return this
+ }
+ // Remove a given child
+ , removeElement: function(element) {
+ this.node.removeChild(element.node)
+
+ return this
+ }
+ // Remove all elements in this container
+ , clear: function() {
+ // remove children
+ while(this.node.hasChildNodes())
+ this.node.removeChild(this.node.lastChild)
+
+ // remove defs reference
+ delete this._defs
+
+ return this
+ }
+ , // Get defs
+ defs: function() {
+ return this.doc().defs()
+ }
+ }
+
+})
+ +SVG.extend(SVG.Parent, {
+ flatten: function(parent) {
+ if(this instanceof SVG.Defs) return this
+
+ parent = parent || (this instanceof SVG.Doc ? this : this.parent(SVG.Parent))
+
+ this.each(function(){
+ if(this instanceof SVG.Defs) return this
+ if(this instanceof SVG.Parent) return this.flatten(parent)
+ return this.toParent(parent)
+ })
+
+ // we need this so that SVG.Doc does not get removed
+ this.node.firstChild || this.remove()
+
+ return this
+ }
+})
+ +SVG.Container = SVG.invent({
+ // Initialize node
+ create: function(element) {
+ this.constructor.call(this, element)
+ }
+
+ // Inherit from
+, inherit: SVG.Parent
+
}) - -// Add common method -SVG.extend(SVG.Circle, SVG.Ellipse, { - // Move over x-axis - x: function(x) { - return x == null ? this.cx() - this.rx() : this.cx(x + this.rx()) - } - // Move over y-axis - , y: function(y) { - return y == null ? this.cy() - this.ry() : this.cy(y + this.ry()) - } - // Move by center over x-axis - , cx: function(x) { - return x == null ? this.attr('cx') : this.attr('cx', x) - } - // Move by center over y-axis - , cy: function(y) { - return y == null ? this.attr('cy') : this.attr('cy', y) - } - // Set width of element - , width: function(width) { - return width == null ? this.rx() * 2 : this.rx(new SVG.Number(width).divide(2)) - } - // Set height of element - , height: function(height) { - return height == null ? this.ry() * 2 : this.ry(new SVG.Number(height).divide(2)) - } - // Custom size function - , size: function(width, height) { - var p = proportionalSize(this, width, height) - - return this - .rx(new SVG.Number(p.width).divide(2)) - .ry(new SVG.Number(p.height).divide(2)) - } -}) -SVG.Line = SVG.invent({ - // Initialize node - create: 'line' - - // Inherit from -, inherit: SVG.Shape - - // Add class methods -, extend: { - // Get array - array: function() { - return new SVG.PointArray([ - [ this.attr('x1'), this.attr('y1') ] - , [ this.attr('x2'), this.attr('y2') ] - ]) - } - // Overwrite native plot() method - , plot: function(x1, y1, x2, y2) { - if (x1 == null) - return this.array() - else if (typeof y1 !== 'undefined') - x1 = { x1: x1, y1: y1, x2: x2, y2: y2 } - else - x1 = new SVG.PointArray(x1).toLine() - - return this.attr(x1) - } - // Move by left top corner - , move: function(x, y) { - return this.attr(this.array().move(x, y).toLine()) - } - // Set element size to given width and height - , size: function(width, height) { - var p = proportionalSize(this, width, height) - - return this.attr(this.array().size(p.width, p.height).toLine()) - } - } - - // Add parent method -, construct: { - // Create a line element - line: function(x1, y1, x2, y2) { - // make sure plot is called as a setter - // x1 is not necessarily a number, it can also be an array, a string and a SVG.PointArray - return SVG.Line.prototype.plot.apply( - this.put(new SVG.Line) - , x1 != null ? [x1, y1, x2, y2] : [0, 0, 0, 0] - ) - } - } -}) - -SVG.Polyline = SVG.invent({ - // Initialize node - create: 'polyline' - - // Inherit from -, inherit: SVG.Shape - - // Add parent method -, construct: { - // Create a wrapped polyline element - polyline: function(p) { - // make sure plot is called as a setter - return this.put(new SVG.Polyline).plot(p || new SVG.PointArray) - } - } -}) - -SVG.Polygon = SVG.invent({ - // Initialize node - create: 'polygon' - - // Inherit from -, inherit: SVG.Shape - - // Add parent method -, construct: { - // Create a wrapped polygon element - polygon: function(p) { - // make sure plot is called as a setter - return this.put(new SVG.Polygon).plot(p || new SVG.PointArray) - } - } +// Add events to elements
+;[ 'click'
+ , 'dblclick'
+ , 'mousedown'
+ , 'mouseup'
+ , 'mouseover'
+ , 'mouseout'
+ , 'mousemove'
+ // , 'mouseenter' -> not supported by IE
+ // , 'mouseleave' -> not supported by IE
+ , 'touchstart'
+ , 'touchmove'
+ , 'touchleave'
+ , 'touchend'
+ , 'touchcancel' ].forEach(function(event) {
+
+ // add event to SVG.Element
+ SVG.Element.prototype[event] = function(f) {
+ // bind event to element rather than element node
+ SVG.on(this.node, event, f)
+ return this
+ }
+})
+
+// Initialize listeners stack
+SVG.listeners = []
+SVG.handlerMap = []
+SVG.listenerId = 0
+
+// Add event binder in the SVG namespace
+SVG.on = function(node, event, listener, binding, options) {
+ // create listener, get object-index
+ var l = listener.bind(binding || node.instance || node)
+ , index = (SVG.handlerMap.indexOf(node) + 1 || SVG.handlerMap.push(node)) - 1
+ , ev = event.split('.')[0]
+ , ns = event.split('.')[1] || '*'
+
+
+ // ensure valid object
+ SVG.listeners[index] = SVG.listeners[index] || {}
+ SVG.listeners[index][ev] = SVG.listeners[index][ev] || {}
+ SVG.listeners[index][ev][ns] = SVG.listeners[index][ev][ns] || {}
+
+ if(!listener._svgjsListenerId)
+ listener._svgjsListenerId = ++SVG.listenerId
+
+ // reference listener
+ SVG.listeners[index][ev][ns][listener._svgjsListenerId] = l
+
+ // add listener
+ node.addEventListener(ev, l, options || false)
+}
+
+// Add event unbinder in the SVG namespace
+SVG.off = function(node, event, listener) {
+ var index = SVG.handlerMap.indexOf(node)
+ , ev = event && event.split('.')[0]
+ , ns = event && event.split('.')[1]
+ , namespace = ''
+
+ if(index == -1) return
+
+ if (listener) {
+ if(typeof listener == 'function') listener = listener._svgjsListenerId
+ if(!listener) return
+
+ // remove listener reference
+ if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns || '*']) {
+ // remove listener
+ node.removeEventListener(ev, SVG.listeners[index][ev][ns || '*'][listener], false)
+
+ delete SVG.listeners[index][ev][ns || '*'][listener]
+ }
+
+ } else if (ns && ev) {
+ // remove all listeners for a namespaced event
+ if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns]) {
+ for (listener in SVG.listeners[index][ev][ns])
+ SVG.off(node, [ev, ns].join('.'), listener)
+
+ delete SVG.listeners[index][ev][ns]
+ }
+
+ } else if (ns){
+ // remove all listeners for a specific namespace
+ for(event in SVG.listeners[index]){
+ for(namespace in SVG.listeners[index][event]){
+ if(ns === namespace){
+ SVG.off(node, [event, ns].join('.'))
+ }
+ }
+ }
+
+ } else if (ev) {
+ // remove all listeners for the event
+ if (SVG.listeners[index][ev]) {
+ for (namespace in SVG.listeners[index][ev])
+ SVG.off(node, [ev, namespace].join('.'))
+
+ delete SVG.listeners[index][ev]
+ }
+
+ } else {
+ // remove all listeners on a given node
+ for (event in SVG.listeners[index])
+ SVG.off(node, event)
+
+ delete SVG.listeners[index]
+ delete SVG.handlerMap[index]
+
+ }
+}
+
+//
+SVG.extend(SVG.Element, {
+ // Bind given event to listener
+ on: function(event, listener, binding, options) {
+ SVG.on(this.node, event, listener, binding, options)
+
+ return this
+ }
+ // Unbind event from listener
+, off: function(event, listener) {
+ SVG.off(this.node, event, listener)
+
+ return this
+ }
+ // Fire given event
+, fire: function(event, data) {
+
+ // Dispatch event
+ if(event instanceof window.Event){
+ this.node.dispatchEvent(event)
+ }else{
+ this.node.dispatchEvent(event = new window.CustomEvent(event, {detail:data, cancelable: true}))
+ }
+
+ this._event = event
+ return this
+ }
+, event: function() {
+ return this._event
+ }
+})
+ +
+SVG.Defs = SVG.invent({
+ // Initialize node
+ create: 'defs'
+
+ // Inherit from
+, inherit: SVG.Container
+
}) - -// Add polygon-specific functions -SVG.extend(SVG.Polyline, SVG.Polygon, { - // Get array - array: function() { - return this._array || (this._array = new SVG.PointArray(this.attr('points'))) - } - // Plot new path -, plot: function(p) { - return (p == null) ? - this.array() : - this.attr('points', (this._array = new SVG.PointArray(p))) - } - // Move by left top corner -, move: function(x, y) { - return this.attr('points', this.array().move(x, y)) - } - // Set element size to given width and height -, size: function(width, height) { - var p = proportionalSize(this, width, height) - - return this.attr('points', this.array().size(p.width, p.height)) - } - +SVG.G = SVG.invent({
+ // Initialize node
+ create: 'g'
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Move over x-axis
+ x: function(x) {
+ return x == null ? this.transform('x') : this.transform({ x: x - this.x() }, true)
+ }
+ // Move over y-axis
+ , y: function(y) {
+ return y == null ? this.transform('y') : this.transform({ y: y - this.y() }, true)
+ }
+ // Move by center over x-axis
+ , cx: function(x) {
+ return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2)
+ }
+ // Move by center over y-axis
+ , cy: function(y) {
+ return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2)
+ }
+ , gbox: function() {
+
+ var bbox = this.bbox()
+ , trans = this.transform()
+
+ bbox.x += trans.x
+ bbox.x2 += trans.x
+ bbox.cx += trans.x
+
+ bbox.y += trans.y
+ bbox.y2 += trans.y
+ bbox.cy += trans.y
+
+ return bbox
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create a group element
+ group: function() {
+ return this.put(new SVG.G)
+ }
+ }
+})
+ +// ### This module adds backward / forward functionality to elements.
+
+//
+SVG.extend(SVG.Element, {
+ // Get all siblings, including myself
+ siblings: function() {
+ return this.parent().children()
+ }
+ // Get the curent position siblings
+, position: function() {
+ return this.parent().index(this)
+ }
+ // Get the next element (will return null if there is none)
+, next: function() {
+ return this.siblings()[this.position() + 1]
+ }
+ // Get the next element (will return null if there is none)
+, previous: function() {
+ return this.siblings()[this.position() - 1]
+ }
+ // Send given element one step forward
+, forward: function() {
+ var i = this.position() + 1
+ , p = this.parent()
+
+ // move node one step forward
+ p.removeElement(this).add(this, i)
+
+ // make sure defs node is always at the top
+ if (p instanceof SVG.Doc)
+ p.node.appendChild(p.defs().node)
+
+ return this
+ }
+ // Send given element one step backward
+, backward: function() {
+ var i = this.position()
+
+ if (i > 0)
+ this.parent().removeElement(this).add(this, i - 1)
+
+ return this
+ }
+ // Send given element all the way to the front
+, front: function() {
+ var p = this.parent()
+
+ // Move node forward
+ p.node.appendChild(this.node)
+
+ // Make sure defs node is always at the top
+ if (p instanceof SVG.Doc)
+ p.node.appendChild(p.defs().node)
+
+ return this
+ }
+ // Send given element all the way to the back
+, back: function() {
+ if (this.position() > 0)
+ this.parent().removeElement(this).add(this, 0)
+
+ return this
+ }
+ // Inserts a given element before the targeted element
+, before: function(element) {
+ element.remove()
+
+ var i = this.position()
+
+ this.parent().add(element, i)
+
+ return this
+ }
+ // Insters a given element after the targeted element
+, after: function(element) {
+ element.remove()
+
+ var i = this.position()
+
+ this.parent().add(element, i + 1)
+
+ return this
+ }
+
}) - -// unify all point to point elements -SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, { - // Define morphable array - morphArray: SVG.PointArray - // Move by left top corner over x-axis -, x: function(x) { - return x == null ? this.bbox().x : this.move(x, this.bbox().y) - } - // Move by left top corner over y-axis -, y: function(y) { - return y == null ? this.bbox().y : this.move(this.bbox().x, y) - } - // Set width of element -, width: function(width) { - var b = this.bbox() - - return width == null ? b.width : this.size(width, b.height) - } - // Set height of element -, height: function(height) { - var b = this.bbox() - - return height == null ? b.height : this.size(b.width, height) - } +SVG.Mask = SVG.invent({
+ // Initialize node
+ create: 'mask'
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Unmask all masked elements and remove itself
+ remove: function() {
+ // unmask all targets
+ this.targets().forEach(function(el) {
+ el.unmask()
+ })
+
+ // remove mask from parent
+ return SVG.Element.prototype.remove.call(this)
+ }
+
+ , targets: function() {
+ return SVG.select('svg [mask*="' +this.id() +'"]')
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create masking element
+ mask: function() {
+ return this.defs().put(new SVG.Mask)
+ }
+ }
+})
+
+
+SVG.extend(SVG.Element, {
+ // Distribute mask to svg element
+ maskWith: function(element) {
+ // use given mask or create a new one
+ var masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element)
+
+ // apply mask
+ return this.attr('mask', 'url("#' + masker.attr('id') + '")')
+ }
+ // Unmask element
+, unmask: function() {
+ return this.attr('mask', null)
+ }
+, masker: function() {
+ return this.reference('mask')
+ }
+})
+ +SVG.ClipPath = SVG.invent({
+ // Initialize node
+ create: 'clipPath'
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Unclip all clipped elements and remove itself
+ remove: function() {
+ // unclip all targets
+ this.targets().forEach(function(el) {
+ el.unclip()
+ })
+
+ // remove clipPath from parent
+ return SVG.Element.prototype.remove.call(this)
+ }
+
+ , targets: function() {
+ return SVG.select('svg [clip-path*="' +this.id() +'"]')
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create clipping element
+ clip: function() {
+ return this.defs().put(new SVG.ClipPath)
+ }
+ }
+})
+
+//
+SVG.extend(SVG.Element, {
+ // Distribute clipPath to svg element
+ clipWith: function(element) {
+ // use given clip or create a new one
+ var clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element)
+
+ // apply mask
+ return this.attr('clip-path', 'url("#' + clipper.attr('id') + '")')
+ }
+ // Unclip element
+, unclip: function() {
+ return this.attr('clip-path', null)
+ }
+, clipper: function() {
+ return this.reference('clip-path')
+ }
+
}) -SVG.Path = SVG.invent({ - // Initialize node - create: 'path' - - // Inherit from -, inherit: SVG.Shape - - // Add class methods -, extend: { - // Define morphable array - morphArray: SVG.PathArray - // Get array - , array: function() { - return this._array || (this._array = new SVG.PathArray(this.attr('d'))) - } - // Plot new poly points - , plot: function(p) { - return (p == null) ? - this.array() : - this.attr('d', (this._array = new SVG.PathArray(p))) - } - // Move by left top corner - , move: function(x, y) { - return this.attr('d', this.array().move(x, y)) - } - // Move by left top corner over x-axis - , x: function(x) { - return x == null ? this.bbox().x : this.move(x, this.bbox().y) - } - // Move by left top corner over y-axis - , y: function(y) { - return y == null ? this.bbox().y : this.move(this.bbox().x, y) - } - // Set element size to given width and height - , size: function(width, height) { - var p = proportionalSize(this, width, height) - - return this.attr('d', this.array().size(p.width, p.height)) - } - // Set width of element - , width: function(width) { - return width == null ? this.bbox().width : this.size(width, this.bbox().height) - } - // Set height of element - , height: function(height) { - return height == null ? this.bbox().height : this.size(this.bbox().width, height) - } - - } - - // Add parent method -, construct: { - // Create a wrapped path element - path: function(d) { - // make sure plot is called as a setter - return this.put(new SVG.Path).plot(d || new SVG.PathArray) - } - } +SVG.Gradient = SVG.invent({
+ // Initialize node
+ create: function(type) {
+ this.constructor.call(this, SVG.create(type + 'Gradient'))
+ }
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Add a color stop
+ at: function(offset, color, opacity) {
+ return this.put(new SVG.Stop).update(offset, color, opacity)
+ }
+ // Update gradient
+ , update: function(block) {
+ // remove all stops
+ this.clear()
+
+ // invoke passed block
+ if (typeof block == 'function')
+ block.call(this, this)
+
+ return this
+ }
+ // Return the fill id
+ , fill: function() {
+ return 'url(#' + this.id() + ')'
+ }
+ // Alias string convertion to fill
+ , toString: function() {
+ return this.fill()
+ }
+ // custom attr to handle transform
+ , attr: function(a, b, c) {
+ if(a == 'transform') a = 'gradientTransform'
+ return SVG.Container.prototype.attr.call(this, a, b, c)
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create gradient element in defs
+ gradient: function(type, block) {
+ return this.defs().gradient(type, block)
+ }
+ }
+})
+
+// Add animatable methods to both gradient and fx module
+SVG.extend(SVG.Gradient, SVG.FX, {
+ // From position
+ from: function(x, y) {
+ return (this._target || this).type == 'radialGradient' ?
+ this.attr({ fx: new SVG.Number(x), fy: new SVG.Number(y) }) :
+ this.attr({ x1: new SVG.Number(x), y1: new SVG.Number(y) })
+ }
+ // To position
+, to: function(x, y) {
+ return (this._target || this).type == 'radialGradient' ?
+ this.attr({ cx: new SVG.Number(x), cy: new SVG.Number(y) }) :
+ this.attr({ x2: new SVG.Number(x), y2: new SVG.Number(y) })
+ }
+})
+
+// Base gradient generation
+SVG.extend(SVG.Defs, {
+ // define gradient
+ gradient: function(type, block) {
+ return this.put(new SVG.Gradient(type)).update(block)
+ }
+
+})
+
+SVG.Stop = SVG.invent({
+ // Initialize node
+ create: 'stop'
+
+ // Inherit from
+, inherit: SVG.Element
+
+ // Add class methods
+, extend: {
+ // add color stops
+ update: function(o) {
+ if (typeof o == 'number' || o instanceof SVG.Number) {
+ o = {
+ offset: arguments[0]
+ , color: arguments[1]
+ , opacity: arguments[2]
+ }
+ }
+
+ // set attributes
+ if (o.opacity != null) this.attr('stop-opacity', o.opacity)
+ if (o.color != null) this.attr('stop-color', o.color)
+ if (o.offset != null) this.attr('offset', new SVG.Number(o.offset))
+
+ return this
+ }
+ }
+
+})
+ +SVG.Pattern = SVG.invent({
+ // Initialize node
+ create: 'pattern'
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Return the fill id
+ fill: function() {
+ return 'url(#' + this.id() + ')'
+ }
+ // Update pattern by rebuilding
+ , update: function(block) {
+ // remove content
+ this.clear()
+
+ // invoke passed block
+ if (typeof block == 'function')
+ block.call(this, this)
+
+ return this
+ }
+ // Alias string convertion to fill
+ , toString: function() {
+ return this.fill()
+ }
+ // custom attr to handle transform
+ , attr: function(a, b, c) {
+ if(a == 'transform') a = 'patternTransform'
+ return SVG.Container.prototype.attr.call(this, a, b, c)
+ }
+
+ }
+
+ // Add parent method
+, construct: {
+ // Create pattern element in defs
+ pattern: function(width, height, block) {
+ return this.defs().pattern(width, height, block)
+ }
+ }
+})
+
+SVG.extend(SVG.Defs, {
+ // Define gradient
+ pattern: function(width, height, block) {
+ return this.put(new SVG.Pattern).update(block).attr({
+ x: 0
+ , y: 0
+ , width: width
+ , height: height
+ , patternUnits: 'userSpaceOnUse'
+ })
+ }
+
}) - -SVG.Image = SVG.invent({ - // Initialize node - create: 'image' - - // Inherit from -, inherit: SVG.Shape - - // Add class methods -, extend: { - // (re)load image - load: function(url, callback) { - if (!url) return this - - var img = new window.Image() - - SVG.on(img, 'load', function(e) { - - var p = this.parent() - - // ensure image size - if (this.width() == 0 && this.height() == 0) - this.size(img.width, img.height) - - if(p instanceof SVG.Pattern) { - // ensure pattern size if not set - if (p.width() == 0 && p.height() == 0) - p.size(this.width(), this.height()) - } - - if(typeof callback == 'function') { - callback.call(this, { - width: img.width - , height: img.height - , ratio: img.width / img.height - , url: url - }) - } - }, this) - - return this.attr('href', (img.src = url), SVG.xlink) - } - } - - // Add parent method -, construct: { - // create image element, load image and set its size - image: function(source, callback) { - return this.put(new SVG.Image).size(0, 0).load(source, callback) - } - } +SVG.Doc = SVG.invent({
+ // Initialize node
+ create: function(element) {
+ if (element) {
+ // ensure the presence of a dom element
+ element = typeof element == 'string' ?
+ document.getElementById(element) :
+ element
+
+ // If the target is an svg element, use that element as the main wrapper.
+ // This allows svg.js to work with svg documents as well.
+ if (element.nodeName == 'svg') {
+ this.constructor.call(this, element)
+ } else {
+ this.constructor.call(this, SVG.create('svg'))
+ element.appendChild(this.node)
+ this.size('100%', '100%')
+ }
+
+ // set svg element attributes and ensure defs node
+ this.namespace().defs()
+ }
+ }
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Add namespaces
+ namespace: function() {
+ return this
+ .attr({ xmlns: SVG.ns, version: '1.1' })
+ .attr('xmlns:xlink', SVG.xlink, SVG.xmlns)
+ .attr('xmlns:svgjs', SVG.svgjs, SVG.xmlns)
+ }
+ // Creates and returns defs element
+ , defs: function() {
+ if (!this._defs) {
+ var defs
+
+ // Find or create a defs element in this instance
+ if (defs = this.node.getElementsByTagName('defs')[0])
+ this._defs = SVG.adopt(defs)
+ else
+ this._defs = new SVG.Defs
+
+ // Make sure the defs node is at the end of the stack
+ this.node.appendChild(this._defs.node)
+ }
+
+ return this._defs
+ }
+ // custom parent method
+ , parent: function() {
+ return this.node.parentNode.nodeName == '#document' ? null : this.node.parentNode
+ }
+ // Fix for possible sub-pixel offset. See:
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=608812
+ , spof: function(spof) {
+ var pos = this.node.getScreenCTM()
+
+ if (pos)
+ this
+ .style('left', (-pos.e % 1) + 'px')
+ .style('top', (-pos.f % 1) + 'px')
+
+ return this
+ }
+
+ // Removes the doc from the DOM
+ , remove: function() {
+ if(this.parent()) {
+ this.parent().removeChild(this.node)
+ }
+
+ return this
+ }
+ , clear: function() {
+ // remove children
+ while(this.node.hasChildNodes())
+ this.node.removeChild(this.node.lastChild)
+
+ // remove defs reference
+ delete this._defs
+
+ // add back parser
+ if(!SVG.parser.draw.parentNode)
+ this.node.appendChild(SVG.parser.draw)
+
+ return this
+ }
+ }
+
+})
+ +SVG.Shape = SVG.invent({
+ // Initialize node
+ create: function(element) {
+ this.constructor.call(this, element)
+ }
+
+ // Inherit from
+, inherit: SVG.Element
+
}) - -SVG.Text = SVG.invent({ - // Initialize node - create: function() { - this.constructor.call(this, SVG.create('text')) - - this.dom.leading = new SVG.Number(1.3) // store leading value for rebuilding - this._rebuild = true // enable automatic updating of dy values - this._build = false // disable build mode for adding multiple lines - - // set default font - this.attr('font-family', SVG.defaults.attrs['font-family']) - } - - // Inherit from -, inherit: SVG.Parent - - // Add class methods -, extend: { - // Move over x-axis - x: function(x) { - // act as getter - if (x == null) - return this.attr('x') - - return this.attr('x', x) - } - // Move over y-axis - , y: function(y) { - var oy = this.attr('y') - , o = typeof oy === 'number' ? oy - this.bbox().y : 0 - - // act as getter - if (y == null) - return typeof oy === 'number' ? oy - o : oy - - return this.attr('y', typeof y === 'number' ? y + o : y) - } - // Move center over x-axis - , cx: function(x) { - return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2) - } - // Move center over y-axis - , cy: function(y) { - return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2) - } - // Set the text content - , text: function(text) { - // act as getter - if (typeof text === 'undefined'){ - var text = '' - var children = this.node.childNodes - for(var i = 0, len = children.length; i < len; ++i){ - - // add newline if its not the first child and newLined is set to true - if(i != 0 && children[i].nodeType != 3 && SVG.adopt(children[i]).dom.newLined == true){ - text += '\n' - } - - // add content of this node - text += children[i].textContent - } - - return text - } - - // remove existing content - this.clear().build(true) - - if (typeof text === 'function') { - // call block - text.call(this, this) - - } else { - // store text and make sure text is not blank - text = text.split('\n') - - // build new lines - for (var i = 0, il = text.length; i < il; i++) - this.tspan(text[i]).newLine() - } - - // disable build mode and rebuild lines - return this.build(false).rebuild() - } - // Set font size - , size: function(size) { - return this.attr('font-size', size).rebuild() - } - // Set / get leading - , leading: function(value) { - // act as getter - if (value == null) - return this.dom.leading - - // act as setter - this.dom.leading = new SVG.Number(value) - - return this.rebuild() - } - // Rebuild appearance type - , rebuild: function(rebuild) { - // store new rebuild flag if given - if (typeof rebuild == 'boolean') - this._rebuild = rebuild - - // define position of all lines - if (this._rebuild) { - var self = this - , blankLineOffset = 0 - , dy = this.dom.leading * new SVG.Number(this.attr('font-size')) - - this.each(function() { - if (this.dom.newLined) { - if (!self.textPath()) - this.attr('x', self.attr('x')) - if(this.text() == '\n') { - blankLineOffset += dy - }else{ - this.attr('dy', dy + blankLineOffset) - blankLineOffset = 0 - } - } - }) - - this.fire('rebuild') - } - - return this - } - // Enable / disable build mode - , build: function(build) { - this._build = !!build - return this - } - // overwrite method from parent to set data properly - , setData: function(o){ - this.dom = o - this.dom.leading = new SVG.Number(o.leading || 1.3) - return this - } - } - - // Add parent method -, construct: { - // Create text element - text: function(text) { - return this.put(new SVG.Text).text(text) - } - // Create plain text element - , plain: function(text) { - return this.put(new SVG.Text).plain(text) - } - } - +
+SVG.Bare = SVG.invent({
+ // Initialize
+ create: function(element, inherit) {
+ // construct element
+ this.constructor.call(this, SVG.create(element))
+
+ // inherit custom methods
+ if (inherit)
+ for (var method in inherit.prototype)
+ if (typeof inherit.prototype[method] === 'function')
+ this[method] = inherit.prototype[method]
+ }
+
+ // Inherit from
+, inherit: SVG.Element
+
+ // Add methods
+, extend: {
+ // Insert some plain text
+ words: function(text) {
+ // remove contents
+ while (this.node.hasChildNodes())
+ this.node.removeChild(this.node.lastChild)
+
+ // create text node
+ this.node.appendChild(document.createTextNode(text))
+
+ return this
+ }
+ }
+})
+
+
+SVG.extend(SVG.Parent, {
+ // Create an element that is not described by SVG.js
+ element: function(element, inherit) {
+ return this.put(new SVG.Bare(element, inherit))
+ }
+})
+ +SVG.Symbol = SVG.invent({
+ // Initialize node
+ create: 'symbol'
+
+ // Inherit from
+, inherit: SVG.Container
+
+, construct: {
+ // create symbol
+ symbol: function() {
+ return this.put(new SVG.Symbol)
+ }
+ }
+})
+ +SVG.Use = SVG.invent({
+ // Initialize node
+ create: 'use'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add class methods
+, extend: {
+ // Use element as a reference
+ element: function(element, file) {
+ // Set lined element
+ return this.attr('href', (file || '') + '#' + element, SVG.xlink)
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create a use element
+ use: function(element, file) {
+ return this.put(new SVG.Use).element(element, file)
+ }
+ }
}) - -SVG.Tspan = SVG.invent({ - // Initialize node - create: 'tspan' - - // Inherit from -, inherit: SVG.Parent - - // Add class methods -, extend: { - // Set text content - text: function(text) { - if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '') - - typeof text === 'function' ? text.call(this, this) : this.plain(text) - - return this - } - // Shortcut dx - , dx: function(dx) { - return this.attr('dx', dx) - } - // Shortcut dy - , dy: function(dy) { - return this.attr('dy', dy) - } - // Create new line - , newLine: function() { - // fetch text parent - var t = this.parent(SVG.Text) - - // mark new line - this.dom.newLined = true - - // apply new hy¡n - return this.dy(t.dom.leading * t.attr('font-size')).attr('x', t.x()) - } - } - +SVG.Rect = SVG.invent({
+ // Initialize node
+ create: 'rect'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add parent method
+, construct: {
+ // Create a rect element
+ rect: function(width, height) {
+ return this.put(new SVG.Rect()).size(width, height)
+ }
+ }
}) - -SVG.extend(SVG.Text, SVG.Tspan, { - // Create plain text node - plain: function(text) { - // clear if build mode is disabled - if (this._build === false) - this.clear() - - // create text node - this.node.appendChild(document.createTextNode(text)) - - return this - } - // Create a tspan -, tspan: function(text) { - var node = (this.textPath && this.textPath() || this).node - , tspan = new SVG.Tspan - - // clear if build mode is disabled - if (this._build === false) - this.clear() - - // add new tspan - node.appendChild(tspan.node) - - return tspan.text(text) - } - // Get length of text element -, length: function() { - return this.node.getComputedTextLength() - } +SVG.Circle = SVG.invent({
+ // Initialize node
+ create: 'circle'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add parent method
+, construct: {
+ // Create circle element, based on ellipse
+ circle: function(size) {
+ return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0)
+ }
+ }
+})
+
+SVG.extend(SVG.Circle, SVG.FX, {
+ // Radius x value
+ rx: function(rx) {
+ return this.attr('r', rx)
+ }
+ // Alias radius x value
+, ry: function(ry) {
+ return this.rx(ry)
+ }
+})
+
+SVG.Ellipse = SVG.invent({
+ // Initialize node
+ create: 'ellipse'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add parent method
+, construct: {
+ // Create an ellipse
+ ellipse: function(width, height) {
+ return this.put(new SVG.Ellipse).size(width, height).move(0, 0)
+ }
+ }
+})
+
+SVG.extend(SVG.Ellipse, SVG.Rect, SVG.FX, {
+ // Radius x value
+ rx: function(rx) {
+ return this.attr('rx', rx)
+ }
+ // Radius y value
+, ry: function(ry) {
+ return this.attr('ry', ry)
+ }
+})
+
+// Add common method
+SVG.extend(SVG.Circle, SVG.Ellipse, {
+ // Move over x-axis
+ x: function(x) {
+ return x == null ? this.cx() - this.rx() : this.cx(x + this.rx())
+ }
+ // Move over y-axis
+ , y: function(y) {
+ return y == null ? this.cy() - this.ry() : this.cy(y + this.ry())
+ }
+ // Move by center over x-axis
+ , cx: function(x) {
+ return x == null ? this.attr('cx') : this.attr('cx', x)
+ }
+ // Move by center over y-axis
+ , cy: function(y) {
+ return y == null ? this.attr('cy') : this.attr('cy', y)
+ }
+ // Set width of element
+ , width: function(width) {
+ return width == null ? this.rx() * 2 : this.rx(new SVG.Number(width).divide(2))
+ }
+ // Set height of element
+ , height: function(height) {
+ return height == null ? this.ry() * 2 : this.ry(new SVG.Number(height).divide(2))
+ }
+ // Custom size function
+ , size: function(width, height) {
+ var p = proportionalSize(this, width, height)
+
+ return this
+ .rx(new SVG.Number(p.width).divide(2))
+ .ry(new SVG.Number(p.height).divide(2))
+ }
}) - -SVG.TextPath = SVG.invent({ - // Initialize node - create: 'textPath' - - // Inherit from -, inherit: SVG.Parent - - // Define parent class -, parent: SVG.Text - - // Add parent method -, construct: { - // Create path for text to run on - path: function(d) { - // create textPath element - var path = new SVG.TextPath - , track = this.doc().defs().path(d) - - // move lines to textpath - while (this.node.hasChildNodes()) - path.node.appendChild(this.node.firstChild) - - // add textPath element as child node - this.node.appendChild(path.node) - - // link textPath to path and add content - path.attr('href', '#' + track, SVG.xlink) - - return this - } - // return the array of the path track element - , array: function() { - var track = this.track() - - return track ? track.array() : null - } - // Plot path if any - , plot: function(d) { - var track = this.track() - , pathArray = null - - if (track) { - pathArray = track.plot(d) - } - - return (d == null) ? pathArray : this - } - // Get the path track element - , track: function() { - var path = this.textPath() - - if (path) - return path.reference('href') - } - // Get the textPath child - , textPath: function() { - if (this.node.firstChild && this.node.firstChild.nodeName == 'textPath') - return SVG.adopt(this.node.firstChild) - } - } +SVG.Line = SVG.invent({
+ // Initialize node
+ create: 'line'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add class methods
+, extend: {
+ // Get array
+ array: function() {
+ return new SVG.PointArray([
+ [ this.attr('x1'), this.attr('y1') ]
+ , [ this.attr('x2'), this.attr('y2') ]
+ ])
+ }
+ // Overwrite native plot() method
+ , plot: function(x1, y1, x2, y2) {
+ if (x1 == null)
+ return this.array()
+ else if (typeof y1 !== 'undefined')
+ x1 = { x1: x1, y1: y1, x2: x2, y2: y2 }
+ else
+ x1 = new SVG.PointArray(x1).toLine()
+
+ return this.attr(x1)
+ }
+ // Move by left top corner
+ , move: function(x, y) {
+ return this.attr(this.array().move(x, y).toLine())
+ }
+ // Set element size to given width and height
+ , size: function(width, height) {
+ var p = proportionalSize(this, width, height)
+
+ return this.attr(this.array().size(p.width, p.height).toLine())
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create a line element
+ line: function(x1, y1, x2, y2) {
+ // make sure plot is called as a setter
+ // x1 is not necessarily a number, it can also be an array, a string and a SVG.PointArray
+ return SVG.Line.prototype.plot.apply(
+ this.put(new SVG.Line)
+ , x1 != null ? [x1, y1, x2, y2] : [0, 0, 0, 0]
+ )
+ }
+ }
+})
+ +SVG.Polyline = SVG.invent({
+ // Initialize node
+ create: 'polyline'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add parent method
+, construct: {
+ // Create a wrapped polyline element
+ polyline: function(p) {
+ // make sure plot is called as a setter
+ return this.put(new SVG.Polyline).plot(p || new SVG.PointArray)
+ }
+ }
+})
+
+SVG.Polygon = SVG.invent({
+ // Initialize node
+ create: 'polygon'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add parent method
+, construct: {
+ // Create a wrapped polygon element
+ polygon: function(p) {
+ // make sure plot is called as a setter
+ return this.put(new SVG.Polygon).plot(p || new SVG.PointArray)
+ }
+ }
+})
+
+// Add polygon-specific functions
+SVG.extend(SVG.Polyline, SVG.Polygon, {
+ // Get array
+ array: function() {
+ return this._array || (this._array = new SVG.PointArray(this.attr('points')))
+ }
+ // Plot new path
+, plot: function(p) {
+ return (p == null) ?
+ this.array() :
+ this.clear().attr('points', typeof p == 'string' ? p : (this._array = new SVG.PointArray(p)))
+ }
+ // Clear array cache
+, clear: function() {
+ delete this._array
+ return this
+ }
+ // Move by left top corner
+, move: function(x, y) {
+ return this.attr('points', this.array().move(x, y))
+ }
+ // Set element size to given width and height
+, size: function(width, height) {
+ var p = proportionalSize(this, width, height)
+
+ return this.attr('points', this.array().size(p.width, p.height))
+ }
+
+})
+ +// unify all point to point elements
+SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, {
+ // Define morphable array
+ morphArray: SVG.PointArray
+ // Move by left top corner over x-axis
+, x: function(x) {
+ return x == null ? this.bbox().x : this.move(x, this.bbox().y)
+ }
+ // Move by left top corner over y-axis
+, y: function(y) {
+ return y == null ? this.bbox().y : this.move(this.bbox().x, y)
+ }
+ // Set width of element
+, width: function(width) {
+ var b = this.bbox()
+
+ return width == null ? b.width : this.size(width, b.height)
+ }
+ // Set height of element
+, height: function(height) {
+ var b = this.bbox()
+
+ return height == null ? b.height : this.size(b.width, height)
+ }
}) - -SVG.Nested = SVG.invent({ - // Initialize node - create: function() { - this.constructor.call(this, SVG.create('svg')) - - this.style('overflow', 'visible') - } - - // Inherit from -, inherit: SVG.Container - - // Add parent method -, construct: { - // Create nested svg document - nested: function() { - return this.put(new SVG.Nested) - } - } +SVG.Path = SVG.invent({
+ // Initialize node
+ create: 'path'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add class methods
+, extend: {
+ // Define morphable array
+ morphArray: SVG.PathArray
+ // Get array
+ , array: function() {
+ return this._array || (this._array = new SVG.PathArray(this.attr('d')))
+ }
+ // Plot new path
+ , plot: function(d) {
+ return (d == null) ?
+ this.array() :
+ this.clear().attr('d', typeof d == 'string' ? d : (this._array = new SVG.PathArray(d)))
+ }
+ // Clear array cache
+ , clear: function() {
+ delete this._array
+ return this
+ }
+ // Move by left top corner
+ , move: function(x, y) {
+ return this.attr('d', this.array().move(x, y))
+ }
+ // Move by left top corner over x-axis
+ , x: function(x) {
+ return x == null ? this.bbox().x : this.move(x, this.bbox().y)
+ }
+ // Move by left top corner over y-axis
+ , y: function(y) {
+ return y == null ? this.bbox().y : this.move(this.bbox().x, y)
+ }
+ // Set element size to given width and height
+ , size: function(width, height) {
+ var p = proportionalSize(this, width, height)
+
+ return this.attr('d', this.array().size(p.width, p.height))
+ }
+ // Set width of element
+ , width: function(width) {
+ return width == null ? this.bbox().width : this.size(width, this.bbox().height)
+ }
+ // Set height of element
+ , height: function(height) {
+ return height == null ? this.bbox().height : this.size(this.bbox().width, height)
+ }
+
+ }
+
+ // Add parent method
+, construct: {
+ // Create a wrapped path element
+ path: function(d) {
+ // make sure plot is called as a setter
+ return this.put(new SVG.Path).plot(d || new SVG.PathArray)
+ }
+ }
+})
+ +SVG.Image = SVG.invent({
+ // Initialize node
+ create: 'image'
+
+ // Inherit from
+, inherit: SVG.Shape
+
+ // Add class methods
+, extend: {
+ // (re)load image
+ load: function(url, callback) {
+ if (!url) return this
+
+ var img = new window.Image()
+
+ SVG.on(img, 'load', function(e) {
+
+ var p = this.parent()
+
+ // ensure image size
+ if (this.width() == 0 && this.height() == 0)
+ this.size(img.width, img.height)
+
+ if(p instanceof SVG.Pattern) {
+ // ensure pattern size if not set
+ if (p.width() == 0 && p.height() == 0)
+ p.size(this.width(), this.height())
+ }
+
+ if(typeof callback == 'function') {
+ callback.call(this, {
+ width: img.width
+ , height: img.height
+ , ratio: img.width / img.height
+ , url: url
+ })
+ }
+ }, this)
+
+ return this.attr('href', (img.src = url), SVG.xlink)
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // create image element, load image and set its size
+ image: function(source, callback) {
+ return this.put(new SVG.Image).size(0, 0).load(source, callback)
+ }
+ }
+})
+ +SVG.Text = SVG.invent({
+ // Initialize node
+ create: function() {
+ this.constructor.call(this, SVG.create('text'))
+
+ this.dom.leading = new SVG.Number(1.3) // store leading value for rebuilding
+ this._rebuild = true // enable automatic updating of dy values
+ this._build = false // disable build mode for adding multiple lines
+
+ // set default font
+ this.attr('font-family', SVG.defaults.attrs['font-family'])
+ }
+
+ // Inherit from
+, inherit: SVG.Parent
+
+ // Add class methods
+, extend: {
+ // Move over x-axis
+ x: function(x) {
+ // act as getter
+ if (x == null)
+ return this.attr('x')
+
+ return this.attr('x', x)
+ }
+ // Move over y-axis
+ , y: function(y) {
+ var oy = this.attr('y')
+ , o = typeof oy === 'number' ? oy - this.bbox().y : 0
+
+ // act as getter
+ if (y == null)
+ return typeof oy === 'number' ? oy - o : oy
+
+ return this.attr('y', typeof y === 'number' ? y + o : y)
+ }
+ // Move center over x-axis
+ , cx: function(x) {
+ return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2)
+ }
+ // Move center over y-axis
+ , cy: function(y) {
+ return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2)
+ }
+ // Set the text content
+ , text: function(text) {
+ // act as getter
+ if (typeof text === 'undefined'){
+ var text = ''
+ var children = this.node.childNodes
+ for(var i = 0, len = children.length; i < len; ++i){
+
+ // add newline if its not the first child and newLined is set to true
+ if(i != 0 && children[i].nodeType != 3 && SVG.adopt(children[i]).dom.newLined == true){
+ text += '\n'
+ }
+
+ // add content of this node
+ text += children[i].textContent
+ }
+
+ return text
+ }
+
+ // remove existing content
+ this.clear().build(true)
+
+ if (typeof text === 'function') {
+ // call block
+ text.call(this, this)
+
+ } else {
+ // store text and make sure text is not blank
+ text = text.split('\n')
+
+ // build new lines
+ for (var i = 0, il = text.length; i < il; i++)
+ this.tspan(text[i]).newLine()
+ }
+
+ // disable build mode and rebuild lines
+ return this.build(false).rebuild()
+ }
+ // Set font size
+ , size: function(size) {
+ return this.attr('font-size', size).rebuild()
+ }
+ // Set / get leading
+ , leading: function(value) {
+ // act as getter
+ if (value == null)
+ return this.dom.leading
+
+ // act as setter
+ this.dom.leading = new SVG.Number(value)
+
+ return this.rebuild()
+ }
+ // Rebuild appearance type
+ , rebuild: function(rebuild) {
+ // store new rebuild flag if given
+ if (typeof rebuild == 'boolean')
+ this._rebuild = rebuild
+
+ // define position of all lines
+ if (this._rebuild) {
+ var self = this
+ , blankLineOffset = 0
+ , dy = this.dom.leading * new SVG.Number(this.attr('font-size'))
+
+ this.each(function() {
+ if (this.dom.newLined) {
+ if (!self.textPath())
+ this.attr('x', self.attr('x'))
+ if(this.text() == '\n') {
+ blankLineOffset += dy
+ }else{
+ this.attr('dy', dy + blankLineOffset)
+ blankLineOffset = 0
+ }
+ }
+ })
+
+ this.fire('rebuild')
+ }
+
+ return this
+ }
+ // Enable / disable build mode
+ , build: function(build) {
+ this._build = !!build
+ return this
+ }
+ // overwrite method from parent to set data properly
+ , setData: function(o){
+ this.dom = o
+ this.dom.leading = new SVG.Number(o.leading || 1.3)
+ return this
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create text element
+ text: function(text) {
+ return this.put(new SVG.Text).text(text)
+ }
+ // Create plain text element
+ , plain: function(text) {
+ return this.put(new SVG.Text).plain(text)
+ }
+ }
+
+})
+
+SVG.Tspan = SVG.invent({
+ // Initialize node
+ create: 'tspan'
+
+ // Inherit from
+, inherit: SVG.Parent
+
+ // Add class methods
+, extend: {
+ // Set text content
+ text: function(text) {
+ if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '')
+
+ typeof text === 'function' ? text.call(this, this) : this.plain(text)
+
+ return this
+ }
+ // Shortcut dx
+ , dx: function(dx) {
+ return this.attr('dx', dx)
+ }
+ // Shortcut dy
+ , dy: function(dy) {
+ return this.attr('dy', dy)
+ }
+ // Create new line
+ , newLine: function() {
+ // fetch text parent
+ var t = this.parent(SVG.Text)
+
+ // mark new line
+ this.dom.newLined = true
+
+ // apply new hy¡n
+ return this.dy(t.dom.leading * t.attr('font-size')).attr('x', t.x())
+ }
+ }
+
+})
+
+SVG.extend(SVG.Text, SVG.Tspan, {
+ // Create plain text node
+ plain: function(text) {
+ // clear if build mode is disabled
+ if (this._build === false)
+ this.clear()
+
+ // create text node
+ this.node.appendChild(document.createTextNode(text))
+
+ return this
+ }
+ // Create a tspan
+, tspan: function(text) {
+ var node = (this.textPath && this.textPath() || this).node
+ , tspan = new SVG.Tspan
+
+ // clear if build mode is disabled
+ if (this._build === false)
+ this.clear()
+
+ // add new tspan
+ node.appendChild(tspan.node)
+
+ return tspan.text(text)
+ }
+ // Get length of text element
+, length: function() {
+ return this.node.getComputedTextLength()
+ }
+})
+ +SVG.TextPath = SVG.invent({
+ // Initialize node
+ create: 'textPath'
+
+ // Inherit from
+, inherit: SVG.Parent
+
+ // Define parent class
+, parent: SVG.Text
+
+ // Add parent method
+, construct: {
+ // Create path for text to run on
+ path: function(d) {
+ // create textPath element
+ var path = new SVG.TextPath
+ , track = this.doc().defs().path(d)
+
+ // move lines to textpath
+ while (this.node.hasChildNodes())
+ path.node.appendChild(this.node.firstChild)
+
+ // add textPath element as child node
+ this.node.appendChild(path.node)
+
+ // link textPath to path and add content
+ path.attr('href', '#' + track, SVG.xlink)
+
+ return this
+ }
+ // return the array of the path track element
+ , array: function() {
+ var track = this.track()
+
+ return track ? track.array() : null
+ }
+ // Plot path if any
+ , plot: function(d) {
+ var track = this.track()
+ , pathArray = null
+
+ if (track) {
+ pathArray = track.plot(d)
+ }
+
+ return (d == null) ? pathArray : this
+ }
+ // Get the path track element
+ , track: function() {
+ var path = this.textPath()
+
+ if (path)
+ return path.reference('href')
+ }
+ // Get the textPath child
+ , textPath: function() {
+ if (this.node.firstChild && this.node.firstChild.nodeName == 'textPath')
+ return SVG.adopt(this.node.firstChild)
+ }
+ }
+})
+ +SVG.Nested = SVG.invent({
+ // Initialize node
+ create: function() {
+ this.constructor.call(this, SVG.create('svg'))
+
+ this.style('overflow', 'visible')
+ }
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add parent method
+, construct: {
+ // Create nested svg document
+ nested: function() {
+ return this.put(new SVG.Nested)
+ }
+ }
}) -SVG.A = SVG.invent({ - // Initialize node - create: 'a' - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Link url - to: function(url) { - return this.attr('href', url, SVG.xlink) - } - // Link show attribute - , show: function(target) { - return this.attr('show', target, SVG.xlink) - } - // Link target attribute - , target: function(target) { - return this.attr('target', target) - } - } - - // Add parent method -, construct: { - // Create a hyperlink element - link: function(url) { - return this.put(new SVG.A).to(url) - } - } +SVG.A = SVG.invent({
+ // Initialize node
+ create: 'a'
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Link url
+ to: function(url) {
+ return this.attr('href', url, SVG.xlink)
+ }
+ // Link show attribute
+ , show: function(target) {
+ return this.attr('show', target, SVG.xlink)
+ }
+ // Link target attribute
+ , target: function(target) {
+ return this.attr('target', target)
+ }
+ }
+
+ // Add parent method
+, construct: {
+ // Create a hyperlink element
+ link: function(url) {
+ return this.put(new SVG.A).to(url)
+ }
+ }
+})
+
+SVG.extend(SVG.Element, {
+ // Create a hyperlink element
+ linkTo: function(url) {
+ var link = new SVG.A
+
+ if (typeof url == 'function')
+ url.call(link, link)
+ else
+ link.to(url)
+
+ return this.parent().put(link).put(this)
+ }
+
}) - -SVG.extend(SVG.Element, { - // Create a hyperlink element - linkTo: function(url) { - var link = new SVG.A - - if (typeof url == 'function') - url.call(link, link) - else - link.to(url) - - return this.parent().put(link).put(this) - } - +SVG.Marker = SVG.invent({
+ // Initialize node
+ create: 'marker'
+
+ // Inherit from
+, inherit: SVG.Container
+
+ // Add class methods
+, extend: {
+ // Set width of element
+ width: function(width) {
+ return this.attr('markerWidth', width)
+ }
+ // Set height of element
+ , height: function(height) {
+ return this.attr('markerHeight', height)
+ }
+ // Set marker refX and refY
+ , ref: function(x, y) {
+ return this.attr('refX', x).attr('refY', y)
+ }
+ // Update marker
+ , update: function(block) {
+ // remove all content
+ this.clear()
+
+ // invoke passed block
+ if (typeof block == 'function')
+ block.call(this, this)
+
+ return this
+ }
+ // Return the fill id
+ , toString: function() {
+ return 'url(#' + this.id() + ')'
+ }
+ }
+
+ // Add parent method
+, construct: {
+ marker: function(width, height, block) {
+ // Create marker element in defs
+ return this.defs().marker(width, height, block)
+ }
+ }
+
+})
+
+SVG.extend(SVG.Defs, {
+ // Create marker
+ marker: function(width, height, block) {
+ // Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto
+ return this.put(new SVG.Marker)
+ .size(width, height)
+ .ref(width / 2, height / 2)
+ .viewbox(0, 0, width, height)
+ .attr('orient', 'auto')
+ .update(block)
+ }
+
+})
+
+SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, SVG.Path, {
+ // Create and attach markers
+ marker: function(marker, width, height, block) {
+ var attr = ['marker']
+
+ // Build attribute name
+ if (marker != 'all') attr.push(marker)
+ attr = attr.join('-')
+
+ // Set marker attribute
+ marker = arguments[1] instanceof SVG.Marker ?
+ arguments[1] :
+ this.doc().marker(width, height, block)
+
+ return this.attr(attr, marker)
+ }
+
}) -SVG.Marker = SVG.invent({ - // Initialize node - create: 'marker' - - // Inherit from -, inherit: SVG.Container - - // Add class methods -, extend: { - // Set width of element - width: function(width) { - return this.attr('markerWidth', width) - } - // Set height of element - , height: function(height) { - return this.attr('markerHeight', height) - } - // Set marker refX and refY - , ref: function(x, y) { - return this.attr('refX', x).attr('refY', y) - } - // Update marker - , update: function(block) { - // remove all content - this.clear() - - // invoke passed block - if (typeof block == 'function') - block.call(this, this) - - return this - } - // Return the fill id - , toString: function() { - return 'url(#' + this.id() + ')' - } - } - - // Add parent method -, construct: { - marker: function(width, height, block) { - // Create marker element in defs - return this.defs().marker(width, height, block) - } - } - +// Define list of available attributes for stroke and fill
+var sugar = {
+ stroke: ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset']
+, fill: ['color', 'opacity', 'rule']
+, prefix: function(t, a) {
+ return a == 'color' ? t : t + '-' + a
+ }
+}
+
+// Add sugar for fill and stroke
+;['fill', 'stroke'].forEach(function(m) {
+ var i, extension = {}
+
+ extension[m] = function(o) {
+ if (typeof o == 'undefined')
+ return this
+ if (typeof o == 'string' || SVG.Color.isRgb(o) || (o && typeof o.fill === 'function'))
+ this.attr(m, o)
+
+ else
+ // set all attributes from sugar.fill and sugar.stroke list
+ for (i = sugar[m].length - 1; i >= 0; i--)
+ if (o[sugar[m][i]] != null)
+ this.attr(sugar.prefix(m, sugar[m][i]), o[sugar[m][i]])
+
+ return this
+ }
+
+ SVG.extend(SVG.Element, SVG.FX, extension)
+
+})
+
+SVG.extend(SVG.Element, SVG.FX, {
+ // Map rotation to transform
+ rotate: function(d, cx, cy) {
+ return this.transform({ rotation: d, cx: cx, cy: cy })
+ }
+ // Map skew to transform
+, skew: function(x, y, cx, cy) {
+ return arguments.length == 1 || arguments.length == 3 ?
+ this.transform({ skew: x, cx: y, cy: cx }) :
+ this.transform({ skewX: x, skewY: y, cx: cx, cy: cy })
+ }
+ // Map scale to transform
+, scale: function(x, y, cx, cy) {
+ return arguments.length == 1 || arguments.length == 3 ?
+ this.transform({ scale: x, cx: y, cy: cx }) :
+ this.transform({ scaleX: x, scaleY: y, cx: cx, cy: cy })
+ }
+ // Map translate to transform
+, translate: function(x, y) {
+ return this.transform({ x: x, y: y })
+ }
+ // Map flip to transform
+, flip: function(a, o) {
+ o = typeof a == 'number' ? a : o
+ return this.transform({ flip: a || 'both', offset: o })
+ }
+ // Map matrix to transform
+, matrix: function(m) {
+ return this.attr('transform', new SVG.Matrix(arguments.length == 6 ? [].slice.call(arguments) : m))
+ }
+ // Opacity
+, opacity: function(value) {
+ return this.attr('opacity', value)
+ }
+ // Relative move over x axis
+, dx: function(x) {
+ return this.x(new SVG.Number(x).plus(this instanceof SVG.FX ? 0 : this.x()), true)
+ }
+ // Relative move over y axis
+, dy: function(y) {
+ return this.y(new SVG.Number(y).plus(this instanceof SVG.FX ? 0 : this.y()), true)
+ }
+ // Relative move over x and y axes
+, dmove: function(x, y) {
+ return this.dx(x).dy(y)
+ }
+})
+
+SVG.extend(SVG.Rect, SVG.Ellipse, SVG.Circle, SVG.Gradient, SVG.FX, {
+ // Add x and y radius
+ radius: function(x, y) {
+ var type = (this._target || this).type;
+ return type == 'radialGradient' || type == 'radialGradient' ?
+ this.attr('r', new SVG.Number(x)) :
+ this.rx(x).ry(y == null ? x : y)
+ }
+})
+
+SVG.extend(SVG.Path, {
+ // Get path length
+ length: function() {
+ return this.node.getTotalLength()
+ }
+ // Get point at length
+, pointAt: function(length) {
+ return new SVG.Point(this.node.getPointAtLength(length))
+ }
+})
+
+SVG.extend(SVG.Parent, SVG.Text, SVG.Tspan, SVG.FX, {
+ // Set font
+ font: function(a, v) {
+ if (typeof a == 'object') {
+ for (v in a) this.font(v, a[v])
+ }
+
+ return a == 'leading' ?
+ this.leading(v) :
+ a == 'anchor' ?
+ this.attr('text-anchor', v) :
+ a == 'size' || a == 'family' || a == 'weight' || a == 'stretch' || a == 'variant' || a == 'style' ?
+ this.attr('font-'+ a, v) :
+ this.attr(a, v)
+ }
+})
+ +
+SVG.extend(SVG.Element, {
+ // Store data values on svg nodes
+ data: function(a, v, r) {
+ if (typeof a == 'object') {
+ for (v in a)
+ this.data(v, a[v])
+
+ } else if (arguments.length < 2) {
+ try {
+ return JSON.parse(this.attr('data-' + a))
+ } catch(e) {
+ return this.attr('data-' + a)
+ }
+
+ } else {
+ this.attr(
+ 'data-' + a
+ , v === null ?
+ null :
+ r === true || typeof v === 'string' || typeof v === 'number' ?
+ v :
+ JSON.stringify(v)
+ )
+ }
+
+ return this
+ }
}) - -SVG.extend(SVG.Defs, { - // Create marker - marker: function(width, height, block) { - // Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto - return this.put(new SVG.Marker) - .size(width, height) - .ref(width / 2, height / 2) - .viewbox(0, 0, width, height) - .attr('orient', 'auto') - .update(block) - } - +SVG.extend(SVG.Element, {
+ // Remember arbitrary data
+ remember: function(k, v) {
+ // remember every item in an object individually
+ if (typeof arguments[0] == 'object')
+ for (var v in k)
+ this.remember(v, k[v])
+
+ // retrieve memory
+ else if (arguments.length == 1)
+ return this.memory()[k]
+
+ // store memory
+ else
+ this.memory()[k] = v
+
+ return this
+ }
+
+ // Erase a given memory
+, forget: function() {
+ if (arguments.length == 0)
+ this._memory = {}
+ else
+ for (var i = arguments.length - 1; i >= 0; i--)
+ delete this.memory()[arguments[i]]
+
+ return this
+ }
+
+ // Initialize or return local memory object
+, memory: function() {
+ return this._memory || (this._memory = {})
+ }
+
}) - -SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, SVG.Path, { - // Create and attach markers - marker: function(marker, width, height, block) { - var attr = ['marker'] - - // Build attribute name - if (marker != 'all') attr.push(marker) - attr = attr.join('-') - - // Set marker attribute - marker = arguments[1] instanceof SVG.Marker ? - arguments[1] : - this.doc().marker(width, height, block) - - return this.attr(attr, marker) - } - -}) -// Define list of available attributes for stroke and fill -var sugar = { - stroke: ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset'] -, fill: ['color', 'opacity', 'rule'] -, prefix: function(t, a) { - return a == 'color' ? t : t + '-' + a - } -} - -// Add sugar for fill and stroke -;['fill', 'stroke'].forEach(function(m) { - var i, extension = {} - - extension[m] = function(o) { - if (typeof o == 'undefined') - return this - if (typeof o == 'string' || SVG.Color.isRgb(o) || (o && typeof o.fill === 'function')) - this.attr(m, o) - - else - // set all attributes from sugar.fill and sugar.stroke list - for (i = sugar[m].length - 1; i >= 0; i--) - if (o[sugar[m][i]] != null) - this.attr(sugar.prefix(m, sugar[m][i]), o[sugar[m][i]]) - - return this - } - - SVG.extend(SVG.Element, SVG.FX, extension) - -}) - -SVG.extend(SVG.Element, SVG.FX, { - // Map rotation to transform - rotate: function(d, cx, cy) { - return this.transform({ rotation: d, cx: cx, cy: cy }) - } - // Map skew to transform -, skew: function(x, y, cx, cy) { - return arguments.length == 1 || arguments.length == 3 ? - this.transform({ skew: x, cx: y, cy: cx }) : - this.transform({ skewX: x, skewY: y, cx: cx, cy: cy }) - } - // Map scale to transform -, scale: function(x, y, cx, cy) { - return arguments.length == 1 || arguments.length == 3 ? - this.transform({ scale: x, cx: y, cy: cx }) : - this.transform({ scaleX: x, scaleY: y, cx: cx, cy: cy }) - } - // Map translate to transform -, translate: function(x, y) { - return this.transform({ x: x, y: y }) - } - // Map flip to transform -, flip: function(a, o) { - o = typeof a == 'number' ? a : o - return this.transform({ flip: a || 'both', offset: o }) - } - // Map matrix to transform -, matrix: function(m) { - return this.attr('transform', new SVG.Matrix(arguments.length == 6 ? [].slice.call(arguments) : m)) - } - // Opacity -, opacity: function(value) { - return this.attr('opacity', value) - } - // Relative move over x axis -, dx: function(x) { - return this.x(new SVG.Number(x).plus(this instanceof SVG.FX ? 0 : this.x()), true) - } - // Relative move over y axis -, dy: function(y) { - return this.y(new SVG.Number(y).plus(this instanceof SVG.FX ? 0 : this.y()), true) - } - // Relative move over x and y axes -, dmove: function(x, y) { - return this.dx(x).dy(y) - } -}) - -SVG.extend(SVG.Rect, SVG.Ellipse, SVG.Circle, SVG.Gradient, SVG.FX, { - // Add x and y radius - radius: function(x, y) { - var type = (this._target || this).type; - return type == 'radialGradient' || type == 'radialGradient' ? - this.attr('r', new SVG.Number(x)) : - this.rx(x).ry(y == null ? x : y) - } -}) - -SVG.extend(SVG.Path, { - // Get path length - length: function() { - return this.node.getTotalLength() - } - // Get point at length -, pointAt: function(length) { - return new SVG.Point(this.node.getPointAtLength(length)) - } -}) - -SVG.extend(SVG.Parent, SVG.Text, SVG.Tspan, SVG.FX, { - // Set font - font: function(a, v) { - if (typeof a == 'object') { - for (v in a) this.font(v, a[v]) - } - - return a == 'leading' ? - this.leading(v) : - a == 'anchor' ? - this.attr('text-anchor', v) : - a == 'size' || a == 'family' || a == 'weight' || a == 'stretch' || a == 'variant' || a == 'style' ? - this.attr('font-'+ a, v) : - this.attr(a, v) - } -}) - - -SVG.extend(SVG.Element, { - // Store data values on svg nodes - data: function(a, v, r) { - if (typeof a == 'object') { - for (v in a) - this.data(v, a[v]) - - } else if (arguments.length < 2) { - try { - return JSON.parse(this.attr('data-' + a)) - } catch(e) { - return this.attr('data-' + a) - } - - } else { - this.attr( - 'data-' + a - , v === null ? - null : - r === true || typeof v === 'string' || typeof v === 'number' ? - v : - JSON.stringify(v) - ) - } - - return this - } -}) -SVG.extend(SVG.Element, { - // Remember arbitrary data - remember: function(k, v) { - // remember every item in an object individually - if (typeof arguments[0] == 'object') - for (var v in k) - this.remember(v, k[v]) - - // retrieve memory - else if (arguments.length == 1) - return this.memory()[k] - - // store memory - else - this.memory()[k] = v - - return this - } - - // Erase a given memory -, forget: function() { - if (arguments.length == 0) - this._memory = {} - else - for (var i = arguments.length - 1; i >= 0; i--) - delete this.memory()[arguments[i]] - - return this - } - - // Initialize or return local memory object -, memory: function() { - return this._memory || (this._memory = {}) - } - -}) -// Method for getting an element by id -SVG.get = function(id) { - var node = document.getElementById(idFromReference(id) || id) - return SVG.adopt(node) -} - -// Select elements by query string -SVG.select = function(query, parent) { - return SVG.utils.map((parent || document).querySelectorAll(query), function(node) { - return SVG.adopt(node) - }) -} - -SVG.$$ = function(query, parent) { - return SVG.utils.map((parent || document).querySelectorAll(query), function(node) { - return SVG.adopt(node) - }) -} - -SVG.$ = function(query, parent) { - return SVG.adopt((parent || document).querySelector(query)) -} - -SVG.extend(SVG.Parent, { - // Scoped select method - select: function(query) { - return SVG.select(query, this.node) - } -}) - -function isNulledBox(box) { - return !box.w && !box.h && !box.x && !box.y -} - -function domContains(node) { - return (document.documentElement.contains || function(node) { - // This is IE - it does not support contains() for top-level SVGs - while (node.parentNode){ - node = node.parentNode; - } - return node == document - }).call(document.documentElement, node) -} - -function pathRegReplace(a, b, c, d) { - return c + d.replace(SVG.regex.dots, ' .') -} - -// creates deep clone of array -function array_clone(arr){ - var clone = arr.slice(0) - for(var i = clone.length; i--;){ - if(Array.isArray(clone[i])){ - clone[i] = array_clone(clone[i]) - } - } - return clone -} - -// tests if a given element is instance of an object -function is(el, obj){ - return el instanceof obj -} - -// tests if a given selector matches an element -function matches(el, selector) { - return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector); -} - -// Convert dash-separated-string to camelCase -function camelCase(s) { - return s.toLowerCase().replace(/-(.)/g, function(m, g) { - return g.toUpperCase() - }) -} - -// Capitalize first letter of a string -function capitalize(s) { - return s.charAt(0).toUpperCase() + s.slice(1) -} - -// Ensure to six-based hex -function fullHex(hex) { - return hex.length == 4 ? - [ '#', - hex.substring(1, 2), hex.substring(1, 2) - , hex.substring(2, 3), hex.substring(2, 3) - , hex.substring(3, 4), hex.substring(3, 4) - ].join('') : hex -} - -// Component to hex value -function compToHex(comp) { - var hex = comp.toString(16) - return hex.length == 1 ? '0' + hex : hex -} - -// Calculate proportional width and height values when necessary -function proportionalSize(element, width, height) { - if (width == null || height == null) { - var box = element.bbox() - - if (width == null) - width = box.width / box.height * height - else if (height == null) - height = box.height / box.width * width - } - - return { - width: width - , height: height - } -} - -// Delta transform point -function deltaTransformPoint(matrix, x, y) { - return { - x: x * matrix.a + y * matrix.c + 0 - , y: x * matrix.b + y * matrix.d + 0 - } -} - -// Map matrix array to object -function arrayToMatrix(a) { - return { a: a[0], b: a[1], c: a[2], d: a[3], e: a[4], f: a[5] } -} - -// Parse matrix if required -function parseMatrix(matrix) { - if (!(matrix instanceof SVG.Matrix)) - matrix = new SVG.Matrix(matrix) - - return matrix -} - -// Add centre point to transform object -function ensureCentre(o, target) { - o.cx = o.cx == null ? target.bbox().cx : o.cx - o.cy = o.cy == null ? target.bbox().cy : o.cy -} - -// PathArray Helpers -function arrayToString(a) { - for (var i = 0, il = a.length, s = ''; i < il; i++) { - s += a[i][0] - - if (a[i][1] != null) { - s += a[i][1] - - if (a[i][2] != null) { - s += ' ' - s += a[i][2] - - if (a[i][3] != null) { - s += ' ' - s += a[i][3] - s += ' ' - s += a[i][4] - - if (a[i][5] != null) { - s += ' ' - s += a[i][5] - s += ' ' - s += a[i][6] - - if (a[i][7] != null) { - s += ' ' - s += a[i][7] - } - } - } - } - } - } - - return s + ' ' -} - -// Deep new id assignment -function assignNewId(node) { - // do the same for SVG child nodes as well - for (var i = node.childNodes.length - 1; i >= 0; i--) - if (node.childNodes[i] instanceof window.SVGElement) - assignNewId(node.childNodes[i]) - - return SVG.adopt(node).id(SVG.eid(node.nodeName)) -} - -// Add more bounding box properties -function fullBox(b) { - if (b.x == null) { - b.x = 0 - b.y = 0 - b.width = 0 - b.height = 0 - } - - b.w = b.width - b.h = b.height - b.x2 = b.x + b.width - b.y2 = b.y + b.height - b.cx = b.x + b.width / 2 - b.cy = b.y + b.height / 2 - - return b -} - -// Get id from reference string -function idFromReference(url) { - var m = (url || '').toString().match(SVG.regex.reference) - - if (m) return m[1] -} - -// Create matrix array for looping -var abcdef = 'abcdef'.split('') - -SVG.Box = SVG.invent({ - create: function(source) { - var base = [0,0,0,0] - source = typeof source === 'string' ? - source.split(SVG.regex.delimiter).map(parseFloat) : - Array.isArray(source) ? - source : - typeof source == 'object' ? - [source.left != null ? source.left : source.x, source.top != null ? source.top : source.y, source.width, source.height] : - arguments.length == 4 ? - [].slice.call(arguments) : - base - - this.x = source[0] - this.y = source[1] - this.width = source[2] - this.height = source[3] - - // add center, right, bottom... - fullBox(this) - } -, extend: { - // Merge rect box with another, return a new instance - merge: function(box) { - var x = Math.min(this.x, box.x) - , y = Math.min(this.y, box.y) - - return new SVG.Box( - x, y, - Math.max(this.x + this.width, box.x + box.width) - x, - Math.max(this.y + this.height, box.y + box.height) - y - ) - } - - , transform: function(m) { - var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, p - - var pts = [ - new SVG.Point(this.x, this.y), - new SVG.Point(this.x2, this.y), - new SVG.Point(this.x, this.y2), - new SVG.Point(this.x2, this.y2) - ] - - pts.forEach(function(p) { - p = p.transform(m) - xMin = Math.min(xMin,p.x) - xMax = Math.max(xMax,p.x) - yMin = Math.min(yMin,p.y) - yMax = Math.max(yMax,p.y) - }) - - return new SVG.Box( - xMin, yMin, - xMax-xMin, - yMax-yMin - ) - } - - , addOffset: function() { - // offset by window scroll position, because getBoundingClientRect changes when window is scrolled - this.x += window.pageXOffset - this.y += window.pageYOffset - return this - } - , toString: function() { - return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height - } - , morph: function(x, y, width, height){ - this.destination = new SVG.Box(x, y, width, height) - return this - } - - , at: function(pos) { - - if(!this.destination) return this - - return new SVG.Box( - this.x + (this.destination.x - this.x) * pos - , this.y + (this.destination.y - this.y) * pos - , this.width + (this.destination.width - this.width) * pos - , this.height + (this.destination.height - this.height) * pos - ) - - } - } - - // Define Parent -, parent: SVG.Element - - // Constructor -, construct: { - // Get bounding box - bbox: function() { - var box - - try { - // find native bbox - box = this.node.getBBox() - - if(isNulledBox(box) && !domContains(this.node)) { - throw new Exception('Element not in the dom') - } - } catch(e) { - try { - var clone = this.clone(SVG.parser.draw).show() - box = clone.node.getBBox() - clone.remove() - } catch(e) { - console.warn('Getting a bounding box of this element is not possible') - } - } - - return new SVG.Box(box) - } - - , rbox: function(el) { - // IE11 throws an error when element not in dom - try{ - var box = new SVG.Box(this.node.getBoundingClientRect()) - if (el) return box.transform(el.screenCTM().inverse()) - return box.addOffset() - } catch(e) { - return new SVG.Box() - } - } - } -}) - -SVG.extend(SVG.Doc, SVG.Nested, SVG.Symbol, SVG.Image, SVG.Pattern, SVG.Marker, SVG.ForeignObject, SVG.View, { - viewbox: function(x, y, width, height) { - // act as getter - if(x == null) return new SVG.Box(this.attr('viewBox')) - - // act as setter - return this.attr('viewBox', new SVG.Box(x, y, width, height)) - } -}) - - -return SVG - -}));
\ No newline at end of file +// Method for getting an element by id
+SVG.get = function(id) {
+ var node = document.getElementById(idFromReference(id) || id)
+ return SVG.adopt(node)
+}
+
+// Select elements by query string
+SVG.select = function(query, parent) {
+ return SVG.utils.map((parent || document).querySelectorAll(query), function(node) {
+ return SVG.adopt(node)
+ })
+}
+
+SVG.$$ = function(query, parent) {
+ return SVG.utils.map((parent || document).querySelectorAll(query), function(node) {
+ return SVG.adopt(node)
+ })
+}
+
+SVG.$ = function(query, parent) {
+ return SVG.adopt((parent || document).querySelector(query))
+}
+
+SVG.extend(SVG.Parent, {
+ // Scoped select method
+ select: function(query) {
+ return SVG.select(query, this.node)
+ }
+})
+ +function isNulledBox(box) {
+ return !box.w && !box.h && !box.x && !box.y
+}
+
+function domContains(node) {
+ return (document.documentElement.contains || function(node) {
+ // This is IE - it does not support contains() for top-level SVGs
+ while (node.parentNode){
+ node = node.parentNode;
+ }
+ return node == document
+ }).call(document.documentElement, node)
+}
+
+function pathRegReplace(a, b, c, d) {
+ return c + d.replace(SVG.regex.dots, ' .')
+}
+
+// creates deep clone of array
+function array_clone(arr){
+ var clone = arr.slice(0)
+ for(var i = clone.length; i--;){
+ if(Array.isArray(clone[i])){
+ clone[i] = array_clone(clone[i])
+ }
+ }
+ return clone
+}
+
+// tests if a given element is instance of an object
+function is(el, obj){
+ return el instanceof obj
+}
+
+// tests if a given selector matches an element
+function matches(el, selector) {
+ return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
+}
+
+// Convert dash-separated-string to camelCase
+function camelCase(s) {
+ return s.toLowerCase().replace(/-(.)/g, function(m, g) {
+ return g.toUpperCase()
+ })
+}
+
+// Capitalize first letter of a string
+function capitalize(s) {
+ return s.charAt(0).toUpperCase() + s.slice(1)
+}
+
+// Ensure to six-based hex
+function fullHex(hex) {
+ return hex.length == 4 ?
+ [ '#',
+ hex.substring(1, 2), hex.substring(1, 2)
+ , hex.substring(2, 3), hex.substring(2, 3)
+ , hex.substring(3, 4), hex.substring(3, 4)
+ ].join('') : hex
+}
+
+// Component to hex value
+function compToHex(comp) {
+ var hex = comp.toString(16)
+ return hex.length == 1 ? '0' + hex : hex
+}
+
+// Calculate proportional width and height values when necessary
+function proportionalSize(element, width, height) {
+ if (width == null || height == null) {
+ var box = element.bbox()
+
+ if (width == null)
+ width = box.width / box.height * height
+ else if (height == null)
+ height = box.height / box.width * width
+ }
+
+ return {
+ width: width
+ , height: height
+ }
+}
+
+// Delta transform point
+function deltaTransformPoint(matrix, x, y) {
+ return {
+ x: x * matrix.a + y * matrix.c + 0
+ , y: x * matrix.b + y * matrix.d + 0
+ }
+}
+
+// Map matrix array to object
+function arrayToMatrix(a) {
+ return { a: a[0], b: a[1], c: a[2], d: a[3], e: a[4], f: a[5] }
+}
+
+// Parse matrix if required
+function parseMatrix(matrix) {
+ if (!(matrix instanceof SVG.Matrix))
+ matrix = new SVG.Matrix(matrix)
+
+ return matrix
+}
+
+// Add centre point to transform object
+function ensureCentre(o, target) {
+ o.cx = o.cx == null ? target.bbox().cx : o.cx
+ o.cy = o.cy == null ? target.bbox().cy : o.cy
+}
+
+// PathArray Helpers
+function arrayToString(a) {
+ for (var i = 0, il = a.length, s = ''; i < il; i++) {
+ s += a[i][0]
+
+ if (a[i][1] != null) {
+ s += a[i][1]
+
+ if (a[i][2] != null) {
+ s += ' '
+ s += a[i][2]
+
+ if (a[i][3] != null) {
+ s += ' '
+ s += a[i][3]
+ s += ' '
+ s += a[i][4]
+
+ if (a[i][5] != null) {
+ s += ' '
+ s += a[i][5]
+ s += ' '
+ s += a[i][6]
+
+ if (a[i][7] != null) {
+ s += ' '
+ s += a[i][7]
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return s + ' '
+}
+
+// Deep new id assignment
+function assignNewId(node) {
+ // do the same for SVG child nodes as well
+ for (var i = node.childNodes.length - 1; i >= 0; i--)
+ if (node.childNodes[i] instanceof window.SVGElement)
+ assignNewId(node.childNodes[i])
+
+ return SVG.adopt(node).id(SVG.eid(node.nodeName))
+}
+
+// Add more bounding box properties
+function fullBox(b) {
+ if (b.x == null) {
+ b.x = 0
+ b.y = 0
+ b.width = 0
+ b.height = 0
+ }
+
+ b.w = b.width
+ b.h = b.height
+ b.x2 = b.x + b.width
+ b.y2 = b.y + b.height
+ b.cx = b.x + b.width / 2
+ b.cy = b.y + b.height / 2
+
+ return b
+}
+
+// Get id from reference string
+function idFromReference(url) {
+ var m = (url || '').toString().match(SVG.regex.reference)
+
+ if (m) return m[1]
+}
+
+// Create matrix array for looping
+var abcdef = 'abcdef'.split('')
+ +SVG.Box = SVG.invent({
+ create: function(source) {
+ var base = [0,0,0,0]
+ source = typeof source === 'string' ?
+ source.split(SVG.regex.delimiter).map(parseFloat) :
+ Array.isArray(source) ?
+ source :
+ typeof source == 'object' ?
+ [source.left != null ? source.left : source.x, source.top != null ? source.top : source.y, source.width, source.height] :
+ arguments.length == 4 ?
+ [].slice.call(arguments) :
+ base
+
+ this.x = source[0]
+ this.y = source[1]
+ this.width = source[2]
+ this.height = source[3]
+
+ // add center, right, bottom...
+ fullBox(this)
+ }
+, extend: {
+ // Merge rect box with another, return a new instance
+ merge: function(box) {
+ var x = Math.min(this.x, box.x)
+ , y = Math.min(this.y, box.y)
+
+ return new SVG.Box(
+ x, y,
+ Math.max(this.x + this.width, box.x + box.width) - x,
+ Math.max(this.y + this.height, box.y + box.height) - y
+ )
+ }
+
+ , transform: function(m) {
+ var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, p, bbox
+
+ var pts = [
+ new SVG.Point(this.x, this.y),
+ new SVG.Point(this.x2, this.y),
+ new SVG.Point(this.x, this.y2),
+ new SVG.Point(this.x2, this.y2)
+ ]
+
+ pts.forEach(function(p) {
+ p = p.transform(m)
+ xMin = Math.min(xMin,p.x)
+ xMax = Math.max(xMax,p.x)
+ yMin = Math.min(yMin,p.y)
+ yMax = Math.max(yMax,p.y)
+ })
+
+ return new SVG.Box(
+ xMin, yMin,
+ xMax-xMin,
+ yMax-yMin
+ )
+ }
+
+ , addOffset: function() {
+ // offset by window scroll position, because getBoundingClientRect changes when window is scrolled
+ this.x += window.pageXOffset
+ this.y += window.pageYOffset
+ return this
+ }
+ , toString: function() {
+ return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height
+ }
+ , morph: function(x, y, width, height){
+ this.destination = new SVG.Box(x, y, width, height)
+ return this
+ }
+
+ , at: function(pos) {
+ if(!this.destination) return this
+
+ return new SVG.Box(
+ this.x + (this.destination.x - this.x) * pos
+ , this.y + (this.destination.y - this.y) * pos
+ , this.width + (this.destination.width - this.width) * pos
+ , this.height + (this.destination.height - this.height) * pos
+ )
+
+ }
+ }
+
+ // Define Parent
+, parent: SVG.Element
+
+ // Constructor
+, construct: {
+ // Get bounding box
+ bbox: function() {
+ var box
+
+ try {
+ // find native bbox
+ box = this.node.getBBox()
+
+ if(isNulledBox(box) && !domContains(this.node)) {
+ throw new Exception('Element not in the dom')
+ }
+ } catch(e) {
+ try {
+ var clone = this.clone(SVG.parser.draw.instance).show()
+ box = clone.node.getBBox()
+ clone.remove()
+ } catch(e) {
+ console.warn('Getting a bounding box of this element is not possible')
+ }
+ }
+
+ return new SVG.Box(box)
+ }
+
+ , rbox: function(el) {
+ // IE11 throws an error when element not in dom
+ try{
+ var box = new SVG.Box(this.node.getBoundingClientRect())
+ if (el) return box.transform(el.screenCTM().inverse())
+ return box.addOffset()
+ } catch(e) {
+ return new SVG.Box()
+ }
+ }
+ }
+})
+
+SVG.extend(SVG.Doc, SVG.Nested, SVG.Symbol, SVG.Image, SVG.Pattern, SVG.Marker, SVG.ForeignObject, SVG.View, {
+ viewbox: function(x, y, width, height) {
+ // act as getter
+ if(x == null) return new SVG.Box(this.attr('viewBox'))
+
+ // act as setter
+ return this.attr('viewBox', new SVG.Box(x, y, width, height))
+ }
+})
+
+
+return SVG
+
+}));
\ No newline at end of file diff --git a/dist/svg.min.js b/dist/svg.min.js index 4e9e07c..45932ad 100644 --- a/dist/svg.min.js +++ b/dist/svg.min.js @@ -1,2 +1,2 @@ -/*! svg.js v2.5.0 MIT*/;!function(t,e){"function"==typeof define&&define.amd?define(function(){return e(t,t.document)}):"object"==typeof exports?module.exports=t.document?e(t,t.document):function(t){return e(t,t.document)}:t.SVG=e(t,t.document)}("undefined"!=typeof window?window:this,function(t,e){function i(t){return!(t.w||t.h||t.x||t.y)}function n(t){return(e.documentElement.contains||function(t){for(;t.parentNode;)t=t.parentNode;return t==e}).call(e.documentElement,t)}function r(t,e,i,n){return i+n.replace(b.regex.dots," .")}function s(t){for(var e=t.slice(0),i=e.length;i--;)Array.isArray(e[i])&&(e[i]=s(e[i]));return e}function a(t,e){return t instanceof e}function o(t,e){return(t.matches||t.matchesSelector||t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||t.oMatchesSelector).call(t,e)}function h(t){return t.toLowerCase().replace(/-(.)/g,function(t,e){return e.toUpperCase()})}function u(t){return t.charAt(0).toUpperCase()+t.slice(1)}function l(t){return 4==t.length?["#",t.substring(1,2),t.substring(1,2),t.substring(2,3),t.substring(2,3),t.substring(3,4),t.substring(3,4)].join(""):t}function c(t){var e=t.toString(16);return 1==e.length?"0"+e:e}function f(t,e,i){if(null==e||null==i){var n=t.bbox();null==e?e=n.width/n.height*i:null==i&&(i=n.height/n.width*e)}return{width:e,height:i}}function d(t,e,i){return{x:e*t.a+i*t.c+0,y:e*t.b+i*t.d+0}}function p(t){return{a:t[0],b:t[1],c:t[2],d:t[3],e:t[4],f:t[5]}}function m(t){return t instanceof b.Matrix||(t=new b.Matrix(t)),t}function x(t,e){t.cx=null==t.cx?e.bbox().cx:t.cx,t.cy=null==t.cy?e.bbox().cy:t.cy}function y(t){for(var e=0,i=t.length,n="";e<i;e++)n+=t[e][0],null!=t[e][1]&&(n+=t[e][1],null!=t[e][2]&&(n+=" ",n+=t[e][2],null!=t[e][3]&&(n+=" ",n+=t[e][3],n+=" ",n+=t[e][4],null!=t[e][5]&&(n+=" ",n+=t[e][5],n+=" ",n+=t[e][6],null!=t[e][7]&&(n+=" ",n+=t[e][7])))));return n+" "}function v(e){for(var i=e.childNodes.length-1;i>=0;i--)e.childNodes[i]instanceof t.SVGElement&&v(e.childNodes[i]);return b.adopt(e).id(b.eid(e.nodeName))}function g(t){return null==t.x&&(t.x=0,t.y=0,t.width=0,t.height=0),t.w=t.width,t.h=t.height,t.x2=t.x+t.width,t.y2=t.y+t.height,t.cx=t.x+t.width/2,t.cy=t.y+t.height/2,t}function w(t){var e=(t||"").toString().match(b.regex.reference);if(e)return e[1]}var b=this.SVG=function(t){if(b.supported)return t=new b.Doc(t),b.parser.draw||b.prepare(),t};if(b.ns="http://www.w3.org/2000/svg",b.xmlns="http://www.w3.org/2000/xmlns/",b.xlink="http://www.w3.org/1999/xlink",b.svgjs="http://svgjs.com/svgjs",b.supported=function(){return!!e.createElementNS&&!!e.createElementNS(b.ns,"svg").createSVGRect}(),!b.supported)return!1;b.did=1e3,b.eid=function(t){return"Svgjs"+u(t)+b.did++},b.create=function(t){var i=e.createElementNS(this.ns,t);return i.setAttribute("id",this.eid(t)),i},b.extend=function(){var t,e,i,n;for(t=[].slice.call(arguments),e=t.pop(),n=t.length-1;n>=0;n--)if(t[n])for(i in e)t[n].prototype[i]=e[i]},b.invent=function(t){var e="function"==typeof t.create?t.create:function(){this.constructor.call(this,b.create(t.create))};return t.inherit&&(e.prototype=new t.inherit),t.extend&&b.extend(e,t.extend),t.construct&&b.extend(t.parent||b.Container,t.construct),e},b.adopt=function(e){if(!e)return null;if(e.instance)return e.instance;var i;return i="svg"==e.nodeName?e.parentNode instanceof t.SVGElement?new b.Nested:new b.Doc:"linearGradient"==e.nodeName?new b.Gradient("linear"):"radialGradient"==e.nodeName?new b.Gradient("radial"):b[u(e.nodeName)]?new(b[u(e.nodeName)]):new b.Element(e),i.type=e.nodeName,i.node=e,e.instance=i,i instanceof b.Doc&&i.namespace().defs(),i.setData(JSON.parse(e.getAttribute("svgjs:data"))||{}),i},b.prepare=function(){var t=e.getElementsByTagName("body")[0],i=(t?new b.Doc(t):new b.Doc(e.documentElement).nested()).size(2,0);b.parser={body:t||e.documentElement,draw:i.style({opacity:0,position:"absolute",left:"-100%",top:"-100%",overflow:"hidden"}),poly:i.polyline().node,path:i.path().node,native:b.create("svg")}},b.parser={native:b.create("svg")},e.addEventListener("DOMContentLoaded",function(){b.parser.draw||b.prepare()},!1),b.regex={numberAndUnit:/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,hex:/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,rgb:/rgb\((\d+),(\d+),(\d+)\)/,reference:/#([a-z0-9\-_]+)/i,transforms:/\)\s*,?\s*/,whitespace:/\s/g,isHex:/^#[a-f0-9]{3,6}$/i,isRgb:/^rgb\(/,isCss:/[^:]+:[^;]+;?/,isBlank:/^(\s+)?$/,isNumber:/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,isPercent:/^-?[\d\.]+%$/,isImage:/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,delimiter:/[\s,]+/,hyphen:/([^e])\-/gi,pathLetters:/[MLHVCSQTAZ]/gi,isPathLetter:/[MLHVCSQTAZ]/i,numbersWithDots:/((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi,dots:/\./g},b.utils={map:function(t,e){var i,n=t.length,r=[];for(i=0;i<n;i++)r.push(e(t[i]));return r},filter:function(t,e){var i,n=t.length,r=[];for(i=0;i<n;i++)e(t[i])&&r.push(t[i]);return r},radians:function(t){return t%360*Math.PI/180},degrees:function(t){return 180*t/Math.PI%360},filterSVGElements:function(e){return this.filter(e,function(e){return e instanceof t.SVGElement})}},b.defaults={attrs:{"fill-opacity":1,"stroke-opacity":1,"stroke-width":0,"stroke-linejoin":"miter","stroke-linecap":"butt",fill:"#000000",stroke:"#000000",opacity:1,x:0,y:0,cx:0,cy:0,width:0,height:0,r:0,rx:0,ry:0,offset:0,"stop-opacity":1,"stop-color":"#000000","font-size":16,"font-family":"Helvetica, Arial, sans-serif","text-anchor":"start"}},b.Color=function(t){var e;this.r=0,this.g=0,this.b=0,t&&("string"==typeof t?b.regex.isRgb.test(t)?(e=b.regex.rgb.exec(t.replace(b.regex.whitespace,"")),this.r=parseInt(e[1]),this.g=parseInt(e[2]),this.b=parseInt(e[3])):b.regex.isHex.test(t)&&(e=b.regex.hex.exec(l(t)),this.r=parseInt(e[1],16),this.g=parseInt(e[2],16),this.b=parseInt(e[3],16)):"object"==typeof t&&(this.r=t.r,this.g=t.g,this.b=t.b))},b.extend(b.Color,{toString:function(){return this.toHex()},toHex:function(){return"#"+c(this.r)+c(this.g)+c(this.b)},toRgb:function(){return"rgb("+[this.r,this.g,this.b].join()+")"},brightness:function(){return this.r/255*.3+this.g/255*.59+this.b/255*.11},morph:function(t){return this.destination=new b.Color(t),this},at:function(t){return this.destination?(t=t<0?0:t>1?1:t,new b.Color({r:~~(this.r+(this.destination.r-this.r)*t),g:~~(this.g+(this.destination.g-this.g)*t),b:~~(this.b+(this.destination.b-this.b)*t)})):this}}),b.Color.test=function(t){return t+="",b.regex.isHex.test(t)||b.regex.isRgb.test(t)},b.Color.isRgb=function(t){return t&&"number"==typeof t.r&&"number"==typeof t.g&&"number"==typeof t.b},b.Color.isColor=function(t){return b.Color.isRgb(t)||b.Color.test(t)},b.Array=function(t,e){t=(t||[]).valueOf(),0==t.length&&e&&(t=e.valueOf()),this.value=this.parse(t)},b.extend(b.Array,{morph:function(t){if(this.destination=this.parse(t),this.value.length!=this.destination.length){for(var e=this.value[this.value.length-1],i=this.destination[this.destination.length-1];this.value.length>this.destination.length;)this.destination.push(i);for(;this.value.length<this.destination.length;)this.value.push(e)}return this},settle:function(){for(var t=0,e=this.value.length,i=[];t<e;t++)i.indexOf(this.value[t])==-1&&i.push(this.value[t]);return this.value=i},at:function(t){if(!this.destination)return this;for(var e=0,i=this.value.length,n=[];e<i;e++)n.push(this.value[e]+(this.destination[e]-this.value[e])*t);return new b.Array(n)},toString:function(){return this.value.join(" ")},valueOf:function(){return this.value},parse:function(t){return t=t.valueOf(),Array.isArray(t)?t:t.trim().split(b.regex.delimiter).map(parseFloat)},reverse:function(){return this.value.reverse(),this},clone:function(){var t=new this.constructor;return t.value=s(this.value),t}}),b.PointArray=function(t,e){b.Array.call(this,t,e||[[0,0]])},b.PointArray.prototype=new b.Array,b.PointArray.prototype.constructor=b.PointArray,b.extend(b.PointArray,{toString:function(){for(var t=0,e=this.value.length,i=[];t<e;t++)i.push(this.value[t].join(","));return i.join(" ")},toLine:function(){return{x1:this.value[0][0],y1:this.value[0][1],x2:this.value[1][0],y2:this.value[1][1]}},at:function(t){if(!this.destination)return this;for(var e=0,i=this.value.length,n=[];e<i;e++)n.push([this.value[e][0]+(this.destination[e][0]-this.value[e][0])*t,this.value[e][1]+(this.destination[e][1]-this.value[e][1])*t]);return new b.PointArray(n)},parse:function(t){var e=[];if(t=t.valueOf(),Array.isArray(t)){if(Array.isArray(t[0]))return t}else t=t.trim().split(b.regex.delimiter).map(parseFloat);t.length%2!==0&&t.pop();for(var i=0,n=t.length;i<n;i+=2)e.push([t[i],t[i+1]]);return e},move:function(t,e){var i=this.bbox();if(t-=i.x,e-=i.y,!isNaN(t)&&!isNaN(e))for(var n=this.value.length-1;n>=0;n--)this.value[n]=[this.value[n][0]+t,this.value[n][1]+e];return this},size:function(t,e){var i,n=this.bbox();for(i=this.value.length-1;i>=0;i--)n.width&&(this.value[i][0]=(this.value[i][0]-n.x)*t/n.width+n.x),n.height&&(this.value[i][1]=(this.value[i][1]-n.y)*e/n.height+n.y);return this},bbox:function(){return b.parser.poly.setAttribute("points",this.toString()),b.parser.poly.getBBox()}}),b.PathArray=function(t,e){b.Array.call(this,t,e||[["M",0,0]])},b.PathArray.prototype=new b.Array,b.PathArray.prototype.constructor=b.PathArray,b.extend(b.PathArray,{toString:function(){return y(this.value)},move:function(t,e){var i=this.bbox();if(t-=i.x,e-=i.y,!isNaN(t)&&!isNaN(e))for(var n,r=this.value.length-1;r>=0;r--)n=this.value[r][0],"M"==n||"L"==n||"T"==n?(this.value[r][1]+=t,this.value[r][2]+=e):"H"==n?this.value[r][1]+=t:"V"==n?this.value[r][1]+=e:"C"==n||"S"==n||"Q"==n?(this.value[r][1]+=t,this.value[r][2]+=e,this.value[r][3]+=t,this.value[r][4]+=e,"C"==n&&(this.value[r][5]+=t,this.value[r][6]+=e)):"A"==n&&(this.value[r][6]+=t,this.value[r][7]+=e);return this},size:function(t,e){var i,n,r=this.bbox();for(i=this.value.length-1;i>=0;i--)n=this.value[i][0],"M"==n||"L"==n||"T"==n?(this.value[i][1]=(this.value[i][1]-r.x)*t/r.width+r.x,this.value[i][2]=(this.value[i][2]-r.y)*e/r.height+r.y):"H"==n?this.value[i][1]=(this.value[i][1]-r.x)*t/r.width+r.x:"V"==n?this.value[i][1]=(this.value[i][1]-r.y)*e/r.height+r.y:"C"==n||"S"==n||"Q"==n?(this.value[i][1]=(this.value[i][1]-r.x)*t/r.width+r.x,this.value[i][2]=(this.value[i][2]-r.y)*e/r.height+r.y,this.value[i][3]=(this.value[i][3]-r.x)*t/r.width+r.x,this.value[i][4]=(this.value[i][4]-r.y)*e/r.height+r.y,"C"==n&&(this.value[i][5]=(this.value[i][5]-r.x)*t/r.width+r.x,this.value[i][6]=(this.value[i][6]-r.y)*e/r.height+r.y)):"A"==n&&(this.value[i][1]=this.value[i][1]*t/r.width,this.value[i][2]=this.value[i][2]*e/r.height,this.value[i][6]=(this.value[i][6]-r.x)*t/r.width+r.x,this.value[i][7]=(this.value[i][7]-r.y)*e/r.height+r.y);return this},equalCommands:function(t){var e,i,n;for(t=new b.PathArray(t),n=this.value.length===t.value.length,e=0,i=this.value.length;n&&e<i;e++)n=this.value[e][0]===t.value[e][0];return n},morph:function(t){return t=new b.PathArray(t),this.equalCommands(t)?this.destination=t:this.destination=null,this},at:function(t){if(!this.destination)return this;var e,i,n,r,s=this.value,a=this.destination.value,o=[],h=new b.PathArray;for(e=0,i=s.length;e<i;e++){for(o[e]=[s[e][0]],n=1,r=s[e].length;n<r;n++)o[e][n]=s[e][n]+(a[e][n]-s[e][n])*t;"A"===o[e][0]&&(o[e][4]=+(0!=o[e][4]),o[e][5]=+(0!=o[e][5]))}return h.value=o,h},parse:function(t){if(t instanceof b.PathArray)return t.valueOf();var e,i,n,s,a,o,h=0,u=0,l={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7};t="string"==typeof t?t.replace(b.regex.numbersWithDots,r).replace(b.regex.pathLetters," $& ").replace(b.regex.hyphen,"$1 -").trim().split(b.regex.delimiter):t.reduce(function(t,e){return[].concat.apply(t,e)},[]);var o=[];do{for(b.regex.isPathLetter.test(t[0])?(s=t[0],t.shift()):"M"==s?s="L":"m"==s&&(s="l"),a=[s.toUpperCase()],e=0;e<l[a[0]];++e)a.push(parseFloat(t.shift()));s==a[0]?"M"==s||"L"==s||"C"==s||"Q"==s||"S"==s||"T"==s?(h=a[l[a[0]]-1],u=a[l[a[0]]]):"V"==s?u=a[1]:"H"==s?h=a[1]:"A"==s&&(h=a[6],u=a[7]):"m"==s||"l"==s||"c"==s||"s"==s||"q"==s||"t"==s?(a[1]+=h,a[2]+=u,null!=a[3]&&(a[3]+=h,a[4]+=u),null!=a[5]&&(a[5]+=h,a[6]+=u),h=a[l[a[0]]-1],u=a[l[a[0]]]):"v"==s?(a[1]+=u,u=a[1]):"h"==s?(a[1]+=h,h=a[1]):"a"==s&&(a[6]+=h,a[7]+=u,h=a[6],u=a[7]),"M"==a[0]&&(i=h,n=u),"Z"==a[0]&&(h=i,u=n),o.push(a)}while(t.length);return o},bbox:function(){return b.parser.path.setAttribute("d",this.toString()),b.parser.path.getBBox()}}),b.Number=b.invent({create:function(t,e){this.value=0,this.unit=e||"","number"==typeof t?this.value=isNaN(t)?0:isFinite(t)?t:t<0?-3.4e38:3.4e38:"string"==typeof t?(e=t.match(b.regex.numberAndUnit),e&&(this.value=parseFloat(e[1]),"%"==e[5]?this.value/=100:"s"==e[5]&&(this.value*=1e3),this.unit=e[5])):t instanceof b.Number&&(this.value=t.valueOf(),this.unit=t.unit)},extend:{toString:function(){return("%"==this.unit?~~(1e8*this.value)/1e6:"s"==this.unit?this.value/1e3:this.value)+this.unit},toJSON:function(){return this.toString()},valueOf:function(){return this.value},plus:function(t){return t=new b.Number(t),new b.Number(this+t,this.unit||t.unit)},minus:function(t){return t=new b.Number(t),new b.Number(this-t,this.unit||t.unit)},times:function(t){return t=new b.Number(t),new b.Number(this*t,this.unit||t.unit)},divide:function(t){return t=new b.Number(t),new b.Number(this/t,this.unit||t.unit)},to:function(t){var e=new b.Number(this);return"string"==typeof t&&(e.unit=t),e},morph:function(t){return this.destination=new b.Number(t),t.relative&&(this.destination.value+=this.value),this},at:function(t){return this.destination?new b.Number(this.destination).minus(this).times(t).plus(this):this}}}),b.Element=b.invent({create:function(t){this._event=null,this.dom={},(this.node=t)&&(this.type=t.nodeName,this.node.instance=this)},extend:{x:function(t){return this.attr("x",t)},y:function(t){return this.attr("y",t)},cx:function(t){return null==t?this.x()+this.width()/2:this.x(t-this.width()/2)},cy:function(t){return null==t?this.y()+this.height()/2:this.y(t-this.height()/2)},move:function(t,e){return this.x(t).y(e)},center:function(t,e){return this.cx(t).cy(e)},width:function(t){return this.attr("width",t)},height:function(t){return this.attr("height",t)},size:function(t,e){var i=f(this,t,e);return this.width(new b.Number(i.width)).height(new b.Number(i.height))},clone:function(t,e){this.writeDataToDom();var i=v(this.node.cloneNode(!0));return t?t.add(i):this.after(i),i},remove:function(){return this.parent()&&this.parent().removeElement(this),this},replace:function(t){return this.after(t).remove(),t},addTo:function(t){return t.put(this)},putIn:function(t){return t.add(this)},id:function(t){return this.attr("id",t)},inside:function(t,e){var i=this.bbox();return t>i.x&&e>i.y&&t<i.x+i.width&&e<i.y+i.height},show:function(){return this.style("display","")},hide:function(){return this.style("display","none")},visible:function(){return"none"!=this.style("display")},toString:function(){return this.attr("id")},classes:function(){var t=this.attr("class");return null==t?[]:t.trim().split(b.regex.delimiter)},hasClass:function(t){return this.classes().indexOf(t)!=-1},addClass:function(t){if(!this.hasClass(t)){var e=this.classes();e.push(t),this.attr("class",e.join(" "))}return this},removeClass:function(t){return this.hasClass(t)&&this.attr("class",this.classes().filter(function(e){return e!=t}).join(" ")),this},toggleClass:function(t){return this.hasClass(t)?this.removeClass(t):this.addClass(t)},reference:function(t){return b.get(this.attr(t))},parent:function(e){var i=this;if(!i.node.parentNode)return null;if(i=b.adopt(i.node.parentNode),!e)return i;for(;i&&i.node instanceof t.SVGElement;){if("string"==typeof e?i.matches(e):i instanceof e)return i;i=b.adopt(i.node.parentNode)}},doc:function(){return this instanceof b.Doc?this:this.parent(b.Doc)},parents:function(t){var e=[],i=this;do{if(i=i.parent(t),!i||!i.node)break;e.push(i)}while(i.parent);return e},matches:function(t){return o(this.node,t)},native:function(){return this.node},svg:function(t){var i,n;if(!(t&&this instanceof b.Parent))return this.node.outerHTML;for(i=e.createElementNS(b.ns,"svg"),i.innerHTML=t,n=i.childNodes.length;n--;)1!=i.firstChild.nodeType?i.removeChild(i.firstChild):this.node.appendChild(i.firstChild);return this},writeDataToDom:function(){return this.is(b.Parent)&&this.each(function(){this.writeDataToDom()}),this.node.removeAttribute("svgjs:data"),Object.keys(this.dom).length&&this.node.setAttribute("svgjs:data",JSON.stringify(this.dom)),this},setData:function(t){return this.dom=t,this},is:function(t){return a(this,t)}}}),b.easing={"-":function(t){return t},"<>":function(t){return-Math.cos(t*Math.PI)/2+.5},">":function(t){return Math.sin(t*Math.PI/2)},"<":function(t){return-Math.cos(t*Math.PI/2)+1}},b.morph=function(t){return function(e,i){return new b.MorphObj(e,i).at(t)}},b.Situation=b.invent({create:function(t){this.init=!1,this.reversed=!1,this.reversing=!1,this.duration=new b.Number(t.duration).valueOf(),this.delay=new b.Number(t.delay).valueOf(),this.start=+new Date+this.delay,this.finish=this.start+this.duration,this.ease=t.ease,this.loop=0,this.loops=!1,this.animations={},this.attrs={},this.styles={},this.transforms=[],this.once={}}}),b.FX=b.invent({create:function(t){this._target=t,this.situations=[],this.active=!1,this.situation=null,this.paused=!1,this.lastPos=0,this.pos=0,this.absPos=0,this._speed=1},extend:{animate:function(t,e,i){"object"==typeof t&&(e=t.ease,i=t.delay,t=t.duration);var n=new b.Situation({duration:t||1e3,delay:i||0,ease:b.easing[e||"-"]||e});return this.queue(n),this},delay:function(t){var e=new b.Situation({duration:t,delay:0,ease:b.easing["-"]});return this.queue(e)},target:function(t){return t&&t instanceof b.Element?(this._target=t,this):this._target},timeToAbsPos:function(t){return(t-this.situation.start)/(this.situation.duration/this._speed)},absPosToTime:function(t){return this.situation.duration/this._speed*t+this.situation.start},startAnimFrame:function(){this.stopAnimFrame(),this.animationFrame=requestAnimationFrame(function(){this.step()}.bind(this))},stopAnimFrame:function(){cancelAnimationFrame(this.animationFrame)},start:function(){return!this.active&&this.situation&&(this.active=!0,this.startCurrent()),this},startCurrent:function(){return this.situation.start=+new Date+this.situation.delay/this._speed,this.situation.finish=this.situation.start+this.situation.duration/this._speed,this.initAnimations().step()},queue:function(t){return("function"==typeof t||t instanceof b.Situation)&&this.situations.push(t),this.situation||(this.situation=this.situations.shift()),this},dequeue:function(){return this.stop(),this.situation=this.situations.shift(),this.situation&&(this.situation instanceof b.Situation?this.start():this.situation.call(this)),this},initAnimations:function(){var t,e,i=this.situation;if(i.init)return this;for(t in i.animations)e=this.target()[t](),i.animations[t]instanceof b.Number&&(e=new b.Number(e)),i.animations[t]=e.morph(i.animations[t]);for(t in i.attrs)i.attrs[t]=new b.MorphObj(this.target().attr(t),i.attrs[t]);for(t in i.styles)i.styles[t]=new b.MorphObj(this.target().style(t),i.styles[t]);return i.initialTransformation=this.target().matrixify(),i.init=!0,this},clearQueue:function(){return this.situations=[],this},clearCurrent:function(){return this.situation=null,this},stop:function(t,e){var i=this.active;return this.active=!1,e&&this.clearQueue(),t&&this.situation&&(!i&&this.startCurrent(),this.atEnd()),this.stopAnimFrame(),this.clearCurrent()},reset:function(){if(this.situation){var t=this.situation;this.stop(),this.situation=t,this.atStart()}return this},finish:function(){for(this.stop(!0,!1);this.dequeue().situation&&this.stop(!0,!1););return this.clearQueue().clearCurrent(),this},atStart:function(){return this.at(0,!0)},atEnd:function(){return this.situation.loops===!0&&(this.situation.loops=this.situation.loop+1),"number"==typeof this.situation.loops?this.at(this.situation.loops,!0):this.at(1,!0)},at:function(t,e){var i=this.situation.duration/this._speed;return this.absPos=t,e||(this.situation.reversed&&(this.absPos=1-this.absPos),this.absPos+=this.situation.loop),this.situation.start=+new Date-this.absPos*i,this.situation.finish=this.situation.start+i,this.step(!0)},speed:function(t){return 0===t?this.pause():t?(this._speed=t,this.at(this.absPos,!0)):this._speed},loop:function(t,e){var i=this.last();return i.loops=null==t||t,i.loop=0,e&&(i.reversing=!0),this},pause:function(){return this.paused=!0,this.stopAnimFrame(),this},play:function(){return this.paused?(this.paused=!1,this.at(this.absPos,!0)):this},reverse:function(t){var e=this.last();return"undefined"==typeof t?e.reversed=!e.reversed:e.reversed=t,this},progress:function(t){return t?this.situation.ease(this.pos):this.pos},after:function(t){var e=this.last(),i=function i(n){n.detail.situation==e&&(t.call(this,e),this.off("finished.fx",i))};return this.target().on("finished.fx",i),this._callStart()},during:function(t){var e=this.last(),i=function(i){i.detail.situation==e&&t.call(this,i.detail.pos,b.morph(i.detail.pos),i.detail.eased,e)};return this.target().off("during.fx",i).on("during.fx",i),this.after(function(){this.off("during.fx",i)}),this._callStart()},afterAll:function(t){var e=function e(i){t.call(this),this.off("allfinished.fx",e)};return this.target().off("allfinished.fx",e).on("allfinished.fx",e),this._callStart()},duringAll:function(t){var e=function(e){t.call(this,e.detail.pos,b.morph(e.detail.pos),e.detail.eased,e.detail.situation)};return this.target().off("during.fx",e).on("during.fx",e),this.afterAll(function(){this.off("during.fx",e)}),this._callStart()},last:function(){return this.situations.length?this.situations[this.situations.length-1]:this.situation},add:function(t,e,i){return this.last()[i||"animations"][t]=e,this._callStart()},step:function(t){if(t||(this.absPos=this.timeToAbsPos(+new Date)),this.situation.loops!==!1){var e,i,n;e=Math.max(this.absPos,0),i=Math.floor(e),this.situation.loops===!0||i<this.situation.loops?(this.pos=e-i,n=this.situation.loop,this.situation.loop=i):(this.absPos=this.situation.loops,this.pos=1,n=this.situation.loop-1,this.situation.loop=this.situation.loops),this.situation.reversing&&(this.situation.reversed=this.situation.reversed!=Boolean((this.situation.loop-n)%2))}else this.absPos=Math.min(this.absPos,1),this.pos=this.absPos;this.pos<0&&(this.pos=0),this.situation.reversed&&(this.pos=1-this.pos);var r=this.situation.ease(this.pos);for(var s in this.situation.once)s>this.lastPos&&s<=r&&(this.situation.once[s].call(this.target(),this.pos,r),delete this.situation.once[s]);return this.active&&this.target().fire("during",{pos:this.pos,eased:r,fx:this,situation:this.situation}),this.situation?(this.eachAt(),1==this.pos&&!this.situation.reversed||this.situation.reversed&&0==this.pos?(this.stopAnimFrame(),this.target().fire("finished",{fx:this,situation:this.situation}),this.situations.length||(this.target().fire("allfinished"),this.target().off(".fx"),this.active=!1),this.active?this.dequeue():this.clearCurrent()):!this.paused&&this.active&&this.startAnimFrame(),this.lastPos=r,this):this},eachAt:function(){var t,e,i=this,n=this.target(),r=this.situation;for(t in r.animations)e=[].concat(r.animations[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(r.ease(i.pos),i.pos):t}),n[t].apply(n,e);for(t in r.attrs)e=[t].concat(r.attrs[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(r.ease(i.pos),i.pos):t}),n.attr.apply(n,e);for(t in r.styles)e=[t].concat(r.styles[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(r.ease(i.pos),i.pos):t}),n.style.apply(n,e);if(r.transforms.length){for(e=r.initialTransformation,t=0,len=r.transforms.length;t<len;t++){var s=r.transforms[t];s instanceof b.Matrix?e=s.relative?e.multiply((new b.Matrix).morph(s).at(r.ease(this.pos))):e.morph(s).at(r.ease(this.pos)):(s.relative||s.undo(e.extract()),e=e.multiply(s.at(r.ease(this.pos))))}n.matrix(e)}return this},once:function(t,e,i){return i||(t=this.situation.ease(t)),this.situation.once[t]=e,this},_callStart:function(){return setTimeout(function(){this.start()}.bind(this),0),this}},parent:b.Element,construct:{animate:function(t,e,i){return(this.fx||(this.fx=new b.FX(this))).animate(t,e,i)},delay:function(t){return(this.fx||(this.fx=new b.FX(this))).delay(t)},stop:function(t,e){return this.fx&&this.fx.stop(t,e),this},finish:function(){return this.fx&&this.fx.finish(),this},pause:function(){return this.fx&&this.fx.pause(),this},play:function(){return this.fx&&this.fx.play(),this},speed:function(t){if(this.fx){if(null==t)return this.fx.speed();this.fx.speed(t)}return this}}}),b.MorphObj=b.invent({create:function(t,e){return b.Color.isColor(e)?new b.Color(t).morph(e):b.regex.numberAndUnit.test(e)?new b.Number(t).morph(e):(this.value=t,void(this.destination=e))},extend:{at:function(t,e){return e<1?this.value:this.destination},valueOf:function(){return this.value}}}),b.extend(b.FX,{attr:function(t,e,i){if("object"==typeof t)for(var n in t)this.attr(n,t[n]);else this.add(t,e,"attrs");return this},style:function(t,e){if("object"==typeof t)for(var i in t)this.style(i,t[i]);else this.add(t,e,"styles");return this},x:function(t,e){if(this.target()instanceof b.G)return this.transform({x:t},e),this;var i=new b.Number(t);return i.relative=e,this.add("x",i)},y:function(t,e){if(this.target()instanceof b.G)return this.transform({y:t},e),this;var i=new b.Number(t);return i.relative=e,this.add("y",i)},cx:function(t){return this.add("cx",new b.Number(t))},cy:function(t){return this.add("cy",new b.Number(t))},move:function(t,e){return this.x(t).y(e)},center:function(t,e){return this.cx(t).cy(e)},size:function(t,e){if(this.target()instanceof b.Text)this.attr("font-size",t);else{var i;t&&e||(i=this.target().bbox()),t||(t=i.width/i.height*e),e||(e=i.height/i.width*t),this.add("width",new b.Number(t)).add("height",new b.Number(e))}return this},plot:function(){return this.add("plot",arguments.length>1?[].slice.call(arguments):arguments[0])},leading:function(t){return this.target().leading?this.add("leading",new b.Number(t)):this},viewbox:function(t,e,i,n){return this.target()instanceof b.Container&&this.add("viewbox",new b.Box(t,e,i,n)),this},update:function(t){if(this.target()instanceof b.Stop){if("number"==typeof t||t instanceof b.Number)return this.update({offset:arguments[0],color:arguments[1],opacity:arguments[2]});null!=t.opacity&&this.attr("stop-opacity",t.opacity),null!=t.color&&this.attr("stop-color",t.color),null!=t.offset&&this.attr("offset",t.offset)}return this}}),b.Matrix=b.invent({create:function(t){var e,i=p([1,0,0,1,0,0]);for(t=t instanceof b.Element?t.matrixify():"string"==typeof t?p(t.split(b.regex.delimiter).map(parseFloat)):6==arguments.length?p([].slice.call(arguments)):Array.isArray(t)?p(t):"object"==typeof t?t:i,e=P.length-1;e>=0;--e)this[P[e]]=t&&"number"==typeof t[P[e]]?t[P[e]]:i[P[e]]},extend:{extract:function(){var t=d(this,0,1),e=d(this,1,0),i=180/Math.PI*Math.atan2(t.y,t.x)-90;return{x:this.e,y:this.f,transformedX:(this.e*Math.cos(i*Math.PI/180)+this.f*Math.sin(i*Math.PI/180))/Math.sqrt(this.a*this.a+this.b*this.b),transformedY:(this.f*Math.cos(i*Math.PI/180)+this.e*Math.sin(-i*Math.PI/180))/Math.sqrt(this.c*this.c+this.d*this.d),skewX:-i,skewY:180/Math.PI*Math.atan2(e.y,e.x),scaleX:Math.sqrt(this.a*this.a+this.b*this.b),scaleY:Math.sqrt(this.c*this.c+this.d*this.d),rotation:i,a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f,matrix:new b.Matrix(this)}},clone:function(){return new b.Matrix(this)},morph:function(t){return this.destination=new b.Matrix(t),this},at:function(t){if(!this.destination)return this;var e=new b.Matrix({a:this.a+(this.destination.a-this.a)*t,b:this.b+(this.destination.b-this.b)*t,c:this.c+(this.destination.c-this.c)*t,d:this.d+(this.destination.d-this.d)*t,e:this.e+(this.destination.e-this.e)*t,f:this.f+(this.destination.f-this.f)*t});return e},multiply:function(t){return new b.Matrix(this.native().multiply(m(t).native()))},inverse:function(){return new b.Matrix(this.native().inverse())},translate:function(t,e){return new b.Matrix(this.native().translate(t||0,e||0))},scale:function(t,e,i,n){return 1==arguments.length?e=t:3==arguments.length&&(n=i,i=e,e=t),this.around(i,n,new b.Matrix(t,0,0,e,0,0))},rotate:function(t,e,i){return t=b.utils.radians(t),this.around(e,i,new b.Matrix(Math.cos(t),Math.sin(t),-Math.sin(t),Math.cos(t),0,0))},flip:function(t,e){return e="number"==typeof t?t:e,"x"==t?this.scale(-1,1,e,0):"y"==t?this.scale(1,-1,0,e):this.scale(-1,-1,e,e)},skew:function(t,e,i,n){return 1==arguments.length?e=t:3==arguments.length&&(n=i,i=e,e=t),t=b.utils.radians(t),e=b.utils.radians(e),this.around(i,n,new b.Matrix(1,Math.tan(e),Math.tan(t),1,0,0))},skewX:function(t,e,i){return this.skew(t,0,e,i)},skewY:function(t,e,i){return this.skew(0,t,e,i)},around:function(t,e,i){return this.multiply(new b.Matrix(1,0,0,1,t||0,e||0)).multiply(i).multiply(new b.Matrix(1,0,0,1,-t||0,-e||0))},native:function(){for(var t=b.parser.native.createSVGMatrix(),e=P.length-1;e>=0;e--)t[P[e]]=this[P[e]];return t},toString:function(){return"matrix("+this.a+","+this.b+","+this.c+","+this.d+","+this.e+","+this.f+")"}},parent:b.Element,construct:{ctm:function(){return new b.Matrix(this.node.getCTM())},screenCTM:function(){if(this instanceof b.Nested){var t=this.rect(1,1),e=t.node.getScreenCTM();return t.remove(),new b.Matrix(e)}return new b.Matrix(this.node.getScreenCTM())}}}),b.Point=b.invent({create:function(t,e){var i,n={x:0,y:0};i=Array.isArray(t)?{x:t[0],y:t[1]}:"object"==typeof t?{x:t.x,y:t.y}:null!=t?{x:t,y:null!=e?e:t}:n,this.x=i.x,this.y=i.y},extend:{clone:function(){return new b.Point(this)},morph:function(t,e){return this.destination=new b.Point(t,e),this},at:function(t){if(!this.destination)return this;var e=new b.Point({x:this.x+(this.destination.x-this.x)*t,y:this.y+(this.destination.y-this.y)*t});return e},native:function(){var t=b.parser.native.createSVGPoint();return t.x=this.x,t.y=this.y,t},transform:function(t){return new b.Point(this.native().matrixTransform(t.native()))}}}),b.extend(b.Element,{point:function(t,e){return new b.Point(t,e).transform(this.screenCTM().inverse())}}),b.extend(b.Element,{attr:function(t,e,i){if(null==t){for(t={},e=this.node.attributes,i=e.length-1;i>=0;i--)t[e[i].nodeName]=b.regex.isNumber.test(e[i].nodeValue)?parseFloat(e[i].nodeValue):e[i].nodeValue;return t}if("object"==typeof t)for(e in t)this.attr(e,t[e]);else if(null===e)this.node.removeAttribute(t);else{if(null==e)return e=this.node.getAttribute(t),null==e?b.defaults.attrs[t]:b.regex.isNumber.test(e)?parseFloat(e):e;"fill"!=t&&"stroke"!=t||(b.regex.isImage.test(e)&&(e=this.doc().defs().image(e)),e instanceof b.Image&&(e=this.doc().defs().pattern(0,0,function(){this.add(e)}))),"number"==typeof e?e=new b.Number(e):b.Color.isColor(e)?e=new b.Color(e):Array.isArray(e)&&(e=new b.Array(e)),"leading"==t?this.leading&&this.leading(e):"string"==typeof i?this.node.setAttributeNS(i,t,e.toString()):this.node.setAttribute(t,e.toString()),!this.rebuild||"font-size"!=t&&"x"!=t||this.rebuild(t,e)}return this}}),b.extend(b.Element,{transform:function(t,e){var i,n=this;if("object"!=typeof t)return i=new b.Matrix(n).extract(),"string"==typeof t?i[t]:i;if(i=new b.Matrix(n),e=!!e||!!t.relative,null!=t.a)i=e?i.multiply(new b.Matrix(t)):new b.Matrix(t);else if(null!=t.rotation)x(t,n),i=e?i.rotate(t.rotation,t.cx,t.cy):i.rotate(t.rotation-i.extract().rotation,t.cx,t.cy);else if(null!=t.scale||null!=t.scaleX||null!=t.scaleY){if(x(t,n),t.scaleX=null!=t.scale?t.scale:null!=t.scaleX?t.scaleX:1,t.scaleY=null!=t.scale?t.scale:null!=t.scaleY?t.scaleY:1,!e){var r=i.extract();t.scaleX=1*t.scaleX/r.scaleX,t.scaleY=1*t.scaleY/r.scaleY}i=i.scale(t.scaleX,t.scaleY,t.cx,t.cy)}else if(null!=t.skew||null!=t.skewX||null!=t.skewY){if(x(t,n),t.skewX=null!=t.skew?t.skew:null!=t.skewX?t.skewX:0,t.skewY=null!=t.skew?t.skew:null!=t.skewY?t.skewY:0,!e){var r=i.extract();i=i.multiply((new b.Matrix).skew(r.skewX,r.skewY,t.cx,t.cy).inverse())}i=i.skew(t.skewX,t.skewY,t.cx,t.cy)}else t.flip?i=i.flip(t.flip,null==t.offset?n.bbox()["c"+t.flip]:t.offset):null==t.x&&null==t.y||(e?i=i.translate(t.x,t.y):(null!=t.x&&(i.e=t.x), -null!=t.y&&(i.f=t.y)));return this.attr("transform",i)}}),b.extend(b.FX,{transform:function(t,e){var i,n=this.target();return"object"!=typeof t?(i=new b.Matrix(n).extract(),"string"==typeof t?i[t]:i):(e=!!e||!!t.relative,null!=t.a?i=new b.Matrix(t):null!=t.rotation?(x(t,n),i=new b.Rotate(t.rotation,t.cx,t.cy)):null!=t.scale||null!=t.scaleX||null!=t.scaleY?(x(t,n),t.scaleX=null!=t.scale?t.scale:null!=t.scaleX?t.scaleX:1,t.scaleY=null!=t.scale?t.scale:null!=t.scaleY?t.scaleY:1,i=new b.Scale(t.scaleX,t.scaleY,t.cx,t.cy)):null!=t.skewX||null!=t.skewY?(x(t,n),t.skewX=null!=t.skewX?t.skewX:0,t.skewY=null!=t.skewY?t.skewY:0,i=new b.Skew(t.skewX,t.skewY,t.cx,t.cy)):t.flip?i=(new b.Matrix).flip(t.flip,null==t.offset?n.bbox()["c"+t.flip]:t.offset):null==t.x&&null==t.y||(i=new b.Translate(t.x,t.y)),i?(i.relative=e,this.last().transforms.push(i),this._callStart()):this)}}),b.extend(b.Element,{untransform:function(){return this.attr("transform",null)},matrixify:function(){var t=(this.attr("transform")||"").split(b.regex.transforms).slice(0,-1).map(function(t){var e=t.trim().split("(");return[e[0],e[1].split(b.regex.delimiter).map(function(t){return parseFloat(t)})]}).reduce(function(t,e){return"matrix"==e[0]?t.multiply(p(e[1])):t[e[0]].apply(t,e[1])},new b.Matrix);return t},toParent:function(t){if(this==t)return this;var e=this.screenCTM(),i=t.screenCTM().inverse();return this.addTo(t).untransform().transform(i.multiply(e)),this},toDoc:function(){return this.toParent(this.doc())}}),b.Transformation=b.invent({create:function(t,e){if(arguments.length>1&&"boolean"!=typeof e)return this.constructor.call(this,[].slice.call(arguments));if(Array.isArray(t))for(var i=0,n=this.arguments.length;i<n;++i)this[this.arguments[i]]=t[i];else if("object"==typeof t)for(var i=0,n=this.arguments.length;i<n;++i)this[this.arguments[i]]=t[this.arguments[i]];this.inversed=!1,e===!0&&(this.inversed=!0)},extend:{arguments:[],method:"",at:function(t){for(var e=[],i=0,n=this.arguments.length;i<n;++i)e.push(this[this.arguments[i]]);var r=this._undo||new b.Matrix;return r=(new b.Matrix).morph(b.Matrix.prototype[this.method].apply(r,e)).at(t),this.inversed?r.inverse():r},undo:function(t){for(var e=0,i=this.arguments.length;e<i;++e)t[this.arguments[e]]="undefined"==typeof this[this.arguments[e]]?0:t[this.arguments[e]];return t.cx=this.cx,t.cy=this.cy,this._undo=new(b[u(this.method)])(t,!0).at(1),this}}}),b.Translate=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["transformedX","transformedY"],method:"translate"}}),b.Rotate=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["rotation","cx","cy"],method:"rotate",at:function(t){var e=(new b.Matrix).rotate((new b.Number).morph(this.rotation-(this._undo?this._undo.rotation:0)).at(t),this.cx,this.cy);return this.inversed?e.inverse():e},undo:function(t){this._undo=t}}}),b.Scale=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["scaleX","scaleY","cx","cy"],method:"scale"}}),b.Skew=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["skewX","skewY","cx","cy"],method:"skew"}}),b.extend(b.Element,{style:function(t,e){if(0==arguments.length)return this.node.style.cssText||"";if(arguments.length<2){if("object"!=typeof t)return this.node.style[h(t)];for(e in t)this.style(e,t[e])}else this.node.style[h(t)]=null===e||b.regex.isBlank.test(e)?"":e;return this}}),b.Parent=b.invent({create:function(t){this.constructor.call(this,t)},inherit:b.Element,extend:{children:function(){return b.utils.map(b.utils.filterSVGElements(this.node.childNodes),function(t){return b.adopt(t)})},add:function(t,e){return null==e?this.node.appendChild(t.node):t.node!=this.node.childNodes[e]&&this.node.insertBefore(t.node,this.node.childNodes[e]),this},put:function(t,e){return this.add(t,e),t},has:function(t){return this.index(t)>=0},index:function(t){return[].slice.call(this.node.childNodes).indexOf(t.node)},get:function(t){return b.adopt(this.node.childNodes[t])},first:function(){return this.get(0)},last:function(){return this.get(this.node.childNodes.length-1)},each:function(t,e){var i,n,r=this.children();for(i=0,n=r.length;i<n;i++)r[i]instanceof b.Element&&t.apply(r[i],[i,r]),e&&r[i]instanceof b.Container&&r[i].each(t,e);return this},removeElement:function(t){return this.node.removeChild(t.node),this},clear:function(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return delete this._defs,this},defs:function(){return this.doc().defs()}}}),b.extend(b.Parent,{flatten:function(t){return this instanceof b.Defs?this:(t=t||(this instanceof b.Doc?this:this.parent(b.Parent)),this.each(function(){return this instanceof b.Defs?this:this instanceof b.Parent?this.flatten(t):this.toParent(t)}),this.node.firstChild||this.remove(),this)}}),b.Container=b.invent({create:function(t){this.constructor.call(this,t)},inherit:b.Parent}),["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","touchstart","touchmove","touchleave","touchend","touchcancel"].forEach(function(t){b.Element.prototype[t]=function(e){var i=this;return this.node["on"+t]="function"==typeof e?function(){return e.apply(i,arguments)}:null,this}}),b.listeners=[],b.handlerMap=[],b.listenerId=0,b.on=function(t,e,i,n){var r=i.bind(n||t.instance||t),s=(b.handlerMap.indexOf(t)+1||b.handlerMap.push(t))-1,a=e.split(".")[0],o=e.split(".")[1]||"*";b.listeners[s]=b.listeners[s]||{},b.listeners[s][a]=b.listeners[s][a]||{},b.listeners[s][a][o]=b.listeners[s][a][o]||{},i._svgjsListenerId||(i._svgjsListenerId=++b.listenerId),b.listeners[s][a][o][i._svgjsListenerId]=r,t.addEventListener(a,r,!1)},b.off=function(t,e,i){var n=b.handlerMap.indexOf(t),r=e&&e.split(".")[0],s=e&&e.split(".")[1];if(n!=-1)if(i){if("function"==typeof i&&(i=i._svgjsListenerId),!i)return;b.listeners[n][r]&&b.listeners[n][r][s||"*"]&&(t.removeEventListener(r,b.listeners[n][r][s||"*"][i],!1),delete b.listeners[n][r][s||"*"][i])}else if(s&&r){if(b.listeners[n][r]&&b.listeners[n][r][s]){for(i in b.listeners[n][r][s])b.off(t,[r,s].join("."),i);delete b.listeners[n][r][s]}}else if(s)for(e in b.listeners[n])for(namespace in b.listeners[n][e])s===namespace&&b.off(t,[e,s].join("."));else if(r){if(b.listeners[n][r]){for(namespace in b.listeners[n][r])b.off(t,[r,namespace].join("."));delete b.listeners[n][r]}}else{for(e in b.listeners[n])b.off(t,e);delete b.listeners[n],delete b.handlerMap[n]}},b.extend(b.Element,{on:function(t,e,i){return b.on(this.node,t,e,i),this},off:function(t,e){return b.off(this.node,t,e),this},fire:function(e,i){return e instanceof t.Event?this.node.dispatchEvent(e):this.node.dispatchEvent(e=new t.CustomEvent(e,{detail:i,cancelable:!0})),this._event=e,this},event:function(){return this._event}}),b.Defs=b.invent({create:"defs",inherit:b.Container}),b.G=b.invent({create:"g",inherit:b.Container,extend:{x:function(t){return null==t?this.transform("x"):this.transform({x:t-this.x()},!0)},y:function(t){return null==t?this.transform("y"):this.transform({y:t-this.y()},!0)},cx:function(t){return null==t?this.gbox().cx:this.x(t-this.gbox().width/2)},cy:function(t){return null==t?this.gbox().cy:this.y(t-this.gbox().height/2)},gbox:function(){var t=this.bbox(),e=this.transform();return t.x+=e.x,t.x2+=e.x,t.cx+=e.x,t.y+=e.y,t.y2+=e.y,t.cy+=e.y,t}},construct:{group:function(){return this.put(new b.G)}}}),b.extend(b.Element,{siblings:function(){return this.parent().children()},position:function(){return this.parent().index(this)},next:function(){return this.siblings()[this.position()+1]},previous:function(){return this.siblings()[this.position()-1]},forward:function(){var t=this.position()+1,e=this.parent();return e.removeElement(this).add(this,t),e instanceof b.Doc&&e.node.appendChild(e.defs().node),this},backward:function(){var t=this.position();return t>0&&this.parent().removeElement(this).add(this,t-1),this},front:function(){var t=this.parent();return t.node.appendChild(this.node),t instanceof b.Doc&&t.node.appendChild(t.defs().node),this},back:function(){return this.position()>0&&this.parent().removeElement(this).add(this,0),this},before:function(t){t.remove();var e=this.position();return this.parent().add(t,e),this},after:function(t){t.remove();var e=this.position();return this.parent().add(t,e+1),this}}),b.Mask=b.invent({create:"mask",inherit:b.Container,extend:{remove:function(){return this.targets().forEach(function(t){t.unmask()}),b.Element.prototype.remove.call(this)},targets:function(){return b.select('svg [mask*="'+this.id()+'"]')}},construct:{mask:function(){return this.defs().put(new b.Mask)}}}),b.extend(b.Element,{maskWith:function(t){var e=t instanceof b.Mask?t:this.parent().mask().add(t);return this.attr("mask",'url("#'+e.attr("id")+'")')},unmask:function(){return this.attr("mask",null)},masker:function(){return this.reference("mask")}}),b.ClipPath=b.invent({create:"clipPath",inherit:b.Container,extend:{remove:function(){return this.targets().forEach(function(t){t.unclip()}),b.Element.prototype.remove.call(this)},targets:function(){return b.select('svg [clip-path*="'+this.id()+'"]')}},construct:{clip:function(){return this.defs().put(new b.ClipPath)}}}),b.extend(b.Element,{clipWith:function(t){var e=t instanceof b.ClipPath?t:this.parent().clip().add(t);return this.attr("clip-path",'url("#'+e.attr("id")+'")')},unclip:function(){return this.attr("clip-path",null)},clipper:function(){return this.reference("clip-path")}}),b.Gradient=b.invent({create:function(t){this.constructor.call(this,b.create(t+"Gradient"))},inherit:b.Container,extend:{at:function(t,e,i){return this.put(new b.Stop).update(t,e,i)},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},fill:function(){return"url(#"+this.id()+")"},toString:function(){return this.fill()},attr:function(t,e,i){return"transform"==t&&(t="gradientTransform"),b.Container.prototype.attr.call(this,t,e,i)}},construct:{gradient:function(t,e){return this.defs().gradient(t,e)}}}),b.extend(b.Gradient,b.FX,{from:function(t,e){return"radialGradient"==(this._target||this).type?this.attr({fx:new b.Number(t),fy:new b.Number(e)}):this.attr({x1:new b.Number(t),y1:new b.Number(e)})},to:function(t,e){return"radialGradient"==(this._target||this).type?this.attr({cx:new b.Number(t),cy:new b.Number(e)}):this.attr({x2:new b.Number(t),y2:new b.Number(e)})}}),b.extend(b.Defs,{gradient:function(t,e){return this.put(new b.Gradient(t)).update(e)}}),b.Stop=b.invent({create:"stop",inherit:b.Element,extend:{update:function(t){return("number"==typeof t||t instanceof b.Number)&&(t={offset:arguments[0],color:arguments[1],opacity:arguments[2]}),null!=t.opacity&&this.attr("stop-opacity",t.opacity),null!=t.color&&this.attr("stop-color",t.color),null!=t.offset&&this.attr("offset",new b.Number(t.offset)),this}}}),b.Pattern=b.invent({create:"pattern",inherit:b.Container,extend:{fill:function(){return"url(#"+this.id()+")"},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},toString:function(){return this.fill()},attr:function(t,e,i){return"transform"==t&&(t="patternTransform"),b.Container.prototype.attr.call(this,t,e,i)}},construct:{pattern:function(t,e,i){return this.defs().pattern(t,e,i)}}}),b.extend(b.Defs,{pattern:function(t,e,i){return this.put(new b.Pattern).update(i).attr({x:0,y:0,width:t,height:e,patternUnits:"userSpaceOnUse"})}}),b.Doc=b.invent({create:function(t){t&&(t="string"==typeof t?e.getElementById(t):t,"svg"==t.nodeName?this.constructor.call(this,t):(this.constructor.call(this,b.create("svg")),t.appendChild(this.node),this.size("100%","100%")),this.namespace().defs())},inherit:b.Container,extend:{namespace:function(){return this.attr({xmlns:b.ns,version:"1.1"}).attr("xmlns:xlink",b.xlink,b.xmlns).attr("xmlns:svgjs",b.svgjs,b.xmlns)},defs:function(){if(!this._defs){var t;(t=this.node.getElementsByTagName("defs")[0])?this._defs=b.adopt(t):this._defs=new b.Defs,this.node.appendChild(this._defs.node)}return this._defs},parent:function(){return"#document"==this.node.parentNode.nodeName?null:this.node.parentNode},spof:function(t){var e=this.node.getScreenCTM();return e&&this.style("left",-e.e%1+"px").style("top",-e.f%1+"px"),this},remove:function(){return this.parent()&&this.parent().removeChild(this.node),this}}}),b.Shape=b.invent({create:function(t){this.constructor.call(this,t)},inherit:b.Element}),b.Bare=b.invent({create:function(t,e){if(this.constructor.call(this,b.create(t)),e)for(var i in e.prototype)"function"==typeof e.prototype[i]&&(this[i]=e.prototype[i])},inherit:b.Element,extend:{words:function(t){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return this.node.appendChild(e.createTextNode(t)),this}}}),b.extend(b.Parent,{element:function(t,e){return this.put(new b.Bare(t,e))}}),b.Symbol=b.invent({create:"symbol",inherit:b.Container,construct:{symbol:function(){return this.put(new b.Symbol)}}}),b.Use=b.invent({create:"use",inherit:b.Shape,extend:{element:function(t,e){return this.attr("href",(e||"")+"#"+t,b.xlink)}},construct:{use:function(t,e){return this.put(new b.Use).element(t,e)}}}),b.Rect=b.invent({create:"rect",inherit:b.Shape,construct:{rect:function(t,e){return this.put(new b.Rect).size(t,e)}}}),b.Circle=b.invent({create:"circle",inherit:b.Shape,construct:{circle:function(t){return this.put(new b.Circle).rx(new b.Number(t).divide(2)).move(0,0)}}}),b.extend(b.Circle,b.FX,{rx:function(t){return this.attr("r",t)},ry:function(t){return this.rx(t)}}),b.Ellipse=b.invent({create:"ellipse",inherit:b.Shape,construct:{ellipse:function(t,e){return this.put(new b.Ellipse).size(t,e).move(0,0)}}}),b.extend(b.Ellipse,b.Rect,b.FX,{rx:function(t){return this.attr("rx",t)},ry:function(t){return this.attr("ry",t)}}),b.extend(b.Circle,b.Ellipse,{x:function(t){return null==t?this.cx()-this.rx():this.cx(t+this.rx())},y:function(t){return null==t?this.cy()-this.ry():this.cy(t+this.ry())},cx:function(t){return null==t?this.attr("cx"):this.attr("cx",t)},cy:function(t){return null==t?this.attr("cy"):this.attr("cy",t)},width:function(t){return null==t?2*this.rx():this.rx(new b.Number(t).divide(2))},height:function(t){return null==t?2*this.ry():this.ry(new b.Number(t).divide(2))},size:function(t,e){var i=f(this,t,e);return this.rx(new b.Number(i.width).divide(2)).ry(new b.Number(i.height).divide(2))}}),b.Line=b.invent({create:"line",inherit:b.Shape,extend:{array:function(){return new b.PointArray([[this.attr("x1"),this.attr("y1")],[this.attr("x2"),this.attr("y2")]])},plot:function(t,e,i,n){return null==t?this.array():(t="undefined"!=typeof e?{x1:t,y1:e,x2:i,y2:n}:new b.PointArray(t).toLine(),this.attr(t))},move:function(t,e){return this.attr(this.array().move(t,e).toLine())},size:function(t,e){var i=f(this,t,e);return this.attr(this.array().size(i.width,i.height).toLine())}},construct:{line:function(t,e,i,n){return b.Line.prototype.plot.apply(this.put(new b.Line),null!=t?[t,e,i,n]:[0,0,0,0])}}}),b.Polyline=b.invent({create:"polyline",inherit:b.Shape,construct:{polyline:function(t){return this.put(new b.Polyline).plot(t||new b.PointArray)}}}),b.Polygon=b.invent({create:"polygon",inherit:b.Shape,construct:{polygon:function(t){return this.put(new b.Polygon).plot(t||new b.PointArray)}}}),b.extend(b.Polyline,b.Polygon,{array:function(){return this._array||(this._array=new b.PointArray(this.attr("points")))},plot:function(t){return null==t?this.array():this.attr("points",this._array=new b.PointArray(t))},move:function(t,e){return this.attr("points",this.array().move(t,e))},size:function(t,e){var i=f(this,t,e);return this.attr("points",this.array().size(i.width,i.height))}}),b.extend(b.Line,b.Polyline,b.Polygon,{morphArray:b.PointArray,x:function(t){return null==t?this.bbox().x:this.move(t,this.bbox().y)},y:function(t){return null==t?this.bbox().y:this.move(this.bbox().x,t)},width:function(t){var e=this.bbox();return null==t?e.width:this.size(t,e.height)},height:function(t){var e=this.bbox();return null==t?e.height:this.size(e.width,t)}}),b.Path=b.invent({create:"path",inherit:b.Shape,extend:{morphArray:b.PathArray,array:function(){return this._array||(this._array=new b.PathArray(this.attr("d")))},plot:function(t){return null==t?this.array():this.attr("d",this._array=new b.PathArray(t))},move:function(t,e){return this.attr("d",this.array().move(t,e))},x:function(t){return null==t?this.bbox().x:this.move(t,this.bbox().y)},y:function(t){return null==t?this.bbox().y:this.move(this.bbox().x,t)},size:function(t,e){var i=f(this,t,e);return this.attr("d",this.array().size(i.width,i.height))},width:function(t){return null==t?this.bbox().width:this.size(t,this.bbox().height)},height:function(t){return null==t?this.bbox().height:this.size(this.bbox().width,t)}},construct:{path:function(t){return this.put(new b.Path).plot(t||new b.PathArray)}}}),b.Image=b.invent({create:"image",inherit:b.Shape,extend:{load:function(e,i){if(!e)return this;var n=new t.Image;return b.on(n,"load",function(t){var r=this.parent();0==this.width()&&0==this.height()&&this.size(n.width,n.height),r instanceof b.Pattern&&0==r.width()&&0==r.height()&&r.size(this.width(),this.height()),"function"==typeof i&&i.call(this,{width:n.width,height:n.height,ratio:n.width/n.height,url:e})},this),this.attr("href",n.src=e,b.xlink)}},construct:{image:function(t,e){return this.put(new b.Image).size(0,0).load(t,e)}}}),b.Text=b.invent({create:function(){this.constructor.call(this,b.create("text")),this.dom.leading=new b.Number(1.3),this._rebuild=!0,this._build=!1,this.attr("font-family",b.defaults.attrs["font-family"])},inherit:b.Parent,extend:{x:function(t){return null==t?this.attr("x"):this.attr("x",t)},y:function(t){var e=this.attr("y"),i="number"==typeof e?e-this.bbox().y:0;return null==t?"number"==typeof e?e-i:e:this.attr("y","number"==typeof t?t+i:t)},cx:function(t){return null==t?this.bbox().cx:this.x(t-this.bbox().width/2)},cy:function(t){return null==t?this.bbox().cy:this.y(t-this.bbox().height/2)},text:function(t){if("undefined"==typeof t){for(var t="",e=this.node.childNodes,i=0,n=e.length;i<n;++i)0!=i&&3!=e[i].nodeType&&1==b.adopt(e[i]).dom.newLined&&(t+="\n"),t+=e[i].textContent;return t}if(this.clear().build(!0),"function"==typeof t)t.call(this,this);else{t=t.split("\n");for(var i=0,r=t.length;i<r;i++)this.tspan(t[i]).newLine()}return this.build(!1).rebuild()},size:function(t){return this.attr("font-size",t).rebuild()},leading:function(t){return null==t?this.dom.leading:(this.dom.leading=new b.Number(t),this.rebuild())},rebuild:function(t){if("boolean"==typeof t&&(this._rebuild=t),this._rebuild){var e=this,i=0,n=this.dom.leading*new b.Number(this.attr("font-size"));this.each(function(){this.dom.newLined&&(e.textPath()||this.attr("x",e.attr("x")),"\n"==this.text()?i+=n:(this.attr("dy",n+i),i=0))}),this.fire("rebuild")}return this},build:function(t){return this._build=!!t,this},setData:function(t){return this.dom=t,this.dom.leading=new b.Number(t.leading||1.3),this}},construct:{text:function(t){return this.put(new b.Text).text(t)},plain:function(t){return this.put(new b.Text).plain(t)}}}),b.Tspan=b.invent({create:"tspan",inherit:b.Parent,extend:{text:function(t){return null==t?this.node.textContent+(this.dom.newLined?"\n":""):("function"==typeof t?t.call(this,this):this.plain(t),this)},dx:function(t){return this.attr("dx",t)},dy:function(t){return this.attr("dy",t)},newLine:function(){var t=this.parent(b.Text);return this.dom.newLined=!0,this.dy(t.dom.leading*t.attr("font-size")).attr("x",t.x())}}}),b.extend(b.Text,b.Tspan,{plain:function(t){return this._build===!1&&this.clear(),this.node.appendChild(e.createTextNode(t)),this},tspan:function(t){var e=(this.textPath&&this.textPath()||this).node,i=new b.Tspan;return this._build===!1&&this.clear(),e.appendChild(i.node),i.text(t)},length:function(){return this.node.getComputedTextLength()}}),b.TextPath=b.invent({create:"textPath",inherit:b.Parent,parent:b.Text,construct:{path:function(t){for(var e=new b.TextPath,i=this.doc().defs().path(t);this.node.hasChildNodes();)e.node.appendChild(this.node.firstChild);return this.node.appendChild(e.node),e.attr("href","#"+i,b.xlink),this},array:function(){var t=this.track();return t?t.array():null},plot:function(t){var e=this.track(),i=null;return e&&(i=e.plot(t)),null==t?i:this},track:function(){var t=this.textPath();if(t)return t.reference("href")},textPath:function(){if(this.node.firstChild&&"textPath"==this.node.firstChild.nodeName)return b.adopt(this.node.firstChild)}}}),b.Nested=b.invent({create:function(){this.constructor.call(this,b.create("svg")),this.style("overflow","visible")},inherit:b.Container,construct:{nested:function(){return this.put(new b.Nested)}}}),b.A=b.invent({create:"a",inherit:b.Container,extend:{to:function(t){return this.attr("href",t,b.xlink)},show:function(t){return this.attr("show",t,b.xlink)},target:function(t){return this.attr("target",t)}},construct:{link:function(t){return this.put(new b.A).to(t)}}}),b.extend(b.Element,{linkTo:function(t){var e=new b.A;return"function"==typeof t?t.call(e,e):e.to(t),this.parent().put(e).put(this)}}),b.Marker=b.invent({create:"marker",inherit:b.Container,extend:{width:function(t){return this.attr("markerWidth",t)},height:function(t){return this.attr("markerHeight",t)},ref:function(t,e){return this.attr("refX",t).attr("refY",e)},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},toString:function(){return"url(#"+this.id()+")"}},construct:{marker:function(t,e,i){return this.defs().marker(t,e,i)}}}),b.extend(b.Defs,{marker:function(t,e,i){return this.put(new b.Marker).size(t,e).ref(t/2,e/2).viewbox(0,0,t,e).attr("orient","auto").update(i)}}),b.extend(b.Line,b.Polyline,b.Polygon,b.Path,{marker:function(t,e,i,n){var r=["marker"];return"all"!=t&&r.push(t),r=r.join("-"),t=arguments[1]instanceof b.Marker?arguments[1]:this.doc().marker(e,i,n),this.attr(r,t)}});var M={stroke:["color","width","opacity","linecap","linejoin","miterlimit","dasharray","dashoffset"],fill:["color","opacity","rule"],prefix:function(t,e){return"color"==e?t:t+"-"+e}};["fill","stroke"].forEach(function(t){var e,i={};i[t]=function(i){if("undefined"==typeof i)return this;if("string"==typeof i||b.Color.isRgb(i)||i&&"function"==typeof i.fill)this.attr(t,i);else for(e=M[t].length-1;e>=0;e--)null!=i[M[t][e]]&&this.attr(M.prefix(t,M[t][e]),i[M[t][e]]);return this},b.extend(b.Element,b.FX,i)}),b.extend(b.Element,b.FX,{rotate:function(t,e,i){return this.transform({rotation:t,cx:e,cy:i})},skew:function(t,e,i,n){return 1==arguments.length||3==arguments.length?this.transform({skew:t,cx:e,cy:i}):this.transform({skewX:t,skewY:e,cx:i,cy:n})},scale:function(t,e,i,n){return 1==arguments.length||3==arguments.length?this.transform({scale:t,cx:e,cy:i}):this.transform({scaleX:t,scaleY:e,cx:i,cy:n})},translate:function(t,e){return this.transform({x:t,y:e})},flip:function(t,e){return e="number"==typeof t?t:e,this.transform({flip:t||"both",offset:e})},matrix:function(t){return this.attr("transform",new b.Matrix(6==arguments.length?[].slice.call(arguments):t))},opacity:function(t){return this.attr("opacity",t)},dx:function(t){return this.x(new b.Number(t).plus(this instanceof b.FX?0:this.x()),!0)},dy:function(t){return this.y(new b.Number(t).plus(this instanceof b.FX?0:this.y()),!0)},dmove:function(t,e){return this.dx(t).dy(e)}}),b.extend(b.Rect,b.Ellipse,b.Circle,b.Gradient,b.FX,{radius:function(t,e){var i=(this._target||this).type;return"radialGradient"==i||"radialGradient"==i?this.attr("r",new b.Number(t)):this.rx(t).ry(null==e?t:e)}}),b.extend(b.Path,{length:function(){return this.node.getTotalLength()},pointAt:function(t){return new b.Point(this.node.getPointAtLength(t))}}),b.extend(b.Parent,b.Text,b.Tspan,b.FX,{font:function(t,e){if("object"==typeof t)for(e in t)this.font(e,t[e]);return"leading"==t?this.leading(e):"anchor"==t?this.attr("text-anchor",e):"size"==t||"family"==t||"weight"==t||"stretch"==t||"variant"==t||"style"==t?this.attr("font-"+t,e):this.attr(t,e)}}),b.extend(b.Element,{data:function(t,e,i){if("object"==typeof t)for(e in t)this.data(e,t[e]);else if(arguments.length<2)try{return JSON.parse(this.attr("data-"+t))}catch(e){return this.attr("data-"+t)}else this.attr("data-"+t,null===e?null:i===!0||"string"==typeof e||"number"==typeof e?e:JSON.stringify(e));return this}}),b.extend(b.Element,{remember:function(t,e){if("object"==typeof arguments[0])for(var e in t)this.remember(e,t[e]);else{if(1==arguments.length)return this.memory()[t];this.memory()[t]=e}return this},forget:function(){if(0==arguments.length)this._memory={};else for(var t=arguments.length-1;t>=0;t--)delete this.memory()[arguments[t]];return this},memory:function(){return this._memory||(this._memory={})}}),b.get=function(t){var i=e.getElementById(w(t)||t);return b.adopt(i)},b.select=function(t,i){return b.utils.map((i||e).querySelectorAll(t),function(t){return b.adopt(t)})},b.$$=function(t,i){return b.utils.map((i||e).querySelectorAll(t),function(t){return b.adopt(t)})},b.$=function(t,i){return b.adopt((i||e).querySelector(t))},b.extend(b.Parent,{select:function(t){return b.select(t,this.node)}});var P="abcdef".split("");return b.Box=b.invent({create:function(t){var e=[0,0,0,0];t="string"==typeof t?t.split(b.regex.delimiter).map(parseFloat):Array.isArray(t)?t:"object"==typeof t?[null!=t.left?t.left:t.x,null!=t.top?t.top:t.y,t.width,t.height]:4==arguments.length?[].slice.call(arguments):e,this.x=t[0],this.y=t[1],this.width=t[2],this.height=t[3],g(this)},extend:{merge:function(t){var e=Math.min(this.x,t.x),i=Math.min(this.y,t.y);return new b.Box(e,i,Math.max(this.x+this.width,t.x+t.width)-e,Math.max(this.y+this.height,t.y+t.height)-i)},transform:function(t){var e=1/0,i=-(1/0),n=1/0,r=-(1/0),s=[new b.Point(this.x,this.y),new b.Point(this.x2,this.y),new b.Point(this.x,this.y2),new b.Point(this.x2,this.y2)];return s.forEach(function(s){s=s.transform(t),e=Math.min(e,s.x),i=Math.max(i,s.x),n=Math.min(n,s.y),r=Math.max(r,s.y)}),new b.Box(e,n,i-e,r-n)},addOffset:function(){return this.x+=t.pageXOffset,this.y+=t.pageYOffset,this},toString:function(){return this.x+" "+this.y+" "+this.width+" "+this.height},morph:function(t,e,i,n){return this.destination=new b.Box(t,e,i,n),this},at:function(t){return this.destination?new b.Box(this.x+(this.destination.x-this.x)*t,this.y+(this.destination.y-this.y)*t,this.width+(this.destination.width-this.width)*t,this.height+(this.destination.height-this.height)*t):this}},parent:b.Element,construct:{bbox:function(){var t;try{if(t=this.node.getBBox(),i(t)&&!n(this.node))throw new Exception("Element not in the dom")}catch(i){try{var e=this.clone(b.parser.draw).show();t=e.node.getBBox(),e.remove()}catch(t){console.warn("Getting a bounding box of this element is not possible")}}return new b.Box(t)},rbox:function(t){try{var e=new b.Box(this.node.getBoundingClientRect());return t?e.transform(t.screenCTM().inverse()):e.addOffset()}catch(t){return new b.Box}}}}),b.extend(b.Doc,b.Nested,b.Symbol,b.Image,b.Pattern,b.Marker,b.ForeignObject,b.View,{viewbox:function(t,e,i,n){return null==t?new b.Box(this.attr("viewBox")):this.attr("viewBox",new b.Box(t,e,i,n))}}),b});
\ No newline at end of file +/*! svg.js v3.0.0 MIT*/;!function(t,e){"function"==typeof define&&define.amd?define(function(){return e(t,t.document)}):"object"==typeof exports?module.exports=t.document?e(t,t.document):function(t){return e(t,t.document)}:t.SVG=e(t,t.document)}("undefined"!=typeof window?window:this,function(t,e){function i(t){return!(t.w||t.h||t.x||t.y)}function n(t){return(e.documentElement.contains||function(t){for(;t.parentNode;)t=t.parentNode;return t==e}).call(e.documentElement,t)}function r(t,e,i,n){return i+n.replace(b.regex.dots," .")}function s(t){for(var e=t.slice(0),i=e.length;i--;)Array.isArray(e[i])&&(e[i]=s(e[i]));return e}function a(t,e){return t instanceof e}function o(t,e){return(t.matches||t.matchesSelector||t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||t.oMatchesSelector).call(t,e)}function h(t){return t.toLowerCase().replace(/-(.)/g,function(t,e){return e.toUpperCase()})}function u(t){return t.charAt(0).toUpperCase()+t.slice(1)}function l(t){return 4==t.length?["#",t.substring(1,2),t.substring(1,2),t.substring(2,3),t.substring(2,3),t.substring(3,4),t.substring(3,4)].join(""):t}function c(t){var e=t.toString(16);return 1==e.length?"0"+e:e}function f(t,e,i){if(null==e||null==i){var n=t.bbox();null==e?e=n.width/n.height*i:null==i&&(i=n.height/n.width*e)}return{width:e,height:i}}function d(t,e,i){return{x:e*t.a+i*t.c+0,y:e*t.b+i*t.d+0}}function p(t){return{a:t[0],b:t[1],c:t[2],d:t[3],e:t[4],f:t[5]}}function x(t){return t instanceof b.Matrix||(t=new b.Matrix(t)),t}function m(t,e){t.cx=null==t.cx?e.bbox().cx:t.cx,t.cy=null==t.cy?e.bbox().cy:t.cy}function y(t){for(var e=0,i=t.length,n="";e<i;e++)n+=t[e][0],null!=t[e][1]&&(n+=t[e][1],null!=t[e][2]&&(n+=" ",n+=t[e][2],null!=t[e][3]&&(n+=" ",n+=t[e][3],n+=" ",n+=t[e][4],null!=t[e][5]&&(n+=" ",n+=t[e][5],n+=" ",n+=t[e][6],null!=t[e][7]&&(n+=" ",n+=t[e][7])))));return n+" "}function v(e){for(var i=e.childNodes.length-1;i>=0;i--)e.childNodes[i]instanceof t.SVGElement&&v(e.childNodes[i]);return b.adopt(e).id(b.eid(e.nodeName))}function g(t){return null==t.x&&(t.x=0,t.y=0,t.width=0,t.height=0),t.w=t.width,t.h=t.height,t.x2=t.x+t.width,t.y2=t.y+t.height,t.cx=t.x+t.width/2,t.cy=t.y+t.height/2,t}function w(t){var e=(t||"").toString().match(b.regex.reference);if(e)return e[1]}var b=this.SVG=function(t){if(b.supported)return t=new b.Doc(t),b.parser.draw||b.prepare(),t};if(b.ns="http://www.w3.org/2000/svg",b.xmlns="http://www.w3.org/2000/xmlns/",b.xlink="http://www.w3.org/1999/xlink",b.svgjs="http://svgjs.com/svgjs",b.supported=function(){return!!e.createElementNS&&!!e.createElementNS(b.ns,"svg").createSVGRect}(),!b.supported)return!1;b.did=1e3,b.eid=function(t){return"Svgjs"+u(t)+b.did++},b.create=function(t){var i=e.createElementNS(this.ns,t);return i.setAttribute("id",this.eid(t)),i},b.extend=function(){var t,e,i,n;for(t=[].slice.call(arguments),e=t.pop(),n=t.length-1;n>=0;n--)if(t[n])for(i in e)t[n].prototype[i]=e[i]},b.invent=function(t){var e="function"==typeof t.create?t.create:function(){this.constructor.call(this,b.create(t.create))};return t.inherit&&(e.prototype=new t.inherit),t.extend&&b.extend(e,t.extend),t.construct&&b.extend(t.parent||b.Container,t.construct),e},b.adopt=function(e){if(!e)return null;if(e.instance)return e.instance;var i;return i="svg"==e.nodeName?e.parentNode instanceof t.SVGElement?new b.Nested:new b.Doc:"linearGradient"==e.nodeName?new b.Gradient("linear"):"radialGradient"==e.nodeName?new b.Gradient("radial"):b[u(e.nodeName)]?new(b[u(e.nodeName)]):new b.Element(e),i.type=e.nodeName,i.node=e,e.instance=i,i instanceof b.Doc&&i.namespace().defs(),i.setData(JSON.parse(e.getAttribute("svgjs:data"))||{}),i},b.prepare=function(){var t=e.getElementsByTagName("body")[0],i=(t?new b.Doc(t):b.adopt(e.documentElement).nested()).size(2,0);b.parser={body:t||e.documentElement,draw:i.style({opacity:0,position:"absolute",left:"-100%",top:"-100%",overflow:"hidden"}).node,poly:i.polyline().node,path:i.path().node,native:b.create("svg")}},b.parser={native:b.create("svg")},e.addEventListener("DOMContentLoaded",function(){b.parser.draw||b.prepare()},!1),b.regex={numberAndUnit:/^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i,hex:/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,rgb:/rgb\((\d+),(\d+),(\d+)\)/,reference:/#([a-z0-9\-_]+)/i,transforms:/\)\s*,?\s*/,whitespace:/\s/g,isHex:/^#[a-f0-9]{3,6}$/i,isRgb:/^rgb\(/,isCss:/[^:]+:[^;]+;?/,isBlank:/^(\s+)?$/,isNumber:/^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,isPercent:/^-?[\d\.]+%$/,isImage:/\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i,delimiter:/[\s,]+/,hyphen:/([^e])\-/gi,pathLetters:/[MLHVCSQTAZ]/gi,isPathLetter:/[MLHVCSQTAZ]/i,numbersWithDots:/((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi,dots:/\./g},b.utils={map:function(t,e){var i,n=t.length,r=[];for(i=0;i<n;i++)r.push(e(t[i]));return r},filter:function(t,e){var i,n=t.length,r=[];for(i=0;i<n;i++)e(t[i])&&r.push(t[i]);return r},radians:function(t){return t%360*Math.PI/180},degrees:function(t){return 180*t/Math.PI%360},filterSVGElements:function(e){return this.filter(e,function(e){return e instanceof t.SVGElement})}},b.defaults={attrs:{"fill-opacity":1,"stroke-opacity":1,"stroke-width":0,"stroke-linejoin":"miter","stroke-linecap":"butt",fill:"#000000",stroke:"#000000",opacity:1,x:0,y:0,cx:0,cy:0,width:0,height:0,r:0,rx:0,ry:0,offset:0,"stop-opacity":1,"stop-color":"#000000","font-size":16,"font-family":"Helvetica, Arial, sans-serif","text-anchor":"start"}},b.Color=function(t){var e;this.r=0,this.g=0,this.b=0,t&&("string"==typeof t?b.regex.isRgb.test(t)?(e=b.regex.rgb.exec(t.replace(b.regex.whitespace,"")),this.r=parseInt(e[1]),this.g=parseInt(e[2]),this.b=parseInt(e[3])):b.regex.isHex.test(t)&&(e=b.regex.hex.exec(l(t)),this.r=parseInt(e[1],16),this.g=parseInt(e[2],16),this.b=parseInt(e[3],16)):"object"==typeof t&&(this.r=t.r,this.g=t.g,this.b=t.b))},b.extend(b.Color,{toString:function(){return this.toHex()},toHex:function(){return"#"+c(this.r)+c(this.g)+c(this.b)},toRgb:function(){return"rgb("+[this.r,this.g,this.b].join()+")"},brightness:function(){return this.r/255*.3+this.g/255*.59+this.b/255*.11},morph:function(t){return this.destination=new b.Color(t),this},at:function(t){return this.destination?(t=t<0?0:t>1?1:t,new b.Color({r:~~(this.r+(this.destination.r-this.r)*t),g:~~(this.g+(this.destination.g-this.g)*t),b:~~(this.b+(this.destination.b-this.b)*t)})):this}}),b.Color.test=function(t){return t+="",b.regex.isHex.test(t)||b.regex.isRgb.test(t)},b.Color.isRgb=function(t){return t&&"number"==typeof t.r&&"number"==typeof t.g&&"number"==typeof t.b},b.Color.isColor=function(t){return b.Color.isRgb(t)||b.Color.test(t)},b.Array=function(t,e){t=(t||[]).valueOf(),0==t.length&&e&&(t=e.valueOf()),this.value=this.parse(t)},b.extend(b.Array,{morph:function(t){if(this.destination=this.parse(t),this.value.length!=this.destination.length){for(var e=this.value[this.value.length-1],i=this.destination[this.destination.length-1];this.value.length>this.destination.length;)this.destination.push(i);for(;this.value.length<this.destination.length;)this.value.push(e)}return this},settle:function(){for(var t=0,e=this.value.length,i=[];t<e;t++)i.indexOf(this.value[t])==-1&&i.push(this.value[t]);return this.value=i},at:function(t){if(!this.destination)return this;for(var e=0,i=this.value.length,n=[];e<i;e++)n.push(this.value[e]+(this.destination[e]-this.value[e])*t);return new b.Array(n)},toString:function(){return this.value.join(" ")},valueOf:function(){return this.value},parse:function(t){return t=t.valueOf(),Array.isArray(t)?t:t.trim().split(b.regex.delimiter).map(parseFloat)},reverse:function(){return this.value.reverse(),this},clone:function(){var t=new this.constructor;return t.value=s(this.value),t}}),b.PointArray=function(t,e){b.Array.call(this,t,e||[[0,0]])},b.PointArray.prototype=new b.Array,b.PointArray.prototype.constructor=b.PointArray,b.extend(b.PointArray,{toString:function(){for(var t=0,e=this.value.length,i=[];t<e;t++)i.push(this.value[t].join(","));return i.join(" ")},toLine:function(){return{x1:this.value[0][0],y1:this.value[0][1],x2:this.value[1][0],y2:this.value[1][1]}},at:function(t){if(!this.destination)return this;for(var e=0,i=this.value.length,n=[];e<i;e++)n.push([this.value[e][0]+(this.destination[e][0]-this.value[e][0])*t,this.value[e][1]+(this.destination[e][1]-this.value[e][1])*t]);return new b.PointArray(n)},parse:function(t){var e=[];if(t=t.valueOf(),Array.isArray(t)){if(Array.isArray(t[0]))return t}else t=t.trim().split(b.regex.delimiter).map(parseFloat);t.length%2!==0&&t.pop();for(var i=0,n=t.length;i<n;i+=2)e.push([t[i],t[i+1]]);return e},move:function(t,e){var i=this.bbox();if(t-=i.x,e-=i.y,!isNaN(t)&&!isNaN(e))for(var n=this.value.length-1;n>=0;n--)this.value[n]=[this.value[n][0]+t,this.value[n][1]+e];return this},size:function(t,e){var i,n=this.bbox();for(i=this.value.length-1;i>=0;i--)n.width&&(this.value[i][0]=(this.value[i][0]-n.x)*t/n.width+n.x),n.height&&(this.value[i][1]=(this.value[i][1]-n.y)*e/n.height+n.y);return this},bbox:function(){return b.parser.poly.setAttribute("points",this.toString()),b.parser.poly.getBBox()}});for(var C={M:function(t,e,i){return e.x=i.x=t[0],e.y=i.y=t[1],["M",e.x,e.y]},L:function(t,e){return e.x=t[0],e.y=t[1],["L",t[0],t[1]]},H:function(t,e){return e.x=t[0],["H",t[0]]},V:function(t,e){return e.y=t[0],["V",t[0]]},C:function(t,e){return e.x=t[4],e.y=t[5],["C",t[0],t[1],t[2],t[3],t[4],t[5]]},S:function(t,e){return e.x=t[2],e.y=t[3],["S",t[0],t[1],t[2],t[3]]},Q:function(t,e){return e.x=t[2],e.y=t[3],["Q",t[0],t[1],t[2],t[3]]},T:function(t,e){return e.x=t[0],e.y=t[1],["T",t[0],t[1]]},Z:function(t,e,i){return e.x=i.x,e.y=i.y,["Z"]},A:function(t,e){return e.x=t[5],e.y=t[6],["A",t[0],t[1],t[2],t[3],t[4],t[5],t[6]]}},M="mlhvqtcsaz".split(""),P=0,N=M.length;P<N;++P)C[M[P]]=function(t){return function(e,i,n){if("H"==t)e[0]=e[0]+i.x;else if("V"==t)e[0]=e[0]+i.y;else if("A"==t)e[5]=e[5]+i.x,e[6]=e[6]+i.y;else for(var r=0,s=e.length;r<s;++r)e[r]=e[r]+(r%2?i.y:i.x);return C[t](e,i,n)}}(M[P].toUpperCase());b.PathArray=function(t,e){b.Array.call(this,t,e||[["M",0,0]])},b.PathArray.prototype=new b.Array,b.PathArray.prototype.constructor=b.PathArray,b.extend(b.PathArray,{toString:function(){return y(this.value)},move:function(t,e){var i=this.bbox();if(t-=i.x,e-=i.y,!isNaN(t)&&!isNaN(e))for(var n,r=this.value.length-1;r>=0;r--)n=this.value[r][0],"M"==n||"L"==n||"T"==n?(this.value[r][1]+=t,this.value[r][2]+=e):"H"==n?this.value[r][1]+=t:"V"==n?this.value[r][1]+=e:"C"==n||"S"==n||"Q"==n?(this.value[r][1]+=t,this.value[r][2]+=e,this.value[r][3]+=t,this.value[r][4]+=e,"C"==n&&(this.value[r][5]+=t,this.value[r][6]+=e)):"A"==n&&(this.value[r][6]+=t,this.value[r][7]+=e);return this},size:function(t,e){var i,n,r=this.bbox();for(i=this.value.length-1;i>=0;i--)n=this.value[i][0],"M"==n||"L"==n||"T"==n?(this.value[i][1]=(this.value[i][1]-r.x)*t/r.width+r.x,this.value[i][2]=(this.value[i][2]-r.y)*e/r.height+r.y):"H"==n?this.value[i][1]=(this.value[i][1]-r.x)*t/r.width+r.x:"V"==n?this.value[i][1]=(this.value[i][1]-r.y)*e/r.height+r.y:"C"==n||"S"==n||"Q"==n?(this.value[i][1]=(this.value[i][1]-r.x)*t/r.width+r.x,this.value[i][2]=(this.value[i][2]-r.y)*e/r.height+r.y,this.value[i][3]=(this.value[i][3]-r.x)*t/r.width+r.x,this.value[i][4]=(this.value[i][4]-r.y)*e/r.height+r.y,"C"==n&&(this.value[i][5]=(this.value[i][5]-r.x)*t/r.width+r.x,this.value[i][6]=(this.value[i][6]-r.y)*e/r.height+r.y)):"A"==n&&(this.value[i][1]=this.value[i][1]*t/r.width,this.value[i][2]=this.value[i][2]*e/r.height,this.value[i][6]=(this.value[i][6]-r.x)*t/r.width+r.x,this.value[i][7]=(this.value[i][7]-r.y)*e/r.height+r.y);return this},equalCommands:function(t){var e,i,n;for(t=new b.PathArray(t),n=this.value.length===t.value.length,e=0,i=this.value.length;n&&e<i;e++)n=this.value[e][0]===t.value[e][0];return n},morph:function(t){return t=new b.PathArray(t),this.equalCommands(t)?this.destination=t:this.destination=null,this},at:function(t){if(!this.destination)return this;var e,i,n,r,s=this.value,a=this.destination.value,o=[],h=new b.PathArray;for(e=0,i=s.length;e<i;e++){for(o[e]=[s[e][0]],n=1,r=s[e].length;n<r;n++)o[e][n]=s[e][n]+(a[e][n]-s[e][n])*t;"A"===o[e][0]&&(o[e][4]=+(0!=o[e][4]),o[e][5]=+(0!=o[e][5]))}return h.value=o,h},parse:function(t){if(t instanceof b.PathArray)return t.valueOf();var e,i,n={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7};t="string"==typeof t?t.replace(b.regex.numbersWithDots,r).replace(b.regex.pathLetters," $& ").replace(b.regex.hyphen,"$1 -").trim().split(b.regex.delimiter):t.reduce(function(t,e){return[].concat.call(t,e)},[]);var i=[],s=new b.Point,a=new b.Point,o=0,h=t.length;do b.regex.isPathLetter.test(t[o])?(e=t[o],++o):"M"==e?e="L":"m"==e&&(e="l"),i.push(C[e].call(null,t.slice(o,o+=n[e.toUpperCase()]).map(parseFloat),s,a));while(h>o);return i},bbox:function(){return b.parser.path.setAttribute("d",this.toString()),b.parser.path.getBBox()}}),b.Number=b.invent({create:function(t,e){this.value=0,this.unit=e||"","number"==typeof t?this.value=isNaN(t)?0:isFinite(t)?t:t<0?-3.4e38:3.4e38:"string"==typeof t?(e=t.match(b.regex.numberAndUnit),e&&(this.value=parseFloat(e[1]),"%"==e[5]?this.value/=100:"s"==e[5]&&(this.value*=1e3),this.unit=e[5])):t instanceof b.Number&&(this.value=t.valueOf(),this.unit=t.unit)},extend:{toString:function(){return("%"==this.unit?~~(1e8*this.value)/1e6:"s"==this.unit?this.value/1e3:this.value)+this.unit},toJSON:function(){return this.toString()},valueOf:function(){return this.value},plus:function(t){return t=new b.Number(t),new b.Number(this+t,this.unit||t.unit)},minus:function(t){return t=new b.Number(t),new b.Number(this-t,this.unit||t.unit)},times:function(t){return t=new b.Number(t),new b.Number(this*t,this.unit||t.unit)},divide:function(t){return t=new b.Number(t),new b.Number(this/t,this.unit||t.unit)},to:function(t){var e=new b.Number(this);return"string"==typeof t&&(e.unit=t),e},morph:function(t){return this.destination=new b.Number(t),t.relative&&(this.destination.value+=this.value),this},at:function(t){return this.destination?new b.Number(this.destination).minus(this).times(t).plus(this):this}}}),b.Element=b.invent({create:function(t){this._event=null,this.dom={},(this.node=t)&&(this.type=t.nodeName,this.node.instance=this)},extend:{x:function(t){return this.attr("x",t)},y:function(t){return this.attr("y",t)},cx:function(t){return null==t?this.x()+this.width()/2:this.x(t-this.width()/2)},cy:function(t){return null==t?this.y()+this.height()/2:this.y(t-this.height()/2)},move:function(t,e){return this.x(t).y(e)},center:function(t,e){return this.cx(t).cy(e)},width:function(t){return this.attr("width",t)},height:function(t){return this.attr("height",t)},size:function(t,e){var i=f(this,t,e);return this.width(new b.Number(i.width)).height(new b.Number(i.height))},clone:function(t,e){this.writeDataToDom();var i=v(this.node.cloneNode(!0));return t?t.add(i):this.after(i),i},remove:function(){return this.parent()&&this.parent().removeElement(this),this},replace:function(t){return this.after(t).remove(),t},addTo:function(t){return t.put(this)},putIn:function(t){return t.add(this)},id:function(t){return this.attr("id",t)},inside:function(t,e){var i=this.bbox();return t>i.x&&e>i.y&&t<i.x+i.width&&e<i.y+i.height},show:function(){return this.style("display","")},hide:function(){return this.style("display","none")},visible:function(){return"none"!=this.style("display")},toString:function(){return this.attr("id")},classes:function(){var t=this.attr("class");return null==t?[]:t.trim().split(b.regex.delimiter)},hasClass:function(t){return this.classes().indexOf(t)!=-1},addClass:function(t){if(!this.hasClass(t)){var e=this.classes();e.push(t),this.attr("class",e.join(" "))}return this},removeClass:function(t){return this.hasClass(t)&&this.attr("class",this.classes().filter(function(e){return e!=t}).join(" ")),this},toggleClass:function(t){return this.hasClass(t)?this.removeClass(t):this.addClass(t)},reference:function(t){return b.get(this.attr(t))},parent:function(e){var i=this;if(!i.node.parentNode)return null;if(i=b.adopt(i.node.parentNode),!e)return i;for(;i&&i.node instanceof t.SVGElement;){if("string"==typeof e?i.matches(e):i instanceof e)return i;i=b.adopt(i.node.parentNode)}},doc:function(){return this instanceof b.Doc?this:this.parent(b.Doc)},parents:function(t){var e=[],i=this;do{if(i=i.parent(t),!i||!i.node)break;e.push(i)}while(i.parent);return e},matches:function(t){return o(this.node,t)},native:function(){return this.node},svg:function(t){var i,n;if(!(t&&this instanceof b.Parent))return this.node.outerHTML;for(i=e.createElementNS(b.ns,"svg"),i.innerHTML=t,n=i.childNodes.length;n--;)1!=i.firstChild.nodeType?i.removeChild(i.firstChild):this.node.appendChild(i.firstChild);return this},writeDataToDom:function(){return this.is(b.Parent)&&this.each(function(){this.writeDataToDom()}),this.node.removeAttribute("svgjs:data"),Object.keys(this.dom).length&&this.node.setAttribute("svgjs:data",JSON.stringify(this.dom)),this},setData:function(t){return this.dom=t,this},is:function(t){return a(this,t)}}}),b.easing={"-":function(t){return t},"<>":function(t){return-Math.cos(t*Math.PI)/2+.5},">":function(t){return Math.sin(t*Math.PI/2)},"<":function(t){return-Math.cos(t*Math.PI/2)+1}},b.morph=function(t){return function(e,i){return new b.MorphObj(e,i).at(t)}},b.Situation=b.invent({create:function(t){this.init=!1,this.reversed=!1,this.reversing=!1,this.duration=new b.Number(t.duration).valueOf(),this.delay=new b.Number(t.delay).valueOf(),this.start=+new Date+this.delay,this.finish=this.start+this.duration,this.ease=t.ease,this.loop=0,this.loops=!1,this.animations={},this.attrs={},this.styles={},this.transforms=[],this.once={}}}),b.FX=b.invent({create:function(t){this._target=t,this.situations=[],this.active=!1,this.situation=null,this.paused=!1,this.lastPos=0,this.pos=0,this.absPos=0,this._speed=1},extend:{animate:function(t,e,i){"object"==typeof t&&(e=t.ease,i=t.delay,t=t.duration);var n=new b.Situation({duration:t||1e3,delay:i||0,ease:b.easing[e||"-"]||e});return this.queue(n),this},delay:function(t){var e=new b.Situation({duration:t,delay:0,ease:b.easing["-"]});return this.queue(e)},target:function(t){return t&&t instanceof b.Element?(this._target=t,this):this._target},timeToAbsPos:function(t){return(t-this.situation.start)/(this.situation.duration/this._speed)},absPosToTime:function(t){return this.situation.duration/this._speed*t+this.situation.start},startAnimFrame:function(){this.stopAnimFrame(),this.animationFrame=t.requestAnimationFrame(function(){this.step()}.bind(this))},stopAnimFrame:function(){t.cancelAnimationFrame(this.animationFrame)},start:function(){return!this.active&&this.situation&&(this.active=!0,this.startCurrent()),this},startCurrent:function(){return this.situation.start=+new Date+this.situation.delay/this._speed,this.situation.finish=this.situation.start+this.situation.duration/this._speed,this.initAnimations().step()},queue:function(t){return("function"==typeof t||t instanceof b.Situation)&&this.situations.push(t),this.situation||(this.situation=this.situations.shift()),this},dequeue:function(){return this.stop(),this.situation=this.situations.shift(),this.situation&&(this.situation instanceof b.Situation?this.start():this.situation.call(this)),this},initAnimations:function(){var t,e,i=this.situation;if(i.init)return this;for(t in i.animations)e=this.target()[t](),i.animations[t]instanceof b.Number&&(e=new b.Number(e)),i.animations[t]=e.morph(i.animations[t]);for(t in i.attrs)i.attrs[t]=new b.MorphObj(this.target().attr(t),i.attrs[t]);for(t in i.styles)i.styles[t]=new b.MorphObj(this.target().style(t),i.styles[t]);return i.initialTransformation=this.target().matrixify(),i.init=!0,this},clearQueue:function(){return this.situations=[],this},clearCurrent:function(){return this.situation=null,this},stop:function(t,e){var i=this.active;return this.active=!1,e&&this.clearQueue(),t&&this.situation&&(!i&&this.startCurrent(),this.atEnd()),this.stopAnimFrame(),this.clearCurrent()},reset:function(){if(this.situation){var t=this.situation;this.stop(),this.situation=t,this.atStart()}return this},finish:function(){for(this.stop(!0,!1);this.dequeue().situation&&this.stop(!0,!1););return this.clearQueue().clearCurrent(),this},atStart:function(){return this.at(0,!0)},atEnd:function(){return this.situation.loops===!0&&(this.situation.loops=this.situation.loop+1),"number"==typeof this.situation.loops?this.at(this.situation.loops,!0):this.at(1,!0)},at:function(t,e){var i=this.situation.duration/this._speed;return this.absPos=t,e||(this.situation.reversed&&(this.absPos=1-this.absPos),this.absPos+=this.situation.loop),this.situation.start=+new Date-this.absPos*i,this.situation.finish=this.situation.start+i,this.step(!0)},speed:function(t){return 0===t?this.pause():t?(this._speed=t,this.at(this.absPos,!0)):this._speed},loop:function(t,e){var i=this.last();return i.loops=null==t||t,i.loop=0,e&&(i.reversing=!0),this},pause:function(){return this.paused=!0,this.stopAnimFrame(),this},play:function(){return this.paused?(this.paused=!1,this.at(this.absPos,!0)):this},reverse:function(t){var e=this.last();return"undefined"==typeof t?e.reversed=!e.reversed:e.reversed=t,this},progress:function(t){return t?this.situation.ease(this.pos):this.pos},after:function(t){var e=this.last(),i=function i(n){n.detail.situation==e&&(t.call(this,e),this.off("finished.fx",i))};return this.target().on("finished.fx",i),this._callStart()},during:function(t){var e=this.last(),i=function(i){i.detail.situation==e&&t.call(this,i.detail.pos,b.morph(i.detail.pos),i.detail.eased,e)};return this.target().off("during.fx",i).on("during.fx",i),this.after(function(){this.off("during.fx",i)}),this._callStart()},afterAll:function(t){var e=function e(i){t.call(this),this.off("allfinished.fx",e)};return this.target().off("allfinished.fx",e).on("allfinished.fx",e),this._callStart()},duringAll:function(t){var e=function(e){t.call(this,e.detail.pos,b.morph(e.detail.pos),e.detail.eased,e.detail.situation)};return this.target().off("during.fx",e).on("during.fx",e),this.afterAll(function(){this.off("during.fx",e)}),this._callStart()},last:function(){return this.situations.length?this.situations[this.situations.length-1]:this.situation},add:function(t,e,i){return this.last()[i||"animations"][t]=e,this._callStart()},step:function(t){if(t||(this.absPos=this.timeToAbsPos(+new Date)),this.situation.loops!==!1){var e,i,n;e=Math.max(this.absPos,0),i=Math.floor(e),this.situation.loops===!0||i<this.situation.loops?(this.pos=e-i,n=this.situation.loop,this.situation.loop=i):(this.absPos=this.situation.loops,this.pos=1,n=this.situation.loop-1,this.situation.loop=this.situation.loops),this.situation.reversing&&(this.situation.reversed=this.situation.reversed!=Boolean((this.situation.loop-n)%2))}else this.absPos=Math.min(this.absPos,1),this.pos=this.absPos;this.pos<0&&(this.pos=0),this.situation.reversed&&(this.pos=1-this.pos);var r=this.situation.ease(this.pos);for(var s in this.situation.once)s>this.lastPos&&s<=r&&(this.situation.once[s].call(this.target(),this.pos,r),delete this.situation.once[s]);return this.active&&this.target().fire("during",{pos:this.pos,eased:r,fx:this,situation:this.situation}),this.situation?(this.eachAt(),1==this.pos&&!this.situation.reversed||this.situation.reversed&&0==this.pos?(this.stopAnimFrame(),this.target().fire("finished",{fx:this,situation:this.situation}),this.situations.length||(this.target().fire("allfinished"),this.target().off(".fx"),this.active=!1),this.active?this.dequeue():this.clearCurrent()):!this.paused&&this.active&&this.startAnimFrame(),this.lastPos=r,this):this},eachAt:function(){var t,e,i,n=this,r=this.target(),s=this.situation;for(t in s.animations)i=[].concat(s.animations[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(s.ease(n.pos),n.pos):t}),r[t].apply(r,i);for(t in s.attrs)i=[t].concat(s.attrs[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(s.ease(n.pos),n.pos):t}),r.attr.apply(r,i);for(t in s.styles)i=[t].concat(s.styles[t]).map(function(t){return"string"!=typeof t&&t.at?t.at(s.ease(n.pos),n.pos):t}),r.style.apply(r,i);if(s.transforms.length){for(i=s.initialTransformation,t=0,e=s.transforms.length;t<e;t++){var a=s.transforms[t];a instanceof b.Matrix?i=a.relative?i.multiply((new b.Matrix).morph(a).at(s.ease(this.pos))):i.morph(a).at(s.ease(this.pos)):(a.relative||a.undo(i.extract()),i=i.multiply(a.at(s.ease(this.pos))))}r.matrix(i)}return this},once:function(t,e,i){return i||(t=this.situation.ease(t)),this.situation.once[t]=e,this},_callStart:function(){return setTimeout(function(){this.start()}.bind(this),0),this}},parent:b.Element,construct:{animate:function(t,e,i){return(this.fx||(this.fx=new b.FX(this))).animate(t,e,i)},delay:function(t){return(this.fx||(this.fx=new b.FX(this))).delay(t)},stop:function(t,e){return this.fx&&this.fx.stop(t,e),this},finish:function(){return this.fx&&this.fx.finish(),this},pause:function(){return this.fx&&this.fx.pause(),this},play:function(){return this.fx&&this.fx.play(),this},speed:function(t){if(this.fx){if(null==t)return this.fx.speed();this.fx.speed(t)}return this}}}),b.MorphObj=b.invent({create:function(t,e){return b.Color.isColor(e)?new b.Color(t).morph(e):b.regex.numberAndUnit.test(e)?new b.Number(t).morph(e):(this.value=t,void(this.destination=e))},extend:{at:function(t,e){return e<1?this.value:this.destination},valueOf:function(){return this.value}}}),b.extend(b.FX,{attr:function(t,e,i){if("object"==typeof t)for(var n in t)this.attr(n,t[n]);else this.add(t,e,"attrs");return this},style:function(t,e){if("object"==typeof t)for(var i in t)this.style(i,t[i]);else this.add(t,e,"styles");return this},x:function(t,e){if(this.target()instanceof b.G)return this.transform({x:t},e),this;var i=new b.Number(t);return i.relative=e,this.add("x",i)},y:function(t,e){if(this.target()instanceof b.G)return this.transform({y:t},e),this;var i=new b.Number(t);return i.relative=e,this.add("y",i)},cx:function(t){return this.add("cx",new b.Number(t))},cy:function(t){return this.add("cy",new b.Number(t))},move:function(t,e){return this.x(t).y(e)},center:function(t,e){return this.cx(t).cy(e)},size:function(t,e){if(this.target()instanceof b.Text)this.attr("font-size",t);else{var i;t&&e||(i=this.target().bbox()),t||(t=i.width/i.height*e),e||(e=i.height/i.width*t),this.add("width",new b.Number(t)).add("height",new b.Number(e))}return this},plot:function(){return this.add("plot",arguments.length>1?[].slice.call(arguments):arguments[0])},leading:function(t){return this.target().leading?this.add("leading",new b.Number(t)):this},viewbox:function(t,e,i,n){return this.target()instanceof b.Container&&this.add("viewbox",new b.Box(t,e,i,n)),this},update:function(t){if(this.target()instanceof b.Stop){if("number"==typeof t||t instanceof b.Number)return this.update({offset:arguments[0],color:arguments[1],opacity:arguments[2]});null!=t.opacity&&this.attr("stop-opacity",t.opacity),null!=t.color&&this.attr("stop-color",t.color),null!=t.offset&&this.attr("offset",t.offset)}return this}}),b.Matrix=b.invent({create:function(t){var e,i=p([1,0,0,1,0,0]);for(t=t instanceof b.Element?t.matrixify():"string"==typeof t?p(t.split(b.regex.delimiter).map(parseFloat)):6==arguments.length?p([].slice.call(arguments)):Array.isArray(t)?p(t):"object"==typeof t?t:i,e=A.length-1;e>=0;--e)this[A[e]]=t&&"number"==typeof t[A[e]]?t[A[e]]:i[A[e]]},extend:{extract:function(){var t=d(this,0,1),e=d(this,1,0),i=180/Math.PI*Math.atan2(t.y,t.x)-90;return{x:this.e,y:this.f,transformedX:(this.e*Math.cos(i*Math.PI/180)+this.f*Math.sin(i*Math.PI/180))/Math.sqrt(this.a*this.a+this.b*this.b),transformedY:(this.f*Math.cos(i*Math.PI/180)+this.e*Math.sin(-i*Math.PI/180))/Math.sqrt(this.c*this.c+this.d*this.d),skewX:-i,skewY:180/Math.PI*Math.atan2(e.y,e.x),scaleX:Math.sqrt(this.a*this.a+this.b*this.b),scaleY:Math.sqrt(this.c*this.c+this.d*this.d),rotation:i,a:this.a,b:this.b,c:this.c,d:this.d,e:this.e,f:this.f,matrix:new b.Matrix(this)}},clone:function(){return new b.Matrix(this)},morph:function(t){return this.destination=new b.Matrix(t),this},at:function(t){if(!this.destination)return this;var e=new b.Matrix({a:this.a+(this.destination.a-this.a)*t,b:this.b+(this.destination.b-this.b)*t,c:this.c+(this.destination.c-this.c)*t,d:this.d+(this.destination.d-this.d)*t,e:this.e+(this.destination.e-this.e)*t,f:this.f+(this.destination.f-this.f)*t});return e},multiply:function(t){return new b.Matrix(this.native().multiply(x(t).native()))},inverse:function(){return new b.Matrix(this.native().inverse())},translate:function(t,e){return new b.Matrix(this.native().translate(t||0,e||0))},scale:function(t,e,i,n){return 1==arguments.length?e=t:3==arguments.length&&(n=i,i=e,e=t),this.around(i,n,new b.Matrix(t,0,0,e,0,0))},rotate:function(t,e,i){return t=b.utils.radians(t),this.around(e,i,new b.Matrix(Math.cos(t),Math.sin(t),-Math.sin(t),Math.cos(t),0,0))},flip:function(t,e){return"x"==t?this.scale(-1,1,e,0):"y"==t?this.scale(1,-1,0,e):this.scale(-1,-1,t,null!=e?e:t)},skew:function(t,e,i,n){return 1==arguments.length?e=t:3==arguments.length&&(n=i,i=e,e=t),t=b.utils.radians(t),e=b.utils.radians(e),this.around(i,n,new b.Matrix(1,Math.tan(e),Math.tan(t),1,0,0))},skewX:function(t,e,i){return this.skew(t,0,e,i)},skewY:function(t,e,i){return this.skew(0,t,e,i)},around:function(t,e,i){return this.multiply(new b.Matrix(1,0,0,1,t||0,e||0)).multiply(i).multiply(new b.Matrix(1,0,0,1,-t||0,-e||0))},native:function(){for(var t=b.parser.native.createSVGMatrix(),e=A.length-1;e>=0;e--)t[A[e]]=this[A[e]];return t},toString:function(){return"matrix("+this.a+","+this.b+","+this.c+","+this.d+","+this.e+","+this.f+")"}},parent:b.Element,construct:{ctm:function(){return new b.Matrix(this.node.getCTM())},screenCTM:function(){if(this instanceof b.Nested){var t=this.rect(1,1),e=t.node.getScreenCTM();return t.remove(),new b.Matrix(e)}return new b.Matrix(this.node.getScreenCTM())}}}),b.Point=b.invent({create:function(t,e){var i,n={x:0,y:0};i=Array.isArray(t)?{x:t[0],y:t[1]}:"object"==typeof t?{x:t.x,y:t.y}:null!=t?{x:t,y:null!=e?e:t}:n,this.x=i.x,this.y=i.y},extend:{clone:function(){return new b.Point(this)},morph:function(t,e){return this.destination=new b.Point(t,e),this},at:function(t){if(!this.destination)return this;var e=new b.Point({x:this.x+(this.destination.x-this.x)*t,y:this.y+(this.destination.y-this.y)*t});return e},native:function(){var t=b.parser.native.createSVGPoint();return t.x=this.x,t.y=this.y,t},transform:function(t){return new b.Point(this.native().matrixTransform(t.native()))}}}),b.extend(b.Element,{point:function(t,e){return new b.Point(t,e).transform(this.screenCTM().inverse())}}),b.extend(b.Element,{attr:function(t,e,i){if(null==t){for(t={},e=this.node.attributes,i=e.length-1;i>=0;i--)t[e[i].nodeName]=b.regex.isNumber.test(e[i].nodeValue)?parseFloat(e[i].nodeValue):e[i].nodeValue;return t}if("object"==typeof t)for(e in t)this.attr(e,t[e]);else if(null===e)this.node.removeAttribute(t);else{if(null==e)return e=this.node.getAttribute(t),null==e?b.defaults.attrs[t]:b.regex.isNumber.test(e)?parseFloat(e):e;"fill"!=t&&"stroke"!=t||(b.regex.isImage.test(e)&&(e=this.doc().defs().image(e)),e instanceof b.Image&&(e=this.doc().defs().pattern(0,0,function(){this.add(e)}))),"number"==typeof e?e=new b.Number(e):b.Color.isColor(e)?e=new b.Color(e):Array.isArray(e)&&(e=new b.Array(e)),"leading"==t?this.leading&&this.leading(e):"string"==typeof i?this.node.setAttributeNS(i,t,e.toString()):this.node.setAttribute(t,e.toString()),!this.rebuild||"font-size"!=t&&"x"!=t||this.rebuild(t,e)}return this}}),b.extend(b.Element,{transform:function(t,e){var i,n,r=this;if("object"!=typeof t)return i=new b.Matrix(r).extract(),"string"==typeof t?i[t]:i;if(i=new b.Matrix(r),e=!!e||!!t.relative,null!=t.a)i=e?i.multiply(new b.Matrix(t)):new b.Matrix(t);else if(null!=t.rotation)m(t,r),i=e?i.rotate(t.rotation,t.cx,t.cy):i.rotate(t.rotation-i.extract().rotation,t.cx,t.cy);else if(null!=t.scale||null!=t.scaleX||null!=t.scaleY){if(m(t,r),t.scaleX=null!=t.scale?t.scale:null!=t.scaleX?t.scaleX:1,t.scaleY=null!=t.scale?t.scale:null!=t.scaleY?t.scaleY:1, +!e){var s=i.extract();t.scaleX=1*t.scaleX/s.scaleX,t.scaleY=1*t.scaleY/s.scaleY}i=i.scale(t.scaleX,t.scaleY,t.cx,t.cy)}else if(null!=t.skew||null!=t.skewX||null!=t.skewY){if(m(t,r),t.skewX=null!=t.skew?t.skew:null!=t.skewX?t.skewX:0,t.skewY=null!=t.skew?t.skew:null!=t.skewY?t.skewY:0,!e){var s=i.extract();i=i.multiply((new b.Matrix).skew(s.skewX,s.skewY,t.cx,t.cy).inverse())}i=i.skew(t.skewX,t.skewY,t.cx,t.cy)}else t.flip?("x"==t.flip||"y"==t.flip?t.offset=null==t.offset?r.bbox()["c"+t.flip]:t.offset:null==t.offset?(n=r.bbox(),t.flip=n.cx,t.offset=n.cy):t.flip=t.offset,i=(new b.Matrix).flip(t.flip,t.offset)):null==t.x&&null==t.y||(e?i=i.translate(t.x,t.y):(null!=t.x&&(i.e=t.x),null!=t.y&&(i.f=t.y)));return this.attr("transform",i)}}),b.extend(b.FX,{transform:function(t,e){var i,n,r=this.target();return"object"!=typeof t?(i=new b.Matrix(r).extract(),"string"==typeof t?i[t]:i):(e=!!e||!!t.relative,null!=t.a?i=new b.Matrix(t):null!=t.rotation?(m(t,r),i=new b.Rotate(t.rotation,t.cx,t.cy)):null!=t.scale||null!=t.scaleX||null!=t.scaleY?(m(t,r),t.scaleX=null!=t.scale?t.scale:null!=t.scaleX?t.scaleX:1,t.scaleY=null!=t.scale?t.scale:null!=t.scaleY?t.scaleY:1,i=new b.Scale(t.scaleX,t.scaleY,t.cx,t.cy)):null!=t.skewX||null!=t.skewY?(m(t,r),t.skewX=null!=t.skewX?t.skewX:0,t.skewY=null!=t.skewY?t.skewY:0,i=new b.Skew(t.skewX,t.skewY,t.cx,t.cy)):t.flip?("x"==t.flip||"y"==t.flip?t.offset=null==t.offset?r.bbox()["c"+t.flip]:t.offset:null==t.offset?(n=r.bbox(),t.flip=n.cx,t.offset=n.cy):t.flip=t.offset,i=(new b.Matrix).flip(t.flip,t.offset)):null==t.x&&null==t.y||(i=new b.Translate(t.x,t.y)),i?(i.relative=e,this.last().transforms.push(i),this._callStart()):this)}}),b.extend(b.Element,{untransform:function(){return this.attr("transform",null)},matrixify:function(){var t=(this.attr("transform")||"").split(b.regex.transforms).slice(0,-1).map(function(t){var e=t.trim().split("(");return[e[0],e[1].split(b.regex.delimiter).map(function(t){return parseFloat(t)})]}).reduce(function(t,e){return"matrix"==e[0]?t.multiply(p(e[1])):t[e[0]].apply(t,e[1])},new b.Matrix);return t},toParent:function(t){if(this==t)return this;var e=this.screenCTM(),i=t.screenCTM().inverse();return this.addTo(t).untransform().transform(i.multiply(e)),this},toDoc:function(){return this.toParent(this.doc())}}),b.Transformation=b.invent({create:function(t,e){if(arguments.length>1&&"boolean"!=typeof e)return this.constructor.call(this,[].slice.call(arguments));if(Array.isArray(t))for(var i=0,n=this.arguments.length;i<n;++i)this[this.arguments[i]]=t[i];else if("object"==typeof t)for(var i=0,n=this.arguments.length;i<n;++i)this[this.arguments[i]]=t[this.arguments[i]];this.inversed=!1,e===!0&&(this.inversed=!0)},extend:{arguments:[],method:"",at:function(t){for(var e=[],i=0,n=this.arguments.length;i<n;++i)e.push(this[this.arguments[i]]);var r=this._undo||new b.Matrix;return r=(new b.Matrix).morph(b.Matrix.prototype[this.method].apply(r,e)).at(t),this.inversed?r.inverse():r},undo:function(t){for(var e=0,i=this.arguments.length;e<i;++e)t[this.arguments[e]]="undefined"==typeof this[this.arguments[e]]?0:t[this.arguments[e]];return t.cx=this.cx,t.cy=this.cy,this._undo=new(b[u(this.method)])(t,!0).at(1),this}}}),b.Translate=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["transformedX","transformedY"],method:"translate"}}),b.Rotate=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["rotation","cx","cy"],method:"rotate",at:function(t){var e=(new b.Matrix).rotate((new b.Number).morph(this.rotation-(this._undo?this._undo.rotation:0)).at(t),this.cx,this.cy);return this.inversed?e.inverse():e},undo:function(t){return this._undo=t,this}}}),b.Scale=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["scaleX","scaleY","cx","cy"],method:"scale"}}),b.Skew=b.invent({parent:b.Matrix,inherit:b.Transformation,create:function(t,e){this.constructor.apply(this,[].slice.call(arguments))},extend:{arguments:["skewX","skewY","cx","cy"],method:"skew"}}),b.extend(b.Element,{style:function(t,e){if(0==arguments.length)return this.node.style.cssText||"";if(arguments.length<2){if("object"!=typeof t)return this.node.style[h(t)];for(e in t)this.style(e,t[e])}else this.node.style[h(t)]=null===e||b.regex.isBlank.test(e)?"":e;return this}}),b.Parent=b.invent({create:function(t){this.constructor.call(this,t)},inherit:b.Element,extend:{children:function(){return b.utils.map(b.utils.filterSVGElements(this.node.childNodes),function(t){return b.adopt(t)})},add:function(t,e){return null==e?this.node.appendChild(t.node):t.node!=this.node.childNodes[e]&&this.node.insertBefore(t.node,this.node.childNodes[e]),this},put:function(t,e){return this.add(t,e),t},has:function(t){return this.index(t)>=0},index:function(t){return[].slice.call(this.node.childNodes).indexOf(t.node)},get:function(t){return b.adopt(this.node.childNodes[t])},first:function(){return this.get(0)},last:function(){return this.get(this.node.childNodes.length-1)},each:function(t,e){var i,n,r=this.children();for(i=0,n=r.length;i<n;i++)r[i]instanceof b.Element&&t.apply(r[i],[i,r]),e&&r[i]instanceof b.Container&&r[i].each(t,e);return this},removeElement:function(t){return this.node.removeChild(t.node),this},clear:function(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return delete this._defs,this},defs:function(){return this.doc().defs()}}}),b.extend(b.Parent,{flatten:function(t){return this instanceof b.Defs?this:(t=t||(this instanceof b.Doc?this:this.parent(b.Parent)),this.each(function(){return this instanceof b.Defs?this:this instanceof b.Parent?this.flatten(t):this.toParent(t)}),this.node.firstChild||this.remove(),this)}}),b.Container=b.invent({create:function(t){this.constructor.call(this,t)},inherit:b.Parent}),["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","touchstart","touchmove","touchleave","touchend","touchcancel"].forEach(function(t){b.Element.prototype[t]=function(e){return b.on(this.node,t,e),this}}),b.listeners=[],b.handlerMap=[],b.listenerId=0,b.on=function(t,e,i,n,r){var s=i.bind(n||t.instance||t),a=(b.handlerMap.indexOf(t)+1||b.handlerMap.push(t))-1,o=e.split(".")[0],h=e.split(".")[1]||"*";b.listeners[a]=b.listeners[a]||{},b.listeners[a][o]=b.listeners[a][o]||{},b.listeners[a][o][h]=b.listeners[a][o][h]||{},i._svgjsListenerId||(i._svgjsListenerId=++b.listenerId),b.listeners[a][o][h][i._svgjsListenerId]=s,t.addEventListener(o,s,r||!1)},b.off=function(t,e,i){var n=b.handlerMap.indexOf(t),r=e&&e.split(".")[0],s=e&&e.split(".")[1],a="";if(n!=-1)if(i){if("function"==typeof i&&(i=i._svgjsListenerId),!i)return;b.listeners[n][r]&&b.listeners[n][r][s||"*"]&&(t.removeEventListener(r,b.listeners[n][r][s||"*"][i],!1),delete b.listeners[n][r][s||"*"][i])}else if(s&&r){if(b.listeners[n][r]&&b.listeners[n][r][s]){for(i in b.listeners[n][r][s])b.off(t,[r,s].join("."),i);delete b.listeners[n][r][s]}}else if(s)for(e in b.listeners[n])for(a in b.listeners[n][e])s===a&&b.off(t,[e,s].join("."));else if(r){if(b.listeners[n][r]){for(a in b.listeners[n][r])b.off(t,[r,a].join("."));delete b.listeners[n][r]}}else{for(e in b.listeners[n])b.off(t,e);delete b.listeners[n],delete b.handlerMap[n]}},b.extend(b.Element,{on:function(t,e,i,n){return b.on(this.node,t,e,i,n),this},off:function(t,e){return b.off(this.node,t,e),this},fire:function(e,i){return e instanceof t.Event?this.node.dispatchEvent(e):this.node.dispatchEvent(e=new t.CustomEvent(e,{detail:i,cancelable:!0})),this._event=e,this},event:function(){return this._event}}),b.Defs=b.invent({create:"defs",inherit:b.Container}),b.G=b.invent({create:"g",inherit:b.Container,extend:{x:function(t){return null==t?this.transform("x"):this.transform({x:t-this.x()},!0)},y:function(t){return null==t?this.transform("y"):this.transform({y:t-this.y()},!0)},cx:function(t){return null==t?this.gbox().cx:this.x(t-this.gbox().width/2)},cy:function(t){return null==t?this.gbox().cy:this.y(t-this.gbox().height/2)},gbox:function(){var t=this.bbox(),e=this.transform();return t.x+=e.x,t.x2+=e.x,t.cx+=e.x,t.y+=e.y,t.y2+=e.y,t.cy+=e.y,t}},construct:{group:function(){return this.put(new b.G)}}}),b.extend(b.Element,{siblings:function(){return this.parent().children()},position:function(){return this.parent().index(this)},next:function(){return this.siblings()[this.position()+1]},previous:function(){return this.siblings()[this.position()-1]},forward:function(){var t=this.position()+1,e=this.parent();return e.removeElement(this).add(this,t),e instanceof b.Doc&&e.node.appendChild(e.defs().node),this},backward:function(){var t=this.position();return t>0&&this.parent().removeElement(this).add(this,t-1),this},front:function(){var t=this.parent();return t.node.appendChild(this.node),t instanceof b.Doc&&t.node.appendChild(t.defs().node),this},back:function(){return this.position()>0&&this.parent().removeElement(this).add(this,0),this},before:function(t){t.remove();var e=this.position();return this.parent().add(t,e),this},after:function(t){t.remove();var e=this.position();return this.parent().add(t,e+1),this}}),b.Mask=b.invent({create:"mask",inherit:b.Container,extend:{remove:function(){return this.targets().forEach(function(t){t.unmask()}),b.Element.prototype.remove.call(this)},targets:function(){return b.select('svg [mask*="'+this.id()+'"]')}},construct:{mask:function(){return this.defs().put(new b.Mask)}}}),b.extend(b.Element,{maskWith:function(t){var e=t instanceof b.Mask?t:this.parent().mask().add(t);return this.attr("mask",'url("#'+e.attr("id")+'")')},unmask:function(){return this.attr("mask",null)},masker:function(){return this.reference("mask")}}),b.ClipPath=b.invent({create:"clipPath",inherit:b.Container,extend:{remove:function(){return this.targets().forEach(function(t){t.unclip()}),b.Element.prototype.remove.call(this)},targets:function(){return b.select('svg [clip-path*="'+this.id()+'"]')}},construct:{clip:function(){return this.defs().put(new b.ClipPath)}}}),b.extend(b.Element,{clipWith:function(t){var e=t instanceof b.ClipPath?t:this.parent().clip().add(t);return this.attr("clip-path",'url("#'+e.attr("id")+'")')},unclip:function(){return this.attr("clip-path",null)},clipper:function(){return this.reference("clip-path")}}),b.Gradient=b.invent({create:function(t){this.constructor.call(this,b.create(t+"Gradient"))},inherit:b.Container,extend:{at:function(t,e,i){return this.put(new b.Stop).update(t,e,i)},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},fill:function(){return"url(#"+this.id()+")"},toString:function(){return this.fill()},attr:function(t,e,i){return"transform"==t&&(t="gradientTransform"),b.Container.prototype.attr.call(this,t,e,i)}},construct:{gradient:function(t,e){return this.defs().gradient(t,e)}}}),b.extend(b.Gradient,b.FX,{from:function(t,e){return"radialGradient"==(this._target||this).type?this.attr({fx:new b.Number(t),fy:new b.Number(e)}):this.attr({x1:new b.Number(t),y1:new b.Number(e)})},to:function(t,e){return"radialGradient"==(this._target||this).type?this.attr({cx:new b.Number(t),cy:new b.Number(e)}):this.attr({x2:new b.Number(t),y2:new b.Number(e)})}}),b.extend(b.Defs,{gradient:function(t,e){return this.put(new b.Gradient(t)).update(e)}}),b.Stop=b.invent({create:"stop",inherit:b.Element,extend:{update:function(t){return("number"==typeof t||t instanceof b.Number)&&(t={offset:arguments[0],color:arguments[1],opacity:arguments[2]}),null!=t.opacity&&this.attr("stop-opacity",t.opacity),null!=t.color&&this.attr("stop-color",t.color),null!=t.offset&&this.attr("offset",new b.Number(t.offset)),this}}}),b.Pattern=b.invent({create:"pattern",inherit:b.Container,extend:{fill:function(){return"url(#"+this.id()+")"},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},toString:function(){return this.fill()},attr:function(t,e,i){return"transform"==t&&(t="patternTransform"),b.Container.prototype.attr.call(this,t,e,i)}},construct:{pattern:function(t,e,i){return this.defs().pattern(t,e,i)}}}),b.extend(b.Defs,{pattern:function(t,e,i){return this.put(new b.Pattern).update(i).attr({x:0,y:0,width:t,height:e,patternUnits:"userSpaceOnUse"})}}),b.Doc=b.invent({create:function(t){t&&(t="string"==typeof t?e.getElementById(t):t,"svg"==t.nodeName?this.constructor.call(this,t):(this.constructor.call(this,b.create("svg")),t.appendChild(this.node),this.size("100%","100%")),this.namespace().defs())},inherit:b.Container,extend:{namespace:function(){return this.attr({xmlns:b.ns,version:"1.1"}).attr("xmlns:xlink",b.xlink,b.xmlns).attr("xmlns:svgjs",b.svgjs,b.xmlns)},defs:function(){if(!this._defs){var t;(t=this.node.getElementsByTagName("defs")[0])?this._defs=b.adopt(t):this._defs=new b.Defs,this.node.appendChild(this._defs.node)}return this._defs},parent:function(){return"#document"==this.node.parentNode.nodeName?null:this.node.parentNode},spof:function(t){var e=this.node.getScreenCTM();return e&&this.style("left",-e.e%1+"px").style("top",-e.f%1+"px"),this},remove:function(){return this.parent()&&this.parent().removeChild(this.node),this},clear:function(){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return delete this._defs,b.parser.draw.parentNode||this.node.appendChild(b.parser.draw),this}}}),b.Shape=b.invent({create:function(t){this.constructor.call(this,t)},inherit:b.Element}),b.Bare=b.invent({create:function(t,e){if(this.constructor.call(this,b.create(t)),e)for(var i in e.prototype)"function"==typeof e.prototype[i]&&(this[i]=e.prototype[i])},inherit:b.Element,extend:{words:function(t){for(;this.node.hasChildNodes();)this.node.removeChild(this.node.lastChild);return this.node.appendChild(e.createTextNode(t)),this}}}),b.extend(b.Parent,{element:function(t,e){return this.put(new b.Bare(t,e))}}),b.Symbol=b.invent({create:"symbol",inherit:b.Container,construct:{symbol:function(){return this.put(new b.Symbol)}}}),b.Use=b.invent({create:"use",inherit:b.Shape,extend:{element:function(t,e){return this.attr("href",(e||"")+"#"+t,b.xlink)}},construct:{use:function(t,e){return this.put(new b.Use).element(t,e)}}}),b.Rect=b.invent({create:"rect",inherit:b.Shape,construct:{rect:function(t,e){return this.put(new b.Rect).size(t,e)}}}),b.Circle=b.invent({create:"circle",inherit:b.Shape,construct:{circle:function(t){return this.put(new b.Circle).rx(new b.Number(t).divide(2)).move(0,0)}}}),b.extend(b.Circle,b.FX,{rx:function(t){return this.attr("r",t)},ry:function(t){return this.rx(t)}}),b.Ellipse=b.invent({create:"ellipse",inherit:b.Shape,construct:{ellipse:function(t,e){return this.put(new b.Ellipse).size(t,e).move(0,0)}}}),b.extend(b.Ellipse,b.Rect,b.FX,{rx:function(t){return this.attr("rx",t)},ry:function(t){return this.attr("ry",t)}}),b.extend(b.Circle,b.Ellipse,{x:function(t){return null==t?this.cx()-this.rx():this.cx(t+this.rx())},y:function(t){return null==t?this.cy()-this.ry():this.cy(t+this.ry())},cx:function(t){return null==t?this.attr("cx"):this.attr("cx",t)},cy:function(t){return null==t?this.attr("cy"):this.attr("cy",t)},width:function(t){return null==t?2*this.rx():this.rx(new b.Number(t).divide(2))},height:function(t){return null==t?2*this.ry():this.ry(new b.Number(t).divide(2))},size:function(t,e){var i=f(this,t,e);return this.rx(new b.Number(i.width).divide(2)).ry(new b.Number(i.height).divide(2))}}),b.Line=b.invent({create:"line",inherit:b.Shape,extend:{array:function(){return new b.PointArray([[this.attr("x1"),this.attr("y1")],[this.attr("x2"),this.attr("y2")]])},plot:function(t,e,i,n){return null==t?this.array():(t="undefined"!=typeof e?{x1:t,y1:e,x2:i,y2:n}:new b.PointArray(t).toLine(),this.attr(t))},move:function(t,e){return this.attr(this.array().move(t,e).toLine())},size:function(t,e){var i=f(this,t,e);return this.attr(this.array().size(i.width,i.height).toLine())}},construct:{line:function(t,e,i,n){return b.Line.prototype.plot.apply(this.put(new b.Line),null!=t?[t,e,i,n]:[0,0,0,0])}}}),b.Polyline=b.invent({create:"polyline",inherit:b.Shape,construct:{polyline:function(t){return this.put(new b.Polyline).plot(t||new b.PointArray)}}}),b.Polygon=b.invent({create:"polygon",inherit:b.Shape,construct:{polygon:function(t){return this.put(new b.Polygon).plot(t||new b.PointArray)}}}),b.extend(b.Polyline,b.Polygon,{array:function(){return this._array||(this._array=new b.PointArray(this.attr("points")))},plot:function(t){return null==t?this.array():this.clear().attr("points","string"==typeof t?t:this._array=new b.PointArray(t))},clear:function(){return delete this._array,this},move:function(t,e){return this.attr("points",this.array().move(t,e))},size:function(t,e){var i=f(this,t,e);return this.attr("points",this.array().size(i.width,i.height))}}),b.extend(b.Line,b.Polyline,b.Polygon,{morphArray:b.PointArray,x:function(t){return null==t?this.bbox().x:this.move(t,this.bbox().y)},y:function(t){return null==t?this.bbox().y:this.move(this.bbox().x,t)},width:function(t){var e=this.bbox();return null==t?e.width:this.size(t,e.height)},height:function(t){var e=this.bbox();return null==t?e.height:this.size(e.width,t)}}),b.Path=b.invent({create:"path",inherit:b.Shape,extend:{morphArray:b.PathArray,array:function(){return this._array||(this._array=new b.PathArray(this.attr("d")))},plot:function(t){return null==t?this.array():this.clear().attr("d","string"==typeof t?t:this._array=new b.PathArray(t))},clear:function(){return delete this._array,this},move:function(t,e){return this.attr("d",this.array().move(t,e))},x:function(t){return null==t?this.bbox().x:this.move(t,this.bbox().y)},y:function(t){return null==t?this.bbox().y:this.move(this.bbox().x,t)},size:function(t,e){var i=f(this,t,e);return this.attr("d",this.array().size(i.width,i.height))},width:function(t){return null==t?this.bbox().width:this.size(t,this.bbox().height)},height:function(t){return null==t?this.bbox().height:this.size(this.bbox().width,t)}},construct:{path:function(t){return this.put(new b.Path).plot(t||new b.PathArray)}}}),b.Image=b.invent({create:"image",inherit:b.Shape,extend:{load:function(e,i){if(!e)return this;var n=new t.Image;return b.on(n,"load",function(t){var r=this.parent();0==this.width()&&0==this.height()&&this.size(n.width,n.height),r instanceof b.Pattern&&0==r.width()&&0==r.height()&&r.size(this.width(),this.height()),"function"==typeof i&&i.call(this,{width:n.width,height:n.height,ratio:n.width/n.height,url:e})},this),this.attr("href",n.src=e,b.xlink)}},construct:{image:function(t,e){return this.put(new b.Image).size(0,0).load(t,e)}}}),b.Text=b.invent({create:function(){this.constructor.call(this,b.create("text")),this.dom.leading=new b.Number(1.3),this._rebuild=!0,this._build=!1,this.attr("font-family",b.defaults.attrs["font-family"])},inherit:b.Parent,extend:{x:function(t){return null==t?this.attr("x"):this.attr("x",t)},y:function(t){var e=this.attr("y"),i="number"==typeof e?e-this.bbox().y:0;return null==t?"number"==typeof e?e-i:e:this.attr("y","number"==typeof t?t+i:t)},cx:function(t){return null==t?this.bbox().cx:this.x(t-this.bbox().width/2)},cy:function(t){return null==t?this.bbox().cy:this.y(t-this.bbox().height/2)},text:function(t){if("undefined"==typeof t){for(var t="",e=this.node.childNodes,i=0,n=e.length;i<n;++i)0!=i&&3!=e[i].nodeType&&1==b.adopt(e[i]).dom.newLined&&(t+="\n"),t+=e[i].textContent;return t}if(this.clear().build(!0),"function"==typeof t)t.call(this,this);else{t=t.split("\n");for(var i=0,r=t.length;i<r;i++)this.tspan(t[i]).newLine()}return this.build(!1).rebuild()},size:function(t){return this.attr("font-size",t).rebuild()},leading:function(t){return null==t?this.dom.leading:(this.dom.leading=new b.Number(t),this.rebuild())},rebuild:function(t){if("boolean"==typeof t&&(this._rebuild=t),this._rebuild){var e=this,i=0,n=this.dom.leading*new b.Number(this.attr("font-size"));this.each(function(){this.dom.newLined&&(e.textPath()||this.attr("x",e.attr("x")),"\n"==this.text()?i+=n:(this.attr("dy",n+i),i=0))}),this.fire("rebuild")}return this},build:function(t){return this._build=!!t,this},setData:function(t){return this.dom=t,this.dom.leading=new b.Number(t.leading||1.3),this}},construct:{text:function(t){return this.put(new b.Text).text(t)},plain:function(t){return this.put(new b.Text).plain(t)}}}),b.Tspan=b.invent({create:"tspan",inherit:b.Parent,extend:{text:function(t){return null==t?this.node.textContent+(this.dom.newLined?"\n":""):("function"==typeof t?t.call(this,this):this.plain(t),this)},dx:function(t){return this.attr("dx",t)},dy:function(t){return this.attr("dy",t)},newLine:function(){var t=this.parent(b.Text);return this.dom.newLined=!0,this.dy(t.dom.leading*t.attr("font-size")).attr("x",t.x())}}}),b.extend(b.Text,b.Tspan,{plain:function(t){return this._build===!1&&this.clear(),this.node.appendChild(e.createTextNode(t)),this},tspan:function(t){var e=(this.textPath&&this.textPath()||this).node,i=new b.Tspan;return this._build===!1&&this.clear(),e.appendChild(i.node),i.text(t)},length:function(){return this.node.getComputedTextLength()}}),b.TextPath=b.invent({create:"textPath",inherit:b.Parent,parent:b.Text,construct:{path:function(t){for(var e=new b.TextPath,i=this.doc().defs().path(t);this.node.hasChildNodes();)e.node.appendChild(this.node.firstChild);return this.node.appendChild(e.node),e.attr("href","#"+i,b.xlink),this},array:function(){var t=this.track();return t?t.array():null},plot:function(t){var e=this.track(),i=null;return e&&(i=e.plot(t)),null==t?i:this},track:function(){var t=this.textPath();if(t)return t.reference("href")},textPath:function(){if(this.node.firstChild&&"textPath"==this.node.firstChild.nodeName)return b.adopt(this.node.firstChild)}}}),b.Nested=b.invent({create:function(){this.constructor.call(this,b.create("svg")),this.style("overflow","visible")},inherit:b.Container,construct:{nested:function(){return this.put(new b.Nested)}}}),b.A=b.invent({create:"a",inherit:b.Container,extend:{to:function(t){return this.attr("href",t,b.xlink)},show:function(t){return this.attr("show",t,b.xlink)},target:function(t){return this.attr("target",t)}},construct:{link:function(t){return this.put(new b.A).to(t)}}}),b.extend(b.Element,{linkTo:function(t){var e=new b.A;return"function"==typeof t?t.call(e,e):e.to(t),this.parent().put(e).put(this)}}),b.Marker=b.invent({create:"marker",inherit:b.Container,extend:{width:function(t){return this.attr("markerWidth",t)},height:function(t){return this.attr("markerHeight",t)},ref:function(t,e){return this.attr("refX",t).attr("refY",e)},update:function(t){return this.clear(),"function"==typeof t&&t.call(this,this),this},toString:function(){return"url(#"+this.id()+")"}},construct:{marker:function(t,e,i){return this.defs().marker(t,e,i)}}}),b.extend(b.Defs,{marker:function(t,e,i){return this.put(new b.Marker).size(t,e).ref(t/2,e/2).viewbox(0,0,t,e).attr("orient","auto").update(i)}}),b.extend(b.Line,b.Polyline,b.Polygon,b.Path,{marker:function(t,e,i,n){var r=["marker"];return"all"!=t&&r.push(t),r=r.join("-"),t=arguments[1]instanceof b.Marker?arguments[1]:this.doc().marker(e,i,n),this.attr(r,t)}});var k={stroke:["color","width","opacity","linecap","linejoin","miterlimit","dasharray","dashoffset"],fill:["color","opacity","rule"],prefix:function(t,e){return"color"==e?t:t+"-"+e}};["fill","stroke"].forEach(function(t){var e,i={};i[t]=function(i){if("undefined"==typeof i)return this;if("string"==typeof i||b.Color.isRgb(i)||i&&"function"==typeof i.fill)this.attr(t,i);else for(e=k[t].length-1;e>=0;e--)null!=i[k[t][e]]&&this.attr(k.prefix(t,k[t][e]),i[k[t][e]]);return this},b.extend(b.Element,b.FX,i)}),b.extend(b.Element,b.FX,{rotate:function(t,e,i){return this.transform({rotation:t,cx:e,cy:i})},skew:function(t,e,i,n){return 1==arguments.length||3==arguments.length?this.transform({skew:t,cx:e,cy:i}):this.transform({skewX:t,skewY:e,cx:i,cy:n})},scale:function(t,e,i,n){return 1==arguments.length||3==arguments.length?this.transform({scale:t,cx:e,cy:i}):this.transform({scaleX:t,scaleY:e,cx:i,cy:n})},translate:function(t,e){return this.transform({x:t,y:e})},flip:function(t,e){return e="number"==typeof t?t:e,this.transform({flip:t||"both",offset:e})},matrix:function(t){return this.attr("transform",new b.Matrix(6==arguments.length?[].slice.call(arguments):t))},opacity:function(t){return this.attr("opacity",t)},dx:function(t){return this.x(new b.Number(t).plus(this instanceof b.FX?0:this.x()),!0)},dy:function(t){return this.y(new b.Number(t).plus(this instanceof b.FX?0:this.y()),!0)},dmove:function(t,e){return this.dx(t).dy(e)}}),b.extend(b.Rect,b.Ellipse,b.Circle,b.Gradient,b.FX,{radius:function(t,e){var i=(this._target||this).type;return"radialGradient"==i||"radialGradient"==i?this.attr("r",new b.Number(t)):this.rx(t).ry(null==e?t:e)}}),b.extend(b.Path,{length:function(){return this.node.getTotalLength()},pointAt:function(t){return new b.Point(this.node.getPointAtLength(t))}}),b.extend(b.Parent,b.Text,b.Tspan,b.FX,{font:function(t,e){if("object"==typeof t)for(e in t)this.font(e,t[e]);return"leading"==t?this.leading(e):"anchor"==t?this.attr("text-anchor",e):"size"==t||"family"==t||"weight"==t||"stretch"==t||"variant"==t||"style"==t?this.attr("font-"+t,e):this.attr(t,e)}}),b.extend(b.Element,{data:function(t,e,i){if("object"==typeof t)for(e in t)this.data(e,t[e]);else if(arguments.length<2)try{return JSON.parse(this.attr("data-"+t))}catch(e){return this.attr("data-"+t)}else this.attr("data-"+t,null===e?null:i===!0||"string"==typeof e||"number"==typeof e?e:JSON.stringify(e));return this}}),b.extend(b.Element,{remember:function(t,e){if("object"==typeof arguments[0])for(var e in t)this.remember(e,t[e]);else{if(1==arguments.length)return this.memory()[t];this.memory()[t]=e}return this},forget:function(){if(0==arguments.length)this._memory={};else for(var t=arguments.length-1;t>=0;t--)delete this.memory()[arguments[t]];return this},memory:function(){return this._memory||(this._memory={})}}),b.get=function(t){var i=e.getElementById(w(t)||t);return b.adopt(i)},b.select=function(t,i){return b.utils.map((i||e).querySelectorAll(t),function(t){return b.adopt(t)})},b.$$=function(t,i){return b.utils.map((i||e).querySelectorAll(t),function(t){return b.adopt(t)})},b.$=function(t,i){return b.adopt((i||e).querySelector(t))},b.extend(b.Parent,{select:function(t){return b.select(t,this.node)}});var A="abcdef".split("");return b.Box=b.invent({create:function(t){var e=[0,0,0,0];t="string"==typeof t?t.split(b.regex.delimiter).map(parseFloat):Array.isArray(t)?t:"object"==typeof t?[null!=t.left?t.left:t.x,null!=t.top?t.top:t.y,t.width,t.height]:4==arguments.length?[].slice.call(arguments):e,this.x=t[0],this.y=t[1],this.width=t[2],this.height=t[3],g(this)},extend:{merge:function(t){var e=Math.min(this.x,t.x),i=Math.min(this.y,t.y);return new b.Box(e,i,Math.max(this.x+this.width,t.x+t.width)-e,Math.max(this.y+this.height,t.y+t.height)-i)},transform:function(t){var e=1/0,i=-(1/0),n=1/0,r=-(1/0),s=[new b.Point(this.x,this.y),new b.Point(this.x2,this.y),new b.Point(this.x,this.y2),new b.Point(this.x2,this.y2)];return s.forEach(function(s){s=s.transform(t),e=Math.min(e,s.x),i=Math.max(i,s.x),n=Math.min(n,s.y),r=Math.max(r,s.y)}),new b.Box(e,n,i-e,r-n)},addOffset:function(){return this.x+=t.pageXOffset,this.y+=t.pageYOffset,this},toString:function(){return this.x+" "+this.y+" "+this.width+" "+this.height},morph:function(t,e,i,n){return this.destination=new b.Box(t,e,i,n),this},at:function(t){return this.destination?new b.Box(this.x+(this.destination.x-this.x)*t,this.y+(this.destination.y-this.y)*t,this.width+(this.destination.width-this.width)*t,this.height+(this.destination.height-this.height)*t):this}},parent:b.Element,construct:{bbox:function(){var t;try{if(t=this.node.getBBox(),i(t)&&!n(this.node))throw new Exception("Element not in the dom")}catch(i){try{var e=this.clone(b.parser.draw.instance).show();t=e.node.getBBox(),e.remove()}catch(t){console.warn("Getting a bounding box of this element is not possible")}}return new b.Box(t)},rbox:function(t){try{var e=new b.Box(this.node.getBoundingClientRect());return t?e.transform(t.screenCTM().inverse()):e.addOffset()}catch(t){return new b.Box}}}}),b.extend(b.Doc,b.Nested,b.Symbol,b.Image,b.Pattern,b.Marker,b.ForeignObject,b.View,{viewbox:function(t,e,i,n){return null==t?new b.Box(this.attr("viewBox")):this.attr("viewBox",new b.Box(t,e,i,n))}}),b});
\ No newline at end of file diff --git a/package.json b/package.json index 2296853..7853409 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "svg.js", - "version": "2.5.0", + "version": "3.0.0", "description": "A lightweight library for manipulating and animating SVG.", "url": "https://svgdotjs.github.io/", "homepage": "https://svgdotjs.github.io/", @@ -36,7 +36,7 @@ }, { "name": "Jon Ege Ronnenberg", - "email": "jon.ronnenberg+svgjs@gmail.com", + "email": "jon@svgjs.com", "url": "https://keybase.io/dotnetcarpenter" } ], @@ -81,7 +81,8 @@ "karma-phantomjs-launcher": "^1.0.2", "request": "^2.78.0", "snazzy": "^6.0.0", - "standard": "^9.0.1" + "standard": "^9.0.1", + "svgdom": "latest" }, "standard": { "ignore": [ diff --git a/spec/SpecRunner.html b/spec/SpecRunner.html index 6d0cc72..0da16b0 100644 --- a/spec/SpecRunner.html +++ b/spec/SpecRunner.html @@ -58,50 +58,52 @@ </svg> <!-- include spec files here... --> - <script src="spec/svg.js"></script> - <script src="spec/selector.js"></script> <script src="spec/adopter.js"></script> - <script src="spec/regex.js"></script> - <script src="spec/container.js"></script> - <script src="spec/element.js"></script> - <script src="spec/memory.js"></script> <script src="spec/arrange.js"></script> - <script src="spec/event.js"></script> + <script src="spec/array.js"></script> + <script src="spec/bare.js"></script> <script src="spec/boxes.js"></script> - <script src="spec/matrix.js"></script> - <script src="spec/transformations.js"></script> - <script src="spec/point.js"></script> - <script src="spec/rect.js"></script> <script src="spec/circle.js"></script> + <script src="spec/clip.js"></script> + <script src="spec/color.js"></script> + <script src="spec/container.js"></script> + <script src="spec/defs.js"></script> + <script src="spec/doc.js"></script> + <script src="spec/easing.js"></script> + <script src="spec/element.js"></script> <script src="spec/ellipse.js"></script> + <script src="spec/event.js"></script> + <script src="spec/fx.js"></script> + <script src="spec/gradient.js"></script> + <script src="spec/group.js"></script> + <script src="spec/helper.js"></script> + <script src="spec/hyperlink.js"></script> + <script src="spec/image.js"></script> <script src="spec/line.js"></script> - <script src="spec/polyline.js"></script> - <script src="spec/polygon.js"></script> - <script src="spec/path.js"></script> <script src="spec/marker.js"></script> - <script src="spec/image.js"></script> - <script src="spec/text.js"></script> - <script src="spec/span.js"></script> - <script src="spec/textpath.js"></script> - <script src="spec/doc.js"></script> - <script src="spec/defs.js"></script> - <script src="spec/nested.js"></script> - <script src="spec/group.js"></script> - <script src="spec/gradient.js"></script> - <script src="spec/pattern.js"></script> - <script src="spec/use.js"></script> - <script src="spec/bare.js"></script> - <script src="spec/symbol.js"></script> <script src="spec/mask.js"></script> - <script src="spec/clip.js"></script> - <script src="spec/color.js"></script> + <script src="spec/matrix.js"></script> + <script src="spec/memory.js"></script> + <script src="spec/nested.js"></script> <script src="spec/number.js"></script> - <script src="spec/array.js"></script> - <script src="spec/hyperlink.js"></script> + <script src="spec/path.js"></script> + <script src="spec/pattern.js"></script> + <script src="spec/point.js"></script> + <script src="spec/polygon.js"></script> + <script src="spec/polyline.js"></script> + <script src="spec/rect.js"></script> + <script src="spec/regex.js"></script> + <script src="spec/selector.js"></script> <script src="spec/sugar.js"></script> - <script src="spec/fx.js"></script> + <script src="spec/svg.js"></script> + <script src="spec/symbol.js"></script> + <script src="spec/text.js"></script> + <script src="spec/textpath.js"></script> + <script src="spec/transformations.js"></script> + <script src="spec/tspan.js"></script> + <script src="spec/use.js"></script> <script src="spec/utils.js"></script> + <script src="spec/viewbox.js"></script> - <script type="text/javascript" src="spec/helper.js"></script> </body> </html> diff --git a/spec/spec/arrange.js b/spec/spec/arrange.js index 07f87d1..3424b2a 100644 --- a/spec/spec/arrange.js +++ b/spec/spec/arrange.js @@ -11,17 +11,17 @@ describe('Arrange', function() { describe('siblings()', function() { it('returns all siblings of targeted element', function() { - expect(e1.siblings().length).toBe(3) - expect([e1,e2,e3]).toEqual(e2.siblings()) + expect(e1.siblings().length).toBe(3+parserInDoc) + expect(parser.concat([e1,e2,e3])).toEqual(e2.siblings()) }) }) describe('position()', function() { it('returns the index position within it\'s parent', function() { - expect(e1.siblings().length).toBe(3) - expect(e1.position()).toBe(0) - expect(e2.position()).toBe(1) - expect(e3.position()).toBe(2) + expect(e1.siblings().length).toBe(3+parserInDoc) + expect(e1.position()).toBe(0+parserInDoc) + expect(e2.position()).toBe(1+parserInDoc) + expect(e3.position()).toBe(2+parserInDoc) }) }) @@ -35,7 +35,7 @@ describe('Arrange', function() { describe('previous()', function() { it('returns the previous sibling within the parent element', function() { - expect(e1.previous()).toBe(undefined) + expect(e1.previous()).toBe(parser[0]) expect(e2.previous()).toBe(e1) expect(e3.previous()).toBe(e2) }) @@ -47,35 +47,39 @@ describe('Arrange', function() { }) it('moves the element one step forward within its parent', function() { e1.forward() - expect(e1.position()).toBe(1) - expect(e2.position()).toBe(0) - expect(e3.position()).toBe(2) + expect(e1.position()).toBe(1+parserInDoc) + expect(e2.position()).toBe(0+parserInDoc) + expect(e3.position()).toBe(2+parserInDoc) }) it('keeps the last element at the same position', function() { e3.forward() - expect(e3.position()).toBe(2) + expect(e3.position()).toBe(2+parserInDoc) }) it('keeps the defs on top of the stack', function() { draw.defs() e3.forward() - expect(draw.node.childNodes[2]).toBe(e3.node) - expect(draw.node.childNodes[3]).toBe(draw.defs().node) + expect(draw.node.childNodes[2+parserInDoc]).toBe(e3.node) + expect(draw.node.childNodes[3+parserInDoc]).toBe(draw.defs().node) }) }) describe('backward()', function() { it('returns the element itself', function() { - expect(e1.backward()).toBe(e1) + if(parserInDoc){ + expect(parser[0].backward()).toBe(parser[0]) + }else{ + expect(e1.backward()).toBe(e1) + } }) it('moves the element one step backwards within its parent', function() { e3.backward() - expect(e1.position()).toBe(0) - expect(e2.position()).toBe(2) - expect(e3.position()).toBe(1) + expect(e1.position()).toBe(0+parserInDoc) + expect(e2.position()).toBe(2+parserInDoc) + expect(e3.position()).toBe(1+parserInDoc) }) it('keeps the first element at the same position', function() { e3.backward() - expect(e1.position()).toBe(0) + expect(e1.position()).toBe(0+parserInDoc) }) }) @@ -85,18 +89,18 @@ describe('Arrange', function() { }) it('moves the element to the top of the stack within its parent', function() { e1.front() - expect(e1.position()).toBe(2) - expect(e2.position()).toBe(0) - expect(e3.position()).toBe(1) + expect(e1.position()).toBe(2+parserInDoc) + expect(e2.position()).toBe(0+parserInDoc) + expect(e3.position()).toBe(1+parserInDoc) }) it('keeps the last element at the same position', function() { e3.front() - expect(e3.position()).toBe(2) + expect(e3.position()).toBe(2+parserInDoc) }) it('keeps the defs on top of the stack', function() { e1.front() - expect(draw.node.childNodes[2]).toBe(e1.node) - expect(draw.node.childNodes[3]).toBe(draw.defs().node) + expect(draw.node.childNodes[2+parserInDoc]).toBe(e1.node) + expect(draw.node.childNodes[3+parserInDoc]).toBe(draw.defs().node) }) }) @@ -106,8 +110,8 @@ describe('Arrange', function() { }) it('moves the element to the bottom of the stack within its parent', function() { e3.back() - expect(e1.position()).toBe(1) - expect(e2.position()).toBe(2) + expect(e1.position()).toBe(1+parserInDoc) + expect(e2.position()).toBe(2+parserInDoc) expect(e3.position()).toBe(0) }) it('keeps the first element at the same position', function() { @@ -122,9 +126,9 @@ describe('Arrange', function() { }) it('inserts a given element before the targeted element', function() { e3.before(e1) - expect(e1.position()).toBe(1) - expect(e2.position()).toBe(0) - expect(e3.position()).toBe(2) + expect(e1.position()).toBe(1+parserInDoc) + expect(e2.position()).toBe(0+parserInDoc) + expect(e3.position()).toBe(2+parserInDoc) }) it('moves elements between containers', function() { var group = draw.group() @@ -133,10 +137,10 @@ describe('Arrange', function() { , e6 = group.rect(80,120) e2.before(e5) - expect(e1.position()).toBe(0) - expect(e2.position()).toBe(2) - expect(e3.position()).toBe(3) - expect(e5.position()).toBe(1) + expect(e1.position()).toBe(0+parserInDoc) + expect(e2.position()).toBe(2+parserInDoc) + expect(e3.position()).toBe(3+parserInDoc) + expect(e5.position()).toBe(1+parserInDoc) }) }) @@ -146,9 +150,9 @@ describe('Arrange', function() { }) it('inserts a given element after the targeted element', function() { e3.after(e1) - expect(e1.position()).toBe(2) - expect(e2.position()).toBe(0) - expect(e3.position()).toBe(1) + expect(e1.position()).toBe(2+parserInDoc) + expect(e2.position()).toBe(0+parserInDoc) + expect(e3.position()).toBe(1+parserInDoc) }) it('moves elements between containers', function() { var group = draw.group() @@ -157,10 +161,10 @@ describe('Arrange', function() { , e6 = group.rect(80,120) e2.after(e5) - expect(e1.position()).toBe(0) - expect(e2.position()).toBe(1) - expect(e3.position()).toBe(3) - expect(e5.position()).toBe(2) + expect(e1.position()).toBe(0+parserInDoc) + expect(e2.position()).toBe(1+parserInDoc) + expect(e3.position()).toBe(3+parserInDoc) + expect(e5.position()).toBe(2+parserInDoc) }) }) diff --git a/spec/spec/array.js b/spec/spec/array.js index 36ffe73..addda87 100644 --- a/spec/spec/array.js +++ b/spec/spec/array.js @@ -228,7 +228,7 @@ describe('PointArray', function () { }) describe('PathArray', function () { - var p1, p2, p3 + var p1, p2, p3, p4, p5, p6, p7 beforeEach(function() { p1 = new SVG.PathArray('m10 10 h 80 v 80 h -80 l 300 400 z') @@ -251,6 +251,16 @@ describe('PathArray', function () { it('parses difficult syntax correctly', function() { expect(p5.toString()).toBe('M10 10L-45 -30.5L0.5 0.89L0.02 0.5L0.5 -0.5C0.5 0.5 0.5 0.5 0.5 0.5L-3 -4Z ') }) + + it('parses flat arrays correctly', function() { + p6 = new SVG.PathArray([ 'M', 0, 0, 'L', 100, 100, 'z' ]) + expect(p6.toString()).toBe('M0 0L100 100Z ') + }) + + it('parses nested arrays correctly', function() { + p7 = new SVG.PathArray([ ['M', 0, 0], ['L', 100, 100], ['z'] ]) + expect(p7.toString()).toBe('M0 0L100 100Z ') + }) // this test is designed to cover a certain line but it doesnt work because of #608 it('returns the valueOf when PathArray is given', function() { diff --git a/spec/spec/bare.js b/spec/spec/bare.js index 9dbb8c2..0488bbd 100644 --- a/spec/spec/bare.js +++ b/spec/spec/bare.js @@ -22,12 +22,20 @@ describe('Bare', function() { describe('words()', function() { it('inserts plain text in a node', function() { var element = draw.element('title').words('These are some words.').id(null) - expect(element.svg()).toBe('<title>These are some words.</title>') + var result = element.svg() + expect( + result == '<title>These are some words.</title>' + || result == '<title xmlns="http://www.w3.org/2000/svg">These are some words.</title>' + ).toBe(true) }) it('removes all nodes before adding words', function() { var element = draw.element('title').words('These are some words.').id(null) element.words('These are some words.') - expect(element.svg()).toBe('<title>These are some words.</title>') + var result = element.svg() + expect( + result == '<title>These are some words.</title>' + || result == '<title xmlns="http://www.w3.org/2000/svg">These are some words.</title>' + ).toBe(true) }) }) }) diff --git a/spec/spec/boxes.js b/spec/spec/boxes.js index 8f7f2d8..9e33c60 100644 --- a/spec/spec/boxes.js +++ b/spec/spec/boxes.js @@ -210,7 +210,7 @@ describe('Boxes', function() { it('returns the elements box in absolute screen coordinates by default', function() { var box = rect.rbox() - expect(roundBox(box)).toEqual(jasmine.objectContaining(roundBox({ + expect(window.roundBox(box)).toEqual(jasmine.objectContaining(window.roundBox({ x: 70 + offset.e, y: 200 + offset.f, width: 100, height: 360 }))) @@ -219,7 +219,7 @@ describe('Boxes', function() { it('returns the elements box in coordinates of given element (doc)', function() { var box = rect.rbox(draw) - expect(roundBox(box)).toEqual(jasmine.objectContaining({ + expect(window.roundBox(box)).toEqual(jasmine.objectContaining({ x: 240, y: 500, width: 200, height: 720 })) }) @@ -227,7 +227,7 @@ describe('Boxes', function() { it('returns the elements box in coordinates of given element (nested)', function() { var box = rect.rbox(nested) - expect(roundBox(box)).toEqual(jasmine.objectContaining({ + expect(window.roundBox(box)).toEqual(jasmine.objectContaining({ x: 70, y: 200, width: 100, height: 360 })) }) diff --git a/spec/spec/circle.js b/spec/spec/circle.js index 41cf2b0..fc66e0c 100644 --- a/spec/spec/circle.js +++ b/spec/spec/circle.js @@ -170,16 +170,8 @@ describe('Circle', function() { describe('translate()', function() { it('sets the translation of an element', function() { circle.transform({ x: 12, y: 12 }) - expect(matrixStringToArray(circle.node.getAttribute('transform'))).toEqual([1,0,0,1,12,12]) + expect(window.matrixStringToArray(circle.node.getAttribute('transform'))).toEqual([1,0,0,1,12,12]) }) }) }) - - - - - - - - diff --git a/spec/spec/container.js b/spec/spec/container.js index 2b4cab1..53c51b3 100644 --- a/spec/spec/container.js +++ b/spec/spec/container.js @@ -205,10 +205,10 @@ describe('Container', function() { }) describe('clear()', function() { - it('removes all children', function() { + it('removes all children except the parser if present', function() { draw.rect(100,100) draw.clear() - expect(draw.children().length).toBe(0) + expect(draw.children().length).toBe(parserInDoc) }) it('creates a new defs node', function() { var oldDefs = draw.defs() @@ -234,7 +234,7 @@ describe('Container', function() { draw.each(function() { children.push(this.type) }) - expect(children).toEqual(['rect', 'ellipse', 'polygon']) + expect(children).toEqual((parserInDoc ? [parser[0].type] : []).concat(['rect', 'ellipse', 'polygon'])) }) it('should only include the its own children', function() { var children = [] @@ -268,7 +268,7 @@ describe('Container', function() { children.push(this) }, true) - expect(children.length).toEqual(draw.children().length + group.children().length) + expect(children.length).toEqual(draw.children().length + group.children().length + (parserInDoc ? parser[0].children().length : 0)) }) }) @@ -278,23 +278,23 @@ describe('Container', function() { var rect = draw.rect(100,100) var circle = draw.circle(100) var line = draw.line(0,0,100,100) - expect(draw.get(0)).toBe(rect) - expect(draw.get(1)).toBe(circle) - expect(draw.get(2)).toBe(line) - expect(draw.get(3)).toBeNull() + expect(draw.get(0+parserInDoc)).toBe(rect) + expect(draw.get(1+parserInDoc)).toBe(circle) + expect(draw.get(2+parserInDoc)).toBe(line) + expect(draw.get(3+parserInDoc)).toBeNull() }) }) - + describe('first()', function() { it('gets the first child', function() { draw.clear() var rect = draw.rect(100,100) var circle = draw.circle(100) var line = draw.line(0,0,100,100) - expect(draw.first()).toBe(rect) + expect(draw.first()).toBe(parserInDoc ? parser[0] : rect) }) }) - + describe('last()', function() { it('gets the last child', function() { draw.clear() @@ -325,9 +325,9 @@ describe('Container', function() { var circle = draw.circle(100) var group = draw.group() var line = group.line(0,0,100,100) - expect(draw.index(rect)).toBe(0) - expect(draw.index(circle)).toBe(1) - expect(draw.index(group)).toBe(2) + expect(draw.index(rect)).toBe(0+parserInDoc) + expect(draw.index(circle)).toBe(1+parserInDoc) + expect(draw.index(group)).toBe(2+parserInDoc) expect(draw.index(line)).toBe(-1) expect(group.index(line)).toBe(0) }) diff --git a/spec/spec/doc.js b/spec/spec/doc.js index d825c76..17bcb28 100644 --- a/spec/spec/doc.js +++ b/spec/spec/doc.js @@ -34,12 +34,17 @@ describe('Doc', function() { }) describe('remove()', function() { - it('removes the doc from the dom', function() { - var cnt = document.getElementsByTagName('body')[0].querySelectorAll('svg').length + it('removes the doc from the dom only if doc is not root element', function() { + var cnt = window.document.querySelectorAll('svg').length draw.remove() - expect(document.getElementsByTagName('body')[0].querySelectorAll('svg').length).toBe(cnt-1) + if(parserInDoc){ + expect(window.document.querySelectorAll('svg').length).toBe(cnt) + }else{ + expect(window.document.querySelectorAll('svg').length).toBe(cnt-1) + } + draw = SVG(drawing).size(100,100); - expect(document.getElementsByTagName('body')[0].querySelectorAll('svg').length).toBe(cnt) + expect(window.document.querySelectorAll('svg').length).toBe(cnt) }) }) diff --git a/spec/spec/element.js b/spec/spec/element.js index a1fe91c..70642f5 100644 --- a/spec/spec/element.js +++ b/spec/spec/element.js @@ -73,15 +73,10 @@ describe('Element', function() { rect.style('cursor', 'pointer') expect(rect.node.style.cursor).toBe('pointer') }) - it('redirects to the style() method when setting a style string', function() { + it('sets the style attribute correctly', function() { rect.attr('style', 'cursor:move;') expect(rect.node.style.cursor).toBe('move') }) - it('removes style attribute on node if the style is empty', function() { - rect.style('cursor', 'move') - rect.style('cursor', '') - expect(rect.style.cursor).toBe(undefined) - }) it('acts as a global getter when no arguments are given', function() { rect.fill('#ff0066') expect(rect.attr().fill).toBe('#ff0066') @@ -143,13 +138,13 @@ describe('Element', function() { describe('style()', function() { it('sets the style with key and value arguments', function() { var rect = draw.rect(100,100).style('cursor', 'crosshair') - expect(stripped(rect.node.style.cssText)).toBe('cursor:crosshair;') + expect(window.stripped(rect.node.style.cssText)).toBe('cursor:crosshair') }) it('sets multiple styles with an object as the first argument', function() { var rect = draw.rect(100,100).style({ cursor: 'help', display: 'block' }) - expect(stripped(rect.node.style.cssText)).toMatch(/cursor:help;/) - expect(stripped(rect.node.style.cssText)).toMatch(/display:block;/) - expect(stripped(rect.node.style.cssText).length).toBe(('display:block;cursor:help;').length) + expect(window.stripped(rect.node.style.cssText)).toMatch(/cursor:help/) + expect(window.stripped(rect.node.style.cssText)).toMatch(/display:block/) + expect(window.stripped(rect.node.style.cssText).length).toBe(('display:block;cursor:help').length) }) it('gets a style with a string key as the fists argument', function() { var rect = draw.rect(100,100).style({ cursor: 'progress', display: 'block' }) @@ -157,17 +152,17 @@ describe('Element', function() { }) it('gets the full css string with no argument', function() { var rect = draw.rect(100,100).style({ cursor: 's-resize', display: 'none' }) - expect(stripped(rect.style())).toMatch(/display:none;/) - expect(stripped(rect.style())).toMatch(/cursor:s-resize;/) - expect(stripped(rect.style()).length).toBe(('cursor:s-resize;display:none;').length) + expect(window.stripped(rect.style())).toMatch(/display:none/) + expect(window.stripped(rect.style())).toMatch(/cursor:s-resize/) + expect(window.stripped(rect.style()).length).toBe(('cursor:s-resize;display:none').length) }) it('removes a style if the value is an empty string', function() { var rect = draw.rect(100,100).style({ cursor: 'n-resize', display: '' }) - expect(stripped(rect.style())).toBe('cursor:n-resize;') + expect(window.stripped(rect.style())).toBe('cursor:n-resize') }) it('removes a style if the value explicitly set to null', function() { var rect = draw.rect(100,100).style('cursor', 'w-resize') - expect(stripped(rect.style())).toBe('cursor:w-resize;') + expect(window.stripped(rect.style())).toBe('cursor:w-resize') rect.style('cursor', null) expect(rect.style()).toBe('') }) @@ -185,44 +180,44 @@ describe('Element', function() { }) it('sets the translation of and element', function() { rect.transform({ x: 10, y: 11 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,10,11]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,10,11]) }) it('performs an absolute translation', function() { rect.transform({ x: 10, y: 11 }).transform({ x: 20, y: 21 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,20,21]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,20,21]) }) it('performs a relative translation when relative is set to true', function() { rect.transform({ x: 10, y: 11 }).transform({ x: 20, y: 21, relative: true }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,30,32]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,30,32]) }) it('performs a relative translation with relative flag', function() { rect.transform({ x: 10, y: 11 }).transform({ x: 20, y: 21 }, true) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,30,32]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,30,32]) }) it('sets the scaleX and scaleY of an element', function() { rect.transform({ scaleX: 0.5, scaleY: 2 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0,2,25,-50]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0,2,25,-50]) }) it('performs a uniform scale with scale given', function() { rect.transform({ scale: 3 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([3,0,0,3,-100,-100]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([3,0,0,3,-100,-100]) }) it('also works with only skaleX', function() { rect.transform({ scaleX: 3 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([3,0,0,1,-100,0]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([3,0,0,1,-100,0]) }) it('also works with only skaleY', function() { rect.transform({ scaleY: 3 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,3,0,-100]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,3,0,-100]) }) - + it('performs an absolute scale by default', function() { rect.transform({ scale: 3 }).transform({ scale: 0.5 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0,0.5,25,25]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0,0.5,25,25]) }) it('performs a relative scale with a relative flag', function() { rect.transform({ scaleX: 0.5, scaleY: 2 }).transform({ scaleX: 3, scaleY: 4 }, true) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1.5,0,0,8,-25,-350]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1.5,0,0,8,-25,-350]) }) it('sets the skewX of an element with center on the element', function() { ctm = rect.transform({ skewX: 10 }).ctm() @@ -290,31 +285,31 @@ describe('Element', function() { }) it('transforms element using a matrix', function() { rect.transform({ a: 0.5, c: 0.5 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0.5,1,0,0]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0.5,1,0,0]) }) it('transforms relative using a matrix', function() { rect.transform({ a: 0.5, c: 0.5 }).transform(new SVG.Matrix({ e: 20, f: 20 }), true) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0.5,1,20,20]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0.5,1,20,20]) }) it('flips the element on x axis', function() { rect.transform({ flip: 'x' }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,1,100,0]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,1,100,0]) }) it('flips the element on x axis with offset', function() { rect.transform({ flip: 'x', offset: 20 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,1,40,0]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,1,40,0]) }) it('flips the element on y axis with offset', function() { rect.transform({ flip: 'y', offset: 20 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,-1,0,40]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,-1,0,40]) }) it('flips the element on both axis with offset', function() { rect.transform({ flip: 'both', offset: 20 }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,-1,40,40]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,-1,40,40]) }) it('flips the element on both axis', function() { rect.transform({ flip: 'both' }) - expect(matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,-1,0,0]) + expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,-1,100,100]) }) }) @@ -326,7 +321,7 @@ describe('Element', function() { }) it('removes the transform attribute', function() { - expect(matrixStringToArray(circle.node.getAttribute('transform'))).toEqual([1,0,0,1,50,100]) + expect(window.matrixStringToArray(circle.node.getAttribute('transform'))).toEqual([1,0,0,1,50,100]) circle.untransform() expect(circle.node.getAttribute('transform')).toBeNull() }) @@ -460,7 +455,7 @@ describe('Element', function() { })) }) - it('ungroups everything to the doc root when called on SVG.Doc / does not flatten defs', function() { + it('ungroups everything to the doc root when called on SVG.Doc / does not ungroup defs/parser', function() { draw.flatten() expect(rect1.parent()).toBe(draw) expect(rect2.parent()).toBe(draw) @@ -476,7 +471,7 @@ describe('Element', function() { a:0.5, b:0, c:0, d:0.5, e:45, f:45 })) - expect(draw.children().length).toBe(3) // 2 * rect + defs + expect(draw.children().length).toBe(3+parserInDoc) // 2 * rect + defs }) }) @@ -811,8 +806,15 @@ describe('Element', function() { // Test for different browsers namely Firefox and Chrome expect( + // IE toBeTested === '<svg xmlns:svgjs="http://svgjs.com/svgjs" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" xmlns="http://www.w3.org/2000/svg" height="100" width="100" id="' + draw.id() + '"><rect height="100" width="100"></rect><circle fill="#ff0066" cy="50" cx="50" r="50"></circle></svg>' - || toBeTested === '<svg id="' + draw.id() + '" width="100" height="100" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.com/svgjs"><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></svg>').toBeTruthy() + + // Firefox + || toBeTested === '<svg id="' + draw.id() + '" width="100" height="100" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.com/svgjs"><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></svg>' + + // svgdom + || toBeTested === '<svg id="' + draw.id() + '" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.com/svgjs" width="100" height="100"><svg id="SvgjsSvg1002" width="2" height="0" style="overflow: hidden; top: -100%; left: -100%; position: absolute; opacity: 0"><polyline id="SvgjsPolyline1003" points="10,10 20,10 30,10"></polyline><path id="SvgjsPath1004" d="M80 80A45 45 0 0 0 125 125L125 80Z "></path></svg><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></svg>' + ).toBeTruthy() }) it('returns partial raw svg when called on a sub group', function() { @@ -824,7 +826,9 @@ describe('Element', function() { expect( toBeTested === '<g><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></g>' - || toBeTested === '<g><rect height="100" width="100"></rect><circle fill="#ff0066" cy="50" cx="50" r="50"></circle></g>').toBeTruthy() + || toBeTested === '<g><rect height="100" width="100"></rect><circle fill="#ff0066" cy="50" cx="50" r="50"></circle></g>' + || toBeTested === '<g xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></g>' + ).toBeTruthy() }) it('returns a single element when called on an element', function() { var group = draw.group().id(null) @@ -834,31 +838,37 @@ describe('Element', function() { expect( toBeTested === '<circle r="50" cx="50" cy="50" fill="#ff0066"></circle>' - || toBeTested === '<circle fill="#ff0066" cy="50" cx="50" r="50"></circle>').toBeTruthy() + || toBeTested === '<circle fill="#ff0066" cy="50" cx="50" r="50"></circle>' + || toBeTested === '<circle xmlns="http://www.w3.org/2000/svg" r="50" cx="50" cy="50" fill="#ff0066"></circle>' + ).toBeTruthy() }) }) describe('with raw svg given', function() { it('imports a full svg document', function() { draw.svg('<svg id="SvgjsSvg1000" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="0 0 50 50"><rect id="SvgjsRect1183" width="100" height="100"></rect><circle id="SvgjsCircle1184" r="50" cx="25" cy="25" fill="#ff0066"></circle></svg>') - expect(draw.get(0).type).toBe('svg') - expect(draw.get(0).children().length).toBe(2) - expect(draw.get(0).get(0).type).toBe('rect') - expect(draw.get(0).get(1).type).toBe('circle') - expect(draw.get(0).get(1).attr('fill')).toBe('#ff0066') + + expect(draw.get(0+parserInDoc).type).toBe('svg') + expect(draw.get(0+parserInDoc).children().length).toBe(2) + expect(draw.get(0+parserInDoc).get(0).type).toBe('rect') + expect(draw.get(0+parserInDoc).get(1).type).toBe('circle') + expect(draw.get(0+parserInDoc).get(1).attr('fill')).toBe('#ff0066') }) it('imports partial svg content', function() { draw.svg('<g id="SvgjsG1185"><rect id="SvgjsRect1186" width="100" height="100"></rect><circle id="SvgjsCircle1187" r="50" cx="25" cy="25" fill="#ff0066"></circle></g>') - expect(draw.get(0).type).toBe('g') - expect(draw.get(0).get(0).type).toBe('rect') - expect(draw.get(0).get(1).type).toBe('circle') - expect(draw.get(0).get(1).attr('fill')).toBe('#ff0066') + expect(draw.get(0+parserInDoc).type).toBe('g') + expect(draw.get(0+parserInDoc).get(0).type).toBe('rect') + expect(draw.get(0+parserInDoc).get(1).type).toBe('circle') + expect(draw.get(0+parserInDoc).get(1).attr('fill')).toBe('#ff0066') }) it('does not import on single elements, even with an argument it acts as a getter', function() { var rect = draw.rect(100,100).id(null) , result = rect.svg('<circle r="300"></rect>') + expect( result === '<rect width="100" height="100"></rect>' - || result === '<rect height="100" width="100"></rect>').toBeTruthy() + || result === '<rect height="100" width="100"></rect>' + || result === '<rect xmlns="http://www.w3.org/2000/svg" width="100" height="100"></rect>' + ).toBeTruthy() }) }) }) diff --git a/spec/spec/event.js b/spec/spec/event.js index 7354e6f..0b9fe5b 100644 --- a/spec/spec/event.js +++ b/spec/spec/event.js @@ -10,26 +10,26 @@ describe('Event', function() { beforeEach(function() { rect = draw.rect(100, 100) + spyOn(SVG,'on').and.callThrough() }) afterEach(function() { toast = context = null }) - if (!window.isTouchDevice) { + if (!this.isTouchDevice) { describe('click()', function() { it('attaches an onclick event to the node of the element', function() { - expect(typeof rect.node.onclick).not.toBe('function') rect.click(action) - expect(typeof rect.node.onclick).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'click', action) }) it('fires the event on click', function() { - dispatchEvent(rect.click(action), 'click') + rect.click(action).fire('click') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.click(action), 'click') + rect.click(action).fire('click') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -39,16 +39,15 @@ describe('Event', function() { describe('dblclick()', function() { it('attaches an ondblclick event to the node of the element', function() { - expect(typeof rect.node.ondblclick).not.toBe('function') rect.dblclick(action) - expect(typeof rect.node.ondblclick).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'dblclick', action) }) it('fires the event on dblclick', function() { - dispatchEvent(rect.dblclick(action), 'dblclick') + rect.dblclick(action).fire('dblclick') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.dblclick(action), 'dblclick') + rect.dblclick(action).fire('dblclick') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -58,16 +57,15 @@ describe('Event', function() { describe('mousedown()', function() { it('attaches an onmousedown event to the node of the element', function() { - expect(typeof rect.node.onmousedown).not.toBe('function') rect.mousedown(action) - expect(typeof rect.node.onmousedown).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mousedown', action) }) it('fires the event on mousedown', function() { - dispatchEvent(rect.mousedown(action), 'mousedown') + rect.mousedown(action).fire('mousedown') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.mousedown(action), 'mousedown') + rect.mousedown(action).fire('mousedown') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -77,16 +75,15 @@ describe('Event', function() { describe('mouseup()', function() { it('attaches an onmouseup event to the node of the element', function() { - expect(typeof rect.node.onmouseup).not.toBe('function') rect.mouseup(action) - expect(typeof rect.node.onmouseup).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mouseup', action) }) it('fires the event on mouseup', function() { - dispatchEvent(rect.mouseup(action), 'mouseup') + rect.mouseup(action).fire('mouseup') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.mouseup(action), 'mouseup') + rect.mouseup(action).fire('mouseup') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -96,16 +93,15 @@ describe('Event', function() { describe('mouseover()', function() { it('attaches an onmouseover event to the node of the element', function() { - expect(typeof rect.node.onmouseover).not.toBe('function') rect.mouseover(action) - expect(typeof rect.node.onmouseover).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mouseover', action) }) it('fires the event on mouseover', function() { - dispatchEvent(rect.mouseover(action), 'mouseover') + rect.mouseover(action).fire('mouseover') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.mouseover(action), 'mouseover') + rect.mouseover(action).fire('mouseover') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -115,16 +111,15 @@ describe('Event', function() { describe('mouseout()', function() { it('attaches an onmouseout event to the node of the element', function() { - expect(typeof rect.node.onmouseout).not.toBe('function') rect.mouseout(action) - expect(typeof rect.node.onmouseout).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mouseout', action) }) it('fires the event on mouseout', function() { - dispatchEvent(rect.mouseout(action), 'mouseout') + rect.mouseout(action).fire('mouseout') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.mouseout(action), 'mouseout') + rect.mouseout(action).fire('mouseout') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -134,16 +129,15 @@ describe('Event', function() { describe('mousemove()', function() { it('attaches an onmousemove event to the node of the element', function() { - expect(typeof rect.node.onmousemove).not.toBe('function') rect.mousemove(action) - expect(typeof rect.node.onmousemove).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mousemove', action) }) it('fires the event on mousemove', function() { - dispatchEvent(rect.mousemove(action), 'mousemove') + rect.mousemove(action).fire('mousemove') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.mousemove(action), 'mousemove') + rect.mousemove(action).fire('mousemove') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -158,11 +152,11 @@ describe('Event', function() { expect(typeof rect.node.onmouseenter).toBe('function') }) it('fires the event on mouseenter', function() { - dispatchEvent(rect.mouseenter(action), 'mouseenter') + rect.mouseenter(action).fire('mouseenter') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.mouseenter(action), 'mouseenter') + rect.mouseenter(action).fire('mouseenter') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -177,11 +171,11 @@ describe('Event', function() { expect(typeof rect.node.onmouseleave).toBe('function') }) it('fires the event on mouseleave', function() { - dispatchEvent(rect.mouseleave(action), 'mouseleave') + rect.mouseleave(action).fire('mouseleave') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.mouseleave(action), 'mouseleave') + rect.mouseleave(action).fire('mouseleave') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -193,16 +187,15 @@ describe('Event', function() { describe('touchstart()', function() { it('attaches an ontouchstart event to the node of the element', function() { - expect(typeof rect.node.ontouchstart).not.toBe('function') rect.touchstart(action) - expect(typeof rect.node.ontouchstart).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchstart', action) }) it('fires the event on touchstart', function() { - dispatchEvent(rect.touchstart(action), 'touchstart') + rect.touchstart(action).fire('touchstart') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.touchstart(action), 'touchstart') + rect.touchstart(action).fire('touchstart') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -212,16 +205,15 @@ describe('Event', function() { describe('touchmove()', function() { it('attaches an ontouchmove event to the node of the element', function() { - expect(typeof rect.node.ontouchmove).not.toBe('function') rect.touchmove(action) - expect(typeof rect.node.ontouchmove).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchmove', action) }) it('fires the event on touchmove', function() { - dispatchEvent(rect.touchmove(action), 'touchmove') + rect.touchmove(action).fire('touchmove') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.touchmove(action), 'touchmove') + rect.touchmove(action).fire('touchmove') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -231,16 +223,15 @@ describe('Event', function() { describe('touchleave()', function() { it('attaches an ontouchleave event to the node of the element', function() { - expect(typeof rect.node.ontouchleave).not.toBe('function') rect.touchleave(action) - expect(typeof rect.node.ontouchleave).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchleave', action) }) it('fires the event on touchleave', function() { - dispatchEvent(rect.touchleave(action), 'touchleave') + rect.touchleave(action).fire('touchleave') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.touchleave(action), 'touchleave') + rect.touchleave(action).fire('touchleave') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -250,16 +241,15 @@ describe('Event', function() { describe('touchend()', function() { it('attaches an ontouchend event to the node of the element', function() { - expect(typeof rect.node.ontouchend).not.toBe('function') rect.touchend(action) - expect(typeof rect.node.ontouchend).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchend', action) }) it('fires the event on touchend', function() { - dispatchEvent(rect.touchend(action), 'touchend') + rect.touchend(action).fire('touchend') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.touchend(action), 'touchend') + rect.touchend(action).fire('touchend') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -269,16 +259,15 @@ describe('Event', function() { describe('touchcancel()', function() { it('attaches an ontouchcancel event to the node of the element', function() { - expect(typeof rect.node.ontouchcancel).not.toBe('function') rect.touchcancel(action) - expect(typeof rect.node.ontouchcancel).toBe('function') + expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchcancel', action) }) it('fires the event on touchcancel', function() { - dispatchEvent(rect.touchcancel(action), 'touchcancel') + rect.touchcancel(action).fire('touchcancel') expect(toast).toBe('ready') }) it('applies the element as context', function() { - dispatchEvent(rect.touchcancel(action), 'touchcancel') + rect.touchcancel(action).fire('touchcancel') expect(context).toBe(rect) }) it('returns the called element', function() { @@ -292,15 +281,15 @@ describe('Event', function() { describe('on()', function() { it('attaches an event to the element', function() { - dispatchEvent(rect.on('event', action), 'event') + rect.on('event', action).fire('event') expect(toast).toBe('ready') }) it('attaches an event to a non svg element', function() { - var body = document.getElementsByTagName('body')[0] - SVG.on(body, 'event', action) - body.dispatchEvent(new CustomEvent('event')) + var el = document.createElement('div') + SVG.on(el, 'event', action) + el.dispatchEvent(new window.CustomEvent('event')) expect(toast).toBe('ready') - SVG.off(body, 'event', action) + SVG.off(el, 'event', action) }) it('attaches multiple handlers on different element', function() { var listenerCnt = SVG.listeners.length @@ -338,11 +327,11 @@ describe('Event', function() { expect(SVG.listeners.length).toBe(listenerCnt + 3) // added listeners on 3 different elements }) it('applies the element as context', function() { - dispatchEvent(rect.on('event', action), 'event') + rect.on('event', action).fire('event') expect(context).toBe(rect) }) it('applies given object as context', function() { - dispatchEvent(rect.on('event', action, this), 'event') + rect.on('event', action, this).fire('event') expect(context).toBe(this) }) it('stores the listener for future reference', function() { @@ -373,13 +362,13 @@ describe('Event', function() { expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['*']).length).toBe(0) - dispatchEvent(rect, 'event') + rect.fire('event') expect(toast).toBeNull() - dispatchEvent(rect2, 'event') + rect2.fire('event') expect(toast).toBe('ready') - dispatchEvent(rect3, 'event') + rect3.fire('event') expect(butter).toBe('melting') expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['*'][action]).toBeUndefined() @@ -396,13 +385,13 @@ describe('Event', function() { expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['namespace']).length).toBe(0) - dispatchEvent(rect, 'event') + rect.fire('event') expect(toast).toBeNull() - dispatchEvent(rect2, 'event') + rect2.fire('event') expect(toast).toBe('ready') - dispatchEvent(rect3, 'event') + rect3.fire('event') expect(butter).toBe('melting') expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['namespace'][action]).toBeUndefined() @@ -412,7 +401,7 @@ describe('Event', function() { rect.on('event.namespace', function() { butter = 'melting'; }) rect.off('.namespace') - dispatchEvent(rect, 'event') + rect.fire('event') expect(toast).toBe('ready') expect(butter).toBeNull() }) @@ -421,7 +410,7 @@ describe('Event', function() { rect.on('event.namespace', function() { butter = 'melting'; }) rect.off('event') - dispatchEvent(rect, 'event') + rect.fire('event') expect(toast).toBeNull() expect(butter).toBeNull() expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']).toBeUndefined() @@ -430,8 +419,8 @@ describe('Event', function() { rect.on('event', action) rect.on('click', function() { butter = 'melting' }) rect.off() - dispatchEvent(rect, 'event') - dispatchEvent(rect, 'click') + rect.fire('event') + rect.fire('click') expect(toast).toBeNull() expect(butter).toBeNull() expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]).toBeUndefined() @@ -477,7 +466,7 @@ describe('Event', function() { }) it('fires my own event', function() { toast = null - rect.fire(new CustomEvent('event')) + rect.fire(new window.CustomEvent('event')) expect(toast).toBe('ready') }) it('makes the event cancelable', function() { @@ -494,11 +483,11 @@ describe('Event', function() { expect(rect.event()).toBe(null) }) it('returns the last fired event', function() { - var event = new CustomEvent('foo') + var event = new window.CustomEvent('foo') rect.fire(event) expect(rect.event()).toBe(event) - event = new CustomEvent('bar') + event = new window.CustomEvent('bar') rect.fire(event) expect(rect.event()).toBe(event) }) diff --git a/spec/spec/fx.js b/spec/spec/fx.js index dc12626..78101d4 100644 --- a/spec/spec/fx.js +++ b/spec/spec/fx.js @@ -1782,6 +1782,34 @@ describe('FX', function() { expect(ctm.f).toBe(0) }) + it('animate a flip(x) transform with an offset', function() { + var ctm + + fx.transform({flip: 'x', offset: 20}).start() + + jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox) + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(0.5) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(1) + expect(ctm.e).toBe(10) + expect(ctm.f).toBe(0) + + jasmine.clock().tick(475) // Have the animation reach its end + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(-1) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(1) + expect(ctm.e).toBe(40) + expect(ctm.f).toBe(0) + }) + it('animate a flip(y) transform', function() { var ctm @@ -1810,6 +1838,90 @@ describe('FX', function() { expect(ctm.f).toBe(300) }) + it('animate a flip(y) transform with an offset', function() { + var ctm + + fx.transform({flip: 'y', offset: 20}).start() + + jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox) + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(1) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(0.5) + expect(ctm.e).toBe(0) + expect(ctm.f).toBe(10) + + jasmine.clock().tick(475) // Have the animation reach its end + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(1) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(-1) + expect(ctm.e).toBe(0) + expect(ctm.f).toBe(40) + }) + + it('animate a flip() transform', function() { + var ctm + + fx.transform({flip: 'both'}).start() + + jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox) + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(0.5) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(0.5) + expect(ctm.e).toBe(75) + expect(ctm.f).toBe(75) + + jasmine.clock().tick(475) // Have the animation reach its end + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(-1) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(-1) + expect(ctm.e).toBe(300) + expect(ctm.f).toBe(300) + }) + + it('animate a flip() transform with an offset', function() { + var ctm + + fx.transform({flip: 'both', offset: 20}).start() + + jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox) + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(0.5) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(0.5) + expect(ctm.e).toBe(10) + expect(ctm.f).toBe(10) + + jasmine.clock().tick(475) // Have the animation reach its end + fx.step() + + ctm = rect.ctm() + expect(ctm.a).toBe(-1) + expect(ctm.b).toBe(0) + expect(ctm.c).toBe(0) + expect(ctm.d).toBe(-1) + expect(ctm.e).toBe(40) + expect(ctm.f).toBe(40) + }) + it('animate relative matrix transform', function(){ var ctm @@ -2194,10 +2306,10 @@ describe('FX', function() { fx.start() // When setting a style color, it get saved as a rgb() string even if it was passed as an hex code - // The style rgb string as spaces while the one returned by SVG.Color do not as show bellow + // The style rgb string has spaces while the one returned by SVG.Color do not as show bellow // CSS: rgb(255, 255, 255) SVG.Color: rgb(255,255,255) // The space in the style rbg string are removed so they can be equal - expect(rect.style('fill').replace(/ /g, '')).toBe(morph.at(0).toRgb()) + expect(rect.style('fill').replace(/\s+/g, '')).toBe(morph.at(0).toRgb()) jasmine.clock().tick(250) // Have the animation be half way fx.step() diff --git a/spec/spec/group.js b/spec/spec/group.js index 63335ae..4d5ff36 100644 --- a/spec/spec/group.js +++ b/spec/spec/group.js @@ -113,6 +113,4 @@ describe('Group', function() { expect(group.node.getAttribute('transform')).toBe('matrix(1,0,0,1,130,85)') }) }) - - }) diff --git a/spec/spec/helper.js b/spec/spec/helper.js index 5c4e35d..025c9dc 100644 --- a/spec/spec/helper.js +++ b/spec/spec/helper.js @@ -1,48 +1,165 @@ // create canavs -var drawing = document.createElement('div') +//var drawing, window = window, document = document, SVG = SVG + +parserInDoc = false + +if(typeof exports === 'object'){ + window = require('svgdom') + SVG = require('../../dist/svg.js') + document = window.document + drawing = document.documentElement + imageUrl = 'spec/fixtures/pixel.png' + parserInDoc = true + + function tag(name, attrs, children) { + var el = document.createElement(name) + for(var i in attrs){ + el.setAttribute(i, attrs[i]) + } + + for(var i in children){ + if(typeof children[i] == 'string') + children[i] = document.createTextNode(children[i]) + + el.appendChild(children[i]) + } + + return el + } + + // create fixtures in svgdom + var el = tag('svg', { + height:0, + width:0, + id:'inlineSVG' + },[ + tag('defs', {}, [ + tag('linearGradient', {}, [ + tag('stop', {offset: '5%', 'stop-color': 'green'}), + tag('stop', {offset: '95%', 'stop-color': 'gold'}), + ]), + tag('radialGradient', {}, [ + tag('stop', {offset: '5%', 'stop-color': 'green'}), + tag('stop', {offset: '95%', 'stop-color': 'gold'}), + ]) + ]), + tag('desc', {}, ['Some description']), + tag('path', { + id: 'lineAB', + d: 'M 100 350 l 150 -300', + stroke: 'red', + 'stroke-width': '3', + fill: 'none' + }), + tag('path', { + id: 'lineBC', + d: 'M 250 50 l 150 300', + stroke: 'red', + 'stroke-width': '3', + fill: 'none' + }), + tag('path', { + d: 'M 175 200 l 150 0', + stroke: 'green', + 'stroke-width': '3', + fill: 'none' + }), + tag('path', { + d: 'M 100 350 q 150 -300 300 0', + stroke: 'blue', + 'stroke-width': '5', + fill: 'none' + }), + tag('g', { + stroke: 'black', + 'stroke-width': '2', + fill: 'black', + id: 'pointGroup' + },[ + tag('circle', { + id: 'pointA', + cx: '100', + cy: '350', + r: '3', + }), + tag('circle', { + id: 'pointB', + cx: '250', + cy: '50', + r: '50', + }), + tag('circle', { + id: 'pointC', + cx: '400', + cy: '350', + r: '50', + }) + ]), + tag('g', { + 'font-size': '30', + font: 'sans-serif', + fill: 'black', + stroke: 'none', + 'text-anchor': 'middle', + id: 'labelGroup' + },[ + tag('text', { + x: '100', + y: '350', + dy: '-30', + }, ['A']), + tag('text', { + x: '250', + y: '50', + dy: '-10', + }, ['B']), + tag('text', { + x: '400', + y: '350', + dx: '30', + }, ['C']) + ]), + tag('polygon', {points: '200,10 250,190 160,210'}), + tag('polyline', {points: '20,20 40,25 60,40 80,120 120,140 200,180'}) + ]) + + document.appendChild(el) + +}else{ + drawing = document.createElement('div') + document.getElementsByTagName('body')[0].appendChild(drawing) + imageUrl = 'fixtures/pixel.png' +} + +parserInDoc |= 0 drawing.id = 'drawing' -document.getElementsByTagName('body')[0].appendChild(drawing) draw = SVG(drawing).size(100,100) +parser = parserInDoc ? [SVG.parser.draw.instance] : [] + // raw path data svgPath = 'M88.006,61.994c3.203,0,6.216-1.248,8.481-3.514C98.752,56.215,100,53.203,100,50c0-3.204-1.248-6.216-3.513-8.481 c-2.266-2.265-5.278-3.513-8.481-3.513c-2.687,0-5.237,0.877-7.327,2.496h-7.746l5.479-5.479 c5.891-0.757,10.457-5.803,10.457-11.896c0-6.614-5.381-11.995-11.994-11.995c-6.093,0-11.14,4.567-11.896,10.457l-5.479,5.479 v-7.747c1.618-2.089,2.495-4.641,2.495-7.327c0-3.204-1.247-6.216-3.513-8.481C56.216,1.248,53.204,0,50,0 c-3.204,0-6.216,1.248-8.481,3.513c-2.265,2.265-3.513,5.277-3.513,8.481c0,2.686,0.877,5.237,2.495,7.327v7.747l-5.479-5.479 c-0.757-5.89-5.803-10.457-11.896-10.457c-6.614,0-11.995,5.381-11.995,11.995c0,6.093,4.567,11.139,10.458,11.896l5.479,5.479 h-7.747c-2.089-1.619-4.641-2.496-7.327-2.496c-3.204,0-6.216,1.248-8.481,3.513C1.248,43.784,0,46.796,0,50 c0,3.203,1.248,6.216,3.513,8.48c2.265,2.266,5.277,3.514,8.481,3.514c2.686,0,5.237-0.877,7.327-2.496h7.747l-5.479,5.479 c-5.891,0.757-10.458,5.804-10.458,11.896c0,6.614,5.381,11.994,11.995,11.994c6.093,0,11.139-4.566,11.896-10.457l5.479-5.479 v7.749c-3.63,4.7-3.291,11.497,1.018,15.806C43.784,98.752,46.796,100,50,100c3.204,0,6.216-1.248,8.481-3.514 c4.309-4.309,4.647-11.105,1.018-15.806v-7.749l5.479,5.479c0.757,5.891,5.804,10.457,11.896,10.457 c6.613,0,11.994-5.38,11.994-11.994c0-6.093-4.566-11.14-10.457-11.896l-5.479-5.479h7.746 C82.769,61.117,85.319,61.994,88.006,61.994z M76.874,68.354c4.705,0,8.52,3.814,8.52,8.521c0,4.705-3.814,8.52-8.52,8.52 s-8.52-3.814-8.52-8.52l-12.33-12.33V81.98c3.327,3.328,3.327,8.723,0,12.049c-3.327,3.328-8.722,3.328-12.049,0 c-3.327-3.326-3.327-8.721,0-12.049V64.544l-12.33,12.33c0,4.705-3.814,8.52-8.52,8.52s-8.52-3.814-8.52-8.52 c0-4.706,3.814-8.521,8.52-8.521l12.33-12.33H18.019c-3.327,3.328-8.722,3.328-12.049,0c-3.327-3.326-3.327-8.721,0-12.048 s8.722-3.327,12.049,0h17.438l-12.33-12.33c-4.706,0-8.52-3.814-8.52-8.52c0-4.706,3.814-8.52,8.52-8.52s8.52,3.814,8.52,8.52 l12.33,12.33V18.019c-3.327-3.327-3.327-8.722,0-12.049s8.722-3.327,12.049,0s3.327,8.722,0,12.049v17.438l12.33-12.33 c0-4.706,3.814-8.52,8.52-8.52s8.52,3.814,8.52,8.52c0,4.705-3.814,8.52-8.52,8.52l-12.33,12.33h17.438 c3.327-3.327,8.722-3.327,12.049,0s3.327,8.722,0,12.048c-3.327,3.328-8.722,3.328-12.049,0H64.544L76.874,68.354z' // image url -imageUrl = 'fixtures/pixel.png' + // lorem ipsum text loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sodales\n imperdiet auctor. Nunc ultrices lectus at erat dictum pharetra\n elementum ante posuere. Duis turpis risus, blandit nec elementum et,\n posuere eget lacus. Aliquam et risus magna, eu aliquet nibh. Fusce\n consequat mi quis purus varius sagittis euismod urna interdum.\n Curabitur aliquet orci quis felis semper vulputate. Vestibulum ac nisi\n magna, id dictum diam. Proin sed metus vel magna blandit\n sodales. Pellentesque at neque ultricies nunc euismod rutrum ut in\n lorem. Mauris euismod tellus in tellus tempus interdum. Phasellus\n mattis sapien et leo feugiat dictum. Vestibulum at volutpat velit.' -// test for touch device -window.isTouchDevice = 'ontouchstart' in document.documentElement +beforeEach(function(){ + // test for touch device + this.isTouchDevice = 'ontouchstart' in document.documentElement +}) // strip spaces from result -function stripped(string) { - return string.replace(/\s+/g, '') -} - -// dispatch an event -function dispatchEvent(element, name) { - var e - - if (document.createEvent) { - e = document.createEvent('HTMLEvents') - e.initEvent(name, true, true) - } else { - e = document.createEventObject() - e.eventType = name - } - - e.eventName = name - - if (document.createEvent) - element.node.dispatchEvent(e) - else - element.node.fireEvent('on' + name, e) +window.stripped = function(string) { + string = string.replace(/\s+/g, '') + if(string.slice(-1) == ';') string = string.slice(0, -1) + return string } // This is needed because of IE11 which uses space as a delimiter in matrix -function matrixStringToArray(source){ +window.matrixStringToArray = function(source){ return source .replace(/matrix\(|\)/, '') .split(SVG.regex.delimiter) @@ -50,7 +167,7 @@ function matrixStringToArray(source){ } // This is needed because of IE11 creating values like 2.99999 when calculating a transformed box -function roundBox(box) { +window.roundBox = function(box) { return new SVG.Box( Math.round(box.x), Math.round(box.y), diff --git a/spec/spec/image.js b/spec/spec/image.js index bc30845..f5de893 100644 --- a/spec/spec/image.js +++ b/spec/spec/image.js @@ -40,4 +40,4 @@ describe('Image', function() { }) }) }) -})
\ No newline at end of file +}) diff --git a/spec/spec/matrix.js b/spec/spec/matrix.js index 8fd40b4..0816f66 100644 --- a/spec/spec/matrix.js +++ b/spec/spec/matrix.js @@ -152,7 +152,7 @@ describe('Matrix', function() { }) }) - + describe('clone()', function() { it('returns a clone of the matrix', function() { var matrix = new SVG.Matrix(2, 0, 0, 5, 0, 0) @@ -333,6 +333,32 @@ describe('Matrix', function() { expect(matrix.f).toBe(203) }) }) + describe('with no axis given', function() { + it('performs a flip over the horizontal and vertical axis with no argument', function() { + var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip() + + expect(matrix.a).toBe(-1) + expect(matrix.d).toBe(-1) + expect(matrix.e).toBe(4) + expect(matrix.f).toBe(3) + }) + it('performs a flip over the horizontal and vertical axis over a given point with one argument that represent both coordinates', function() { + var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip(100) + + expect(matrix.a).toBe(-1) + expect(matrix.d).toBe(-1) + expect(matrix.e).toBe(204) + expect(matrix.f).toBe(203) + }) + it('performs a flip over the horizontal and vertical axis over a given point with two arguments', function() { + var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip(50, 100) + + expect(matrix.a).toBe(-1) + expect(matrix.d).toBe(-1) + expect(matrix.e).toBe(104) + expect(matrix.f).toBe(203) + }) + }) }) describe('skew()', function() { @@ -438,7 +464,7 @@ describe('Matrix', function() { describe('native()', function() { it('returns the node reference', function() { - expect(new SVG.Matrix().native() instanceof SVGMatrix).toBeTruthy() + expect(new SVG.Matrix().native() instanceof window.SVGMatrix).toBeTruthy() }) }) diff --git a/spec/spec/memory.js b/spec/spec/memory.js index c7bb942..32773a0 100644 --- a/spec/spec/memory.js +++ b/spec/spec/memory.js @@ -12,9 +12,8 @@ describe('Memory', function () { describe('remember()', function() { it('accepts an object with values', function() { - rect.remember({ bbox: rect.bbox() }) - rect.size(200,300) - expect(rect.remember('bbox').width).toBe(100) + rect.remember({ some: {cool:'and',nested:'stuff',foo:5} }) + expect(rect.remember('some').foo).toBe(5) }) it('accepts key / value arguments', function() { rect.remember('fill', rect.attr('fill')) diff --git a/spec/spec/path.js b/spec/spec/path.js index e458b63..e0b5f25 100644 --- a/spec/spec/path.js +++ b/spec/spec/path.js @@ -16,7 +16,6 @@ describe('Path', function() { }) }) - describe('array()', function() { it('returns an instance of SVG.PathArray', function() { expect(path.array() instanceof SVG.PathArray).toBeTruthy() @@ -128,7 +127,7 @@ describe('Path', function() { var box = path.bbox() expect(box.width).toBeCloseTo(234) }) - it('gets the width of the element aithout an agrument', function() { + it('gets the width of the element without an argument', function() { path.width(456) expect(path.width()).toBeCloseTo(456) }) @@ -140,7 +139,7 @@ describe('Path', function() { var box = path.bbox() expect(box.height).toBeCloseTo(654) }) - it('gets the height of the element aithout an agrument', function() { + it('gets the height of the element without an argument', function() { path.height(321) expect(path.height()).toBeCloseTo(321) }) @@ -156,14 +155,14 @@ describe('Path', function() { it('defines the width and height proportionally with only the width value given', function() { var box = path.bbox() path.size(500) - expect(path.width()).toBe(500) + expect(path.width()).toBeCloseTo(500) expect(path.width() / path.height()).toBe(box.width / box.height) }) it('defines the width and height proportionally with only the height value given', function() { var box = path.bbox() path.size(null, 525) expect(path.height()).toBe(525) - expect(path.width() / path.height()).toBe(box.width / box.height) + expect(path.width() / path.height()).toBeCloseTo(box.width / box.height) }) }) @@ -192,28 +191,51 @@ describe('Path', function() { }) describe('plot()', function() { - it('change the d attribute of the underlying path node when a string is passed', function() { + it('changes the d attribute of the underlying path node when a string is passed', function() { var pathString = 'm 3,2 c 0,0 -0,13 8,14 L 5,4' , pathArray = new SVG.PathArray(pathString) expect(path.plot(pathString)).toBe(path) - expect(path.attr('d')).toBe(pathArray.toString()) + expect(path.attr('d')).toBe(pathString) + }) + it('clears the array cache when a value is passed', function() { + path = draw.path([ ['M', 50, 60], ['A', 60, 60, 0, 0, 0, 50, -60], ['z'] ]) + expect(path._array instanceof SVG.PathArray).toBeTruthy() + path.plot('m 3,2 c 0,0 -0,13 8,14 L 5,4') + expect(path._array).toBeUndefined() }) + it('applies a given path string value as is', function() { + var pathString = 'm 3,2 c 0,0 -0,13 8,14 L 5,4' - it('return the path array when no arguments are passed', function () { + path = draw.path(pathString) + expect(path.attr('d')).toBe(pathString) + }) + it('does not parse and cache a given string value to SVG.PathArray', function() { + path = draw.path('m 3,2 c 0,0 -0,13 8,14 L 5,4') + expect(path._array).toBeUndefined() + }) + it('caches a given array value', function() { + path = draw.path([ ['M', 50, 60], ['A', 60, 60, 0, 0, 0, 50, -60], ['H', 100], ['L', 20, 30], ['Z'] ]) + expect(path._array instanceof SVG.PathArray).toBeTruthy() + }) + it('returns the path array when no arguments are passed', function () { expect(path.plot()).toBe(path.array()) }) }) + describe('clear()', function() { + it('clears the cached SVG.PathArray instance', function() { + path = draw.path(svgPath) + path.clear() + expect(path._array).toBeUndefined() + }) + }) + describe('toString()', function() { it('renders path array correctly to string', function() { - path = path.plot('M 50 60 A 60 60 0 0 0 50 -60 H 100 V 100 L 20 30 C 10 20 30 40 50 60 ') + path = path.plot(['M', 50, 60, 'A', 60, 60, 0, 0, 0, 50, -60, 'H', 100, 'V', 100, 'L', 20, 30, 'C', 10, 20, 30, 40, 50, 60 ]) expect(path.node.getAttribute('d')).toBe('M50 60A60 60 0 0 0 50 -60H100V100L20 30C10 20 30 40 50 60 ') }) - it('renders path array correctly to string', function() { - path = path.plot('M 50 60 A 60 60 1 1 0 50 -60 H 100 V 100 L 20 30 C 10 20 30 40 50 60 ') - expect(path.node.getAttribute('d')).toBe('M50 60A60 60 1 1 0 50 -60H100V100L20 30C10 20 30 40 50 60 ') - }) }) describe('length()', function() { diff --git a/spec/spec/point.js b/spec/spec/point.js index ae10ec8..8eacb84 100644 --- a/spec/spec/point.js +++ b/spec/spec/point.js @@ -134,7 +134,7 @@ describe('Point', function() { describe('native()', function() { it('returns native SVGPoint', function() { - expect(new SVG.Point().native() instanceof SVGPoint).toBeTruthy() + expect(new SVG.Point().native() instanceof window.SVGPoint).toBeTruthy() }) }) }) diff --git a/spec/spec/polygon.js b/spec/spec/polygon.js index 34d0969..789c3b9 100644 --- a/spec/spec/polygon.js +++ b/spec/spec/polygon.js @@ -185,18 +185,44 @@ describe('Polygon', function() { }) }) - describe('plot()', function() { - it('change the points attribute of the underlying polygon node when a string is passed', function() { + it('changes the points attribute of the underlying polygon node when a string is passed', function() { var pointString = '100,50 75,20 200,100' , pointArray = new SVG.PointArray(pointString) expect(polygon.plot(pointString)).toBe(polygon) expect(polygon.attr('points')).toBe(pointArray.toString()) }) - - it('return the point array when no arguments are passed', function () { + it('returns the point array when no arguments are passed', function () { expect(polygon.plot()).toBe(polygon.array()) }) + it('clears the array cache when a value is passed', function() { + polygon = draw.polygon([100,50,75,20,200,100]) + expect(polygon._array instanceof SVG.PointArray).toBeTruthy() + polygon.plot('100,50 75,20 200,100') + expect(polygon._array).toBeUndefined() + }) + it('applies a given polygon string value as is', function() { + var polyString = '100,50,75,20,200,100' + + polygon = draw.polygon(polyString) + expect(polygon.attr('points')).toBe(polyString) + }) + it('does not parse and cache a given string value to SVG.PointArray', function() { + polygon = draw.polygon('100,50 75,20 200,100') + expect(polygon._array).toBeUndefined() + }) + it('caches a given array value', function() { + polygon = draw.polygon([100,50,75,20,200,100]) + expect(polygon._array instanceof SVG.PointArray).toBeTruthy() + }) + }) + + describe('clear()', function() { + it('clears the cached SVG.PointArray instance', function() { + polygon = draw.polygon([100,50,75,20,200,100]) + polygon.clear() + expect(polygon._array).toBeUndefined() + }) }) }) diff --git a/spec/spec/polyline.js b/spec/spec/polyline.js index aa7120c..ca516bd 100644 --- a/spec/spec/polyline.js +++ b/spec/spec/polyline.js @@ -193,9 +193,36 @@ describe('Polyline', function() { expect(polyline.plot(pointString)).toBe(polyline) expect(polyline.attr('points')).toBe(pointArray.toString()) }) - it('return the point array when no arguments are passed', function () { expect(polyline.plot()).toBe(polyline.array()) }) + it('clears the array cache when a value is passed', function() { + polyline = draw.polyline([100,50,75,20,200,100]) + expect(polyline._array instanceof SVG.PointArray).toBeTruthy() + polyline.plot('100,50 75,20 200,100') + expect(polyline._array).toBeUndefined() + }) + it('applies a given polyline string value as is', function() { + var polyString = '100,50,75,20,200,100' + + polyline = draw.polyline(polyString) + expect(polyline.attr('points')).toBe(polyString) + }) + it('does not parse and cache a given string value to SVG.PointArray', function() { + polyline = draw.polyline('100,50 75,20 200,100') + expect(polyline._array).toBeUndefined() + }) + it('caches a given array value', function() { + polyline = draw.polyline([100,50,75,20,200,100]) + expect(polyline._array instanceof SVG.PointArray).toBeTruthy() + }) + }) + + describe('clear()', function() { + it('clears the cached SVG.PointArray instance', function() { + polyline = draw.polyline([100,50,75,20,200,100]) + polyline.clear() + expect(polyline._array).toBeUndefined() + }) }) }) diff --git a/spec/spec/rect.js b/spec/spec/rect.js index 84de937..5ce65c0 100644 --- a/spec/spec/rect.js +++ b/spec/spec/rect.js @@ -15,8 +15,7 @@ describe('Rect', function() { }) it('should set the value of x with the first argument', function() { rect.x(123) - var box = rect.bbox() - expect(box.x).toBe(123) + expect(rect.node.getAttribute('x')).toBe('123') }) }) @@ -26,8 +25,7 @@ describe('Rect', function() { }) it('should set the value of y with the first argument', function() { rect.y(345) - var box = rect.bbox() - expect(box.y).toBe(345) + expect(rect.node.getAttribute('y')).toBe('345') }) }) diff --git a/spec/spec/svg.js b/spec/spec/svg.js index 0fa699a..35f42e8 100644 --- a/spec/spec/svg.js +++ b/spec/spec/svg.js @@ -1,50 +1,58 @@ describe('SVG', function() { - + describe('()', function() { var drawing, wrapper - + beforeEach(function() { - wrapper = document.createElement('div') - document.getElementsByTagName('body')[0].appendChild(wrapper) + wrapper = document.createElement('svg') + document.documentElement.appendChild(wrapper) drawing = SVG(wrapper) }) - + afterEach(function() { wrapper.parentNode.removeChild(wrapper) }) - + it('creates a new svg drawing', function() { expect(drawing.type).toBe('svg') }) it('creates an instance of SVG.Doc', function() { expect(drawing instanceof SVG.Doc).toBe(true) }) - it('sets size to 100%', function() { - expect(drawing.width()).toBe('100%') - expect(drawing.height()).toBe('100%') - }) + + if(parserInDoc){ + it('sets no default size in svg documents', function() { + expect(drawing.width()).toBe(0) + expect(drawing.height()).toBe(0) + }) + }else{ + it('sets size to 100% in html documents', function() { + expect(drawing.width()).toBe('100%') + expect(drawing.height()).toBe('100%') + }) + } }) - + describe('create()', function() { it('creates an element with given node name and return it', function() { var element = SVG.create('rect') - + expect(element.nodeName).toBe('rect') }) it('increases the global id sequence', function() { var did = SVG.did , element = SVG.create('rect') - + expect(did + 1).toBe(SVG.did) }) it('adds a unique id containing the node name', function() { var did = SVG.did , element = SVG.create('rect') - + expect(element.getAttribute('id')).toBe('SvgjsRect' + did) }) }) - + describe('extend()', function() { it('adds all functions in the given object to the target object', function() { SVG.extend(SVG.Rect, { @@ -52,7 +60,7 @@ describe('SVG', function() { return this.opacity(0.2) } }) - + expect(typeof SVG.Rect.prototype.soft).toBe('function') expect(draw.rect(100,100).soft().attr('opacity')).toBe(0.2) }) @@ -62,7 +70,7 @@ describe('SVG', function() { return this.opacity(0.5) } }) - + expect(typeof SVG.Rect.prototype.soft).toBe('function') expect(draw.rect(100,100).soft().attr('opacity')).toBe(0.5) expect(typeof SVG.Ellipse.prototype.soft).toBe('function') @@ -76,34 +84,31 @@ describe('SVG', function() { return this.opacity(0.3) } }) - + expect(typeof SVG.Rect.prototype.soft).toBe('function') expect(draw.rect(100,100).soft().attr('opacity')).toBe(0.3) expect(typeof SVG.Bogus).toBe('undefined') }) }) - + describe('prepare()', function() { var drawing, wrapper, parser - + beforeEach(function() { - wrapper = document.createElement('div') - document.getElementsByTagName('body')[0].appendChild(wrapper) + wrapper = document.createElement('svg') + document.documentElement.appendChild(wrapper) drawing = SVG(wrapper) - - parser = document.getElementsByTagName('body')[0].lastChild }) - + it('creates a parser element when calling SVG()', function() { - expect(SVG.parser.draw.node.nodeName).toBe('svg') + expect(SVG.parser.draw.nodeName).toBe('svg') }) it('hides the parser', function() { - expect(SVG.parser.draw.node.getAttribute('style')).toBe('opacity: 0; position: absolute; left: -100%; top: -100%; overflow: hidden;') + expect(window.stripped(SVG.parser.draw.getAttribute('style'))).toBe('opacity:0;position:absolute;left:-100%;top:-100%;overflow:hidden') }) it('holds polyline and path', function() { expect(SVG.select('polyline', SVG.parser.draw.node)[0].type).toBe('polyline') expect(SVG.select('path', SVG.parser.draw.node)[0].type).toBe('path') }) }) - -})
\ No newline at end of file +}) diff --git a/spec/spec/text.js b/spec/spec/text.js index 2b0454f..61533de 100644 --- a/spec/spec/text.js +++ b/spec/spec/text.js @@ -151,12 +151,12 @@ describe('Text', function() { it('adds content in a nested tspan', function() { text.text('It is a bear!') expect(text.node.childNodes[0].nodeType).toBe(1) - expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('It is a bear!') + expect(text.node.childNodes[0].childNodes[0].data).toBe('It is a bear!') }) it('adds content in a nested tspan even with an empty string', function() { text.text('') expect(text.node.childNodes[0].nodeType).toBe(1) - expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('') + expect(text.node.childNodes[0].childNodes[0].data).toBe('') }) it('creates multiple lines with a newline separated string', function() { text.text('It is\nJUST\na bear!') @@ -177,9 +177,9 @@ describe('Text', function() { add.plain('hut') }) expect(text.node.childNodes[0].nodeType).toBe(1) - expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('mastaba') + expect(text.node.childNodes[0].childNodes[0].data).toBe('mastaba') expect(text.node.childNodes[1].nodeType).toBe(3) - expect(text.node.childNodes[1].nodeValue).toBe('hut') + expect(text.node.childNodes[1].data).toBe('hut') }) }) @@ -187,12 +187,12 @@ describe('Text', function() { it('adds content without a tspan', function() { text.plain('It is a bear!') expect(text.node.childNodes[0].nodeType).toBe(3) - expect(text.node.childNodes[0].nodeValue).toBe('It is a bear!') + expect(text.node.childNodes[0].data).toBe('It is a bear!') }) it('clears content before adding new content', function() { text.plain('It is not a bear!') expect(text.node.childNodes.length).toBe(1) - expect(text.node.childNodes[0].nodeValue).toBe('It is not a bear!') + expect(text.node.childNodes[0].data).toBe('It is not a bear!') }) it('restores the content from the dom', function() { text.plain('Just plain text!') @@ -204,12 +204,12 @@ describe('Text', function() { it('adds content in a tspan', function() { text.tspan('It is a bear!') expect(text.node.childNodes[0].nodeType).toBe(1) - expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('It is a bear!') + expect(text.node.childNodes[0].childNodes[0].data).toBe('It is a bear!') }) it('clears content before adding new content', function() { text.tspan('It is not a bear!') expect(text.node.childNodes.length).toBe(1) - expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('It is not a bear!') + expect(text.node.childNodes[0].childNodes[0].data).toBe('It is not a bear!') }) }) @@ -257,28 +257,28 @@ describe('Text', function() { text.clear().build(true) text.plain('A great piece!') text.plain('Another great piece!') - expect(text.node.childNodes[0].nodeValue).toBe('A great piece!') - expect(text.node.childNodes[1].nodeValue).toBe('Another great piece!') + expect(text.node.childNodes[0].data).toBe('A great piece!') + expect(text.node.childNodes[1].data).toBe('Another great piece!') }) it('enables adding multiple tspan nodes when given true', function() { text.clear().build(true) text.tspan('A great piece!') text.tspan('Another great piece!') - expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('A great piece!') - expect(text.node.childNodes[1].childNodes[0].nodeValue).toBe('Another great piece!') + expect(text.node.childNodes[0].childNodes[0].data).toBe('A great piece!') + expect(text.node.childNodes[1].childNodes[0].data).toBe('Another great piece!') }) it('disables adding multiple plain text nodes when given false', function() { text.clear().build(true) text.plain('A great piece!') text.build(false).plain('Another great piece!') - expect(text.node.childNodes[0].nodeValue).toBe('Another great piece!') + expect(text.node.childNodes[0].data).toBe('Another great piece!') expect(text.node.childNodes[1]).toBe(undefined) }) it('disables adding multiple tspan nodes when given false', function() { text.clear().build(true) text.tspan('A great piece!') text.build(false).tspan('Another great piece!') - expect(text.node.childNodes[0].childNodes[0].nodeValue).toBe('Another great piece!') + expect(text.node.childNodes[0].childNodes[0].data).toBe('Another great piece!') expect(text.node.childNodes[1]).toBe(undefined) }) }) diff --git a/spec/spec/transformations.js b/spec/spec/transformations.js index 72767af..3399981 100644 --- a/spec/spec/transformations.js +++ b/spec/spec/transformations.js @@ -196,8 +196,8 @@ describe('Transformations:', function() { expect(morphed.b).toEqual(0) expect(morphed.c).toEqual(0) expect(morphed.d).toBeCloseTo(0.6) - expect(morphed.e).toEqual(20) - expect(morphed.f).toEqual(20) + expect(morphed.e).toBeCloseTo(20) + expect(morphed.f).toBeCloseTo(20) }) }) }) diff --git a/spec/support/jasmine.json b/spec/support/jasmine.json new file mode 100644 index 0000000..c7845fc --- /dev/null +++ b/spec/support/jasmine.json @@ -0,0 +1,9 @@ +{ + "spec_dir": "spec/spec", + "spec_files": [ + "!(helpers).js" + ], + "helpers": [ + "helpers.js" + ] +} diff --git a/src/boxes.js b/src/boxes.js index 5ab261a..ce9dc48 100644 --- a/src/boxes.js +++ b/src/boxes.js @@ -33,7 +33,7 @@ SVG.Box = SVG.invent({ } , transform: function(m) { - var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, p + var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, p, bbox var pts = [ new SVG.Point(this.x, this.y), @@ -72,7 +72,6 @@ SVG.Box = SVG.invent({ } , at: function(pos) { - if(!this.destination) return this return new SVG.Box( @@ -103,7 +102,7 @@ SVG.Box = SVG.invent({ } } catch(e) { try { - var clone = this.clone(SVG.parser.draw).show() + var clone = this.clone(SVG.parser.draw.instance).show() box = clone.node.getBBox() clone.remove() } catch(e) { @@ -71,10 +71,24 @@ SVG.Doc = SVG.invent({ // Removes the doc from the DOM , remove: function() { if(this.parent()) { - this.parent().removeChild(this.node); + this.parent().removeChild(this.node) } - return this; + return this + } + , clear: function() { + // remove children + while(this.node.hasChildNodes()) + this.node.removeChild(this.node.lastChild) + + // remove defs reference + delete this._defs + + // add back parser + if(!SVG.parser.draw.parentNode) + this.node.appendChild(SVG.parser.draw) + + return this } } diff --git a/src/event.js b/src/event.js index 115e175..60f7a69 100644 --- a/src/event.js +++ b/src/event.js @@ -16,15 +16,10 @@ // add event to SVG.Element SVG.Element.prototype[event] = function(f) { - var self = this - // bind event to element rather than element node - this.node['on' + event] = typeof f == 'function' ? - function() { return f.apply(self, arguments) } : null - + SVG.on(this.node, event, f) return this } - }) // Initialize listeners stack @@ -33,7 +28,7 @@ SVG.handlerMap = [] SVG.listenerId = 0 // Add event binder in the SVG namespace -SVG.on = function(node, event, listener, binding) { +SVG.on = function(node, event, listener, binding, options) { // create listener, get object-index var l = listener.bind(binding || node.instance || node) , index = (SVG.handlerMap.indexOf(node) + 1 || SVG.handlerMap.push(node)) - 1 @@ -53,7 +48,7 @@ SVG.on = function(node, event, listener, binding) { SVG.listeners[index][ev][ns][listener._svgjsListenerId] = l // add listener - node.addEventListener(ev, l, false) + node.addEventListener(ev, l, options || false) } // Add event unbinder in the SVG namespace @@ -61,6 +56,7 @@ SVG.off = function(node, event, listener) { var index = SVG.handlerMap.indexOf(node) , ev = event && event.split('.')[0] , ns = event && event.split('.')[1] + , namespace = '' if(index == -1) return @@ -118,8 +114,8 @@ SVG.off = function(node, event, listener) { // SVG.extend(SVG.Element, { // Bind given event to listener - on: function(event, listener, binding) { - SVG.on(this.node, event, listener, binding) + on: function(event, listener, binding, options) { + SVG.on(this.node, event, listener, binding, options) return this } @@ -145,4 +141,4 @@ SVG.extend(SVG.Element, { , event: function() { return this._event } -})
\ No newline at end of file +}) @@ -148,12 +148,12 @@ SVG.FX = SVG.invent({ // starts the animationloop , startAnimFrame: function(){ this.stopAnimFrame() - this.animationFrame = requestAnimationFrame(function(){ this.step() }.bind(this)) + this.animationFrame = window.requestAnimationFrame(function(){ this.step() }.bind(this)) } // cancels the animationframe , stopAnimFrame: function(){ - cancelAnimationFrame(this.animationFrame) + window.cancelAnimationFrame(this.animationFrame) } // kicks off the animation - only does something when the queue is currently not active and at least one situation is set @@ -584,7 +584,7 @@ SVG.FX = SVG.invent({ // calculates the step for every property and calls block with it , eachAt: function(){ - var i, at, self = this, target = this.target(), s = this.situation + var i, len, at, self = this, target = this.target(), s = this.situation // apply animations which can be called trough a method for(i in s.animations){ diff --git a/src/matrix.js b/src/matrix.js index 970e3be..7b8ced9 100644 --- a/src/matrix.js +++ b/src/matrix.js @@ -115,12 +115,11 @@ SVG.Matrix = SVG.invent({ } // Flip matrix on x or y, at a given offset , flip: function(a, o) { - o = typeof a == 'number' ? a : o return a == 'x' ? this.scale(-1, 1, o, 0) : a == 'y' ? this.scale(1, -1, 0, o) : - this.scale(-1, -1, o, o) + this.scale(-1, -1, a, o != null ? o : a) } // Skew , skew: function(x, y, cx, cy) { diff --git a/src/path.js b/src/path.js index 0c70a47..e5504bb 100644 --- a/src/path.js +++ b/src/path.js @@ -13,11 +13,16 @@ SVG.Path = SVG.invent({ , array: function() { return this._array || (this._array = new SVG.PathArray(this.attr('d'))) } - // Plot new poly points - , plot: function(p) { - return (p == null) ? + // Plot new path + , plot: function(d) { + return (d == null) ? this.array() : - this.attr('d', (this._array = new SVG.PathArray(p))) + this.clear().attr('d', typeof d == 'string' ? d : (this._array = new SVG.PathArray(d))) + } + // Clear array cache + , clear: function() { + delete this._array + return this } // Move by left top corner , move: function(x, y) { diff --git a/src/patharray.js b/src/patharray.js index 385342f..1313e59 100644 --- a/src/patharray.js +++ b/src/patharray.js @@ -1,3 +1,76 @@ +var pathHandlers = { + M: function(c, p, p0) { + p.x = p0.x = c[0] + p.y = p0.y = c[1] + + return ['M', p.x, p.y] + }, + L: function(c, p) { + p.x = c[0] + p.y = c[1] + return ['L', c[0], c[1]] + }, + H: function(c, p) { + p.x = c[0] + return ['H', c[0]] + }, + V: function(c, p) { + p.y = c[0] + return ['V', c[0]] + }, + C: function(c, p) { + p.x = c[4] + p.y = c[5] + return ['C', c[0], c[1], c[2], c[3], c[4], c[5]] + }, + S: function(c, p) { + p.x = c[2] + p.y = c[3] + return ['S', c[0], c[1], c[2], c[3]] + }, + Q: function(c, p) { + p.x = c[2] + p.y = c[3] + return ['Q', c[0], c[1], c[2], c[3]] + }, + T: function(c, p) { + p.x = c[0] + p.y = c[1] + return ['T', c[0], c[1]] + }, + Z: function(c, p, p0) { + p.x = p0.x + p.y = p0.y + return ['Z'] + }, + A: function(c, p) { + p.x = c[5] + p.y = c[6] + return ['A', c[0], c[1], c[2], c[3], c[4], c[5], c[6]] + } +} + +var mlhvqtcsa = 'mlhvqtcsaz'.split('') + +for(var i = 0, il = mlhvqtcsa.length; i < il; ++i){ + pathHandlers[mlhvqtcsa[i]] = (function(i){ + return function(c, p, p0) { + if(i == 'H') c[0] = c[0] + p.x + else if(i == 'V') c[0] = c[0] + p.y + else if(i == 'A'){ + c[5] = c[5] + p.x, + c[6] = c[6] + p.y + } + else + for(var j = 0, jl = c.length; j < jl; ++j) { + c[j] = c[j] + (j%2 ? p.y : p.x) + } + + return pathHandlers[i](c, p, p0) + } + })(mlhvqtcsa[i].toUpperCase()) +} + // Path points array SVG.PathArray = function(array, fallback) { SVG.Array.call(this, array, fallback || [['M', 0, 0]]) @@ -180,20 +253,22 @@ SVG.extend(SVG.PathArray, { }else{ array = array.reduce(function(prev, curr){ - return [].concat.apply(prev, curr) + return [].concat.call(prev, curr) }, []) } // array now is an array containing all parts of a path e.g. ['M', '0', '0', 'L', '30', '30' ...] - var arr = [] + , p = new SVG.Point() + , p0 = new SVG.Point() + , index = 0 + , len = array.length do{ - // Test if we have a path letter - if(SVG.regex.isPathLetter.test(array[0])){ - s = array[0] - array.shift() + if(SVG.regex.isPathLetter.test(array[index])){ + s = array[index] + ++index // If last letter was a move command and we got no new, it defaults to [L]ine }else if(s == 'M'){ s = 'L' @@ -201,80 +276,13 @@ SVG.extend(SVG.PathArray, { s = 'l' } - // add path letter as first element - seg = [s.toUpperCase()] - - // push all necessary parameters to segment - for(i = 0; i < paramCnt[seg[0]]; ++i){ - seg.push(parseFloat(array.shift())) - } - - // upper case - if(s == seg[0]){ - - if(s == 'M' || s == 'L' || s == 'C' || s == 'Q' || s == 'S' || s == 'T'){ - x = seg[paramCnt[seg[0]]-1] - y = seg[paramCnt[seg[0]]] - }else if(s == 'V'){ - y = seg[1] - }else if(s == 'H'){ - x = seg[1] - }else if(s == 'A'){ - x = seg[6] - y = seg[7] - } - - // lower case - }else{ - - // convert relative to absolute values - if(s == 'm' || s == 'l' || s == 'c' || s == 's' || s == 'q' || s == 't'){ - - seg[1] += x - seg[2] += y - - if(seg[3] != null){ - seg[3] += x - seg[4] += y - } - - if(seg[5] != null){ - seg[5] += x - seg[6] += y - } - - // move pointer - x = seg[paramCnt[seg[0]]-1] - y = seg[paramCnt[seg[0]]] - - }else if(s == 'v'){ - seg[1] += y - y = seg[1] - }else if(s == 'h'){ - seg[1] += x - x = seg[1] - }else if(s == 'a'){ - seg[6] += x - seg[7] += y - x = seg[6] - y = seg[7] - } - - } - - if(seg[0] == 'M'){ - x0 = x - y0 = y - } - - if(seg[0] == 'Z'){ - x = x0 - y = y0 - } - - arr.push(seg) + arr.push(pathHandlers[s].call(null, + array.slice(index, (index = index + paramCnt[s.toUpperCase()])).map(parseFloat), + p, p0 + ) + ) - }while(array.length) + }while(len > index) return arr diff --git a/src/poly.js b/src/poly.js index af1f075..269b112 100644 --- a/src/poly.js +++ b/src/poly.js @@ -42,7 +42,12 @@ SVG.extend(SVG.Polyline, SVG.Polygon, { , plot: function(p) { return (p == null) ? this.array() : - this.attr('points', (this._array = new SVG.PointArray(p))) + this.clear().attr('points', typeof p == 'string' ? p : (this._array = new SVG.PointArray(p))) + } + // Clear array cache +, clear: function() { + delete this._array + return this } // Move by left top corner , move: function(x, y) { @@ -126,7 +126,7 @@ SVG.adopt = function(node) { SVG.prepare = function() { // Select document body and create invisible svg element var body = document.getElementsByTagName('body')[0] - , draw = (body ? new SVG.Doc(body) : new SVG.Doc(document.documentElement).nested()).size(2, 0) + , draw = (body ? new SVG.Doc(body) : SVG.adopt(document.documentElement).nested()).size(2, 0) // Create parser object SVG.parser = { @@ -137,7 +137,7 @@ SVG.prepare = function() { left:'-100%', top:'-100%', overflow:'hidden' - }) + }).node , poly: draw.polyline().node , path: draw.path().node , native: SVG.create('svg') diff --git a/src/transform.js b/src/transform.js index f2061db..b738603 100644 --- a/src/transform.js +++ b/src/transform.js @@ -3,7 +3,7 @@ SVG.extend(SVG.Element, { transform: function(o, relative) { // get target in case of the fx module, otherwise reference this var target = this - , matrix + , matrix, bbox // act as a getter if (typeof o !== 'object') { @@ -76,10 +76,19 @@ SVG.extend(SVG.Element, { // act on flip } else if (o.flip) { - matrix = matrix.flip( - o.flip - , o.offset == null ? target.bbox()['c' + o.flip] : o.offset - ) + if(o.flip == 'x' || o.flip == 'y') { + o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset + } else { + if(o.offset == null) { + bbox = target.bbox() + o.flip = bbox.cx + o.offset = bbox.cy + } else { + o.flip = o.offset + } + } + + matrix = new SVG.Matrix().flip(o.flip, o.offset) // act on translate } else if (o.x != null || o.y != null) { @@ -101,7 +110,7 @@ SVG.extend(SVG.FX, { transform: function(o, relative) { // get target in case of the fx module, otherwise reference this var target = this.target() - , matrix + , matrix, bbox // act as a getter if (typeof o !== 'object') { @@ -150,10 +159,19 @@ SVG.extend(SVG.FX, { // act on flip } else if (o.flip) { - matrix = new SVG.Matrix().flip( - o.flip - , o.offset == null ? target.bbox()['c' + o.flip] : o.offset - ) + if(o.flip == 'x' || o.flip == 'y') { + o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset + } else { + if(o.offset == null) { + bbox = target.bbox() + o.flip = bbox.cx + o.offset = bbox.cy + } else { + o.flip = o.offset + } + } + + matrix = new SVG.Matrix().flip(o.flip, o.offset) // act on translate } else if (o.x != null || o.y != null) { @@ -313,6 +331,7 @@ SVG.Rotate = SVG.invent({ } , undo: function(o){ this._undo = o + return this } } @@ -1,4 +1,5 @@ (function(root, factory) { + /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(function(){ return factory(root, root.document) @@ -14,4 +15,4 @@ return SVG -}));
\ No newline at end of file +})); diff --git a/svg.js.d.ts b/svg.js.d.ts index e058cd4..ec803bd 100644 --- a/svg.js.d.ts +++ b/svg.js.d.ts @@ -6,7 +6,7 @@ declare var svgjs: svgjs.Library; // todo add SVG.FX
declare namespace svgjs {
export interface Library {
- (selector: string): Doc;
+ (id: string): Doc;
(domElement: HTMLElement): Doc;
ns: string;
xmlns: string;
@@ -43,17 +43,20 @@ declare namespace svgjs { }
// array.js
+ type ArrayAlias = _Array | number[] | string;
+
interface _Array {
- new (array?: any[], fallback?: any): _Array;
- value: any[];
- morph(array: any[]): this;
- settle(): number;
- at(pos: number): any;
+ new (array?: ArrayAlias, fallback?: number[]): _Array;
+ value: number[];
+ morph(array: number[]): this;
+ settle(): number[];
+ at(pos: NumberAlias): _Array;
toString(): string;
- valueOf(): any[];
- // parse(array:any[]):any[];
- split(string: string): any[];
+ valueOf(): number[];
+ parse(array: ArrayAlias): number[];
+ split(string: string): number[];
reverse(): this;
+ clone(): _Array;
}
interface Library { Array: _Array }
@@ -67,32 +70,39 @@ declare namespace svgjs { // bare.js
export interface Bare extends Element {
new (element: string, inherit?: any): Bare;
- words(text: any): this;
+ words(text: string): this;
}
interface Parent {
- element(element: string, inherit?: any): Bare;
- symbol(): Bare;
+ element(element: string, inherit?: Object): Bare;
}
interface Library { Bare: Bare; }
// boxes.js
- export interface BBox {
- new (element?: Element): BBox;
+ interface Box {
height: number;
width: number;
y: number;
x: number;
cx: number;
cy: number;
- merge(bbox: BBox): BBox;
+ w: number;
+ h: number;
+ x2: number;
+ y2: number;
+ merge(box: Box): Box;
+ transform(m: Matrix): Box
+ }
+
+ export interface BBox extends Box {
+ new (element?: Element): BBox;
}
- export interface RBox extends BBox {
+ export interface RBox extends Box {
new (element?: Element): RBox;
}
- export interface TBox extends BBox {
+ export interface TBox extends Box {
new (element?: Element): TBox;
}
- interface Container {
+ interface Element {
bbox(): BBox;
rbox(): RBox;
tbox(): TBox;
@@ -106,6 +116,8 @@ declare namespace svgjs { // clip.js
export interface ClipPath extends Container {
new (): ClipPath;
+ targets: Element[];
+ remove(): this;
}
interface Container {
clip(): ClipPath;
@@ -116,31 +128,39 @@ declare namespace svgjs { unclip(): this;
}
interface Library { ClipPath: ClipPath; }
-
+
// color.js
- export interface Color {
- new (): Color;
- new (color: string): Color;
- new (color: Color): Color;
+ interface ColorLike {
r: number;
g: number;
b: number;
+ }
+
+ type ColorAlias = string | ColorLike;
+
+ export interface Color extends ColorLike{
+ new (): Color;
+ new (color: ColorAlias): Color;
toString(): string;
toHex(): string;
toRgb(): string;
brightness(): number;
- morph(color: Color): Color;
- morph(color: string): Color;
+ morph(color: ColorAlias): Color;
at(pos: number): Color;
}
interface Library { Color: Color; }
// container.js
+ interface ViewBoxLike {
+ x: number;
+ y: number;
+ width: number;
+ height:number;
+ }
+
export interface Container extends Parent {
new (): Container;
- viewbox(): ViewBox;
- viewbox(v): this;
}
interface Library { Container: Container }
@@ -190,7 +210,7 @@ declare namespace svgjs { // doc.js
export interface Doc extends Container {
new (): Doc;
- new (selector: string): Doc;
+ new (id: string): Doc;
new (domElement: HTMLElement): Doc;
namespace(): this;
defs(): Defs;
@@ -206,22 +226,24 @@ declare namespace svgjs { node: LinkedHTMLElement;
type: string;
- x(x: number): this;
+ x(x: NumberAlias): this;
x(): number;
- y(y: number): this;
+ y(y: NumberAlias): this;
y(): number;
- cx(x: number, anchor?: boolean): this;
+ //cx(x: number, anchor?: boolean): this;
+ cx(x: number): this;
cx(): number;
- cy(y: number, anchor?: boolean): this;
+ //cy(y: number, anchor?: boolean): this;
+ cy(y: number): this;
cy(): number;
- move(x: number, y: number): this;
+ move(x: NumberAlias, y: NumberAlias): this;
center(x: number, y: number): this;
- width(width: number): this;
+ width(width: NumberAlias): this;
width(): number;
- height(height: number): this;
+ height(height: NumberAlias): this;
height(): number;
- size(w: number, h: number, anchor?: boolean): this;
+ size(width?: NumberAlias, height?: NumberAlias): this;
clone(): Element;
remove(): this;
@@ -255,28 +277,21 @@ declare namespace svgjs { native(): LinkedHTMLElement;
svg(svg: string): this;
+
+ writeDataToDom(): this,
+ setData(data: object): this,
+
is(cls: any): boolean;
}
interface Library { Element: Element; }
// ellipse.js
interface CircleMethods extends Shape {
- x(rx: any): this;
- x(): any;
- y(ry: any): this;
- y(): any;
-
- rx(rx: any): this;
- rx(): any;
- ry(ry: any): this;
- ry(): any;
+ rx(rx: number): this;
+ rx(): this;
+ ry(ry: number): this;
+ ry(): this;
- width(): number;
- width(width: any): this;
- height(): number;
- height(height: any): this;
-
- size(width: any, height: any): this;
radius(x: number, y?: number): this;
}
export interface Circle extends CircleMethods {
@@ -286,8 +301,8 @@ declare namespace svgjs { new (): Ellipse;
}
interface Container {
- circle(size?: any): Circle;
- ellipse(width?: any, height?: any): Ellipse;
+ circle(size?: number): Circle;
+ ellipse(width?: number, height?: number): Ellipse;
}
interface Library {
Circle: Circle;
@@ -299,6 +314,7 @@ declare namespace svgjs { on(event: string, cb: Function, context?: Object): this;
off(event: string, cb: Function, context?: Object): this;
fire(event: string, data?: any): this;
+ fire(event: Event): this;
click(cb: Function): this;
dblclick(cb: Function): this;
@@ -329,26 +345,32 @@ declare namespace svgjs { stop(jumpToEnd:boolean,clearQueue:boolean): Animation;
}
// TODO finishs FX
-
+ interface StopProperties {
+ color?: ColorAlias;
+ offset?: number;
+ opacity?: number;
+ }
+
// gradient.js
export interface Stop extends Element {
new (): Stop;
- update(offset?: number | _Number, color?: any, opacity?: number | _Number): this;
- update(opts: { color: string | Color, offset: number | _Number, opacity: number | _Number }): this;
+ update(offset?: number, color?: ColorAlias, opacity?: number): this;
+ update(opts: StopProperties): this;
}
export interface Gradient extends Container {
- new (type?: string): Gradient;
- at(offset?: number | _Number, color?: any, opacity?: number | _Number): Stop;
- at(opts: { color: string | Color, offset: number | _Number, opacity: number | _Number }): Stop;
+ new (type: string): Gradient;
+ at(offset?: number, color?: ColorAlias, opacity?: number): Stop;
+ at(opts: StopProperties): Stop;
update(block?: Function): this;
- fill(): this;
+ fill(): string;
+ fill(...any): never;
toString(): string;
- from(x, y): this;
- to(x, y): this;
+ from(x: number, y: number): this;
+ to(x: number, y: number): this;
radius(x: number, y?: number): this;
}
interface Container {
- gradient(type: string, block?: (stop: Gradient) => any): Gradient;
+ gradient(type: string, block?: (stop: Gradient) => void): Gradient;
}
interface Library {
Gradient: Gradient;
@@ -366,14 +388,20 @@ declare namespace svgjs { // hyperlink.js
export interface A extends Container {
new (): A;
- to(url: any): this;
- show(target?: any): this;
- target(target: any): this;
+ to(url: string): this;
+ to(): string;
+ show(target: string): this;
+ show(): string;
+ show(...any): never;
+ target(target: string): this;
+ target(): string;
+ }
+ interface Container {
+ link(url: string): A;
}
- interface Container { link(url?: string): A; }
interface Element {
linkTo(url: string): A;
- linkTo(url: (link: A) => any): A;
+ linkTo(url: (link: A) => void): A;
}
interface Library { A: A; }
@@ -381,8 +409,8 @@ declare namespace svgjs { export interface Image extends Shape {
new (): Image;
load(url?: string): this;
- loaded(cb: (image: Image, info: { width: number, height: number, ratio: number, url: string }) => any): this;
- error(cb: (image: Image, info: { width: number, height: number, ratio: number, url: string }) => any): this;
+ loaded(cb: (info: { width: number, height: number, ratio: number, url: string }) => void): this;
+ error(cb: (event: Event) => void): this;
}
interface Container {
image(): Image;
@@ -392,16 +420,19 @@ declare namespace svgjs { interface Library { Image: Image; }
// line.js
+ interface ArrayPoint extends Array<number> { }
+ type PointArrayAlias = ArrayPoint | number[] | PointArray | string;
+
export interface Line extends Shape {
new (): Line;
array(): PointArray;
- plot(points: number[][]): this;
+ plot(points: PointArrayAlias): this;
plot(x1: number, y1: number, x2: number, y2: number): this;
move(x: number, y: number): this;
- size(width: number, height: number): this;
+ size(width?: number, height?: number): this;
}
interface Container {
- line(points: number[][]): Line;
+ line(points: PointArrayAlias): Line;
line(x1: number, y1: number, x2: number, y2: number): Line;
}
interface Library { Line: Line; }
@@ -409,30 +440,30 @@ declare namespace svgjs { // marker.js
export interface Marker extends Container {
new (): Marker;
- ref(x, y): this;
- update(block: (marker: Marker) => any): this;
+ ref(x: string | number, y: string | number): this;
+ update(block: (marker: Marker) => void): this;
toString(): string;
}
interface Container {
- marker(width?: number, height?: number, block?: (marker: Marker) => any): Marker
+ marker(width?: number, height?: number, block?: (marker: Marker) => void): Marker
}
interface Defs {
- marker(width?: number, height?: number, block?: (marker: Marker) => any): Marker
+ marker(width?: number, height?: number, block?: (marker: Marker) => void): Marker
}
interface Line {
- marker(position: string, width?: number, height?: number, block?: (marker: Marker) => any): Marker;
+ marker(position: string, width?: number, height?: number, block?: (marker: Marker) => void): Marker;
marker(position: string, marker: Marker): Marker;
}
interface Polyline {
- marker(position: string, width?: number, height?: number, block?: (marker: Marker) => any): Marker;
+ marker(position: string, width?: number, height?: number, block?: (marker: Marker) => void): Marker;
marker(position: string, marker: Marker): Marker;
}
interface Polygon {
- marker(position: string, width?: number, height?: number, block?: (marker: Marker) => any): Marker;
+ marker(position: string, width?: number, height?: number, block?: (marker: Marker) => void): Marker;
marker(position: string, marker: Marker): Marker;
}
interface Path {
- marker(position: string, width?: number, height?: number, block?: (marker: Marker) => any): Marker;
+ marker(position: string, width?: number, height?: number, block?: (marker: Marker) => void): Marker;
marker(position: string, marker: Marker): Marker;
}
interface Library {
@@ -472,12 +503,22 @@ declare namespace svgjs { f: number;
matrix: Matrix;
}
+
+ interface MatrixLike {
+ a: number;
+ b: number;
+ c: number;
+ d: number;
+ e: number;
+ f: number;
+ }
+
+ type MatrixAlias = MatrixLike | number[] | Element | string;
+
export interface Matrix {
new (): Matrix;
- new (source: string): Matrix;
- new (element: Element): Matrix;
+ new (source: MatrixAlias): Matrix;
new (a: number, b: number, c: number, d: number, e: number, f: number): Matrix;
- new (source: {a: number, b: number, c: number, d: number, e: number, f: number}): Matrix;
a: number;
b: number;
c: number;
@@ -486,22 +527,23 @@ declare namespace svgjs { f: number;
extract(): MatrixExtract;
clone(): Matrix;
- morph(matrix: Matrix): Matrix;
+ morph(matrix: Matrix): this;
at(pos: number): Matrix;
multiply(matrix: Matrix): Matrix;
inverse(): Matrix;
translate(x: number, y: number): Matrix;
scale(x: number, y?: number, cx?: number, cy?: number): Matrix;
rotate(r: number, cx?: number, cy?: number): Matrix;
- flip(a: string, offset: number): Matrix;
- skew(x: number, y: number, cx: number, cy: number): Matrix;
+ flip(a: string, offset?: number): Matrix;
+ flip(offset?: number): Matrix;
+ skew(x: number, y?: number, cx?: number, cy?: number): Matrix;
skewX(x: number, cx?: number, cy?: number): Matrix;
skewY(y: number, cx?: number, cy?: number): Matrix;
around(cx: number, cy: number, matrix: Matrix): Matrix;
native(): SVGMatrix;
toString(): string;
}
- interface Container {
+ interface Element {
ctm(): Matrix;
screenCTM(): Matrix;
}
@@ -542,6 +584,8 @@ declare namespace svgjs { at(pos: number): _Number;
}
interface Library { Number: _Number; }
+
+ type NumberAlias = _Number | number | string;
// parent.js
export interface Parent extends Element {
@@ -554,7 +598,7 @@ declare namespace svgjs { get(i: number): Element;
first(): Element;
last(): Element;
- each(block: Function, deep?: boolean): this;
+ each(block: (index: number, children: Element[]) => void, deep?: boolean): this;
removeElement(element: Element): this;
clear(): this;
defs(): Defs;
@@ -562,29 +606,29 @@ declare namespace svgjs { interface Library{ Parent: Parent }
// path.js
+ interface PathArrayPoint extends Array<number | string> { }
+ type PathArrayAlias = PathArray | (string | number)[] | PathArrayPoint[] | string;
+
export interface Path extends Shape {
new (): Path;
morphArray: PathArray;
array(): PathArray;
- plot(d: string): this;
- plot(pathArray: PathArray): this;
+ plot(d: PathArrayAlias): this;
}
interface Container {
path(): Path;
- path(d: string): Path;
- plot(pathArray: PathArray): Path;
+ path(d: PathArrayAlias): Path;
}
interface Library{ Path: Path }
// pathArray.js
- interface PathArrayPoint extends Array<any> { }
export interface PathArray extends _Array {
new (): PathArray;
- new (d: string): PathArray;
- new (array: PathArrayPoint[]): PathArray;
+ new (d: PathArrayAlias): PathArray;
move(x: number, y: number): this;
- size(width: number, height: number): this;
- parse(array: any[]): any[];
+ size(width?: number, height?: number): this;
+ parse(array: PathArrayAlias): PathArrayPoint[];
+ parse(array: ArrayAlias): never;
bbox(): BBox;
}
interface Library { PathArray: PathArray; }
@@ -592,16 +636,17 @@ declare namespace svgjs { // pattern.js
export interface Pattern extends Container {
new (): Pattern;
- update(block: (pattern: Pattern) => any): this;
+ fill(): string;
+ fill(...any): never;
+ update(block: (pattern: Pattern) => void): this;
toString(): string;
}
interface Container {
- pattern(width?: number, height?: number, block?: (pattern: Pattern) => any): Pattern
+ pattern(width?: number, height?: number, block?: (pattern: Pattern) => void): Pattern
}
interface Library { Pattern: Pattern }
// point.js
- interface ArrayPoint extends Array<number> { }
export interface Point {
new (): Point;
new (position: ArrayPoint): Point;
@@ -610,7 +655,7 @@ declare namespace svgjs { new (x: number, y: number): Point;
clone(): Point;
- morph(point: Point): Point;
+ morph(point: Point): this;
at(pos: number): Point;
native(): SVGPoint;
transform(matrix: Matrix): Point;
@@ -626,18 +671,18 @@ declare namespace svgjs { // pointArray.js
export interface PointArray extends _Array {
new (): PointArray;
- new (points: string): PointArray;
- new (points: ArrayPoint[]): PointArray;
- toStirng(): string;
+ new (points: PointArrayAlias): PointArray;
+ toString(): string;
toLine(): {
x1: number;
y1: number;
x2: number;
y2: number;
};
- parse(points: string): ArrayPoint[];
+ parse(points: PointArrayAlias): ArrayPoint[];
+ parse(array: ArrayAlias): never;
move(x: number, y: number): this;
- size(width: number, height: number): this;
+ size(width?: number, height?: number): this;
bbox(): BBox;
}
interface Library { PointArray: PointArray }
@@ -645,8 +690,7 @@ declare namespace svgjs { // poly.js
interface poly extends Shape {
array(): PointArray;
- plot(p: string): this;
- plot(p: ArrayPoint[]): this;
+ plot(p: PointArrayAlias): this;
move(x: number, y: number): this;
size(width: number, height: number): this;
}
@@ -655,16 +699,14 @@ declare namespace svgjs { }
interface Library { PolyLine: PolyLine; }
interface Container {
- polyline(points: string): PolyLine;
- polyline(points: ArrayPoint[]): PolyLine;
+ polyline(points: PointArrayAlias): PolyLine;
}
export interface Polygon extends poly {
new (): Polygon;
}
interface Library { Polygon: Polygon; }
interface Container {
- polygon(points: string): Polygon;
- polygon(points: ArrayPoint[]): Polygon;
+ polygon(points: PointArrayAlias): Polygon;
}
// rect.js
@@ -683,8 +725,7 @@ declare namespace svgjs { hex: RegExp;
rgb: RegExp;
reference: RegExp;
- matrix: RegExp;
- matrixElements: RegExp;
+ transforms: RegExp;
whitespace: RegExp;
isHex: RegExp;
isRgb: RegExp;
@@ -693,13 +734,11 @@ declare namespace svgjs { isNumber: RegExp;
isPercent: RegExp;
isImage: RegExp;
- negExp: RegExp;
- comma: RegExp;
+ delimiter: RegExp;
hyphen: RegExp;
pathLetters: RegExp;
isPathLetter: RegExp;
- whitespaces: RegExp;
- X: RegExp;
+ dots: RegExp;
}
}
@@ -717,7 +756,7 @@ declare namespace svgjs { new (members?: Element[]): Set;
add(...elments: Element[]): this;
remove(element: Element): this;
- each(block: Function): this;
+ each(block: (index: number, members: Element[]) => void): this;
clear(): this;
length(): number;
has(element: Element): this;
@@ -759,19 +798,22 @@ declare namespace svgjs { fill(fill: { color?: string; opacity?: number, rule?: string }): this;
fill(color: string): this;
fill(pattern: Element): this;
+ fill(image: Image): this;
stroke(stroke: StrokeData): this;
stroke(color: string): this;
rotate(d: number, cx?: number, cy?: number): this;
skew(x: number, y?: number, cx?: number, cy?: number): this;
scale(x: number, y?: number, cx?: number, cy?: number): this;
translate(x: number, y: number): this;
- flip(a?: any, offset?: number): this;
- matrix(m: any): this;
+ flip(a: string, offset?: number): this;
+ flip(offset?: number): this;
+ matrix(m: MatrixAlias): this;
+ matrix(a: number, b: number, c: number, d: number, e: number, f: number): this;
opacity(o: number): this;
opacity(): number;
- dx(x: number): this;
- dy(y: number): this;
- dmove(x: number, y: number): this;
+ dx(x: NumberAlias): this;
+ dy(y: NumberAlias): this;
+ dmove(x: NumberAlias, y: NumberAlias): this;
}
interface Path {
length(): number;
@@ -797,31 +839,36 @@ declare namespace svgjs { new (): Text;
clone(): Text;
text(): string;
- text(text: any): this;
- size(fontSize: number): this;
- leading(fontSize: number): this;
+ text(text: string): this;
+ text(block: (text: Text) => void): this;
+ size(fontSize: NumberAlias): this;
+ leading(leading: number): this;
lines(): number;
rebuild(enabled: boolean): this;
build(enabled: boolean): this;
- plain(text: any): this;
- tspan(text: any): Tspan;
+ plain(text: string): this;
+ tspan(text: string): Tspan;
+ tspan(block: (tspan: Tspan) => void): this;
clear(): this;
length(): number;
}
interface Container {
- text(text: any): Text;
- plain(text: any): Text;
+ text(text: string): Text;
+ text(block: (tspan: Tspan) => void): Text;
+ plain(text: string): Text;
}
interface Library { Text: Text; }
export interface Tspan extends Shape {
new (): Tspan;
text(): string;
- text(text: any): this;
- dx(x: number): this;
- dy(y: number): this;
+ text(text: string): Tspan;
+ text(block: (tspan: Tspan) => void): this;
+ dx(x: NumberAlias): this;
+ dy(y: NumberAlias): this;
newLine(): this;
plain(text: any): this;
- tspan(text: any): Tspan;
+ tspan(text: string): Tspan;
+ tspan(block: (tspan: Tspan) => void): this;
clear(): this;
length(): number;
}
@@ -832,8 +879,7 @@ declare namespace svgjs { new (): TextPath;
}
interface Text {
- path(d: any): this;
- plot(d: any): this;
+ path(d: PathArrayAlias): this;
track(): Element;
textPath(): Element;
}
@@ -841,12 +887,12 @@ declare namespace svgjs { // transform.js
interface Element {
- transform(t: Transform): Element;
+ transform(t: Transform, relative?: boolean): Element;
transform(): Transform;
untransform(): this;
matrixify(): Matrix;
toParent(parent: Parent): this;
- toDoc(doc: Parent): this;
+ toDoc(): this;
}
interface Transform {
x?: number;
@@ -858,7 +904,7 @@ declare namespace svgjs { scaleY?: number;
skewX?: number;
skewY?: number;
- matrix?: string; // 1,0,0,1,0,0
+ matrix?: Matrix; // 1,0,0,1,0,0
a?: number; // direct digits of matrix
b?: number;
c?: number;
@@ -870,6 +916,7 @@ declare namespace svgjs { new (...Transform): Transformation;
new (source: Transform, inversed?: boolean): Transformation;
at(pos: number): Matrix;
+ undo(transform: Transform): this
}
export interface Translate extends Transformation {new (): Translate}
export interface Rotate extends Transformation {new (): Rotate}
@@ -902,28 +949,34 @@ declare namespace svgjs { // utilities.js
interface Library {
utils: {
- map(arrya: any[], block: Function): any;
+ map(array: any[], block: Function): any;
+ filter(array: any[], block: Function): any;
radians(d: number): number;
degrees(r: number): number;
+ filterSVGElements: HTMLElement[]
}
}
// viewbox.js
+ type ViewBoxAlias = ViewBoxLike | number[] | string | Element;
+
interface ViewBox {
- new (source: Element): ViewBox;
- new (source: string): ViewBox;
- new (source: any[]): ViewBox;
+ new (source: ViewBoxAlias): ViewBox;
+ new (x: number, y: number, width: number, height: number): ViewBox;
x: number;
y: number;
width: number;
height: number;
zoom?: number;
+ toString(): string;
+ morph(source: ViewBoxAlias): ViewBox;
+ morph(x: number, y: number, width: number, height: number): ViewBox;
+ at(pos:number): ViewBox;
}
interface Container {
- toString(): string;
- morph(v: { x: number, y: number, width: number, height: number }): this;
- morph(v: any[]): this;
- // at(pos:number):ViewBox;
+ viewbox(): ViewBox;
+ viewbox(x: number, y: number, width: number, height: number): this;
+ viewbox(viewbox: ViewBoxLike): this;
}
interface Library { ViewBox: ViewBox; }
|