Debian Codegraph @

deps/svg/svg-3.1.2.js

raw
1 /*!
2 * @svgdotjs/svg.js - A lightweight library for manipulating and animating SVG.
3 * @version 3.1.2
4 * https://svgjs.dev/
5 *
6 * @copyright Wout Fierens <[email protected]>
7 * @license MIT
8 *
9 * BUILT: Wed Jan 26 2022 23:19:07 GMT+0100 (Mitteleuropäische Normalzeit)
10 */;
11 var SVG = (function () {
12 'use strict';
13
14 const methods$1 = {};
15 const names = [];
16 function registerMethods(name, m) {
17 if (Array.isArray(name)) {
18 for (const _name of name) {
19 registerMethods(_name, m);
20 }
21
22 return;
23 }
24
25 if (typeof name === 'object') {
26 for (const _name in name) {
27 registerMethods(_name, name[_name]);
28 }
29
30 return;
31 }
32
33 addMethodNames(Object.getOwnPropertyNames(m));
34 methods$1[name] = Object.assign(methods$1[name] || {}, m);
35 }
36 function getMethodsFor(name) {
37 return methods$1[name] || {};
38 }
39 function getMethodNames() {
40 return [...new Set(names)];
41 }
42 function addMethodNames(_names) {
43 names.push(..._names);
44 }
45
46 // Map function
47 function map(array, block) {
48 let i;
49 const il = array.length;
50 const result = [];
51
52 for (i = 0; i < il; i++) {
53 result.push(block(array[i]));
54 }
55
56 return result;
57 } // Filter function
58
59 function filter(array, block) {
60 let i;
61 const il = array.length;
62 const result = [];
63
64 for (i = 0; i < il; i++) {
65 if (block(array[i])) {
66 result.push(array[i]);
67 }
68 }
69
70 return result;
71 } // Degrees to radians
72
73 function radians(d) {
74 return d % 360 * Math.PI / 180;
75 } // Radians to degrees
76
77 function degrees(r) {
78 return r * 180 / Math.PI % 360;
79 } // Convert dash-separated-string to camelCase
80
81 function camelCase(s) {
82 return s.toLowerCase().replace(/-(.)/g, function (m, g) {
83 return g.toUpperCase();
84 });
85 } // Convert camel cased string to dash separated
86
87 function unCamelCase(s) {
88 return s.replace(/([A-Z])/g, function (m, g) {
89 return '-' + g.toLowerCase();
90 });
91 } // Capitalize first letter of a string
92
93 function capitalize(s) {
94 return s.charAt(0).toUpperCase() + s.slice(1);
95 } // Calculate proportional width and height values when necessary
96
97 function proportionalSize(element, width, height, box) {
98 if (width == null || height == null) {
99 box = box || element.bbox();
100
101 if (width == null) {
102 width = box.width / box.height * height;
103 } else if (height == null) {
104 height = box.height / box.width * width;
105 }
106 }
107
108 return {
109 width: width,
110 height: height
111 };
112 }
113 /**
114 * This function adds support for string origins.
115 * It searches for an origin in o.origin o.ox and o.originX.
116 * This way, origin: {x: 'center', y: 50} can be passed as well as ox: 'center', oy: 50
117 **/
118
119 function getOrigin(o, element) {
120 const origin = o.origin; // First check if origin is in ox or originX
121
122 let ox = o.ox != null ? o.ox : o.originX != null ? o.originX : 'center';
123 let oy = o.oy != null ? o.oy : o.originY != null ? o.originY : 'center'; // Then check if origin was used and overwrite in that case
124
125 if (origin != null) {
126 [ox, oy] = Array.isArray(origin) ? origin : typeof origin === 'object' ? [origin.x, origin.y] : [origin, origin];
127 } // Make sure to only call bbox when actually needed
128
129
130 const condX = typeof ox === 'string';
131 const condY = typeof oy === 'string';
132
133 if (condX || condY) {
134 const {
135 height,
136 width,
137 x,
138 y
139 } = element.bbox(); // And only overwrite if string was passed for this specific axis
140
141 if (condX) {
142 ox = ox.includes('left') ? x : ox.includes('right') ? x + width : x + width / 2;
143 }
144
145 if (condY) {
146 oy = oy.includes('top') ? y : oy.includes('bottom') ? y + height : y + height / 2;
147 }
148 } // Return the origin as it is if it wasn't a string
149
150
151 return [ox, oy];
152 }
153
154 var utils = {
155 __proto__: null,
156 map: map,
157 filter: filter,
158 radians: radians,
159 degrees: degrees,
160 camelCase: camelCase,
161 unCamelCase: unCamelCase,
162 capitalize: capitalize,
163 proportionalSize: proportionalSize,
164 getOrigin: getOrigin
165 };
166
167 // Default namespaces
168 const svg = 'http://www.w3.org/2000/svg';
169 const html = 'http://www.w3.org/1999/xhtml';
170 const xmlns = 'http://www.w3.org/2000/xmlns/';
171 const xlink = 'http://www.w3.org/1999/xlink';
172 const svgjs = 'http://svgjs.dev/svgjs';
173
174 var namespaces = {
175 __proto__: null,
176 svg: svg,
177 html: html,
178 xmlns: xmlns,
179 xlink: xlink,
180 svgjs: svgjs
181 };
182
183 const globals = {
184 window: typeof window === 'undefined' ? null : window,
185 document: typeof document === 'undefined' ? null : document
186 };
187 function registerWindow(win = null, doc = null) {
188 globals.window = win;
189 globals.document = doc;
190 }
191 const save = {};
192 function saveWindow() {
193 save.window = globals.window;
194 save.document = globals.document;
195 }
196 function restoreWindow() {
197 globals.window = save.window;
198 globals.document = save.document;
199 }
200 function withWindow(win, fn) {
201 saveWindow();
202 registerWindow(win, win.document);
203 fn(win, win.document);
204 restoreWindow();
205 }
206 function getWindow() {
207 return globals.window;
208 }
209
210 class Base {// constructor (node/*, {extensions = []} */) {
211 // // this.tags = []
212 // //
213 // // for (let extension of extensions) {
214 // // extension.setup.call(this, node)
215 // // this.tags.push(extension.name)
216 // // }
217 // }
218 }
219
220 const elements = {};
221 const root = '___SYMBOL___ROOT___'; // Method for element creation
222
223 function create(name, ns = svg) {
224 // create element
225 return globals.document.createElementNS(ns, name);
226 }
227 function makeInstance(element, isHTML = false) {
228 if (element instanceof Base) return element;
229
230 if (typeof element === 'object') {
231 return adopter(element);
232 }
233
234 if (element == null) {
235 return new elements[root]();
236 }
237
238 if (typeof element === 'string' && element.charAt(0) !== '<') {
239 return adopter(globals.document.querySelector(element));
240 } // Make sure, that HTML elements are created with the correct namespace
241
242
243 const wrapper = isHTML ? globals.document.createElement('div') : create('svg');
244 wrapper.innerHTML = element; // We can use firstChild here because we know,
245 // that the first char is < and thus an element
246
247 element = adopter(wrapper.firstChild); // make sure, that element doesnt have its wrapper attached
248
249 wrapper.removeChild(wrapper.firstChild);
250 return element;
251 }
252 function nodeOrNew(name, node) {
253 return node && node.ownerDocument && node instanceof node.ownerDocument.defaultView.Node ? node : create(name);
254 } // Adopt existing svg elements
255
256 function adopt(node) {
257 // check for presence of node
258 if (!node) return null; // make sure a node isn't already adopted
259
260 if (node.instance instanceof Base) return node.instance;
261
262 if (node.nodeName === '#document-fragment') {
263 return new elements.Fragment(node);
264 } // initialize variables
265
266
267 let className = capitalize(node.nodeName || 'Dom'); // Make sure that gradients are adopted correctly
268
269 if (className === 'LinearGradient' || className === 'RadialGradient') {
270 className = 'Gradient'; // Fallback to Dom if element is not known
271 } else if (!elements[className]) {
272 className = 'Dom';
273 }
274
275 return new elements[className](node);
276 }
277 let adopter = adopt;
278 function mockAdopt(mock = adopt) {
279 adopter = mock;
280 }
281 function register(element, name = element.name, asRoot = false) {
282 elements[name] = element;
283 if (asRoot) elements[root] = element;
284 addMethodNames(Object.getOwnPropertyNames(element.prototype));
285 return element;
286 }
287 function getClass(name) {
288 return elements[name];
289 } // Element id sequence
290
291 let did = 1000; // Get next named element id
292
293 function eid(name) {
294 return 'Svgjs' + capitalize(name) + did++;
295 } // Deep new id assignment
296
297 function assignNewId(node) {
298 // do the same for SVG child nodes as well
299 for (let i = node.children.length - 1; i >= 0; i--) {
300 assignNewId(node.children[i]);
301 }
302
303 if (node.id) {
304 node.id = eid(node.nodeName);
305 return node;
306 }
307
308 return node;
309 } // Method for extending objects
310
311 function extend(modules, methods) {
312 let key, i;
313 modules = Array.isArray(modules) ? modules : [modules];
314
315 for (i = modules.length - 1; i >= 0; i--) {
316 for (key in methods) {
317 modules[i].prototype[key] = methods[key];
318 }
319 }
320 }
321 function wrapWithAttrCheck(fn) {
322 return function (...args) {
323 const o = args[args.length - 1];
324
325 if (o && o.constructor === Object && !(o instanceof Array)) {
326 return fn.apply(this, args.slice(0, -1)).attr(o);
327 } else {
328 return fn.apply(this, args);
329 }
330 };
331 }
332
333 function siblings() {
334 return this.parent().children();
335 } // Get the current position siblings
336
337 function position() {
338 return this.parent().index(this);
339 } // Get the next element (will return null if there is none)
340
341 function next() {
342 return this.siblings()[this.position() + 1];
343 } // Get the next element (will return null if there is none)
344
345 function prev() {
346 return this.siblings()[this.position() - 1];
347 } // Send given element one step forward
348
349 function forward() {
350 const i = this.position();
351 const p = this.parent(); // move node one step forward
352
353 p.add(this.remove(), i + 1);
354 return this;
355 } // Send given element one step backward
356
357 function backward() {
358 const i = this.position();
359 const p = this.parent();
360 p.add(this.remove(), i ? i - 1 : 0);
361 return this;
362 } // Send given element all the way to the front
363
364 function front() {
365 const p = this.parent(); // Move node forward
366
367 p.add(this.remove());
368 return this;
369 } // Send given element all the way to the back
370
371 function back() {
372 const p = this.parent(); // Move node back
373
374 p.add(this.remove(), 0);
375 return this;
376 } // Inserts a given element before the targeted element
377
378 function before(element) {
379 element = makeInstance(element);
380 element.remove();
381 const i = this.position();
382 this.parent().add(element, i);
383 return this;
384 } // Inserts a given element after the targeted element
385
386 function after(element) {
387 element = makeInstance(element);
388 element.remove();
389 const i = this.position();
390 this.parent().add(element, i + 1);
391 return this;
392 }
393 function insertBefore(element) {
394 element = makeInstance(element);
395 element.before(this);
396 return this;
397 }
398 function insertAfter(element) {
399 element = makeInstance(element);
400 element.after(this);
401 return this;
402 }
403 registerMethods('Dom', {
404 siblings,
405 position,
406 next,
407 prev,
408 forward,
409 backward,
410 front,
411 back,
412 before,
413 after,
414 insertBefore,
415 insertAfter
416 });
417
418 // Parse unit value
419 const numberAndUnit = /^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i; // Parse hex value
420
421 const hex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i; // Parse rgb value
422
423 const rgb = /rgb\((\d+),(\d+),(\d+)\)/; // Parse reference id
424
425 const reference = /(#[a-z_][a-z0-9\-_]*)/i; // splits a transformation chain
426
427 const transforms = /\)\s*,?\s*/; // Whitespace
428
429 const whitespace = /\s/g; // Test hex value
430
431 const isHex = /^#[a-f0-9]{3}$|^#[a-f0-9]{6}$/i; // Test rgb value
432
433 const isRgb = /^rgb\(/; // Test for blank string
434
435 const isBlank = /^(\s+)?$/; // Test for numeric string
436
437 const isNumber = /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; // Test for image url
438
439 const isImage = /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i; // split at whitespace and comma
440
441 const delimiter = /[\s,]+/; // Test for path letter
442
443 const isPathLetter = /[MLHVCSQTAZ]/i;
444
445 var regex = {
446 __proto__: null,
447 numberAndUnit: numberAndUnit,
448 hex: hex,
449 rgb: rgb,
450 reference: reference,
451 transforms: transforms,
452 whitespace: whitespace,
453 isHex: isHex,
454 isRgb: isRgb,
455 isBlank: isBlank,
456 isNumber: isNumber,
457 isImage: isImage,
458 delimiter: delimiter,
459 isPathLetter: isPathLetter
460 };
461
462 function classes() {
463 const attr = this.attr('class');
464 return attr == null ? [] : attr.trim().split(delimiter);
465 } // Return true if class exists on the node, false otherwise
466
467 function hasClass(name) {
468 return this.classes().indexOf(name) !== -1;
469 } // Add class to the node
470
471 function addClass(name) {
472 if (!this.hasClass(name)) {
473 const array = this.classes();
474 array.push(name);
475 this.attr('class', array.join(' '));
476 }
477
478 return this;
479 } // Remove class from the node
480
481 function removeClass(name) {
482 if (this.hasClass(name)) {
483 this.attr('class', this.classes().filter(function (c) {
484 return c !== name;
485 }).join(' '));
486 }
487
488 return this;
489 } // Toggle the presence of a class on the node
490
491 function toggleClass(name) {
492 return this.hasClass(name) ? this.removeClass(name) : this.addClass(name);
493 }
494 registerMethods('Dom', {
495 classes,
496 hasClass,
497 addClass,
498 removeClass,
499 toggleClass
500 });
501
502 function css(style, val) {
503 const ret = {};
504
505 if (arguments.length === 0) {
506 // get full style as object
507 this.node.style.cssText.split(/\s*;\s*/).filter(function (el) {
508 return !!el.length;
509 }).forEach(function (el) {
510 const t = el.split(/\s*:\s*/);
511 ret[t[0]] = t[1];
512 });
513 return ret;
514 }
515
516 if (arguments.length < 2) {
517 // get style properties as array
518 if (Array.isArray(style)) {
519 for (const name of style) {
520 const cased = camelCase(name);
521 ret[name] = this.node.style[cased];
522 }
523
524 return ret;
525 } // get style for property
526
527
528 if (typeof style === 'string') {
529 return this.node.style[camelCase(style)];
530 } // set styles in object
531
532
533 if (typeof style === 'object') {
534 for (const name in style) {
535 // set empty string if null/undefined/'' was given
536 this.node.style[camelCase(name)] = style[name] == null || isBlank.test(style[name]) ? '' : style[name];
537 }
538 }
539 } // set style for property
540
541
542 if (arguments.length === 2) {
543 this.node.style[camelCase(style)] = val == null || isBlank.test(val) ? '' : val;
544 }
545
546 return this;
547 } // Show element
548
549 function show() {
550 return this.css('display', '');
551 } // Hide element
552
553 function hide() {
554 return this.css('display', 'none');
555 } // Is element visible?
556
557 function visible() {
558 return this.css('display') !== 'none';
559 }
560 registerMethods('Dom', {
561 css,
562 show,
563 hide,
564 visible
565 });
566
567 function data(a, v, r) {
568 if (a == null) {
569 // get an object of attributes
570 return this.data(map(filter(this.node.attributes, el => el.nodeName.indexOf('data-') === 0), el => el.nodeName.slice(5)));
571 } else if (a instanceof Array) {
572 const data = {};
573
574 for (const key of a) {
575 data[key] = this.data(key);
576 }
577
578 return data;
579 } else if (typeof a === 'object') {
580 for (v in a) {
581 this.data(v, a[v]);
582 }
583 } else if (arguments.length < 2) {
584 try {
585 return JSON.parse(this.attr('data-' + a));
586 } catch (e) {
587 return this.attr('data-' + a);
588 }
589 } else {
590 this.attr('data-' + a, v === null ? null : r === true || typeof v === 'string' || typeof v === 'number' ? v : JSON.stringify(v));
591 }
592
593 return this;
594 }
595 registerMethods('Dom', {
596 data
597 });
598
599 function remember(k, v) {
600 // remember every item in an object individually
601 if (typeof arguments[0] === 'object') {
602 for (const key in k) {
603 this.remember(key, k[key]);
604 }
605 } else if (arguments.length === 1) {
606 // retrieve memory
607 return this.memory()[k];
608 } else {
609 // store memory
610 this.memory()[k] = v;
611 }
612
613 return this;
614 } // Erase a given memory
615
616 function forget() {
617 if (arguments.length === 0) {
618 this._memory = {};
619 } else {
620 for (let i = arguments.length - 1; i >= 0; i--) {
621 delete this.memory()[arguments[i]];
622 }
623 }
624
625 return this;
626 } // This triggers creation of a new hidden class which is not performant
627 // However, this function is not rarely used so it will not happen frequently
628 // Return local memory object
629
630 function memory() {
631 return this._memory = this._memory || {};
632 }
633 registerMethods('Dom', {
634 remember,
635 forget,
636 memory
637 });
638
639 function sixDigitHex(hex) {
640 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;
641 }
642
643 function componentHex(component) {
644 const integer = Math.round(component);
645 const bounded = Math.max(0, Math.min(255, integer));
646 const hex = bounded.toString(16);
647 return hex.length === 1 ? '0' + hex : hex;
648 }
649
650 function is(object, space) {
651 for (let i = space.length; i--;) {
652 if (object[space[i]] == null) {
653 return false;
654 }
655 }
656
657 return true;
658 }
659
660 function getParameters(a, b) {
661 const params = is(a, 'rgb') ? {
662 _a: a.r,
663 _b: a.g,
664 _c: a.b,
665 _d: 0,
666 space: 'rgb'
667 } : is(a, 'xyz') ? {
668 _a: a.x,
669 _b: a.y,
670 _c: a.z,
671 _d: 0,
672 space: 'xyz'
673 } : is(a, 'hsl') ? {
674 _a: a.h,
675 _b: a.s,
676 _c: a.l,
677 _d: 0,
678 space: 'hsl'
679 } : is(a, 'lab') ? {
680 _a: a.l,
681 _b: a.a,
682 _c: a.b,
683 _d: 0,
684 space: 'lab'
685 } : is(a, 'lch') ? {
686 _a: a.l,
687 _b: a.c,
688 _c: a.h,
689 _d: 0,
690 space: 'lch'
691 } : is(a, 'cmyk') ? {
692 _a: a.c,
693 _b: a.m,
694 _c: a.y,
695 _d: a.k,
696 space: 'cmyk'
697 } : {
698 _a: 0,
699 _b: 0,
700 _c: 0,
701 space: 'rgb'
702 };
703 params.space = b || params.space;
704 return params;
705 }
706
707 function cieSpace(space) {
708 if (space === 'lab' || space === 'xyz' || space === 'lch') {
709 return true;
710 } else {
711 return false;
712 }
713 }
714
715 function hueToRgb(p, q, t) {
716 if (t < 0) t += 1;
717 if (t > 1) t -= 1;
718 if (t < 1 / 6) return p + (q - p) * 6 * t;
719 if (t < 1 / 2) return q;
720 if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
721 return p;
722 }
723
724 class Color {
725 constructor(...inputs) {
726 this.init(...inputs);
727 } // Test if given value is a color
728
729
730 static isColor(color) {
731 return color && (color instanceof Color || this.isRgb(color) || this.test(color));
732 } // Test if given value is an rgb object
733
734
735 static isRgb(color) {
736 return color && typeof color.r === 'number' && typeof color.g === 'number' && typeof color.b === 'number';
737 }
738 /*
739 Generating random colors
740 */
741
742
743 static random(mode = 'vibrant', t, u) {
744 // Get the math modules
745 const {
746 random,
747 round,
748 sin,
749 PI: pi
750 } = Math; // Run the correct generator
751
752 if (mode === 'vibrant') {
753 const l = (81 - 57) * random() + 57;
754 const c = (83 - 45) * random() + 45;
755 const h = 360 * random();
756 const color = new Color(l, c, h, 'lch');
757 return color;
758 } else if (mode === 'sine') {
759 t = t == null ? random() : t;
760 const r = round(80 * sin(2 * pi * t / 0.5 + 0.01) + 150);
761 const g = round(50 * sin(2 * pi * t / 0.5 + 4.6) + 200);
762 const b = round(100 * sin(2 * pi * t / 0.5 + 2.3) + 150);
763 const color = new Color(r, g, b);
764 return color;
765 } else if (mode === 'pastel') {
766 const l = (94 - 86) * random() + 86;
767 const c = (26 - 9) * random() + 9;
768 const h = 360 * random();
769 const color = new Color(l, c, h, 'lch');
770 return color;
771 } else if (mode === 'dark') {
772 const l = 10 + 10 * random();
773 const c = (125 - 75) * random() + 86;
774 const h = 360 * random();
775 const color = new Color(l, c, h, 'lch');
776 return color;
777 } else if (mode === 'rgb') {
778 const r = 255 * random();
779 const g = 255 * random();
780 const b = 255 * random();
781 const color = new Color(r, g, b);
782 return color;
783 } else if (mode === 'lab') {
784 const l = 100 * random();
785 const a = 256 * random() - 128;
786 const b = 256 * random() - 128;
787 const color = new Color(l, a, b, 'lab');
788 return color;
789 } else if (mode === 'grey') {
790 const grey = 255 * random();
791 const color = new Color(grey, grey, grey);
792 return color;
793 } else {
794 throw new Error('Unsupported random color mode');
795 }
796 } // Test if given value is a color string
797
798
799 static test(color) {
800 return typeof color === 'string' && (isHex.test(color) || isRgb.test(color));
801 }
802
803 cmyk() {
804 // Get the rgb values for the current color
805 const {
806 _a,
807 _b,
808 _c
809 } = this.rgb();
810 const [r, g, b] = [_a, _b, _c].map(v => v / 255); // Get the cmyk values in an unbounded format
811
812 const k = Math.min(1 - r, 1 - g, 1 - b);
813
814 if (k === 1) {
815 // Catch the black case
816 return new Color(0, 0, 0, 1, 'cmyk');
817 }
818
819 const c = (1 - r - k) / (1 - k);
820 const m = (1 - g - k) / (1 - k);
821 const y = (1 - b - k) / (1 - k); // Construct the new color
822
823 const color = new Color(c, m, y, k, 'cmyk');
824 return color;
825 }
826
827 hsl() {
828 // Get the rgb values
829 const {
830 _a,
831 _b,
832 _c
833 } = this.rgb();
834 const [r, g, b] = [_a, _b, _c].map(v => v / 255); // Find the maximum and minimum values to get the lightness
835
836 const max = Math.max(r, g, b);
837 const min = Math.min(r, g, b);
838 const l = (max + min) / 2; // If the r, g, v values are identical then we are grey
839
840 const isGrey = max === min; // Calculate the hue and saturation
841
842 const delta = max - min;
843 const s = isGrey ? 0 : l > 0.5 ? delta / (2 - max - min) : delta / (max + min);
844 const h = isGrey ? 0 : max === r ? ((g - b) / delta + (g < b ? 6 : 0)) / 6 : max === g ? ((b - r) / delta + 2) / 6 : max === b ? ((r - g) / delta + 4) / 6 : 0; // Construct and return the new color
845
846 const color = new Color(360 * h, 100 * s, 100 * l, 'hsl');
847 return color;
848 }
849
850 init(a = 0, b = 0, c = 0, d = 0, space = 'rgb') {
851 // This catches the case when a falsy value is passed like ''
852 a = !a ? 0 : a; // Reset all values in case the init function is rerun with new color space
853
854 if (this.space) {
855 for (const component in this.space) {
856 delete this[this.space[component]];
857 }
858 }
859
860 if (typeof a === 'number') {
861 // Allow for the case that we don't need d...
862 space = typeof d === 'string' ? d : space;
863 d = typeof d === 'string' ? 0 : d; // Assign the values straight to the color
864
865 Object.assign(this, {
866 _a: a,
867 _b: b,
868 _c: c,
869 _d: d,
870 space
871 }); // If the user gave us an array, make the color from it
872 } else if (a instanceof Array) {
873 this.space = b || (typeof a[3] === 'string' ? a[3] : a[4]) || 'rgb';
874 Object.assign(this, {
875 _a: a[0],
876 _b: a[1],
877 _c: a[2],
878 _d: a[3] || 0
879 });
880 } else if (a instanceof Object) {
881 // Set the object up and assign its values directly
882 const values = getParameters(a, b);
883 Object.assign(this, values);
884 } else if (typeof a === 'string') {
885 if (isRgb.test(a)) {
886 const noWhitespace = a.replace(whitespace, '');
887 const [_a, _b, _c] = rgb.exec(noWhitespace).slice(1, 4).map(v => parseInt(v));
888 Object.assign(this, {
889 _a,
890 _b,
891 _c,
892 _d: 0,
893 space: 'rgb'
894 });
895 } else if (isHex.test(a)) {
896 const hexParse = v => parseInt(v, 16);
897
898 const [, _a, _b, _c] = hex.exec(sixDigitHex(a)).map(hexParse);
899 Object.assign(this, {
900 _a,
901 _b,
902 _c,
903 _d: 0,
904 space: 'rgb'
905 });
906 } else throw Error('Unsupported string format, can\'t construct Color');
907 } // Now add the components as a convenience
908
909
910 const {
911 _a,
912 _b,
913 _c,
914 _d
915 } = this;
916 const components = this.space === 'rgb' ? {
917 r: _a,
918 g: _b,
919 b: _c
920 } : this.space === 'xyz' ? {
921 x: _a,
922 y: _b,
923 z: _c
924 } : this.space === 'hsl' ? {
925 h: _a,
926 s: _b,
927 l: _c
928 } : this.space === 'lab' ? {
929 l: _a,
930 a: _b,
931 b: _c
932 } : this.space === 'lch' ? {
933 l: _a,
934 c: _b,
935 h: _c
936 } : this.space === 'cmyk' ? {
937 c: _a,
938 m: _b,
939 y: _c,
940 k: _d
941 } : {};
942 Object.assign(this, components);
943 }
944
945 lab() {
946 // Get the xyz color
947 const {
948 x,
949 y,
950 z
951 } = this.xyz(); // Get the lab components
952
953 const l = 116 * y - 16;
954 const a = 500 * (x - y);
955 const b = 200 * (y - z); // Construct and return a new color
956
957 const color = new Color(l, a, b, 'lab');
958 return color;
959 }
960
961 lch() {
962 // Get the lab color directly
963 const {
964 l,
965 a,
966 b
967 } = this.lab(); // Get the chromaticity and the hue using polar coordinates
968
969 const c = Math.sqrt(a ** 2 + b ** 2);
970 let h = 180 * Math.atan2(b, a) / Math.PI;
971
972 if (h < 0) {
973 h *= -1;
974 h = 360 - h;
975 } // Make a new color and return it
976
977
978 const color = new Color(l, c, h, 'lch');
979 return color;
980 }
981 /*
982 Conversion Methods
983 */
984
985
986 rgb() {
987 if (this.space === 'rgb') {
988 return this;
989 } else if (cieSpace(this.space)) {
990 // Convert to the xyz color space
991 let {
992 x,
993 y,
994 z
995 } = this;
996
997 if (this.space === 'lab' || this.space === 'lch') {
998 // Get the values in the lab space
999 let {
1000 l,
1001 a,
1002 b
1003 } = this;
1004
1005 if (this.space === 'lch') {
1006 const {
1007 c,
1008 h
1009 } = this;
1010 const dToR = Math.PI / 180;
1011 a = c * Math.cos(dToR * h);
1012 b = c * Math.sin(dToR * h);
1013 } // Undo the nonlinear function
1014
1015
1016 const yL = (l + 16) / 116;
1017 const xL = a / 500 + yL;
1018 const zL = yL - b / 200; // Get the xyz values
1019
1020 const ct = 16 / 116;
1021 const mx = 0.008856;
1022 const nm = 7.787;
1023 x = 0.95047 * (xL ** 3 > mx ? xL ** 3 : (xL - ct) / nm);
1024 y = 1.00000 * (yL ** 3 > mx ? yL ** 3 : (yL - ct) / nm);
1025 z = 1.08883 * (zL ** 3 > mx ? zL ** 3 : (zL - ct) / nm);
1026 } // Convert xyz to unbounded rgb values
1027
1028
1029 const rU = x * 3.2406 + y * -1.5372 + z * -0.4986;
1030 const gU = x * -0.9689 + y * 1.8758 + z * 0.0415;
1031 const bU = x * 0.0557 + y * -0.2040 + z * 1.0570; // Convert the values to true rgb values
1032
1033 const pow = Math.pow;
1034 const bd = 0.0031308;
1035 const r = rU > bd ? 1.055 * pow(rU, 1 / 2.4) - 0.055 : 12.92 * rU;
1036 const g = gU > bd ? 1.055 * pow(gU, 1 / 2.4) - 0.055 : 12.92 * gU;
1037 const b = bU > bd ? 1.055 * pow(bU, 1 / 2.4) - 0.055 : 12.92 * bU; // Make and return the color
1038
1039 const color = new Color(255 * r, 255 * g, 255 * b);
1040 return color;
1041 } else if (this.space === 'hsl') {
1042 // https://bgrins.github.io/TinyColor/docs/tinycolor.html
1043 // Get the current hsl values
1044 let {
1045 h,
1046 s,
1047 l
1048 } = this;
1049 h /= 360;
1050 s /= 100;
1051 l /= 100; // If we are grey, then just make the color directly
1052
1053 if (s === 0) {
1054 l *= 255;
1055 const color = new Color(l, l, l);
1056 return color;
1057 } // TODO I have no idea what this does :D If you figure it out, tell me!
1058
1059
1060 const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
1061 const p = 2 * l - q; // Get the rgb values
1062
1063 const r = 255 * hueToRgb(p, q, h + 1 / 3);
1064 const g = 255 * hueToRgb(p, q, h);
1065 const b = 255 * hueToRgb(p, q, h - 1 / 3); // Make a new color
1066
1067 const color = new Color(r, g, b);
1068 return color;
1069 } else if (this.space === 'cmyk') {
1070 // https://gist.github.com/felipesabino/5066336
1071 // Get the normalised cmyk values
1072 const {
1073 c,
1074 m,
1075 y,
1076 k
1077 } = this; // Get the rgb values
1078
1079 const r = 255 * (1 - Math.min(1, c * (1 - k) + k));
1080 const g = 255 * (1 - Math.min(1, m * (1 - k) + k));
1081 const b = 255 * (1 - Math.min(1, y * (1 - k) + k)); // Form the color and return it
1082
1083 const color = new Color(r, g, b);
1084 return color;
1085 } else {
1086 return this;
1087 }
1088 }
1089
1090 toArray() {
1091 const {
1092 _a,
1093 _b,
1094 _c,
1095 _d,
1096 space
1097 } = this;
1098 return [_a, _b, _c, _d, space];
1099 }
1100
1101 toHex() {
1102 const [r, g, b] = this._clamped().map(componentHex);
1103
1104 return `#${r}${g}${b}`;
1105 }
1106
1107 toRgb() {
1108 const [rV, gV, bV] = this._clamped();
1109
1110 const string = `rgb(${rV},${gV},${bV})`;
1111 return string;
1112 }
1113
1114 toString() {
1115 return this.toHex();
1116 }
1117
1118 xyz() {
1119 // Normalise the red, green and blue values
1120 const {
1121 _a: r255,
1122 _b: g255,
1123 _c: b255
1124 } = this.rgb();
1125 const [r, g, b] = [r255, g255, b255].map(v => v / 255); // Convert to the lab rgb space
1126
1127 const rL = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
1128 const gL = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
1129 const bL = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; // Convert to the xyz color space without bounding the values
1130
1131 const xU = (rL * 0.4124 + gL * 0.3576 + bL * 0.1805) / 0.95047;
1132 const yU = (rL * 0.2126 + gL * 0.7152 + bL * 0.0722) / 1.00000;
1133 const zU = (rL * 0.0193 + gL * 0.1192 + bL * 0.9505) / 1.08883; // Get the proper xyz values by applying the bounding
1134
1135 const x = xU > 0.008856 ? Math.pow(xU, 1 / 3) : 7.787 * xU + 16 / 116;
1136 const y = yU > 0.008856 ? Math.pow(yU, 1 / 3) : 7.787 * yU + 16 / 116;
1137 const z = zU > 0.008856 ? Math.pow(zU, 1 / 3) : 7.787 * zU + 16 / 116; // Make and return the color
1138
1139 const color = new Color(x, y, z, 'xyz');
1140 return color;
1141 }
1142 /*
1143 Input and Output methods
1144 */
1145
1146
1147 _clamped() {
1148 const {
1149 _a,
1150 _b,
1151 _c
1152 } = this.rgb();
1153 const {
1154 max,
1155 min,
1156 round
1157 } = Math;
1158
1159 const format = v => max(0, min(round(v), 255));
1160
1161 return [_a, _b, _c].map(format);
1162 }
1163 /*
1164 Constructing colors
1165 */
1166
1167
1168 }
1169
1170 class Point {
1171 // Initialize
1172 constructor(...args) {
1173 this.init(...args);
1174 } // Clone point
1175
1176
1177 clone() {
1178 return new Point(this);
1179 }
1180
1181 init(x, y) {
1182 const base = {
1183 x: 0,
1184 y: 0
1185 }; // ensure source as object
1186
1187 const source = Array.isArray(x) ? {
1188 x: x[0],
1189 y: x[1]
1190 } : typeof x === 'object' ? {
1191 x: x.x,
1192 y: x.y
1193 } : {
1194 x: x,
1195 y: y
1196 }; // merge source
1197
1198 this.x = source.x == null ? base.x : source.x;
1199 this.y = source.y == null ? base.y : source.y;
1200 return this;
1201 }
1202
1203 toArray() {
1204 return [this.x, this.y];
1205 }
1206
1207 transform(m) {
1208 return this.clone().transformO(m);
1209 } // Transform point with matrix
1210
1211
1212 transformO(m) {
1213 if (!Matrix.isMatrixLike(m)) {
1214 m = new Matrix(m);
1215 }
1216
1217 const {
1218 x,
1219 y
1220 } = this; // Perform the matrix multiplication
1221
1222 this.x = m.a * x + m.c * y + m.e;
1223 this.y = m.b * x + m.d * y + m.f;
1224 return this;
1225 }
1226
1227 }
1228 function point(x, y) {
1229 return new Point(x, y).transform(this.screenCTM().inverse());
1230 }
1231
1232 function closeEnough(a, b, threshold) {
1233 return Math.abs(b - a) < (threshold || 1e-6);
1234 }
1235
1236 class Matrix {
1237 constructor(...args) {
1238 this.init(...args);
1239 }
1240
1241 static formatTransforms(o) {
1242 // Get all of the parameters required to form the matrix
1243 const flipBoth = o.flip === 'both' || o.flip === true;
1244 const flipX = o.flip && (flipBoth || o.flip === 'x') ? -1 : 1;
1245 const flipY = o.flip && (flipBoth || o.flip === 'y') ? -1 : 1;
1246 const skewX = o.skew && o.skew.length ? o.skew[0] : isFinite(o.skew) ? o.skew : isFinite(o.skewX) ? o.skewX : 0;
1247 const skewY = o.skew && o.skew.length ? o.skew[1] : isFinite(o.skew) ? o.skew : isFinite(o.skewY) ? o.skewY : 0;
1248 const scaleX = o.scale && o.scale.length ? o.scale[0] * flipX : isFinite(o.scale) ? o.scale * flipX : isFinite(o.scaleX) ? o.scaleX * flipX : flipX;
1249 const scaleY = o.scale && o.scale.length ? o.scale[1] * flipY : isFinite(o.scale) ? o.scale * flipY : isFinite(o.scaleY) ? o.scaleY * flipY : flipY;
1250 const shear = o.shear || 0;
1251 const theta = o.rotate || o.theta || 0;
1252 const origin = new Point(o.origin || o.around || o.ox || o.originX, o.oy || o.originY);
1253 const ox = origin.x;
1254 const oy = origin.y; // We need Point to be invalid if nothing was passed because we cannot default to 0 here. Thats why NaN
1255
1256 const position = new Point(o.position || o.px || o.positionX || NaN, o.py || o.positionY || NaN);
1257 const px = position.x;
1258 const py = position.y;
1259 const translate = new Point(o.translate || o.tx || o.translateX, o.ty || o.translateY);
1260 const tx = translate.x;
1261 const ty = translate.y;
1262 const relative = new Point(o.relative || o.rx || o.relativeX, o.ry || o.relativeY);
1263 const rx = relative.x;
1264 const ry = relative.y; // Populate all of the values
1265
1266 return {
1267 scaleX,
1268 scaleY,
1269 skewX,
1270 skewY,
1271 shear,
1272 theta,
1273 rx,
1274 ry,
1275 tx,
1276 ty,
1277 ox,
1278 oy,
1279 px,
1280 py
1281 };
1282 }
1283
1284 static fromArray(a) {
1285 return {
1286 a: a[0],
1287 b: a[1],
1288 c: a[2],
1289 d: a[3],
1290 e: a[4],
1291 f: a[5]
1292 };
1293 }
1294
1295 static isMatrixLike(o) {
1296 return o.a != null || o.b != null || o.c != null || o.d != null || o.e != null || o.f != null;
1297 } // left matrix, right matrix, target matrix which is overwritten
1298
1299
1300 static matrixMultiply(l, r, o) {
1301 // Work out the product directly
1302 const a = l.a * r.a + l.c * r.b;
1303 const b = l.b * r.a + l.d * r.b;
1304 const c = l.a * r.c + l.c * r.d;
1305 const d = l.b * r.c + l.d * r.d;
1306 const e = l.e + l.a * r.e + l.c * r.f;
1307 const f = l.f + l.b * r.e + l.d * r.f; // make sure to use local variables because l/r and o could be the same
1308
1309 o.a = a;
1310 o.b = b;
1311 o.c = c;
1312 o.d = d;
1313 o.e = e;
1314 o.f = f;
1315 return o;
1316 }
1317
1318 around(cx, cy, matrix) {
1319 return this.clone().aroundO(cx, cy, matrix);
1320 } // Transform around a center point
1321
1322
1323 aroundO(cx, cy, matrix) {
1324 const dx = cx || 0;
1325 const dy = cy || 0;
1326 return this.translateO(-dx, -dy).lmultiplyO(matrix).translateO(dx, dy);
1327 } // Clones this matrix
1328
1329
1330 clone() {
1331 return new Matrix(this);
1332 } // Decomposes this matrix into its affine parameters
1333
1334
1335 decompose(cx = 0, cy = 0) {
1336 // Get the parameters from the matrix
1337 const a = this.a;
1338 const b = this.b;
1339 const c = this.c;
1340 const d = this.d;
1341 const e = this.e;
1342 const f = this.f; // Figure out if the winding direction is clockwise or counterclockwise
1343
1344 const determinant = a * d - b * c;
1345 const ccw = determinant > 0 ? 1 : -1; // Since we only shear in x, we can use the x basis to get the x scale
1346 // and the rotation of the resulting matrix
1347
1348 const sx = ccw * Math.sqrt(a * a + b * b);
1349 const thetaRad = Math.atan2(ccw * b, ccw * a);
1350 const theta = 180 / Math.PI * thetaRad;
1351 const ct = Math.cos(thetaRad);
1352 const st = Math.sin(thetaRad); // We can then solve the y basis vector simultaneously to get the other
1353 // two affine parameters directly from these parameters
1354
1355 const lam = (a * c + b * d) / determinant;
1356 const sy = c * sx / (lam * a - b) || d * sx / (lam * b + a); // Use the translations
1357
1358 const tx = e - cx + cx * ct * sx + cy * (lam * ct * sx - st * sy);
1359 const ty = f - cy + cx * st * sx + cy * (lam * st * sx + ct * sy); // Construct the decomposition and return it
1360
1361 return {
1362 // Return the affine parameters
1363 scaleX: sx,
1364 scaleY: sy,
1365 shear: lam,
1366 rotate: theta,
1367 translateX: tx,
1368 translateY: ty,
1369 originX: cx,
1370 originY: cy,
1371 // Return the matrix parameters
1372 a: this.a,
1373 b: this.b,
1374 c: this.c,
1375 d: this.d,
1376 e: this.e,
1377 f: this.f
1378 };
1379 } // Check if two matrices are equal
1380
1381
1382 equals(other) {
1383 if (other === this) return true;
1384 const comp = new Matrix(other);
1385 return closeEnough(this.a, comp.a) && closeEnough(this.b, comp.b) && closeEnough(this.c, comp.c) && closeEnough(this.d, comp.d) && closeEnough(this.e, comp.e) && closeEnough(this.f, comp.f);
1386 } // Flip matrix on x or y, at a given offset
1387
1388
1389 flip(axis, around) {
1390 return this.clone().flipO(axis, around);
1391 }
1392
1393 flipO(axis, around) {
1394 return axis === 'x' ? this.scaleO(-1, 1, around, 0) : axis === 'y' ? this.scaleO(1, -1, 0, around) : this.scaleO(-1, -1, axis, around || axis); // Define an x, y flip point
1395 } // Initialize
1396
1397
1398 init(source) {
1399 const base = Matrix.fromArray([1, 0, 0, 1, 0, 0]); // ensure source as object
1400
1401 source = source instanceof Element ? source.matrixify() : typeof source === 'string' ? Matrix.fromArray(source.split(delimiter).map(parseFloat)) : Array.isArray(source) ? Matrix.fromArray(source) : typeof source === 'object' && Matrix.isMatrixLike(source) ? source : typeof source === 'object' ? new Matrix().transform(source) : arguments.length === 6 ? Matrix.fromArray([].slice.call(arguments)) : base; // Merge the source matrix with the base matrix
1402
1403 this.a = source.a != null ? source.a : base.a;
1404 this.b = source.b != null ? source.b : base.b;
1405 this.c = source.c != null ? source.c : base.c;
1406 this.d = source.d != null ? source.d : base.d;
1407 this.e = source.e != null ? source.e : base.e;
1408 this.f = source.f != null ? source.f : base.f;
1409 return this;
1410 }
1411
1412 inverse() {
1413 return this.clone().inverseO();
1414 } // Inverses matrix
1415
1416
1417 inverseO() {
1418 // Get the current parameters out of the matrix
1419 const a = this.a;
1420 const b = this.b;
1421 const c = this.c;
1422 const d = this.d;
1423 const e = this.e;
1424 const f = this.f; // Invert the 2x2 matrix in the top left
1425
1426 const det = a * d - b * c;
1427 if (!det) throw new Error('Cannot invert ' + this); // Calculate the top 2x2 matrix
1428
1429 const na = d / det;
1430 const nb = -b / det;
1431 const nc = -c / det;
1432 const nd = a / det; // Apply the inverted matrix to the top right
1433
1434 const ne = -(na * e + nc * f);
1435 const nf = -(nb * e + nd * f); // Construct the inverted matrix
1436
1437 this.a = na;
1438 this.b = nb;
1439 this.c = nc;
1440 this.d = nd;
1441 this.e = ne;
1442 this.f = nf;
1443 return this;
1444 }
1445
1446 lmultiply(matrix) {
1447 return this.clone().lmultiplyO(matrix);
1448 }
1449
1450 lmultiplyO(matrix) {
1451 const r = this;
1452 const l = matrix instanceof Matrix ? matrix : new Matrix(matrix);
1453 return Matrix.matrixMultiply(l, r, this);
1454 } // Left multiplies by the given matrix
1455
1456
1457 multiply(matrix) {
1458 return this.clone().multiplyO(matrix);
1459 }
1460
1461 multiplyO(matrix) {
1462 // Get the matrices
1463 const l = this;
1464 const r = matrix instanceof Matrix ? matrix : new Matrix(matrix);
1465 return Matrix.matrixMultiply(l, r, this);
1466 } // Rotate matrix
1467
1468
1469 rotate(r, cx, cy) {
1470 return this.clone().rotateO(r, cx, cy);
1471 }
1472
1473 rotateO(r, cx = 0, cy = 0) {
1474 // Convert degrees to radians
1475 r = radians(r);
1476 const cos = Math.cos(r);
1477 const sin = Math.sin(r);
1478 const {
1479 a,
1480 b,
1481 c,
1482 d,
1483 e,
1484 f
1485 } = this;
1486 this.a = a * cos - b * sin;
1487 this.b = b * cos + a * sin;
1488 this.c = c * cos - d * sin;
1489 this.d = d * cos + c * sin;
1490 this.e = e * cos - f * sin + cy * sin - cx * cos + cx;
1491 this.f = f * cos + e * sin - cx * sin - cy * cos + cy;
1492 return this;
1493 } // Scale matrix
1494
1495
1496 scale(x, y, cx, cy) {
1497 return this.clone().scaleO(...arguments);
1498 }
1499
1500 scaleO(x, y = x, cx = 0, cy = 0) {
1501 // Support uniform scaling
1502 if (arguments.length === 3) {
1503 cy = cx;
1504 cx = y;
1505 y = x;
1506 }
1507
1508 const {
1509 a,
1510 b,
1511 c,
1512 d,
1513 e,
1514 f
1515 } = this;
1516 this.a = a * x;
1517 this.b = b * y;
1518 this.c = c * x;
1519 this.d = d * y;
1520 this.e = e * x - cx * x + cx;
1521 this.f = f * y - cy * y + cy;
1522 return this;
1523 } // Shear matrix
1524
1525
1526 shear(a, cx, cy) {
1527 return this.clone().shearO(a, cx, cy);
1528 }
1529
1530 shearO(lx, cx = 0, cy = 0) {
1531 const {
1532 a,
1533 b,
1534 c,
1535 d,
1536 e,
1537 f
1538 } = this;
1539 this.a = a + b * lx;
1540 this.c = c + d * lx;
1541 this.e = e + f * lx - cy * lx;
1542 return this;
1543 } // Skew Matrix
1544
1545
1546 skew(x, y, cx, cy) {
1547 return this.clone().skewO(...arguments);
1548 }
1549
1550 skewO(x, y = x, cx = 0, cy = 0) {
1551 // support uniformal skew
1552 if (arguments.length === 3) {
1553 cy = cx;
1554 cx = y;
1555 y = x;
1556 } // Convert degrees to radians
1557
1558
1559 x = radians(x);
1560 y = radians(y);
1561 const lx = Math.tan(x);
1562 const ly = Math.tan(y);
1563 const {
1564 a,
1565 b,
1566 c,
1567 d,
1568 e,
1569 f
1570 } = this;
1571 this.a = a + b * lx;
1572 this.b = b + a * ly;
1573 this.c = c + d * lx;
1574 this.d = d + c * ly;
1575 this.e = e + f * lx - cy * lx;
1576 this.f = f + e * ly - cx * ly;
1577 return this;
1578 } // SkewX
1579
1580
1581 skewX(x, cx, cy) {
1582 return this.skew(x, 0, cx, cy);
1583 } // SkewY
1584
1585
1586 skewY(y, cx, cy) {
1587 return this.skew(0, y, cx, cy);
1588 }
1589
1590 toArray() {
1591 return [this.a, this.b, this.c, this.d, this.e, this.f];
1592 } // Convert matrix to string
1593
1594
1595 toString() {
1596 return 'matrix(' + this.a + ',' + this.b + ',' + this.c + ',' + this.d + ',' + this.e + ',' + this.f + ')';
1597 } // Transform a matrix into another matrix by manipulating the space
1598
1599
1600 transform(o) {
1601 // Check if o is a matrix and then left multiply it directly
1602 if (Matrix.isMatrixLike(o)) {
1603 const matrix = new Matrix(o);
1604 return matrix.multiplyO(this);
1605 } // Get the proposed transformations and the current transformations
1606
1607
1608 const t = Matrix.formatTransforms(o);
1609 const current = this;
1610 const {
1611 x: ox,
1612 y: oy
1613 } = new Point(t.ox, t.oy).transform(current); // Construct the resulting matrix
1614
1615 const transformer = new Matrix().translateO(t.rx, t.ry).lmultiplyO(current).translateO(-ox, -oy).scaleO(t.scaleX, t.scaleY).skewO(t.skewX, t.skewY).shearO(t.shear).rotateO(t.theta).translateO(ox, oy); // If we want the origin at a particular place, we force it there
1616
1617 if (isFinite(t.px) || isFinite(t.py)) {
1618 const origin = new Point(ox, oy).transform(transformer); // TODO: Replace t.px with isFinite(t.px)
1619 // Doesnt work because t.px is also 0 if it wasnt passed
1620
1621 const dx = isFinite(t.px) ? t.px - origin.x : 0;
1622 const dy = isFinite(t.py) ? t.py - origin.y : 0;
1623 transformer.translateO(dx, dy);
1624 } // Translate now after positioning
1625
1626
1627 transformer.translateO(t.tx, t.ty);
1628 return transformer;
1629 } // Translate matrix
1630
1631
1632 translate(x, y) {
1633 return this.clone().translateO(x, y);
1634 }
1635
1636 translateO(x, y) {
1637 this.e += x || 0;
1638 this.f += y || 0;
1639 return this;
1640 }
1641
1642 valueOf() {
1643 return {
1644 a: this.a,
1645 b: this.b,
1646 c: this.c,
1647 d: this.d,
1648 e: this.e,
1649 f: this.f
1650 };
1651 }
1652
1653 }
1654 function ctm() {
1655 return new Matrix(this.node.getCTM());
1656 }
1657 function screenCTM() {
1658 /* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537
1659 This is needed because FF does not return the transformation matrix
1660 for the inner coordinate system when getScreenCTM() is called on nested svgs.
1661 However all other Browsers do that */
1662 if (typeof this.isRoot === 'function' && !this.isRoot()) {
1663 const rect = this.rect(1, 1);
1664 const m = rect.node.getScreenCTM();
1665 rect.remove();
1666 return new Matrix(m);
1667 }
1668
1669 return new Matrix(this.node.getScreenCTM());
1670 }
1671 register(Matrix, 'Matrix');
1672
1673 function parser() {
1674 // Reuse cached element if possible
1675 if (!parser.nodes) {
1676 const svg = makeInstance().size(2, 0);
1677 svg.node.style.cssText = ['opacity: 0', 'position: absolute', 'left: -100%', 'top: -100%', 'overflow: hidden'].join(';');
1678 svg.attr('focusable', 'false');
1679 svg.attr('aria-hidden', 'true');
1680 const path = svg.path().node;
1681 parser.nodes = {
1682 svg,
1683 path
1684 };
1685 }
1686
1687 if (!parser.nodes.svg.node.parentNode) {
1688 const b = globals.document.body || globals.document.documentElement;
1689 parser.nodes.svg.addTo(b);
1690 }
1691
1692 return parser.nodes;
1693 }
1694
1695 function isNulledBox(box) {
1696 return !box.width && !box.height && !box.x && !box.y;
1697 }
1698 function domContains(node) {
1699 return node === globals.document || (globals.document.documentElement.contains || function (node) {
1700 // This is IE - it does not support contains() for top-level SVGs
1701 while (node.parentNode) {
1702 node = node.parentNode;
1703 }
1704
1705 return node === globals.document;
1706 }).call(globals.document.documentElement, node);
1707 }
1708 class Box {
1709 constructor(...args) {
1710 this.init(...args);
1711 }
1712
1713 addOffset() {
1714 // offset by window scroll position, because getBoundingClientRect changes when window is scrolled
1715 this.x += globals.window.pageXOffset;
1716 this.y += globals.window.pageYOffset;
1717 return new Box(this);
1718 }
1719
1720 init(source) {
1721 const base = [0, 0, 0, 0];
1722 source = typeof source === 'string' ? source.split(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;
1723 this.x = source[0] || 0;
1724 this.y = source[1] || 0;
1725 this.width = this.w = source[2] || 0;
1726 this.height = this.h = source[3] || 0; // Add more bounding box properties
1727
1728 this.x2 = this.x + this.w;
1729 this.y2 = this.y + this.h;
1730 this.cx = this.x + this.w / 2;
1731 this.cy = this.y + this.h / 2;
1732 return this;
1733 }
1734
1735 isNulled() {
1736 return isNulledBox(this);
1737 } // Merge rect box with another, return a new instance
1738
1739
1740 merge(box) {
1741 const x = Math.min(this.x, box.x);
1742 const y = Math.min(this.y, box.y);
1743 const width = Math.max(this.x + this.width, box.x + box.width) - x;
1744 const height = Math.max(this.y + this.height, box.y + box.height) - y;
1745 return new Box(x, y, width, height);
1746 }
1747
1748 toArray() {
1749 return [this.x, this.y, this.width, this.height];
1750 }
1751
1752 toString() {
1753 return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height;
1754 }
1755
1756 transform(m) {
1757 if (!(m instanceof Matrix)) {
1758 m = new Matrix(m);
1759 }
1760
1761 let xMin = Infinity;
1762 let xMax = -Infinity;
1763 let yMin = Infinity;
1764 let yMax = -Infinity;
1765 const pts = [new Point(this.x, this.y), new Point(this.x2, this.y), new Point(this.x, this.y2), new Point(this.x2, this.y2)];
1766 pts.forEach(function (p) {
1767 p = p.transform(m);
1768 xMin = Math.min(xMin, p.x);
1769 xMax = Math.max(xMax, p.x);
1770 yMin = Math.min(yMin, p.y);
1771 yMax = Math.max(yMax, p.y);
1772 });
1773 return new Box(xMin, yMin, xMax - xMin, yMax - yMin);
1774 }
1775
1776 }
1777
1778 function getBox(el, getBBoxFn, retry) {
1779 let box;
1780
1781 try {
1782 // Try to get the box with the provided function
1783 box = getBBoxFn(el.node); // If the box is worthless and not even in the dom, retry
1784 // by throwing an error here...
1785
1786 if (isNulledBox(box) && !domContains(el.node)) {
1787 throw new Error('Element not in the dom');
1788 }
1789 } catch (e) {
1790 // ... and calling the retry handler here
1791 box = retry(el);
1792 }
1793
1794 return box;
1795 }
1796
1797 function bbox() {
1798 // Function to get bbox is getBBox()
1799 const getBBox = node => node.getBBox(); // Take all measures so that a stupid browser renders the element
1800 // so we can get the bbox from it when we try again
1801
1802
1803 const retry = el => {
1804 try {
1805 const clone = el.clone().addTo(parser().svg).show();
1806 const box = clone.node.getBBox();
1807 clone.remove();
1808 return box;
1809 } catch (e) {
1810 // We give up...
1811 throw new Error(`Getting bbox of element "${el.node.nodeName}" is not possible: ${e.toString()}`);
1812 }
1813 };
1814
1815 const box = getBox(this, getBBox, retry);
1816 const bbox = new Box(box);
1817 return bbox;
1818 }
1819 function rbox(el) {
1820 const getRBox = node => node.getBoundingClientRect();
1821
1822 const retry = el => {
1823 // There is no point in trying tricks here because if we insert the element into the dom ourselves
1824 // it obviously will be at the wrong position
1825 throw new Error(`Getting rbox of element "${el.node.nodeName}" is not possible`);
1826 };
1827
1828 const box = getBox(this, getRBox, retry);
1829 const rbox = new Box(box); // If an element was passed, we want the bbox in the coordinate system of that element
1830
1831 if (el) {
1832 return rbox.transform(el.screenCTM().inverseO());
1833 } // Else we want it in absolute screen coordinates
1834 // Therefore we need to add the scrollOffset
1835
1836
1837 return rbox.addOffset();
1838 } // Checks whether the given point is inside the bounding box
1839
1840 function inside(x, y) {
1841 const box = this.bbox();
1842 return x > box.x && y > box.y && x < box.x + box.width && y < box.y + box.height;
1843 }
1844 registerMethods({
1845 viewbox: {
1846 viewbox(x, y, width, height) {
1847 // act as getter
1848 if (x == null) return new Box(this.attr('viewBox')); // act as setter
1849
1850 return this.attr('viewBox', new Box(x, y, width, height));
1851 },
1852
1853 zoom(level, point) {
1854 // Its best to rely on the attributes here and here is why:
1855 // clientXYZ: Doesn't work on non-root svgs because they dont have a CSSBox (silly!)
1856 // getBoundingClientRect: Doesn't work because Chrome just ignores width and height of nested svgs completely
1857 // that means, their clientRect is always as big as the content.
1858 // Furthermore this size is incorrect if the element is further transformed by its parents
1859 // computedStyle: Only returns meaningful values if css was used with px. We dont go this route here!
1860 // getBBox: returns the bounding box of its content - that doesnt help!
1861 let {
1862 width,
1863 height
1864 } = this.attr(['width', 'height']); // Width and height is a string when a number with a unit is present which we can't use
1865 // So we try clientXYZ
1866
1867 if (!width && !height || typeof width === 'string' || typeof height === 'string') {
1868 width = this.node.clientWidth;
1869 height = this.node.clientHeight;
1870 } // Giving up...
1871
1872
1873 if (!width || !height) {
1874 throw new Error('Impossible to get absolute width and height. Please provide an absolute width and height attribute on the zooming element');
1875 }
1876
1877 const v = this.viewbox();
1878 const zoomX = width / v.width;
1879 const zoomY = height / v.height;
1880 const zoom = Math.min(zoomX, zoomY);
1881
1882 if (level == null) {
1883 return zoom;
1884 }
1885
1886 let zoomAmount = zoom / level; // Set the zoomAmount to the highest value which is safe to process and recover from
1887 // The * 100 is a bit of wiggle room for the matrix transformation
1888
1889 if (zoomAmount === Infinity) zoomAmount = Number.MAX_SAFE_INTEGER / 100;
1890 point = point || new Point(width / 2 / zoomX + v.x, height / 2 / zoomY + v.y);
1891 const box = new Box(v).transform(new Matrix({
1892 scale: zoomAmount,
1893 origin: point
1894 }));
1895 return this.viewbox(box);
1896 }
1897
1898 }
1899 });
1900 register(Box, 'Box');
1901
1902 class List extends Array {
1903 constructor(arr = [], ...args) {
1904 super(arr, ...args);
1905 if (typeof arr === 'number') return this;
1906 this.length = 0;
1907 this.push(...arr);
1908 }
1909
1910 }
1911 extend([List], {
1912 each(fnOrMethodName, ...args) {
1913 if (typeof fnOrMethodName === 'function') {
1914 return this.map((el, i, arr) => {
1915 return fnOrMethodName.call(el, el, i, arr);
1916 });
1917 } else {
1918 return this.map(el => {
1919 return el[fnOrMethodName](...args);
1920 });
1921 }
1922 },
1923
1924 toArray() {
1925 return Array.prototype.concat.apply([], this);
1926 }
1927
1928 });
1929 const reserved = ['toArray', 'constructor', 'each'];
1930
1931 List.extend = function (methods) {
1932 methods = methods.reduce((obj, name) => {
1933 // Don't overwrite own methods
1934 if (reserved.includes(name)) return obj; // Don't add private methods
1935
1936 if (name[0] === '_') return obj; // Relay every call to each()
1937
1938 obj[name] = function (...attrs) {
1939 return this.each(name, ...attrs);
1940 };
1941
1942 return obj;
1943 }, {});
1944 extend([List], methods);
1945 };
1946
1947 function baseFind(query, parent) {
1948 return new List(map((parent || globals.document).querySelectorAll(query), function (node) {
1949 return adopt(node);
1950 }));
1951 } // Scoped find method
1952
1953 function find(query) {
1954 return baseFind(query, this.node);
1955 }
1956 function findOne(query) {
1957 return adopt(this.node.querySelector(query));
1958 }
1959
1960 let listenerId = 0;
1961 const windowEvents = {};
1962 function getEvents(instance) {
1963 let n = instance.getEventHolder(); // We dont want to save events in global space
1964
1965 if (n === globals.window) n = windowEvents;
1966 if (!n.events) n.events = {};
1967 return n.events;
1968 }
1969 function getEventTarget(instance) {
1970 return instance.getEventTarget();
1971 }
1972 function clearEvents(instance) {
1973 let n = instance.getEventHolder();
1974 if (n === globals.window) n = windowEvents;
1975 if (n.events) n.events = {};
1976 } // Add event binder in the SVG namespace
1977
1978 function on(node, events, listener, binding, options) {
1979 const l = listener.bind(binding || node);
1980 const instance = makeInstance(node);
1981 const bag = getEvents(instance);
1982 const n = getEventTarget(instance); // events can be an array of events or a string of events
1983
1984 events = Array.isArray(events) ? events : events.split(delimiter); // add id to listener
1985
1986 if (!listener._svgjsListenerId) {
1987 listener._svgjsListenerId = ++listenerId;
1988 }
1989
1990 events.forEach(function (event) {
1991 const ev = event.split('.')[0];
1992 const ns = event.split('.')[1] || '*'; // ensure valid object
1993
1994 bag[ev] = bag[ev] || {};
1995 bag[ev][ns] = bag[ev][ns] || {}; // reference listener
1996
1997 bag[ev][ns][listener._svgjsListenerId] = l; // add listener
1998
1999 n.addEventListener(ev, l, options || false);
2000 });
2001 } // Add event unbinder in the SVG namespace
2002
2003 function off(node, events, listener, options) {
2004 const instance = makeInstance(node);
2005 const bag = getEvents(instance);
2006 const n = getEventTarget(instance); // listener can be a function or a number
2007
2008 if (typeof listener === 'function') {
2009 listener = listener._svgjsListenerId;
2010 if (!listener) return;
2011 } // events can be an array of events or a string or undefined
2012
2013
2014 events = Array.isArray(events) ? events : (events || '').split(delimiter);
2015 events.forEach(function (event) {
2016 const ev = event && event.split('.')[0];
2017 const ns = event && event.split('.')[1];
2018 let namespace, l;
2019
2020 if (listener) {
2021 // remove listener reference
2022 if (bag[ev] && bag[ev][ns || '*']) {
2023 // removeListener
2024 n.removeEventListener(ev, bag[ev][ns || '*'][listener], options || false);
2025 delete bag[ev][ns || '*'][listener];
2026 }
2027 } else if (ev && ns) {
2028 // remove all listeners for a namespaced event
2029 if (bag[ev] && bag[ev][ns]) {
2030 for (l in bag[ev][ns]) {
2031 off(n, [ev, ns].join('.'), l);
2032 }
2033
2034 delete bag[ev][ns];
2035 }
2036 } else if (ns) {
2037 // remove all listeners for a specific namespace
2038 for (event in bag) {
2039 for (namespace in bag[event]) {
2040 if (ns === namespace) {
2041 off(n, [event, ns].join('.'));
2042 }
2043 }
2044 }
2045 } else if (ev) {
2046 // remove all listeners for the event
2047 if (bag[ev]) {
2048 for (namespace in bag[ev]) {
2049 off(n, [ev, namespace].join('.'));
2050 }
2051
2052 delete bag[ev];
2053 }
2054 } else {
2055 // remove all listeners on a given node
2056 for (event in bag) {
2057 off(n, event);
2058 }
2059
2060 clearEvents(instance);
2061 }
2062 });
2063 }
2064 function dispatch(node, event, data, options) {
2065 const n = getEventTarget(node); // Dispatch event
2066
2067 if (event instanceof globals.window.Event) {
2068 n.dispatchEvent(event);
2069 } else {
2070 event = new globals.window.CustomEvent(event, {
2071 detail: data,
2072 cancelable: true,
2073 ...options
2074 });
2075 n.dispatchEvent(event);
2076 }
2077
2078 return event;
2079 }
2080
2081 class EventTarget extends Base {
2082 addEventListener() {}
2083
2084 dispatch(event, data, options) {
2085 return dispatch(this, event, data, options);
2086 }
2087
2088 dispatchEvent(event) {
2089 const bag = this.getEventHolder().events;
2090 if (!bag) return true;
2091 const events = bag[event.type];
2092
2093 for (const i in events) {
2094 for (const j in events[i]) {
2095 events[i][j](event);
2096 }
2097 }
2098
2099 return !event.defaultPrevented;
2100 } // Fire given event
2101
2102
2103 fire(event, data, options) {
2104 this.dispatch(event, data, options);
2105 return this;
2106 }
2107
2108 getEventHolder() {
2109 return this;
2110 }
2111
2112 getEventTarget() {
2113 return this;
2114 } // Unbind event from listener
2115
2116
2117 off(event, listener, options) {
2118 off(this, event, listener, options);
2119 return this;
2120 } // Bind given event to listener
2121
2122
2123 on(event, listener, binding, options) {
2124 on(this, event, listener, binding, options);
2125 return this;
2126 }
2127
2128 removeEventListener() {}
2129
2130 }
2131 register(EventTarget, 'EventTarget');
2132
2133 function noop() {} // Default animation values
2134
2135 const timeline = {
2136 duration: 400,
2137 ease: '>',
2138 delay: 0
2139 }; // Default attribute values
2140
2141 const attrs = {
2142 // fill and stroke
2143 'fill-opacity': 1,
2144 'stroke-opacity': 1,
2145 'stroke-width': 0,
2146 'stroke-linejoin': 'miter',
2147 'stroke-linecap': 'butt',
2148 fill: '#000000',
2149 stroke: '#000000',
2150 opacity: 1,
2151 // position
2152 x: 0,
2153 y: 0,
2154 cx: 0,
2155 cy: 0,
2156 // size
2157 width: 0,
2158 height: 0,
2159 // radius
2160 r: 0,
2161 rx: 0,
2162 ry: 0,
2163 // gradient
2164 offset: 0,
2165 'stop-opacity': 1,
2166 'stop-color': '#000000',
2167 // text
2168 'text-anchor': 'start'
2169 };
2170
2171 var defaults = {
2172 __proto__: null,
2173 noop: noop,
2174 timeline: timeline,
2175 attrs: attrs
2176 };
2177
2178 class SVGArray extends Array {
2179 constructor(...args) {
2180 super(...args);
2181 this.init(...args);
2182 }
2183
2184 clone() {
2185 return new this.constructor(this);
2186 }
2187
2188 init(arr) {
2189 // This catches the case, that native map tries to create an array with new Array(1)
2190 if (typeof arr === 'number') return this;
2191 this.length = 0;
2192 this.push(...this.parse(arr));
2193 return this;
2194 } // Parse whitespace separated string
2195
2196
2197 parse(array = []) {
2198 // If already is an array, no need to parse it
2199 if (array instanceof Array) return array;
2200 return array.trim().split(delimiter).map(parseFloat);
2201 }
2202
2203 toArray() {
2204 return Array.prototype.concat.apply([], this);
2205 }
2206
2207 toSet() {
2208 return new Set(this);
2209 }
2210
2211 toString() {
2212 return this.join(' ');
2213 } // Flattens the array if needed
2214
2215
2216 valueOf() {
2217 const ret = [];
2218 ret.push(...this);
2219 return ret;
2220 }
2221
2222 }
2223
2224 class SVGNumber {
2225 // Initialize
2226 constructor(...args) {
2227 this.init(...args);
2228 }
2229
2230 convert(unit) {
2231 return new SVGNumber(this.value, unit);
2232 } // Divide number
2233
2234
2235 divide(number) {
2236 number = new SVGNumber(number);
2237 return new SVGNumber(this / number, this.unit || number.unit);
2238 }
2239
2240 init(value, unit) {
2241 unit = Array.isArray(value) ? value[1] : unit;
2242 value = Array.isArray(value) ? value[0] : value; // initialize defaults
2243
2244 this.value = 0;
2245 this.unit = unit || ''; // parse value
2246
2247 if (typeof value === 'number') {
2248 // ensure a valid numeric value
2249 this.value = isNaN(value) ? 0 : !isFinite(value) ? value < 0 ? -3.4e+38 : +3.4e+38 : value;
2250 } else if (typeof value === 'string') {
2251 unit = value.match(numberAndUnit);
2252
2253 if (unit) {
2254 // make value numeric
2255 this.value = parseFloat(unit[1]); // normalize
2256
2257 if (unit[5] === '%') {
2258 this.value /= 100;
2259 } else if (unit[5] === 's') {
2260 this.value *= 1000;
2261 } // store unit
2262
2263
2264 this.unit = unit[5];
2265 }
2266 } else {
2267 if (value instanceof SVGNumber) {
2268 this.value = value.valueOf();
2269 this.unit = value.unit;
2270 }
2271 }
2272
2273 return this;
2274 } // Subtract number
2275
2276
2277 minus(number) {
2278 number = new SVGNumber(number);
2279 return new SVGNumber(this - number, this.unit || number.unit);
2280 } // Add number
2281
2282
2283 plus(number) {
2284 number = new SVGNumber(number);
2285 return new SVGNumber(this + number, this.unit || number.unit);
2286 } // Multiply number
2287
2288
2289 times(number) {
2290 number = new SVGNumber(number);
2291 return new SVGNumber(this * number, this.unit || number.unit);
2292 }
2293
2294 toArray() {
2295 return [this.value, this.unit];
2296 }
2297
2298 toJSON() {
2299 return this.toString();
2300 }
2301
2302 toString() {
2303 return (this.unit === '%' ? ~~(this.value * 1e8) / 1e6 : this.unit === 's' ? this.value / 1e3 : this.value) + this.unit;
2304 }
2305
2306 valueOf() {
2307 return this.value;
2308 }
2309
2310 }
2311
2312 const hooks = [];
2313 function registerAttrHook(fn) {
2314 hooks.push(fn);
2315 } // Set svg element attribute
2316
2317 function attr(attr, val, ns) {
2318 // act as full getter
2319 if (attr == null) {
2320 // get an object of attributes
2321 attr = {};
2322 val = this.node.attributes;
2323
2324 for (const node of val) {
2325 attr[node.nodeName] = isNumber.test(node.nodeValue) ? parseFloat(node.nodeValue) : node.nodeValue;
2326 }
2327
2328 return attr;
2329 } else if (attr instanceof Array) {
2330 // loop through array and get all values
2331 return attr.reduce((last, curr) => {
2332 last[curr] = this.attr(curr);
2333 return last;
2334 }, {});
2335 } else if (typeof attr === 'object' && attr.constructor === Object) {
2336 // apply every attribute individually if an object is passed
2337 for (val in attr) this.attr(val, attr[val]);
2338 } else if (val === null) {
2339 // remove value
2340 this.node.removeAttribute(attr);
2341 } else if (val == null) {
2342 // act as a getter if the first and only argument is not an object
2343 val = this.node.getAttribute(attr);
2344 return val == null ? attrs[attr] : isNumber.test(val) ? parseFloat(val) : val;
2345 } else {
2346 // Loop through hooks and execute them to convert value
2347 val = hooks.reduce((_val, hook) => {
2348 return hook(attr, _val, this);
2349 }, val); // ensure correct numeric values (also accepts NaN and Infinity)
2350
2351 if (typeof val === 'number') {
2352 val = new SVGNumber(val);
2353 } else if (Color.isColor(val)) {
2354 // ensure full hex color
2355 val = new Color(val);
2356 } else if (val.constructor === Array) {
2357 // Check for plain arrays and parse array values
2358 val = new SVGArray(val);
2359 } // if the passed attribute is leading...
2360
2361
2362 if (attr === 'leading') {
2363 // ... call the leading method instead
2364 if (this.leading) {
2365 this.leading(val);
2366 }
2367 } else {
2368 // set given attribute on node
2369 typeof ns === 'string' ? this.node.setAttributeNS(ns, attr, val.toString()) : this.node.setAttribute(attr, val.toString());
2370 } // rebuild if required
2371
2372
2373 if (this.rebuild && (attr === 'font-size' || attr === 'x')) {
2374 this.rebuild();
2375 }
2376 }
2377
2378 return this;
2379 }
2380
2381 class Dom extends EventTarget {
2382 constructor(node, attrs) {
2383 super();
2384 this.node = node;
2385 this.type = node.nodeName;
2386
2387 if (attrs && node !== attrs) {
2388 this.attr(attrs);
2389 }
2390 } // Add given element at a position
2391
2392
2393 add(element, i) {
2394 element = makeInstance(element); // If non-root svg nodes are added we have to remove their namespaces
2395
2396 if (element.removeNamespace && this.node instanceof globals.window.SVGElement) {
2397 element.removeNamespace();
2398 }
2399
2400 if (i == null) {
2401 this.node.appendChild(element.node);
2402 } else if (element.node !== this.node.childNodes[i]) {
2403 this.node.insertBefore(element.node, this.node.childNodes[i]);
2404 }
2405
2406 return this;
2407 } // Add element to given container and return self
2408
2409
2410 addTo(parent, i) {
2411 return makeInstance(parent).put(this, i);
2412 } // Returns all child elements
2413
2414
2415 children() {
2416 return new List(map(this.node.children, function (node) {
2417 return adopt(node);
2418 }));
2419 } // Remove all elements in this container
2420
2421
2422 clear() {
2423 // remove children
2424 while (this.node.hasChildNodes()) {
2425 this.node.removeChild(this.node.lastChild);
2426 }
2427
2428 return this;
2429 } // Clone element
2430
2431
2432 clone(deep = true) {
2433 // write dom data to the dom so the clone can pickup the data
2434 this.writeDataToDom(); // clone element and assign new id
2435
2436 return new this.constructor(assignNewId(this.node.cloneNode(deep)));
2437 } // Iterates over all children and invokes a given block
2438
2439
2440 each(block, deep) {
2441 const children = this.children();
2442 let i, il;
2443
2444 for (i = 0, il = children.length; i < il; i++) {
2445 block.apply(children[i], [i, children]);
2446
2447 if (deep) {
2448 children[i].each(block, deep);
2449 }
2450 }
2451
2452 return this;
2453 }
2454
2455 element(nodeName, attrs) {
2456 return this.put(new Dom(create(nodeName), attrs));
2457 } // Get first child
2458
2459
2460 first() {
2461 return adopt(this.node.firstChild);
2462 } // Get a element at the given index
2463
2464
2465 get(i) {
2466 return adopt(this.node.childNodes[i]);
2467 }
2468
2469 getEventHolder() {
2470 return this.node;
2471 }
2472
2473 getEventTarget() {
2474 return this.node;
2475 } // Checks if the given element is a child
2476
2477
2478 has(element) {
2479 return this.index(element) >= 0;
2480 }
2481
2482 html(htmlOrFn, outerHTML) {
2483 return this.xml(htmlOrFn, outerHTML, html);
2484 } // Get / set id
2485
2486
2487 id(id) {
2488 // generate new id if no id set
2489 if (typeof id === 'undefined' && !this.node.id) {
2490 this.node.id = eid(this.type);
2491 } // don't set directly with this.node.id to make `null` work correctly
2492
2493
2494 return this.attr('id', id);
2495 } // Gets index of given element
2496
2497
2498 index(element) {
2499 return [].slice.call(this.node.childNodes).indexOf(element.node);
2500 } // Get the last child
2501
2502
2503 last() {
2504 return adopt(this.node.lastChild);
2505 } // matches the element vs a css selector
2506
2507
2508 matches(selector) {
2509 const el = this.node;
2510 const matcher = el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector || null;
2511 return matcher && matcher.call(el, selector);
2512 } // Returns the parent element instance
2513
2514
2515 parent(type) {
2516 let parent = this; // check for parent
2517
2518 if (!parent.node.parentNode) return null; // get parent element
2519
2520 parent = adopt(parent.node.parentNode);
2521 if (!type) return parent; // loop trough ancestors if type is given
2522
2523 do {
2524 if (typeof type === 'string' ? parent.matches(type) : parent instanceof type) return parent;
2525 } while (parent = adopt(parent.node.parentNode));
2526
2527 return parent;
2528 } // Basically does the same as `add()` but returns the added element instead
2529
2530
2531 put(element, i) {
2532 element = makeInstance(element);
2533 this.add(element, i);
2534 return element;
2535 } // Add element to given container and return container
2536
2537
2538 putIn(parent, i) {
2539 return makeInstance(parent).add(this, i);
2540 } // Remove element
2541
2542
2543 remove() {
2544 if (this.parent()) {
2545 this.parent().removeElement(this);
2546 }
2547
2548 return this;
2549 } // Remove a given child
2550
2551
2552 removeElement(element) {
2553 this.node.removeChild(element.node);
2554 return this;
2555 } // Replace this with element
2556
2557
2558 replace(element) {
2559 element = makeInstance(element);
2560
2561 if (this.node.parentNode) {
2562 this.node.parentNode.replaceChild(element.node, this.node);
2563 }
2564
2565 return element;
2566 }
2567
2568 round(precision = 2, map = null) {
2569 const factor = 10 ** precision;
2570 const attrs = this.attr(map);
2571
2572 for (const i in attrs) {
2573 if (typeof attrs[i] === 'number') {
2574 attrs[i] = Math.round(attrs[i] * factor) / factor;
2575 }
2576 }
2577
2578 this.attr(attrs);
2579 return this;
2580 } // Import / Export raw svg
2581
2582
2583 svg(svgOrFn, outerSVG) {
2584 return this.xml(svgOrFn, outerSVG, svg);
2585 } // Return id on string conversion
2586
2587
2588 toString() {
2589 return this.id();
2590 }
2591
2592 words(text) {
2593 // This is faster than removing all children and adding a new one
2594 this.node.textContent = text;
2595 return this;
2596 }
2597
2598 wrap(node) {
2599 const parent = this.parent();
2600
2601 if (!parent) {
2602 return this.addTo(node);
2603 }
2604
2605 const position = parent.index(this);
2606 return parent.put(node, position).put(this);
2607 } // write svgjs data to the dom
2608
2609
2610 writeDataToDom() {
2611 // dump variables recursively
2612 this.each(function () {
2613 this.writeDataToDom();
2614 });
2615 return this;
2616 } // Import / Export raw svg
2617
2618
2619 xml(xmlOrFn, outerXML, ns) {
2620 if (typeof xmlOrFn === 'boolean') {
2621 ns = outerXML;
2622 outerXML = xmlOrFn;
2623 xmlOrFn = null;
2624 } // act as getter if no svg string is given
2625
2626
2627 if (xmlOrFn == null || typeof xmlOrFn === 'function') {
2628 // The default for exports is, that the outerNode is included
2629 outerXML = outerXML == null ? true : outerXML; // write svgjs data to the dom
2630
2631 this.writeDataToDom();
2632 let current = this; // An export modifier was passed
2633
2634 if (xmlOrFn != null) {
2635 current = adopt(current.node.cloneNode(true)); // If the user wants outerHTML we need to process this node, too
2636
2637 if (outerXML) {
2638 const result = xmlOrFn(current);
2639 current = result || current; // The user does not want this node? Well, then he gets nothing
2640
2641 if (result === false) return '';
2642 } // Deep loop through all children and apply modifier
2643
2644
2645 current.each(function () {
2646 const result = xmlOrFn(this);
2647
2648 const _this = result || this; // If modifier returns false, discard node
2649
2650
2651 if (result === false) {
2652 this.remove(); // If modifier returns new node, use it
2653 } else if (result && this !== _this) {
2654 this.replace(_this);
2655 }
2656 }, true);
2657 } // Return outer or inner content
2658
2659
2660 return outerXML ? current.node.outerHTML : current.node.innerHTML;
2661 } // Act as setter if we got a string
2662 // The default for import is, that the current node is not replaced
2663
2664
2665 outerXML = outerXML == null ? false : outerXML; // Create temporary holder
2666
2667 const well = create('wrapper', ns);
2668 const fragment = globals.document.createDocumentFragment(); // Dump raw svg
2669
2670 well.innerHTML = xmlOrFn; // Transplant nodes into the fragment
2671
2672 for (let len = well.children.length; len--;) {
2673 fragment.appendChild(well.firstElementChild);
2674 }
2675
2676 const parent = this.parent(); // Add the whole fragment at once
2677
2678 return outerXML ? this.replace(fragment) && parent : this.add(fragment);
2679 }
2680
2681 }
2682 extend(Dom, {
2683 attr,
2684 find,
2685 findOne
2686 });
2687 register(Dom, 'Dom');
2688
2689 class Element extends Dom {
2690 constructor(node, attrs) {
2691 super(node, attrs); // initialize data object
2692
2693 this.dom = {}; // create circular reference
2694
2695 this.node.instance = this;
2696
2697 if (node.hasAttribute('svgjs:data')) {
2698 // pull svgjs data from the dom (getAttributeNS doesn't work in html5)
2699 this.setData(JSON.parse(node.getAttribute('svgjs:data')) || {});
2700 }
2701 } // Move element by its center
2702
2703
2704 center(x, y) {
2705 return this.cx(x).cy(y);
2706 } // Move by center over x-axis
2707
2708
2709 cx(x) {
2710 return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2);
2711 } // Move by center over y-axis
2712
2713
2714 cy(y) {
2715 return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2);
2716 } // Get defs
2717
2718
2719 defs() {
2720 const root = this.root();
2721 return root && root.defs();
2722 } // Relative move over x and y axes
2723
2724
2725 dmove(x, y) {
2726 return this.dx(x).dy(y);
2727 } // Relative move over x axis
2728
2729
2730 dx(x = 0) {
2731 return this.x(new SVGNumber(x).plus(this.x()));
2732 } // Relative move over y axis
2733
2734
2735 dy(y = 0) {
2736 return this.y(new SVGNumber(y).plus(this.y()));
2737 }
2738
2739 getEventHolder() {
2740 return this;
2741 } // Set height of element
2742
2743
2744 height(height) {
2745 return this.attr('height', height);
2746 } // Move element to given x and y values
2747
2748
2749 move(x, y) {
2750 return this.x(x).y(y);
2751 } // return array of all ancestors of given type up to the root svg
2752
2753
2754 parents(until = this.root()) {
2755 const isSelector = typeof until === 'string';
2756
2757 if (!isSelector) {
2758 until = makeInstance(until);
2759 }
2760
2761 const parents = new List();
2762 let parent = this;
2763
2764 while ((parent = parent.parent()) && parent.node !== globals.document && parent.nodeName !== '#document-fragment') {
2765 parents.push(parent);
2766
2767 if (!isSelector && parent.node === until.node) {
2768 break;
2769 }
2770
2771 if (isSelector && parent.matches(until)) {
2772 break;
2773 }
2774
2775 if (parent.node === this.root().node) {
2776 // We worked our way to the root and didn't match `until`
2777 return null;
2778 }
2779 }
2780
2781 return parents;
2782 } // Get referenced element form attribute value
2783
2784
2785 reference(attr) {
2786 attr = this.attr(attr);
2787 if (!attr) return null;
2788 const m = (attr + '').match(reference);
2789 return m ? makeInstance(m[1]) : null;
2790 } // Get parent document
2791
2792
2793 root() {
2794 const p = this.parent(getClass(root));
2795 return p && p.root();
2796 } // set given data to the elements data property
2797
2798
2799 setData(o) {
2800 this.dom = o;
2801 return this;
2802 } // Set element size to given width and height
2803
2804
2805 size(width, height) {
2806 const p = proportionalSize(this, width, height);
2807 return this.width(new SVGNumber(p.width)).height(new SVGNumber(p.height));
2808 } // Set width of element
2809
2810
2811 width(width) {
2812 return this.attr('width', width);
2813 } // write svgjs data to the dom
2814
2815
2816 writeDataToDom() {
2817 // remove previously set data
2818 this.node.removeAttribute('svgjs:data');
2819
2820 if (Object.keys(this.dom).length) {
2821 this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)); // see #428
2822 }
2823
2824 return super.writeDataToDom();
2825 } // Move over x-axis
2826
2827
2828 x(x) {
2829 return this.attr('x', x);
2830 } // Move over y-axis
2831
2832
2833 y(y) {
2834 return this.attr('y', y);
2835 }
2836
2837 }
2838 extend(Element, {
2839 bbox,
2840 rbox,
2841 inside,
2842 point,
2843 ctm,
2844 screenCTM
2845 });
2846 register(Element, 'Element');
2847
2848 const sugar = {
2849 stroke: ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset'],
2850 fill: ['color', 'opacity', 'rule'],
2851 prefix: function (t, a) {
2852 return a === 'color' ? t : t + '-' + a;
2853 }
2854 } // Add sugar for fill and stroke
2855 ;
2856 ['fill', 'stroke'].forEach(function (m) {
2857 const extension = {};
2858 let i;
2859
2860 extension[m] = function (o) {
2861 if (typeof o === 'undefined') {
2862 return this.attr(m);
2863 }
2864
2865 if (typeof o === 'string' || o instanceof Color || Color.isRgb(o) || o instanceof Element) {
2866 this.attr(m, o);
2867 } else {
2868 // set all attributes from sugar.fill and sugar.stroke list
2869 for (i = sugar[m].length - 1; i >= 0; i--) {
2870 if (o[sugar[m][i]] != null) {
2871 this.attr(sugar.prefix(m, sugar[m][i]), o[sugar[m][i]]);
2872 }
2873 }
2874 }
2875
2876 return this;
2877 };
2878
2879 registerMethods(['Element', 'Runner'], extension);
2880 });
2881 registerMethods(['Element', 'Runner'], {
2882 // Let the user set the matrix directly
2883 matrix: function (mat, b, c, d, e, f) {
2884 // Act as a getter
2885 if (mat == null) {
2886 return new Matrix(this);
2887 } // Act as a setter, the user can pass a matrix or a set of numbers
2888
2889
2890 return this.attr('transform', new Matrix(mat, b, c, d, e, f));
2891 },
2892 // Map rotation to transform
2893 rotate: function (angle, cx, cy) {
2894 return this.transform({
2895 rotate: angle,
2896 ox: cx,
2897 oy: cy
2898 }, true);
2899 },
2900 // Map skew to transform
2901 skew: function (x, y, cx, cy) {
2902 return arguments.length === 1 || arguments.length === 3 ? this.transform({
2903 skew: x,
2904 ox: y,
2905 oy: cx
2906 }, true) : this.transform({
2907 skew: [x, y],
2908 ox: cx,
2909 oy: cy
2910 }, true);
2911 },
2912 shear: function (lam, cx, cy) {
2913 return this.transform({
2914 shear: lam,
2915 ox: cx,
2916 oy: cy
2917 }, true);
2918 },
2919 // Map scale to transform
2920 scale: function (x, y, cx, cy) {
2921 return arguments.length === 1 || arguments.length === 3 ? this.transform({
2922 scale: x,
2923 ox: y,
2924 oy: cx
2925 }, true) : this.transform({
2926 scale: [x, y],
2927 ox: cx,
2928 oy: cy
2929 }, true);
2930 },
2931 // Map translate to transform
2932 translate: function (x, y) {
2933 return this.transform({
2934 translate: [x, y]
2935 }, true);
2936 },
2937 // Map relative translations to transform
2938 relative: function (x, y) {
2939 return this.transform({
2940 relative: [x, y]
2941 }, true);
2942 },
2943 // Map flip to transform
2944 flip: function (direction = 'both', origin = 'center') {
2945 if ('xybothtrue'.indexOf(direction) === -1) {
2946 origin = direction;
2947 direction = 'both';
2948 }
2949
2950 return this.transform({
2951 flip: direction,
2952 origin: origin
2953 }, true);
2954 },
2955 // Opacity
2956 opacity: function (value) {
2957 return this.attr('opacity', value);
2958 }
2959 });
2960 registerMethods('radius', {
2961 // Add x and y radius
2962 radius: function (x, y = x) {
2963 const type = (this._element || this).type;
2964 return type === 'radialGradient' ? this.attr('r', new SVGNumber(x)) : this.rx(x).ry(y);
2965 }
2966 });
2967 registerMethods('Path', {
2968 // Get path length
2969 length: function () {
2970 return this.node.getTotalLength();
2971 },
2972 // Get point at length
2973 pointAt: function (length) {
2974 return new Point(this.node.getPointAtLength(length));
2975 }
2976 });
2977 registerMethods(['Element', 'Runner'], {
2978 // Set font
2979 font: function (a, v) {
2980 if (typeof a === 'object') {
2981 for (v in a) this.font(v, a[v]);
2982
2983 return this;
2984 }
2985
2986 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);
2987 }
2988 }); // Add events to elements
2989
2990 const methods = ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout', 'mousemove', 'mouseenter', 'mouseleave', 'touchstart', 'touchmove', 'touchleave', 'touchend', 'touchcancel'].reduce(function (last, event) {
2991 // add event to Element
2992 const fn = function (f) {
2993 if (f === null) {
2994 this.off(event);
2995 } else {
2996 this.on(event, f);
2997 }
2998
2999 return this;
3000 };
3001
3002 last[event] = fn;
3003 return last;
3004 }, {});
3005 registerMethods('Element', methods);
3006
3007 function untransform() {
3008 return this.attr('transform', null);
3009 } // merge the whole transformation chain into one matrix and returns it
3010
3011 function matrixify() {
3012 const matrix = (this.attr('transform') || '' // split transformations
3013 ).split(transforms).slice(0, -1).map(function (str) {
3014 // generate key => value pairs
3015 const kv = str.trim().split('(');
3016 return [kv[0], kv[1].split(delimiter).map(function (str) {
3017 return parseFloat(str);
3018 })];
3019 }).reverse() // merge every transformation into one matrix
3020 .reduce(function (matrix, transform) {
3021 if (transform[0] === 'matrix') {
3022 return matrix.lmultiply(Matrix.fromArray(transform[1]));
3023 }
3024
3025 return matrix[transform[0]].apply(matrix, transform[1]);
3026 }, new Matrix());
3027 return matrix;
3028 } // add an element to another parent without changing the visual representation on the screen
3029
3030 function toParent(parent, i) {
3031 if (this === parent) return this;
3032 const ctm = this.screenCTM();
3033 const pCtm = parent.screenCTM().inverse();
3034 this.addTo(parent, i).untransform().transform(pCtm.multiply(ctm));
3035 return this;
3036 } // same as above with parent equals root-svg
3037
3038 function toRoot(i) {
3039 return this.toParent(this.root(), i);
3040 } // Add transformations
3041
3042 function transform(o, relative) {
3043 // Act as a getter if no object was passed
3044 if (o == null || typeof o === 'string') {
3045 const decomposed = new Matrix(this).decompose();
3046 return o == null ? decomposed : decomposed[o];
3047 }
3048
3049 if (!Matrix.isMatrixLike(o)) {
3050 // Set the origin according to the defined transform
3051 o = { ...o,
3052 origin: getOrigin(o, this)
3053 };
3054 } // The user can pass a boolean, an Element or an Matrix or nothing
3055
3056
3057 const cleanRelative = relative === true ? this : relative || false;
3058 const result = new Matrix(cleanRelative).transform(o);
3059 return this.attr('transform', result);
3060 }
3061 registerMethods('Element', {
3062 untransform,
3063 matrixify,
3064 toParent,
3065 toRoot,
3066 transform
3067 });
3068
3069 class Container extends Element {
3070 flatten(parent = this, index) {
3071 this.each(function () {
3072 if (this instanceof Container) {
3073 return this.flatten().ungroup();
3074 }
3075 });
3076 return this;
3077 }
3078
3079 ungroup(parent = this.parent(), index = parent.index(this)) {
3080 // when parent != this, we want append all elements to the end
3081 index = index === -1 ? parent.children().length : index;
3082 this.each(function (i, children) {
3083 // reverse each
3084 return children[children.length - i - 1].toParent(parent, index);
3085 });
3086 return this.remove();
3087 }
3088
3089 }
3090 register(Container, 'Container');
3091
3092 class Defs extends Container {
3093 constructor(node, attrs = node) {
3094 super(nodeOrNew('defs', node), attrs);
3095 }
3096
3097 flatten() {
3098 return this;
3099 }
3100
3101 ungroup() {
3102 return this;
3103 }
3104
3105 }
3106 register(Defs, 'Defs');
3107
3108 class Shape extends Element {}
3109 register(Shape, 'Shape');
3110
3111 function rx(rx) {
3112 return this.attr('rx', rx);
3113 } // Radius y value
3114
3115 function ry(ry) {
3116 return this.attr('ry', ry);
3117 } // Move over x-axis
3118
3119 function x$3(x) {
3120 return x == null ? this.cx() - this.rx() : this.cx(x + this.rx());
3121 } // Move over y-axis
3122
3123 function y$3(y) {
3124 return y == null ? this.cy() - this.ry() : this.cy(y + this.ry());
3125 } // Move by center over x-axis
3126
3127 function cx$1(x) {
3128 return this.attr('cx', x);
3129 } // Move by center over y-axis
3130
3131 function cy$1(y) {
3132 return this.attr('cy', y);
3133 } // Set width of element
3134
3135 function width$2(width) {
3136 return width == null ? this.rx() * 2 : this.rx(new SVGNumber(width).divide(2));
3137 } // Set height of element
3138
3139 function height$2(height) {
3140 return height == null ? this.ry() * 2 : this.ry(new SVGNumber(height).divide(2));
3141 }
3142
3143 var circled = {
3144 __proto__: null,
3145 rx: rx,
3146 ry: ry,
3147 x: x$3,
3148 y: y$3,
3149 cx: cx$1,
3150 cy: cy$1,
3151 width: width$2,
3152 height: height$2
3153 };
3154
3155 class Ellipse extends Shape {
3156 constructor(node, attrs = node) {
3157 super(nodeOrNew('ellipse', node), attrs);
3158 }
3159
3160 size(width, height) {
3161 const p = proportionalSize(this, width, height);
3162 return this.rx(new SVGNumber(p.width).divide(2)).ry(new SVGNumber(p.height).divide(2));
3163 }
3164
3165 }
3166 extend(Ellipse, circled);
3167 registerMethods('Container', {
3168 // Create an ellipse
3169 ellipse: wrapWithAttrCheck(function (width = 0, height = width) {
3170 return this.put(new Ellipse()).size(width, height).move(0, 0);
3171 })
3172 });
3173 register(Ellipse, 'Ellipse');
3174
3175 class Fragment extends Dom {
3176 constructor(node = globals.document.createDocumentFragment()) {
3177 super(node);
3178 } // Import / Export raw xml
3179
3180
3181 xml(xmlOrFn, outerXML, ns) {
3182 if (typeof xmlOrFn === 'boolean') {
3183 ns = outerXML;
3184 outerXML = xmlOrFn;
3185 xmlOrFn = null;
3186 } // because this is a fragment we have to put all elements into a wrapper first
3187 // before we can get the innerXML from it
3188
3189
3190 if (xmlOrFn == null || typeof xmlOrFn === 'function') {
3191 const wrapper = new Dom(create('wrapper', ns));
3192 wrapper.add(this.node.cloneNode(true));
3193 return wrapper.xml(false, ns);
3194 } // Act as setter if we got a string
3195
3196
3197 return super.xml(xmlOrFn, false, ns);
3198 }
3199
3200 }
3201
3202 register(Fragment, 'Fragment');
3203
3204 function from(x, y) {
3205 return (this._element || this).type === 'radialGradient' ? this.attr({
3206 fx: new SVGNumber(x),
3207 fy: new SVGNumber(y)
3208 }) : this.attr({
3209 x1: new SVGNumber(x),
3210 y1: new SVGNumber(y)
3211 });
3212 }
3213 function to(x, y) {
3214 return (this._element || this).type === 'radialGradient' ? this.attr({
3215 cx: new SVGNumber(x),
3216 cy: new SVGNumber(y)
3217 }) : this.attr({
3218 x2: new SVGNumber(x),
3219 y2: new SVGNumber(y)
3220 });
3221 }
3222
3223 var gradiented = {
3224 __proto__: null,
3225 from: from,
3226 to: to
3227 };
3228
3229 class Gradient extends Container {
3230 constructor(type, attrs) {
3231 super(nodeOrNew(type + 'Gradient', typeof type === 'string' ? null : type), attrs);
3232 } // custom attr to handle transform
3233
3234
3235 attr(a, b, c) {
3236 if (a === 'transform') a = 'gradientTransform';
3237 return super.attr(a, b, c);
3238 }
3239
3240 bbox() {
3241 return new Box();
3242 }
3243
3244 targets() {
3245 return baseFind('svg [fill*="' + this.id() + '"]');
3246 } // Alias string conversion to fill
3247
3248
3249 toString() {
3250 return this.url();
3251 } // Update gradient
3252
3253
3254 update(block) {
3255 // remove all stops
3256 this.clear(); // invoke passed block
3257
3258 if (typeof block === 'function') {
3259 block.call(this, this);
3260 }
3261
3262 return this;
3263 } // Return the fill id
3264
3265
3266 url() {
3267 return 'url("#' + this.id() + '")';
3268 }
3269
3270 }
3271 extend(Gradient, gradiented);
3272 registerMethods({
3273 Container: {
3274 // Create gradient element in defs
3275 gradient(...args) {
3276 return this.defs().gradient(...args);
3277 }
3278
3279 },
3280 // define gradient
3281 Defs: {
3282 gradient: wrapWithAttrCheck(function (type, block) {
3283 return this.put(new Gradient(type)).update(block);
3284 })
3285 }
3286 });
3287 register(Gradient, 'Gradient');
3288
3289 class Pattern extends Container {
3290 // Initialize node
3291 constructor(node, attrs = node) {
3292 super(nodeOrNew('pattern', node), attrs);
3293 } // custom attr to handle transform
3294
3295
3296 attr(a, b, c) {
3297 if (a === 'transform') a = 'patternTransform';
3298 return super.attr(a, b, c);
3299 }
3300
3301 bbox() {
3302 return new Box();
3303 }
3304
3305 targets() {
3306 return baseFind('svg [fill*="' + this.id() + '"]');
3307 } // Alias string conversion to fill
3308
3309
3310 toString() {
3311 return this.url();
3312 } // Update pattern by rebuilding
3313
3314
3315 update(block) {
3316 // remove content
3317 this.clear(); // invoke passed block
3318
3319 if (typeof block === 'function') {
3320 block.call(this, this);
3321 }
3322
3323 return this;
3324 } // Return the fill id
3325
3326
3327 url() {
3328 return 'url("#' + this.id() + '")';
3329 }
3330
3331 }
3332 registerMethods({
3333 Container: {
3334 // Create pattern element in defs
3335 pattern(...args) {
3336 return this.defs().pattern(...args);
3337 }
3338
3339 },
3340 Defs: {
3341 pattern: wrapWithAttrCheck(function (width, height, block) {
3342 return this.put(new Pattern()).update(block).attr({
3343 x: 0,
3344 y: 0,
3345 width: width,
3346 height: height,
3347 patternUnits: 'userSpaceOnUse'
3348 });
3349 })
3350 }
3351 });
3352 register(Pattern, 'Pattern');
3353
3354 class Image extends Shape {
3355 constructor(node, attrs = node) {
3356 super(nodeOrNew('image', node), attrs);
3357 } // (re)load image
3358
3359
3360 load(url, callback) {
3361 if (!url) return this;
3362 const img = new globals.window.Image();
3363 on(img, 'load', function (e) {
3364 const p = this.parent(Pattern); // ensure image size
3365
3366 if (this.width() === 0 && this.height() === 0) {
3367 this.size(img.width, img.height);
3368 }
3369
3370 if (p instanceof Pattern) {
3371 // ensure pattern size if not set
3372 if (p.width() === 0 && p.height() === 0) {
3373 p.size(this.width(), this.height());
3374 }
3375 }
3376
3377 if (typeof callback === 'function') {
3378 callback.call(this, e);
3379 }
3380 }, this);
3381 on(img, 'load error', function () {
3382 // dont forget to unbind memory leaking events
3383 off(img);
3384 });
3385 return this.attr('href', img.src = url, xlink);
3386 }
3387
3388 }
3389 registerAttrHook(function (attr, val, _this) {
3390 // convert image fill and stroke to patterns
3391 if (attr === 'fill' || attr === 'stroke') {
3392 if (isImage.test(val)) {
3393 val = _this.root().defs().image(val);
3394 }
3395 }
3396
3397 if (val instanceof Image) {
3398 val = _this.root().defs().pattern(0, 0, pattern => {
3399 pattern.add(val);
3400 });
3401 }
3402
3403 return val;
3404 });
3405 registerMethods({
3406 Container: {
3407 // create image element, load image and set its size
3408 image: wrapWithAttrCheck(function (source, callback) {
3409 return this.put(new Image()).size(0, 0).load(source, callback);
3410 })
3411 }
3412 });
3413 register(Image, 'Image');
3414
3415 class PointArray extends SVGArray {
3416 // Get bounding box of points
3417 bbox() {
3418 let maxX = -Infinity;
3419 let maxY = -Infinity;
3420 let minX = Infinity;
3421 let minY = Infinity;
3422 this.forEach(function (el) {
3423 maxX = Math.max(el[0], maxX);
3424 maxY = Math.max(el[1], maxY);
3425 minX = Math.min(el[0], minX);
3426 minY = Math.min(el[1], minY);
3427 });
3428 return new Box(minX, minY, maxX - minX, maxY - minY);
3429 } // Move point string
3430
3431
3432 move(x, y) {
3433 const box = this.bbox(); // get relative offset
3434
3435 x -= box.x;
3436 y -= box.y; // move every point
3437
3438 if (!isNaN(x) && !isNaN(y)) {
3439 for (let i = this.length - 1; i >= 0; i--) {
3440 this[i] = [this[i][0] + x, this[i][1] + y];
3441 }
3442 }
3443
3444 return this;
3445 } // Parse point string and flat array
3446
3447
3448 parse(array = [0, 0]) {
3449 const points = []; // if it is an array, we flatten it and therefore clone it to 1 depths
3450
3451 if (array instanceof Array) {
3452 array = Array.prototype.concat.apply([], array);
3453 } else {
3454 // Else, it is considered as a string
3455 // parse points
3456 array = array.trim().split(delimiter).map(parseFloat);
3457 } // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints
3458 // Odd number of coordinates is an error. In such cases, drop the last odd coordinate.
3459
3460
3461 if (array.length % 2 !== 0) array.pop(); // wrap points in two-tuples
3462
3463 for (let i = 0, len = array.length; i < len; i = i + 2) {
3464 points.push([array[i], array[i + 1]]);
3465 }
3466
3467 return points;
3468 } // Resize poly string
3469
3470
3471 size(width, height) {
3472 let i;
3473 const box = this.bbox(); // recalculate position of all points according to new size
3474
3475 for (i = this.length - 1; i >= 0; i--) {
3476 if (box.width) this[i][0] = (this[i][0] - box.x) * width / box.width + box.x;
3477 if (box.height) this[i][1] = (this[i][1] - box.y) * height / box.height + box.y;
3478 }
3479
3480 return this;
3481 } // Convert array to line object
3482
3483
3484 toLine() {
3485 return {
3486 x1: this[0][0],
3487 y1: this[0][1],
3488 x2: this[1][0],
3489 y2: this[1][1]
3490 };
3491 } // Convert array to string
3492
3493
3494 toString() {
3495 const array = []; // convert to a poly point string
3496
3497 for (let i = 0, il = this.length; i < il; i++) {
3498 array.push(this[i].join(','));
3499 }
3500
3501 return array.join(' ');
3502 }
3503
3504 transform(m) {
3505 return this.clone().transformO(m);
3506 } // transform points with matrix (similar to Point.transform)
3507
3508
3509 transformO(m) {
3510 if (!Matrix.isMatrixLike(m)) {
3511 m = new Matrix(m);
3512 }
3513
3514 for (let i = this.length; i--;) {
3515 // Perform the matrix multiplication
3516 const [x, y] = this[i];
3517 this[i][0] = m.a * x + m.c * y + m.e;
3518 this[i][1] = m.b * x + m.d * y + m.f;
3519 }
3520
3521 return this;
3522 }
3523
3524 }
3525
3526 const MorphArray = PointArray; // Move by left top corner over x-axis
3527
3528 function x$2(x) {
3529 return x == null ? this.bbox().x : this.move(x, this.bbox().y);
3530 } // Move by left top corner over y-axis
3531
3532 function y$2(y) {
3533 return y == null ? this.bbox().y : this.move(this.bbox().x, y);
3534 } // Set width of element
3535
3536 function width$1(width) {
3537 const b = this.bbox();
3538 return width == null ? b.width : this.size(width, b.height);
3539 } // Set height of element
3540
3541 function height$1(height) {
3542 const b = this.bbox();
3543 return height == null ? b.height : this.size(b.width, height);
3544 }
3545
3546 var pointed = {
3547 __proto__: null,
3548 MorphArray: MorphArray,
3549 x: x$2,
3550 y: y$2,
3551 width: width$1,
3552 height: height$1
3553 };
3554
3555 class Line extends Shape {
3556 // Initialize node
3557 constructor(node, attrs = node) {
3558 super(nodeOrNew('line', node), attrs);
3559 } // Get array
3560
3561
3562 array() {
3563 return new PointArray([[this.attr('x1'), this.attr('y1')], [this.attr('x2'), this.attr('y2')]]);
3564 } // Move by left top corner
3565
3566
3567 move(x, y) {
3568 return this.attr(this.array().move(x, y).toLine());
3569 } // Overwrite native plot() method
3570
3571
3572 plot(x1, y1, x2, y2) {
3573 if (x1 == null) {
3574 return this.array();
3575 } else if (typeof y1 !== 'undefined') {
3576 x1 = {
3577 x1,
3578 y1,
3579 x2,
3580 y2
3581 };
3582 } else {
3583 x1 = new PointArray(x1).toLine();
3584 }
3585
3586 return this.attr(x1);
3587 } // Set element size to given width and height
3588
3589
3590 size(width, height) {
3591 const p = proportionalSize(this, width, height);
3592 return this.attr(this.array().size(p.width, p.height).toLine());
3593 }
3594
3595 }
3596 extend(Line, pointed);
3597 registerMethods({
3598 Container: {
3599 // Create a line element
3600 line: wrapWithAttrCheck(function (...args) {
3601 // make sure plot is called as a setter
3602 // x1 is not necessarily a number, it can also be an array, a string and a PointArray
3603 return Line.prototype.plot.apply(this.put(new Line()), args[0] != null ? args : [0, 0, 0, 0]);
3604 })
3605 }
3606 });
3607 register(Line, 'Line');
3608
3609 class Marker extends Container {
3610 // Initialize node
3611 constructor(node, attrs = node) {
3612 super(nodeOrNew('marker', node), attrs);
3613 } // Set height of element
3614
3615
3616 height(height) {
3617 return this.attr('markerHeight', height);
3618 }
3619
3620 orient(orient) {
3621 return this.attr('orient', orient);
3622 } // Set marker refX and refY
3623
3624
3625 ref(x, y) {
3626 return this.attr('refX', x).attr('refY', y);
3627 } // Return the fill id
3628
3629
3630 toString() {
3631 return 'url(#' + this.id() + ')';
3632 } // Update marker
3633
3634
3635 update(block) {
3636 // remove all content
3637 this.clear(); // invoke passed block
3638
3639 if (typeof block === 'function') {
3640 block.call(this, this);
3641 }
3642
3643 return this;
3644 } // Set width of element
3645
3646
3647 width(width) {
3648 return this.attr('markerWidth', width);
3649 }
3650
3651 }
3652 registerMethods({
3653 Container: {
3654 marker(...args) {
3655 // Create marker element in defs
3656 return this.defs().marker(...args);
3657 }
3658
3659 },
3660 Defs: {
3661 // Create marker
3662 marker: wrapWithAttrCheck(function (width, height, block) {
3663 // Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto
3664 return this.put(new Marker()).size(width, height).ref(width / 2, height / 2).viewbox(0, 0, width, height).attr('orient', 'auto').update(block);
3665 })
3666 },
3667 marker: {
3668 // Create and attach markers
3669 marker(marker, width, height, block) {
3670 let attr = ['marker']; // Build attribute name
3671
3672 if (marker !== 'all') attr.push(marker);
3673 attr = attr.join('-'); // Set marker attribute
3674
3675 marker = arguments[1] instanceof Marker ? arguments[1] : this.defs().marker(width, height, block);
3676 return this.attr(attr, marker);
3677 }
3678
3679 }
3680 });
3681 register(Marker, 'Marker');
3682
3683 /***
3684 Base Class
3685 ==========
3686 The base stepper class that will be
3687 ***/
3688
3689 function makeSetterGetter(k, f) {
3690 return function (v) {
3691 if (v == null) return this[k];
3692 this[k] = v;
3693 if (f) f.call(this);
3694 return this;
3695 };
3696 }
3697
3698 const easing = {
3699 '-': function (pos) {
3700 return pos;
3701 },
3702 '<>': function (pos) {
3703 return -Math.cos(pos * Math.PI) / 2 + 0.5;
3704 },
3705 '>': function (pos) {
3706 return Math.sin(pos * Math.PI / 2);
3707 },
3708 '<': function (pos) {
3709 return -Math.cos(pos * Math.PI / 2) + 1;
3710 },
3711 bezier: function (x1, y1, x2, y2) {
3712 // see https://www.w3.org/TR/css-easing-1/#cubic-bezier-algo
3713 return function (t) {
3714 if (t < 0) {
3715 if (x1 > 0) {
3716 return y1 / x1 * t;
3717 } else if (x2 > 0) {
3718 return y2 / x2 * t;
3719 } else {
3720 return 0;
3721 }
3722 } else if (t > 1) {
3723 if (x2 < 1) {
3724 return (1 - y2) / (1 - x2) * t + (y2 - x2) / (1 - x2);
3725 } else if (x1 < 1) {
3726 return (1 - y1) / (1 - x1) * t + (y1 - x1) / (1 - x1);
3727 } else {
3728 return 1;
3729 }
3730 } else {
3731 return 3 * t * (1 - t) ** 2 * y1 + 3 * t ** 2 * (1 - t) * y2 + t ** 3;
3732 }
3733 };
3734 },
3735 // see https://www.w3.org/TR/css-easing-1/#step-timing-function-algo
3736 steps: function (steps, stepPosition = 'end') {
3737 // deal with "jump-" prefix
3738 stepPosition = stepPosition.split('-').reverse()[0];
3739 let jumps = steps;
3740
3741 if (stepPosition === 'none') {
3742 --jumps;
3743 } else if (stepPosition === 'both') {
3744 ++jumps;
3745 } // The beforeFlag is essentially useless
3746
3747
3748 return (t, beforeFlag = false) => {
3749 // Step is called currentStep in referenced url
3750 let step = Math.floor(t * steps);
3751 const jumping = t * step % 1 === 0;
3752
3753 if (stepPosition === 'start' || stepPosition === 'both') {
3754 ++step;
3755 }
3756
3757 if (beforeFlag && jumping) {
3758 --step;
3759 }
3760
3761 if (t >= 0 && step < 0) {
3762 step = 0;
3763 }
3764
3765 if (t <= 1 && step > jumps) {
3766 step = jumps;
3767 }
3768
3769 return step / jumps;
3770 };
3771 }
3772 };
3773 class Stepper {
3774 done() {
3775 return false;
3776 }
3777
3778 }
3779 /***
3780 Easing Functions
3781 ================
3782 ***/
3783
3784 class Ease extends Stepper {
3785 constructor(fn = timeline.ease) {
3786 super();
3787 this.ease = easing[fn] || fn;
3788 }
3789
3790 step(from, to, pos) {
3791 if (typeof from !== 'number') {
3792 return pos < 1 ? from : to;
3793 }
3794
3795 return from + (to - from) * this.ease(pos);
3796 }
3797
3798 }
3799 /***
3800 Controller Types
3801 ================
3802 ***/
3803
3804 class Controller extends Stepper {
3805 constructor(fn) {
3806 super();
3807 this.stepper = fn;
3808 }
3809
3810 done(c) {
3811 return c.done;
3812 }
3813
3814 step(current, target, dt, c) {
3815 return this.stepper(current, target, dt, c);
3816 }
3817
3818 }
3819
3820 function recalculate() {
3821 // Apply the default parameters
3822 const duration = (this._duration || 500) / 1000;
3823 const overshoot = this._overshoot || 0; // Calculate the PID natural response
3824
3825 const eps = 1e-10;
3826 const pi = Math.PI;
3827 const os = Math.log(overshoot / 100 + eps);
3828 const zeta = -os / Math.sqrt(pi * pi + os * os);
3829 const wn = 3.9 / (zeta * duration); // Calculate the Spring values
3830
3831 this.d = 2 * zeta * wn;
3832 this.k = wn * wn;
3833 }
3834
3835 class Spring extends Controller {
3836 constructor(duration = 500, overshoot = 0) {
3837 super();
3838 this.duration(duration).overshoot(overshoot);
3839 }
3840
3841 step(current, target, dt, c) {
3842 if (typeof current === 'string') return current;
3843 c.done = dt === Infinity;
3844 if (dt === Infinity) return target;
3845 if (dt === 0) return current;
3846 if (dt > 100) dt = 16;
3847 dt /= 1000; // Get the previous velocity
3848
3849 const velocity = c.velocity || 0; // Apply the control to get the new position and store it
3850
3851 const acceleration = -this.d * velocity - this.k * (current - target);
3852 const newPosition = current + velocity * dt + acceleration * dt * dt / 2; // Store the velocity
3853
3854 c.velocity = velocity + acceleration * dt; // Figure out if we have converged, and if so, pass the value
3855
3856 c.done = Math.abs(target - newPosition) + Math.abs(velocity) < 0.002;
3857 return c.done ? target : newPosition;
3858 }
3859
3860 }
3861 extend(Spring, {
3862 duration: makeSetterGetter('_duration', recalculate),
3863 overshoot: makeSetterGetter('_overshoot', recalculate)
3864 });
3865 class PID extends Controller {
3866 constructor(p = 0.1, i = 0.01, d = 0, windup = 1000) {
3867 super();
3868 this.p(p).i(i).d(d).windup(windup);
3869 }
3870
3871 step(current, target, dt, c) {
3872 if (typeof current === 'string') return current;
3873 c.done = dt === Infinity;
3874 if (dt === Infinity) return target;
3875 if (dt === 0) return current;
3876 const p = target - current;
3877 let i = (c.integral || 0) + p * dt;
3878 const d = (p - (c.error || 0)) / dt;
3879 const windup = this._windup; // antiwindup
3880
3881 if (windup !== false) {
3882 i = Math.max(-windup, Math.min(i, windup));
3883 }
3884
3885 c.error = p;
3886 c.integral = i;
3887 c.done = Math.abs(p) < 0.001;
3888 return c.done ? target : current + (this.P * p + this.I * i + this.D * d);
3889 }
3890
3891 }
3892 extend(PID, {
3893 windup: makeSetterGetter('_windup'),
3894 p: makeSetterGetter('P'),
3895 i: makeSetterGetter('I'),
3896 d: makeSetterGetter('D')
3897 });
3898
3899 const segmentParameters = {
3900 M: 2,
3901 L: 2,
3902 H: 1,
3903 V: 1,
3904 C: 6,
3905 S: 4,
3906 Q: 4,
3907 T: 2,
3908 A: 7,
3909 Z: 0
3910 };
3911 const pathHandlers = {
3912 M: function (c, p, p0) {
3913 p.x = p0.x = c[0];
3914 p.y = p0.y = c[1];
3915 return ['M', p.x, p.y];
3916 },
3917 L: function (c, p) {
3918 p.x = c[0];
3919 p.y = c[1];
3920 return ['L', c[0], c[1]];
3921 },
3922 H: function (c, p) {
3923 p.x = c[0];
3924 return ['H', c[0]];
3925 },
3926 V: function (c, p) {
3927 p.y = c[0];
3928 return ['V', c[0]];
3929 },
3930 C: function (c, p) {
3931 p.x = c[4];
3932 p.y = c[5];
3933 return ['C', c[0], c[1], c[2], c[3], c[4], c[5]];
3934 },
3935 S: function (c, p) {
3936 p.x = c[2];
3937 p.y = c[3];
3938 return ['S', c[0], c[1], c[2], c[3]];
3939 },
3940 Q: function (c, p) {
3941 p.x = c[2];
3942 p.y = c[3];
3943 return ['Q', c[0], c[1], c[2], c[3]];
3944 },
3945 T: function (c, p) {
3946 p.x = c[0];
3947 p.y = c[1];
3948 return ['T', c[0], c[1]];
3949 },
3950 Z: function (c, p, p0) {
3951 p.x = p0.x;
3952 p.y = p0.y;
3953 return ['Z'];
3954 },
3955 A: function (c, p) {
3956 p.x = c[5];
3957 p.y = c[6];
3958 return ['A', c[0], c[1], c[2], c[3], c[4], c[5], c[6]];
3959 }
3960 };
3961 const mlhvqtcsaz = 'mlhvqtcsaz'.split('');
3962
3963 for (let i = 0, il = mlhvqtcsaz.length; i < il; ++i) {
3964 pathHandlers[mlhvqtcsaz[i]] = function (i) {
3965 return function (c, p, p0) {
3966 if (i === 'H') c[0] = c[0] + p.x;else if (i === 'V') c[0] = c[0] + p.y;else if (i === 'A') {
3967 c[5] = c[5] + p.x;
3968 c[6] = c[6] + p.y;
3969 } else {
3970 for (let j = 0, jl = c.length; j < jl; ++j) {
3971 c[j] = c[j] + (j % 2 ? p.y : p.x);
3972 }
3973 }
3974 return pathHandlers[i](c, p, p0);
3975 };
3976 }(mlhvqtcsaz[i].toUpperCase());
3977 }
3978
3979 function makeAbsolut(parser) {
3980 const command = parser.segment[0];
3981 return pathHandlers[command](parser.segment.slice(1), parser.p, parser.p0);
3982 }
3983
3984 function segmentComplete(parser) {
3985 return parser.segment.length && parser.segment.length - 1 === segmentParameters[parser.segment[0].toUpperCase()];
3986 }
3987
3988 function startNewSegment(parser, token) {
3989 parser.inNumber && finalizeNumber(parser, false);
3990 const pathLetter = isPathLetter.test(token);
3991
3992 if (pathLetter) {
3993 parser.segment = [token];
3994 } else {
3995 const lastCommand = parser.lastCommand;
3996 const small = lastCommand.toLowerCase();
3997 const isSmall = lastCommand === small;
3998 parser.segment = [small === 'm' ? isSmall ? 'l' : 'L' : lastCommand];
3999 }
4000
4001 parser.inSegment = true;
4002 parser.lastCommand = parser.segment[0];
4003 return pathLetter;
4004 }
4005
4006 function finalizeNumber(parser, inNumber) {
4007 if (!parser.inNumber) throw new Error('Parser Error');
4008 parser.number && parser.segment.push(parseFloat(parser.number));
4009 parser.inNumber = inNumber;
4010 parser.number = '';
4011 parser.pointSeen = false;
4012 parser.hasExponent = false;
4013
4014 if (segmentComplete(parser)) {
4015 finalizeSegment(parser);
4016 }
4017 }
4018
4019 function finalizeSegment(parser) {
4020 parser.inSegment = false;
4021
4022 if (parser.absolute) {
4023 parser.segment = makeAbsolut(parser);
4024 }
4025
4026 parser.segments.push(parser.segment);
4027 }
4028
4029 function isArcFlag(parser) {
4030 if (!parser.segment.length) return false;
4031 const isArc = parser.segment[0].toUpperCase() === 'A';
4032 const length = parser.segment.length;
4033 return isArc && (length === 4 || length === 5);
4034 }
4035
4036 function isExponential(parser) {
4037 return parser.lastToken.toUpperCase() === 'E';
4038 }
4039
4040 function pathParser(d, toAbsolute = true) {
4041 let index = 0;
4042 let token = '';
4043 const parser = {
4044 segment: [],
4045 inNumber: false,
4046 number: '',
4047 lastToken: '',
4048 inSegment: false,
4049 segments: [],
4050 pointSeen: false,
4051 hasExponent: false,
4052 absolute: toAbsolute,
4053 p0: new Point(),
4054 p: new Point()
4055 };
4056
4057 while (parser.lastToken = token, token = d.charAt(index++)) {
4058 if (!parser.inSegment) {
4059 if (startNewSegment(parser, token)) {
4060 continue;
4061 }
4062 }
4063
4064 if (token === '.') {
4065 if (parser.pointSeen || parser.hasExponent) {
4066 finalizeNumber(parser, false);
4067 --index;
4068 continue;
4069 }
4070
4071 parser.inNumber = true;
4072 parser.pointSeen = true;
4073 parser.number += token;
4074 continue;
4075 }
4076
4077 if (!isNaN(parseInt(token))) {
4078 if (parser.number === '0' || isArcFlag(parser)) {
4079 parser.inNumber = true;
4080 parser.number = token;
4081 finalizeNumber(parser, true);
4082 continue;
4083 }
4084
4085 parser.inNumber = true;
4086 parser.number += token;
4087 continue;
4088 }
4089
4090 if (token === ' ' || token === ',') {
4091 if (parser.inNumber) {
4092 finalizeNumber(parser, false);
4093 }
4094
4095 continue;
4096 }
4097
4098 if (token === '-') {
4099 if (parser.inNumber && !isExponential(parser)) {
4100 finalizeNumber(parser, false);
4101 --index;
4102 continue;
4103 }
4104
4105 parser.number += token;
4106 parser.inNumber = true;
4107 continue;
4108 }
4109
4110 if (token.toUpperCase() === 'E') {
4111 parser.number += token;
4112 parser.hasExponent = true;
4113 continue;
4114 }
4115
4116 if (isPathLetter.test(token)) {
4117 if (parser.inNumber) {
4118 finalizeNumber(parser, false);
4119 } else if (!segmentComplete(parser)) {
4120 throw new Error('parser Error');
4121 } else {
4122 finalizeSegment(parser);
4123 }
4124
4125 --index;
4126 }
4127 }
4128
4129 if (parser.inNumber) {
4130 finalizeNumber(parser, false);
4131 }
4132
4133 if (parser.inSegment && segmentComplete(parser)) {
4134 finalizeSegment(parser);
4135 }
4136
4137 return parser.segments;
4138 }
4139
4140 function arrayToString(a) {
4141 let s = '';
4142
4143 for (let i = 0, il = a.length; i < il; i++) {
4144 s += a[i][0];
4145
4146 if (a[i][1] != null) {
4147 s += a[i][1];
4148
4149 if (a[i][2] != null) {
4150 s += ' ';
4151 s += a[i][2];
4152
4153 if (a[i][3] != null) {
4154 s += ' ';
4155 s += a[i][3];
4156 s += ' ';
4157 s += a[i][4];
4158
4159 if (a[i][5] != null) {
4160 s += ' ';
4161 s += a[i][5];
4162 s += ' ';
4163 s += a[i][6];
4164
4165 if (a[i][7] != null) {
4166 s += ' ';
4167 s += a[i][7];
4168 }
4169 }
4170 }
4171 }
4172 }
4173 }
4174
4175 return s + ' ';
4176 }
4177
4178 class PathArray extends SVGArray {
4179 // Get bounding box of path
4180 bbox() {
4181 parser().path.setAttribute('d', this.toString());
4182 return new Box(parser.nodes.path.getBBox());
4183 } // Move path string
4184
4185
4186 move(x, y) {
4187 // get bounding box of current situation
4188 const box = this.bbox(); // get relative offset
4189
4190 x -= box.x;
4191 y -= box.y;
4192
4193 if (!isNaN(x) && !isNaN(y)) {
4194 // move every point
4195 for (let l, i = this.length - 1; i >= 0; i--) {
4196 l = this[i][0];
4197
4198 if (l === 'M' || l === 'L' || l === 'T') {
4199 this[i][1] += x;
4200 this[i][2] += y;
4201 } else if (l === 'H') {
4202 this[i][1] += x;
4203 } else if (l === 'V') {
4204 this[i][1] += y;
4205 } else if (l === 'C' || l === 'S' || l === 'Q') {
4206 this[i][1] += x;
4207 this[i][2] += y;
4208 this[i][3] += x;
4209 this[i][4] += y;
4210
4211 if (l === 'C') {
4212 this[i][5] += x;
4213 this[i][6] += y;
4214 }
4215 } else if (l === 'A') {
4216 this[i][6] += x;
4217 this[i][7] += y;
4218 }
4219 }
4220 }
4221
4222 return this;
4223 } // Absolutize and parse path to array
4224
4225
4226 parse(d = 'M0 0') {
4227 if (Array.isArray(d)) {
4228 d = Array.prototype.concat.apply([], d).toString();
4229 }
4230
4231 return pathParser(d);
4232 } // Resize path string
4233
4234
4235 size(width, height) {
4236 // get bounding box of current situation
4237 const box = this.bbox();
4238 let i, l; // If the box width or height is 0 then we ignore
4239 // transformations on the respective axis
4240
4241 box.width = box.width === 0 ? 1 : box.width;
4242 box.height = box.height === 0 ? 1 : box.height; // recalculate position of all points according to new size
4243
4244 for (i = this.length - 1; i >= 0; i--) {
4245 l = this[i][0];
4246
4247 if (l === 'M' || l === 'L' || l === 'T') {
4248 this[i][1] = (this[i][1] - box.x) * width / box.width + box.x;
4249 this[i][2] = (this[i][2] - box.y) * height / box.height + box.y;
4250 } else if (l === 'H') {
4251 this[i][1] = (this[i][1] - box.x) * width / box.width + box.x;
4252 } else if (l === 'V') {
4253 this[i][1] = (this[i][1] - box.y) * height / box.height + box.y;
4254 } else if (l === 'C' || l === 'S' || l === 'Q') {
4255 this[i][1] = (this[i][1] - box.x) * width / box.width + box.x;
4256 this[i][2] = (this[i][2] - box.y) * height / box.height + box.y;
4257 this[i][3] = (this[i][3] - box.x) * width / box.width + box.x;
4258 this[i][4] = (this[i][4] - box.y) * height / box.height + box.y;
4259
4260 if (l === 'C') {
4261 this[i][5] = (this[i][5] - box.x) * width / box.width + box.x;
4262 this[i][6] = (this[i][6] - box.y) * height / box.height + box.y;
4263 }
4264 } else if (l === 'A') {
4265 // resize radii
4266 this[i][1] = this[i][1] * width / box.width;
4267 this[i][2] = this[i][2] * height / box.height; // move position values
4268
4269 this[i][6] = (this[i][6] - box.x) * width / box.width + box.x;
4270 this[i][7] = (this[i][7] - box.y) * height / box.height + box.y;
4271 }
4272 }
4273
4274 return this;
4275 } // Convert array to string
4276
4277
4278 toString() {
4279 return arrayToString(this);
4280 }
4281
4282 }
4283
4284 const getClassForType = value => {
4285 const type = typeof value;
4286
4287 if (type === 'number') {
4288 return SVGNumber;
4289 } else if (type === 'string') {
4290 if (Color.isColor(value)) {
4291 return Color;
4292 } else if (delimiter.test(value)) {
4293 return isPathLetter.test(value) ? PathArray : SVGArray;
4294 } else if (numberAndUnit.test(value)) {
4295 return SVGNumber;
4296 } else {
4297 return NonMorphable;
4298 }
4299 } else if (morphableTypes.indexOf(value.constructor) > -1) {
4300 return value.constructor;
4301 } else if (Array.isArray(value)) {
4302 return SVGArray;
4303 } else if (type === 'object') {
4304 return ObjectBag;
4305 } else {
4306 return NonMorphable;
4307 }
4308 };
4309
4310 class Morphable {
4311 constructor(stepper) {
4312 this._stepper = stepper || new Ease('-');
4313 this._from = null;
4314 this._to = null;
4315 this._type = null;
4316 this._context = null;
4317 this._morphObj = null;
4318 }
4319
4320 at(pos) {
4321 return this._morphObj.morph(this._from, this._to, pos, this._stepper, this._context);
4322 }
4323
4324 done() {
4325 const complete = this._context.map(this._stepper.done).reduce(function (last, curr) {
4326 return last && curr;
4327 }, true);
4328
4329 return complete;
4330 }
4331
4332 from(val) {
4333 if (val == null) {
4334 return this._from;
4335 }
4336
4337 this._from = this._set(val);
4338 return this;
4339 }
4340
4341 stepper(stepper) {
4342 if (stepper == null) return this._stepper;
4343 this._stepper = stepper;
4344 return this;
4345 }
4346
4347 to(val) {
4348 if (val == null) {
4349 return this._to;
4350 }
4351
4352 this._to = this._set(val);
4353 return this;
4354 }
4355
4356 type(type) {
4357 // getter
4358 if (type == null) {
4359 return this._type;
4360 } // setter
4361
4362
4363 this._type = type;
4364 return this;
4365 }
4366
4367 _set(value) {
4368 if (!this._type) {
4369 this.type(getClassForType(value));
4370 }
4371
4372 let result = new this._type(value);
4373
4374 if (this._type === Color) {
4375 result = this._to ? result[this._to[4]]() : this._from ? result[this._from[4]]() : result;
4376 }
4377
4378 if (this._type === ObjectBag) {
4379 result = this._to ? result.align(this._to) : this._from ? result.align(this._from) : result;
4380 }
4381
4382 result = result.toConsumable();
4383 this._morphObj = this._morphObj || new this._type();
4384 this._context = this._context || Array.apply(null, Array(result.length)).map(Object).map(function (o) {
4385 o.done = true;
4386 return o;
4387 });
4388 return result;
4389 }
4390
4391 }
4392 class NonMorphable {
4393 constructor(...args) {
4394 this.init(...args);
4395 }
4396
4397 init(val) {
4398 val = Array.isArray(val) ? val[0] : val;
4399 this.value = val;
4400 return this;
4401 }
4402
4403 toArray() {
4404 return [this.value];
4405 }
4406
4407 valueOf() {
4408 return this.value;
4409 }
4410
4411 }
4412 class TransformBag {
4413 constructor(...args) {
4414 this.init(...args);
4415 }
4416
4417 init(obj) {
4418 if (Array.isArray(obj)) {
4419 obj = {
4420 scaleX: obj[0],
4421 scaleY: obj[1],
4422 shear: obj[2],
4423 rotate: obj[3],
4424 translateX: obj[4],
4425 translateY: obj[5],
4426 originX: obj[6],
4427 originY: obj[7]
4428 };
4429 }
4430
4431 Object.assign(this, TransformBag.defaults, obj);
4432 return this;
4433 }
4434
4435 toArray() {
4436 const v = this;
4437 return [v.scaleX, v.scaleY, v.shear, v.rotate, v.translateX, v.translateY, v.originX, v.originY];
4438 }
4439
4440 }
4441 TransformBag.defaults = {
4442 scaleX: 1,
4443 scaleY: 1,
4444 shear: 0,
4445 rotate: 0,
4446 translateX: 0,
4447 translateY: 0,
4448 originX: 0,
4449 originY: 0
4450 };
4451
4452 const sortByKey = (a, b) => {
4453 return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
4454 };
4455
4456 class ObjectBag {
4457 constructor(...args) {
4458 this.init(...args);
4459 }
4460
4461 align(other) {
4462 const values = this.values;
4463
4464 for (let i = 0, il = values.length; i < il; ++i) {
4465 // If the type is the same we only need to check if the color is in the correct format
4466 if (values[i + 1] === other[i + 1]) {
4467 if (values[i + 1] === Color && other[i + 7] !== values[i + 7]) {
4468 const space = other[i + 7];
4469 const color = new Color(this.values.splice(i + 3, 5))[space]().toArray();
4470 this.values.splice(i + 3, 0, ...color);
4471 }
4472
4473 i += values[i + 2] + 2;
4474 continue;
4475 }
4476
4477 if (!other[i + 1]) {
4478 return this;
4479 } // The types differ, so we overwrite the new type with the old one
4480 // And initialize it with the types default (e.g. black for color or 0 for number)
4481
4482
4483 const defaultObject = new other[i + 1]().toArray(); // Than we fix the values array
4484
4485 const toDelete = values[i + 2] + 3;
4486 values.splice(i, toDelete, other[i], other[i + 1], other[i + 2], ...defaultObject);
4487 i += values[i + 2] + 2;
4488 }
4489
4490 return this;
4491 }
4492
4493 init(objOrArr) {
4494 this.values = [];
4495
4496 if (Array.isArray(objOrArr)) {
4497 this.values = objOrArr.slice();
4498 return;
4499 }
4500
4501 objOrArr = objOrArr || {};
4502 const entries = [];
4503
4504 for (const i in objOrArr) {
4505 const Type = getClassForType(objOrArr[i]);
4506 const val = new Type(objOrArr[i]).toArray();
4507 entries.push([i, Type, val.length, ...val]);
4508 }
4509
4510 entries.sort(sortByKey);
4511 this.values = entries.reduce((last, curr) => last.concat(curr), []);
4512 return this;
4513 }
4514
4515 toArray() {
4516 return this.values;
4517 }
4518
4519 valueOf() {
4520 const obj = {};
4521 const arr = this.values; // for (var i = 0, len = arr.length; i < len; i += 2) {
4522
4523 while (arr.length) {
4524 const key = arr.shift();
4525 const Type = arr.shift();
4526 const num = arr.shift();
4527 const values = arr.splice(0, num);
4528 obj[key] = new Type(values); // .valueOf()
4529 }
4530
4531 return obj;
4532 }
4533
4534 }
4535 const morphableTypes = [NonMorphable, TransformBag, ObjectBag];
4536 function registerMorphableType(type = []) {
4537 morphableTypes.push(...[].concat(type));
4538 }
4539 function makeMorphable() {
4540 extend(morphableTypes, {
4541 to(val) {
4542 return new Morphable().type(this.constructor).from(this.toArray()) // this.valueOf())
4543 .to(val);
4544 },
4545
4546 fromArray(arr) {
4547 this.init(arr);
4548 return this;
4549 },
4550
4551 toConsumable() {
4552 return this.toArray();
4553 },
4554
4555 morph(from, to, pos, stepper, context) {
4556 const mapper = function (i, index) {
4557 return stepper.step(i, to[index], pos, context[index], context);
4558 };
4559
4560 return this.fromArray(from.map(mapper));
4561 }
4562
4563 });
4564 }
4565
4566 class Path extends Shape {
4567 // Initialize node
4568 constructor(node, attrs = node) {
4569 super(nodeOrNew('path', node), attrs);
4570 } // Get array
4571
4572
4573 array() {
4574 return this._array || (this._array = new PathArray(this.attr('d')));
4575 } // Clear array cache
4576
4577
4578 clear() {
4579 delete this._array;
4580 return this;
4581 } // Set height of element
4582
4583
4584 height(height) {
4585 return height == null ? this.bbox().height : this.size(this.bbox().width, height);
4586 } // Move by left top corner
4587
4588
4589 move(x, y) {
4590 return this.attr('d', this.array().move(x, y));
4591 } // Plot new path
4592
4593
4594 plot(d) {
4595 return d == null ? this.array() : this.clear().attr('d', typeof d === 'string' ? d : this._array = new PathArray(d));
4596 } // Set element size to given width and height
4597
4598
4599 size(width, height) {
4600 const p = proportionalSize(this, width, height);
4601 return this.attr('d', this.array().size(p.width, p.height));
4602 } // Set width of element
4603
4604
4605 width(width) {
4606 return width == null ? this.bbox().width : this.size(width, this.bbox().height);
4607 } // Move by left top corner over x-axis
4608
4609
4610 x(x) {
4611 return x == null ? this.bbox().x : this.move(x, this.bbox().y);
4612 } // Move by left top corner over y-axis
4613
4614
4615 y(y) {
4616 return y == null ? this.bbox().y : this.move(this.bbox().x, y);
4617 }
4618
4619 } // Define morphable array
4620
4621 Path.prototype.MorphArray = PathArray; // Add parent method
4622
4623 registerMethods({
4624 Container: {
4625 // Create a wrapped path element
4626 path: wrapWithAttrCheck(function (d) {
4627 // make sure plot is called as a setter
4628 return this.put(new Path()).plot(d || new PathArray());
4629 })
4630 }
4631 });
4632 register(Path, 'Path');
4633
4634 function array() {
4635 return this._array || (this._array = new PointArray(this.attr('points')));
4636 } // Clear array cache
4637
4638 function clear() {
4639 delete this._array;
4640 return this;
4641 } // Move by left top corner
4642
4643 function move$2(x, y) {
4644 return this.attr('points', this.array().move(x, y));
4645 } // Plot new path
4646
4647 function plot(p) {
4648 return p == null ? this.array() : this.clear().attr('points', typeof p === 'string' ? p : this._array = new PointArray(p));
4649 } // Set element size to given width and height
4650
4651 function size$1(width, height) {
4652 const p = proportionalSize(this, width, height);
4653 return this.attr('points', this.array().size(p.width, p.height));
4654 }
4655
4656 var poly = {
4657 __proto__: null,
4658 array: array,
4659 clear: clear,
4660 move: move$2,
4661 plot: plot,
4662 size: size$1
4663 };
4664
4665 class Polygon extends Shape {
4666 // Initialize node
4667 constructor(node, attrs = node) {
4668 super(nodeOrNew('polygon', node), attrs);
4669 }
4670
4671 }
4672 registerMethods({
4673 Container: {
4674 // Create a wrapped polygon element
4675 polygon: wrapWithAttrCheck(function (p) {
4676 // make sure plot is called as a setter
4677 return this.put(new Polygon()).plot(p || new PointArray());
4678 })
4679 }
4680 });
4681 extend(Polygon, pointed);
4682 extend(Polygon, poly);
4683 register(Polygon, 'Polygon');
4684
4685 class Polyline extends Shape {
4686 // Initialize node
4687 constructor(node, attrs = node) {
4688 super(nodeOrNew('polyline', node), attrs);
4689 }
4690
4691 }
4692 registerMethods({
4693 Container: {
4694 // Create a wrapped polygon element
4695 polyline: wrapWithAttrCheck(function (p) {
4696 // make sure plot is called as a setter
4697 return this.put(new Polyline()).plot(p || new PointArray());
4698 })
4699 }
4700 });
4701 extend(Polyline, pointed);
4702 extend(Polyline, poly);
4703 register(Polyline, 'Polyline');
4704
4705 class Rect extends Shape {
4706 // Initialize node
4707 constructor(node, attrs = node) {
4708 super(nodeOrNew('rect', node), attrs);
4709 }
4710
4711 }
4712 extend(Rect, {
4713 rx,
4714 ry
4715 });
4716 registerMethods({
4717 Container: {
4718 // Create a rect element
4719 rect: wrapWithAttrCheck(function (width, height) {
4720 return this.put(new Rect()).size(width, height);
4721 })
4722 }
4723 });
4724 register(Rect, 'Rect');
4725
4726 class Queue {
4727 constructor() {
4728 this._first = null;
4729 this._last = null;
4730 } // Shows us the first item in the list
4731
4732
4733 first() {
4734 return this._first && this._first.value;
4735 } // Shows us the last item in the list
4736
4737
4738 last() {
4739 return this._last && this._last.value;
4740 }
4741
4742 push(value) {
4743 // An item stores an id and the provided value
4744 const item = typeof value.next !== 'undefined' ? value : {
4745 value: value,
4746 next: null,
4747 prev: null
4748 }; // Deal with the queue being empty or populated
4749
4750 if (this._last) {
4751 item.prev = this._last;
4752 this._last.next = item;
4753 this._last = item;
4754 } else {
4755 this._last = item;
4756 this._first = item;
4757 } // Return the current item
4758
4759
4760 return item;
4761 } // Removes the item that was returned from the push
4762
4763
4764 remove(item) {
4765 // Relink the previous item
4766 if (item.prev) item.prev.next = item.next;
4767 if (item.next) item.next.prev = item.prev;
4768 if (item === this._last) this._last = item.prev;
4769 if (item === this._first) this._first = item.next; // Invalidate item
4770
4771 item.prev = null;
4772 item.next = null;
4773 }
4774
4775 shift() {
4776 // Check if we have a value
4777 const remove = this._first;
4778 if (!remove) return null; // If we do, remove it and relink things
4779
4780 this._first = remove.next;
4781 if (this._first) this._first.prev = null;
4782 this._last = this._first ? this._last : null;
4783 return remove.value;
4784 }
4785
4786 }
4787
4788 const Animator = {
4789 nextDraw: null,
4790 frames: new Queue(),
4791 timeouts: new Queue(),
4792 immediates: new Queue(),
4793 timer: () => globals.window.performance || globals.window.Date,
4794 transforms: [],
4795
4796 frame(fn) {
4797 // Store the node
4798 const node = Animator.frames.push({
4799 run: fn
4800 }); // Request an animation frame if we don't have one
4801
4802 if (Animator.nextDraw === null) {
4803 Animator.nextDraw = globals.window.requestAnimationFrame(Animator._draw);
4804 } // Return the node so we can remove it easily
4805
4806
4807 return node;
4808 },
4809
4810 timeout(fn, delay) {
4811 delay = delay || 0; // Work out when the event should fire
4812
4813 const time = Animator.timer().now() + delay; // Add the timeout to the end of the queue
4814
4815 const node = Animator.timeouts.push({
4816 run: fn,
4817 time: time
4818 }); // Request another animation frame if we need one
4819
4820 if (Animator.nextDraw === null) {
4821 Animator.nextDraw = globals.window.requestAnimationFrame(Animator._draw);
4822 }
4823
4824 return node;
4825 },
4826
4827 immediate(fn) {
4828 // Add the immediate fn to the end of the queue
4829 const node = Animator.immediates.push(fn); // Request another animation frame if we need one
4830
4831 if (Animator.nextDraw === null) {
4832 Animator.nextDraw = globals.window.requestAnimationFrame(Animator._draw);
4833 }
4834
4835 return node;
4836 },
4837
4838 cancelFrame(node) {
4839 node != null && Animator.frames.remove(node);
4840 },
4841
4842 clearTimeout(node) {
4843 node != null && Animator.timeouts.remove(node);
4844 },
4845
4846 cancelImmediate(node) {
4847 node != null && Animator.immediates.remove(node);
4848 },
4849
4850 _draw(now) {
4851 // Run all the timeouts we can run, if they are not ready yet, add them
4852 // to the end of the queue immediately! (bad timeouts!!! [sarcasm])
4853 let nextTimeout = null;
4854 const lastTimeout = Animator.timeouts.last();
4855
4856 while (nextTimeout = Animator.timeouts.shift()) {
4857 // Run the timeout if its time, or push it to the end
4858 if (now >= nextTimeout.time) {
4859 nextTimeout.run();
4860 } else {
4861 Animator.timeouts.push(nextTimeout);
4862 } // If we hit the last item, we should stop shifting out more items
4863
4864
4865 if (nextTimeout === lastTimeout) break;
4866 } // Run all of the animation frames
4867
4868
4869 let nextFrame = null;
4870 const lastFrame = Animator.frames.last();
4871
4872 while (nextFrame !== lastFrame && (nextFrame = Animator.frames.shift())) {
4873 nextFrame.run(now);
4874 }
4875
4876 let nextImmediate = null;
4877
4878 while (nextImmediate = Animator.immediates.shift()) {
4879 nextImmediate();
4880 } // If we have remaining timeouts or frames, draw until we don't anymore
4881
4882
4883 Animator.nextDraw = Animator.timeouts.first() || Animator.frames.first() ? globals.window.requestAnimationFrame(Animator._draw) : null;
4884 }
4885
4886 };
4887
4888 const makeSchedule = function (runnerInfo) {
4889 const start = runnerInfo.start;
4890 const duration = runnerInfo.runner.duration();
4891 const end = start + duration;
4892 return {
4893 start: start,
4894 duration: duration,
4895 end: end,
4896 runner: runnerInfo.runner
4897 };
4898 };
4899
4900 const defaultSource = function () {
4901 const w = globals.window;
4902 return (w.performance || w.Date).now();
4903 };
4904
4905 class Timeline extends EventTarget {
4906 // Construct a new timeline on the given element
4907 constructor(timeSource = defaultSource) {
4908 super();
4909 this._timeSource = timeSource; // Store the timing variables
4910
4911 this._startTime = 0;
4912 this._speed = 1.0; // Determines how long a runner is hold in memory. Can be a dt or true/false
4913
4914 this._persist = 0; // Keep track of the running animations and their starting parameters
4915
4916 this._nextFrame = null;
4917 this._paused = true;
4918 this._runners = [];
4919 this._runnerIds = [];
4920 this._lastRunnerId = -1;
4921 this._time = 0;
4922 this._lastSourceTime = 0;
4923 this._lastStepTime = 0; // Make sure that step is always called in class context
4924
4925 this._step = this._stepFn.bind(this, false);
4926 this._stepImmediate = this._stepFn.bind(this, true);
4927 }
4928
4929 active() {
4930 return !!this._nextFrame;
4931 }
4932
4933 finish() {
4934 // Go to end and pause
4935 this.time(this.getEndTimeOfTimeline() + 1);
4936 return this.pause();
4937 } // Calculates the end of the timeline
4938
4939
4940 getEndTime() {
4941 const lastRunnerInfo = this.getLastRunnerInfo();
4942 const lastDuration = lastRunnerInfo ? lastRunnerInfo.runner.duration() : 0;
4943 const lastStartTime = lastRunnerInfo ? lastRunnerInfo.start : this._time;
4944 return lastStartTime + lastDuration;
4945 }
4946
4947 getEndTimeOfTimeline() {
4948 const endTimes = this._runners.map(i => i.start + i.runner.duration());
4949
4950 return Math.max(0, ...endTimes);
4951 }
4952
4953 getLastRunnerInfo() {
4954 return this.getRunnerInfoById(this._lastRunnerId);
4955 }
4956
4957 getRunnerInfoById(id) {
4958 return this._runners[this._runnerIds.indexOf(id)] || null;
4959 }
4960
4961 pause() {
4962 this._paused = true;
4963 return this._continue();
4964 }
4965
4966 persist(dtOrForever) {
4967 if (dtOrForever == null) return this._persist;
4968 this._persist = dtOrForever;
4969 return this;
4970 }
4971
4972 play() {
4973 // Now make sure we are not paused and continue the animation
4974 this._paused = false;
4975 return this.updateTime()._continue();
4976 }
4977
4978 reverse(yes) {
4979 const currentSpeed = this.speed();
4980 if (yes == null) return this.speed(-currentSpeed);
4981 const positive = Math.abs(currentSpeed);
4982 return this.speed(yes ? -positive : positive);
4983 } // schedules a runner on the timeline
4984
4985
4986 schedule(runner, delay, when) {
4987 if (runner == null) {
4988 return this._runners.map(makeSchedule);
4989 } // The start time for the next animation can either be given explicitly,
4990 // derived from the current timeline time or it can be relative to the
4991 // last start time to chain animations directly
4992
4993
4994 let absoluteStartTime = 0;
4995 const endTime = this.getEndTime();
4996 delay = delay || 0; // Work out when to start the animation
4997
4998 if (when == null || when === 'last' || when === 'after') {
4999 // Take the last time and increment
5000 absoluteStartTime = endTime;
5001 } else if (when === 'absolute' || when === 'start') {
5002 absoluteStartTime = delay;
5003 delay = 0;
5004 } else if (when === 'now') {
5005 absoluteStartTime = this._time;
5006 } else if (when === 'relative') {
5007 const runnerInfo = this.getRunnerInfoById(runner.id);
5008
5009 if (runnerInfo) {
5010 absoluteStartTime = runnerInfo.start + delay;
5011 delay = 0;
5012 }
5013 } else if (when === 'with-last') {
5014 const lastRunnerInfo = this.getLastRunnerInfo();
5015 const lastStartTime = lastRunnerInfo ? lastRunnerInfo.start : this._time;
5016 absoluteStartTime = lastStartTime;
5017 } else {
5018 throw new Error('Invalid value for the "when" parameter');
5019 } // Manage runner
5020
5021
5022 runner.unschedule();
5023 runner.timeline(this);
5024 const persist = runner.persist();
5025 const runnerInfo = {
5026 persist: persist === null ? this._persist : persist,
5027 start: absoluteStartTime + delay,
5028 runner
5029 };
5030 this._lastRunnerId = runner.id;
5031
5032 this._runners.push(runnerInfo);
5033
5034 this._runners.sort((a, b) => a.start - b.start);
5035
5036 this._runnerIds = this._runners.map(info => info.runner.id);
5037
5038 this.updateTime()._continue();
5039
5040 return this;
5041 }
5042
5043 seek(dt) {
5044 return this.time(this._time + dt);
5045 }
5046
5047 source(fn) {
5048 if (fn == null) return this._timeSource;
5049 this._timeSource = fn;
5050 return this;
5051 }
5052
5053 speed(speed) {
5054 if (speed == null) return this._speed;
5055 this._speed = speed;
5056 return this;
5057 }
5058
5059 stop() {
5060 // Go to start and pause
5061 this.time(0);
5062 return this.pause();
5063 }
5064
5065 time(time) {
5066 if (time == null) return this._time;
5067 this._time = time;
5068 return this._continue(true);
5069 } // Remove the runner from this timeline
5070
5071
5072 unschedule(runner) {
5073 const index = this._runnerIds.indexOf(runner.id);
5074
5075 if (index < 0) return this;
5076
5077 this._runners.splice(index, 1);
5078
5079 this._runnerIds.splice(index, 1);
5080
5081 runner.timeline(null);
5082 return this;
5083 } // Makes sure, that after pausing the time doesn't jump
5084
5085
5086 updateTime() {
5087 if (!this.active()) {
5088 this._lastSourceTime = this._timeSource();
5089 }
5090
5091 return this;
5092 } // Checks if we are running and continues the animation
5093
5094
5095 _continue(immediateStep = false) {
5096 Animator.cancelFrame(this._nextFrame);
5097 this._nextFrame = null;
5098 if (immediateStep) return this._stepImmediate();
5099 if (this._paused) return this;
5100 this._nextFrame = Animator.frame(this._step);
5101 return this;
5102 }
5103
5104 _stepFn(immediateStep = false) {
5105 // Get the time delta from the last time and update the time
5106 const time = this._timeSource();
5107
5108 let dtSource = time - this._lastSourceTime;
5109 if (immediateStep) dtSource = 0;
5110 const dtTime = this._speed * dtSource + (this._time - this._lastStepTime);
5111 this._lastSourceTime = time; // Only update the time if we use the timeSource.
5112 // Otherwise use the current time
5113
5114 if (!immediateStep) {
5115 // Update the time
5116 this._time += dtTime;
5117 this._time = this._time < 0 ? 0 : this._time;
5118 }
5119
5120 this._lastStepTime = this._time;
5121 this.fire('time', this._time); // This is for the case that the timeline was seeked so that the time
5122 // is now before the startTime of the runner. Thats why we need to set
5123 // the runner to position 0
5124 // FIXME:
5125 // However, reseting in insertion order leads to bugs. Considering the case,
5126 // where 2 runners change the same attribute but in different times,
5127 // reseting both of them will lead to the case where the later defined
5128 // runner always wins the reset even if the other runner started earlier
5129 // and therefore should win the attribute battle
5130 // this can be solved by reseting them backwards
5131
5132 for (let k = this._runners.length; k--;) {
5133 // Get and run the current runner and ignore it if its inactive
5134 const runnerInfo = this._runners[k];
5135 const runner = runnerInfo.runner; // Make sure that we give the actual difference
5136 // between runner start time and now
5137
5138 const dtToStart = this._time - runnerInfo.start; // Dont run runner if not started yet
5139 // and try to reset it
5140
5141 if (dtToStart <= 0) {
5142 runner.reset();
5143 }
5144 } // Run all of the runners directly
5145
5146
5147 let runnersLeft = false;
5148
5149 for (let i = 0, len = this._runners.length; i < len; i++) {
5150 // Get and run the current runner and ignore it if its inactive
5151 const runnerInfo = this._runners[i];
5152 const runner = runnerInfo.runner;
5153 let dt = dtTime; // Make sure that we give the actual difference
5154 // between runner start time and now
5155
5156 const dtToStart = this._time - runnerInfo.start; // Dont run runner if not started yet
5157
5158 if (dtToStart <= 0) {
5159 runnersLeft = true;
5160 continue;
5161 } else if (dtToStart < dt) {
5162 // Adjust dt to make sure that animation is on point
5163 dt = dtToStart;
5164 }
5165
5166 if (!runner.active()) continue; // If this runner is still going, signal that we need another animation
5167 // frame, otherwise, remove the completed runner
5168
5169 const finished = runner.step(dt).done;
5170
5171 if (!finished) {
5172 runnersLeft = true; // continue
5173 } else if (runnerInfo.persist !== true) {
5174 // runner is finished. And runner might get removed
5175 const endTime = runner.duration() - runner.time() + this._time;
5176
5177 if (endTime + runnerInfo.persist < this._time) {
5178 // Delete runner and correct index
5179 runner.unschedule();
5180 --i;
5181 --len;
5182 }
5183 }
5184 } // Basically: we continue when there are runners right from us in time
5185 // when -->, and when runners are left from us when <--
5186
5187
5188 if (runnersLeft && !(this._speed < 0 && this._time === 0) || this._runnerIds.length && this._speed < 0 && this._time > 0) {
5189 this._continue();
5190 } else {
5191 this.pause();
5192 this.fire('finished');
5193 }
5194
5195 return this;
5196 }
5197
5198 }
5199 registerMethods({
5200 Element: {
5201 timeline: function (timeline) {
5202 if (timeline == null) {
5203 this._timeline = this._timeline || new Timeline();
5204 return this._timeline;
5205 } else {
5206 this._timeline = timeline;
5207 return this;
5208 }
5209 }
5210 }
5211 });
5212
5213 class Runner extends EventTarget {
5214 constructor(options) {
5215 super(); // Store a unique id on the runner, so that we can identify it later
5216
5217 this.id = Runner.id++; // Ensure a default value
5218
5219 options = options == null ? timeline.duration : options; // Ensure that we get a controller
5220
5221 options = typeof options === 'function' ? new Controller(options) : options; // Declare all of the variables
5222
5223 this._element = null;
5224 this._timeline = null;
5225 this.done = false;
5226 this._queue = []; // Work out the stepper and the duration
5227
5228 this._duration = typeof options === 'number' && options;
5229 this._isDeclarative = options instanceof Controller;
5230 this._stepper = this._isDeclarative ? options : new Ease(); // We copy the current values from the timeline because they can change
5231
5232 this._history = {}; // Store the state of the runner
5233
5234 this.enabled = true;
5235 this._time = 0;
5236 this._lastTime = 0; // At creation, the runner is in reseted state
5237
5238 this._reseted = true; // Save transforms applied to this runner
5239
5240 this.transforms = new Matrix();
5241 this.transformId = 1; // Looping variables
5242
5243 this._haveReversed = false;
5244 this._reverse = false;
5245 this._loopsDone = 0;
5246 this._swing = false;
5247 this._wait = 0;
5248 this._times = 1;
5249 this._frameId = null; // Stores how long a runner is stored after beeing done
5250
5251 this._persist = this._isDeclarative ? true : null;
5252 }
5253
5254 static sanitise(duration, delay, when) {
5255 // Initialise the default parameters
5256 let times = 1;
5257 let swing = false;
5258 let wait = 0;
5259 duration = duration || timeline.duration;
5260 delay = delay || timeline.delay;
5261 when = when || 'last'; // If we have an object, unpack the values
5262
5263 if (typeof duration === 'object' && !(duration instanceof Stepper)) {
5264 delay = duration.delay || delay;
5265 when = duration.when || when;
5266 swing = duration.swing || swing;
5267 times = duration.times || times;
5268 wait = duration.wait || wait;
5269 duration = duration.duration || timeline.duration;
5270 }
5271
5272 return {
5273 duration: duration,
5274 delay: delay,
5275 swing: swing,
5276 times: times,
5277 wait: wait,
5278 when: when
5279 };
5280 }
5281
5282 active(enabled) {
5283 if (enabled == null) return this.enabled;
5284 this.enabled = enabled;
5285 return this;
5286 }
5287 /*
5288 Private Methods
5289 ===============
5290 Methods that shouldn't be used externally
5291 */
5292
5293
5294 addTransform(transform, index) {
5295 this.transforms.lmultiplyO(transform);
5296 return this;
5297 }
5298
5299 after(fn) {
5300 return this.on('finished', fn);
5301 }
5302
5303 animate(duration, delay, when) {
5304 const o = Runner.sanitise(duration, delay, when);
5305 const runner = new Runner(o.duration);
5306 if (this._timeline) runner.timeline(this._timeline);
5307 if (this._element) runner.element(this._element);
5308 return runner.loop(o).schedule(o.delay, o.when);
5309 }
5310
5311 clearTransform() {
5312 this.transforms = new Matrix();
5313 return this;
5314 } // TODO: Keep track of all transformations so that deletion is faster
5315
5316
5317 clearTransformsFromQueue() {
5318 if (!this.done || !this._timeline || !this._timeline._runnerIds.includes(this.id)) {
5319 this._queue = this._queue.filter(item => {
5320 return !item.isTransform;
5321 });
5322 }
5323 }
5324
5325 delay(delay) {
5326 return this.animate(0, delay);
5327 }
5328
5329 duration() {
5330 return this._times * (this._wait + this._duration) - this._wait;
5331 }
5332
5333 during(fn) {
5334 return this.queue(null, fn);
5335 }
5336
5337 ease(fn) {
5338 this._stepper = new Ease(fn);
5339 return this;
5340 }
5341 /*
5342 Runner Definitions
5343 ==================
5344 These methods help us define the runtime behaviour of the Runner or they
5345 help us make new runners from the current runner
5346 */
5347
5348
5349 element(element) {
5350 if (element == null) return this._element;
5351 this._element = element;
5352
5353 element._prepareRunner();
5354
5355 return this;
5356 }
5357
5358 finish() {
5359 return this.step(Infinity);
5360 }
5361
5362 loop(times, swing, wait) {
5363 // Deal with the user passing in an object
5364 if (typeof times === 'object') {
5365 swing = times.swing;
5366 wait = times.wait;
5367 times = times.times;
5368 } // Sanitise the values and store them
5369
5370
5371 this._times = times || Infinity;
5372 this._swing = swing || false;
5373 this._wait = wait || 0; // Allow true to be passed
5374
5375 if (this._times === true) {
5376 this._times = Infinity;
5377 }
5378
5379 return this;
5380 }
5381
5382 loops(p) {
5383 const loopDuration = this._duration + this._wait;
5384
5385 if (p == null) {
5386 const loopsDone = Math.floor(this._time / loopDuration);
5387 const relativeTime = this._time - loopsDone * loopDuration;
5388 const position = relativeTime / this._duration;
5389 return Math.min(loopsDone + position, this._times);
5390 }
5391
5392 const whole = Math.floor(p);
5393 const partial = p % 1;
5394 const time = loopDuration * whole + this._duration * partial;
5395 return this.time(time);
5396 }
5397
5398 persist(dtOrForever) {
5399 if (dtOrForever == null) return this._persist;
5400 this._persist = dtOrForever;
5401 return this;
5402 }
5403
5404 position(p) {
5405 // Get all of the variables we need
5406 const x = this._time;
5407 const d = this._duration;
5408 const w = this._wait;
5409 const t = this._times;
5410 const s = this._swing;
5411 const r = this._reverse;
5412 let position;
5413
5414 if (p == null) {
5415 /*
5416 This function converts a time to a position in the range [0, 1]
5417 The full explanation can be found in this desmos demonstration
5418 https://www.desmos.com/calculator/u4fbavgche
5419 The logic is slightly simplified here because we can use booleans
5420 */
5421 // Figure out the value without thinking about the start or end time
5422 const f = function (x) {
5423 const swinging = s * Math.floor(x % (2 * (w + d)) / (w + d));
5424 const backwards = swinging && !r || !swinging && r;
5425 const uncliped = Math.pow(-1, backwards) * (x % (w + d)) / d + backwards;
5426 const clipped = Math.max(Math.min(uncliped, 1), 0);
5427 return clipped;
5428 }; // Figure out the value by incorporating the start time
5429
5430
5431 const endTime = t * (w + d) - w;
5432 position = x <= 0 ? Math.round(f(1e-5)) : x < endTime ? f(x) : Math.round(f(endTime - 1e-5));
5433 return position;
5434 } // Work out the loops done and add the position to the loops done
5435
5436
5437 const loopsDone = Math.floor(this.loops());
5438 const swingForward = s && loopsDone % 2 === 0;
5439 const forwards = swingForward && !r || r && swingForward;
5440 position = loopsDone + (forwards ? p : 1 - p);
5441 return this.loops(position);
5442 }
5443
5444 progress(p) {
5445 if (p == null) {
5446 return Math.min(1, this._time / this.duration());
5447 }
5448
5449 return this.time(p * this.duration());
5450 }
5451 /*
5452 Basic Functionality
5453 ===================
5454 These methods allow us to attach basic functions to the runner directly
5455 */
5456
5457
5458 queue(initFn, runFn, retargetFn, isTransform) {
5459 this._queue.push({
5460 initialiser: initFn || noop,
5461 runner: runFn || noop,
5462 retarget: retargetFn,
5463 isTransform: isTransform,
5464 initialised: false,
5465 finished: false
5466 });
5467
5468 const timeline = this.timeline();
5469 timeline && this.timeline()._continue();
5470 return this;
5471 }
5472
5473 reset() {
5474 if (this._reseted) return this;
5475 this.time(0);
5476 this._reseted = true;
5477 return this;
5478 }
5479
5480 reverse(reverse) {
5481 this._reverse = reverse == null ? !this._reverse : reverse;
5482 return this;
5483 }
5484
5485 schedule(timeline, delay, when) {
5486 // The user doesn't need to pass a timeline if we already have one
5487 if (!(timeline instanceof Timeline)) {
5488 when = delay;
5489 delay = timeline;
5490 timeline = this.timeline();
5491 } // If there is no timeline, yell at the user...
5492
5493
5494 if (!timeline) {
5495 throw Error('Runner cannot be scheduled without timeline');
5496 } // Schedule the runner on the timeline provided
5497
5498
5499 timeline.schedule(this, delay, when);
5500 return this;
5501 }
5502
5503 step(dt) {
5504 // If we are inactive, this stepper just gets skipped
5505 if (!this.enabled) return this; // Update the time and get the new position
5506
5507 dt = dt == null ? 16 : dt;
5508 this._time += dt;
5509 const position = this.position(); // Figure out if we need to run the stepper in this frame
5510
5511 const running = this._lastPosition !== position && this._time >= 0;
5512 this._lastPosition = position; // Figure out if we just started
5513
5514 const duration = this.duration();
5515 const justStarted = this._lastTime <= 0 && this._time > 0;
5516 const justFinished = this._lastTime < duration && this._time >= duration;
5517 this._lastTime = this._time;
5518
5519 if (justStarted) {
5520 this.fire('start', this);
5521 } // Work out if the runner is finished set the done flag here so animations
5522 // know, that they are running in the last step (this is good for
5523 // transformations which can be merged)
5524
5525
5526 const declarative = this._isDeclarative;
5527 this.done = !declarative && !justFinished && this._time >= duration; // Runner is running. So its not in reseted state anymore
5528
5529 this._reseted = false;
5530 let converged = false; // Call initialise and the run function
5531
5532 if (running || declarative) {
5533 this._initialise(running); // clear the transforms on this runner so they dont get added again and again
5534
5535
5536 this.transforms = new Matrix();
5537 converged = this._run(declarative ? dt : position);
5538 this.fire('step', this);
5539 } // correct the done flag here
5540 // declaritive animations itself know when they converged
5541
5542
5543 this.done = this.done || converged && declarative;
5544
5545 if (justFinished) {
5546 this.fire('finished', this);
5547 }
5548
5549 return this;
5550 }
5551 /*
5552 Runner animation methods
5553 ========================
5554 Control how the animation plays
5555 */
5556
5557
5558 time(time) {
5559 if (time == null) {
5560 return this._time;
5561 }
5562
5563 const dt = time - this._time;
5564 this.step(dt);
5565 return this;
5566 }
5567
5568 timeline(timeline) {
5569 // check explicitly for undefined so we can set the timeline to null
5570 if (typeof timeline === 'undefined') return this._timeline;
5571 this._timeline = timeline;
5572 return this;
5573 }
5574
5575 unschedule() {
5576 const timeline = this.timeline();
5577 timeline && timeline.unschedule(this);
5578 return this;
5579 } // Run each initialise function in the runner if required
5580
5581
5582 _initialise(running) {
5583 // If we aren't running, we shouldn't initialise when not declarative
5584 if (!running && !this._isDeclarative) return; // Loop through all of the initialisers
5585
5586 for (let i = 0, len = this._queue.length; i < len; ++i) {
5587 // Get the current initialiser
5588 const current = this._queue[i]; // Determine whether we need to initialise
5589
5590 const needsIt = this._isDeclarative || !current.initialised && running;
5591 running = !current.finished; // Call the initialiser if we need to
5592
5593 if (needsIt && running) {
5594 current.initialiser.call(this);
5595 current.initialised = true;
5596 }
5597 }
5598 } // Save a morpher to the morpher list so that we can retarget it later
5599
5600
5601 _rememberMorpher(method, morpher) {
5602 this._history[method] = {
5603 morpher: morpher,
5604 caller: this._queue[this._queue.length - 1]
5605 }; // We have to resume the timeline in case a controller
5606 // is already done without being ever run
5607 // This can happen when e.g. this is done:
5608 // anim = el.animate(new SVG.Spring)
5609 // and later
5610 // anim.move(...)
5611
5612 if (this._isDeclarative) {
5613 const timeline = this.timeline();
5614 timeline && timeline.play();
5615 }
5616 } // Try to set the target for a morpher if the morpher exists, otherwise
5617 // Run each run function for the position or dt given
5618
5619
5620 _run(positionOrDt) {
5621 // Run all of the _queue directly
5622 let allfinished = true;
5623
5624 for (let i = 0, len = this._queue.length; i < len; ++i) {
5625 // Get the current function to run
5626 const current = this._queue[i]; // Run the function if its not finished, we keep track of the finished
5627 // flag for the sake of declarative _queue
5628
5629 const converged = current.runner.call(this, positionOrDt);
5630 current.finished = current.finished || converged === true;
5631 allfinished = allfinished && current.finished;
5632 } // We report when all of the constructors are finished
5633
5634
5635 return allfinished;
5636 } // do nothing and return false
5637
5638
5639 _tryRetarget(method, target, extra) {
5640 if (this._history[method]) {
5641 // if the last method wasnt even initialised, throw it away
5642 if (!this._history[method].caller.initialised) {
5643 const index = this._queue.indexOf(this._history[method].caller);
5644
5645 this._queue.splice(index, 1);
5646
5647 return false;
5648 } // for the case of transformations, we use the special retarget function
5649 // which has access to the outer scope
5650
5651
5652 if (this._history[method].caller.retarget) {
5653 this._history[method].caller.retarget.call(this, target, extra); // for everything else a simple morpher change is sufficient
5654
5655 } else {
5656 this._history[method].morpher.to(target);
5657 }
5658
5659 this._history[method].caller.finished = false;
5660 const timeline = this.timeline();
5661 timeline && timeline.play();
5662 return true;
5663 }
5664
5665 return false;
5666 }
5667
5668 }
5669 Runner.id = 0;
5670 class FakeRunner {
5671 constructor(transforms = new Matrix(), id = -1, done = true) {
5672 this.transforms = transforms;
5673 this.id = id;
5674 this.done = done;
5675 }
5676
5677 clearTransformsFromQueue() {}
5678
5679 }
5680 extend([Runner, FakeRunner], {
5681 mergeWith(runner) {
5682 return new FakeRunner(runner.transforms.lmultiply(this.transforms), runner.id);
5683 }
5684
5685 }); // FakeRunner.emptyRunner = new FakeRunner()
5686
5687 const lmultiply = (last, curr) => last.lmultiplyO(curr);
5688
5689 const getRunnerTransform = runner => runner.transforms;
5690
5691 function mergeTransforms() {
5692 // Find the matrix to apply to the element and apply it
5693 const runners = this._transformationRunners.runners;
5694 const netTransform = runners.map(getRunnerTransform).reduce(lmultiply, new Matrix());
5695 this.transform(netTransform);
5696
5697 this._transformationRunners.merge();
5698
5699 if (this._transformationRunners.length() === 1) {
5700 this._frameId = null;
5701 }
5702 }
5703
5704 class RunnerArray {
5705 constructor() {
5706 this.runners = [];
5707 this.ids = [];
5708 }
5709
5710 add(runner) {
5711 if (this.runners.includes(runner)) return;
5712 const id = runner.id + 1;
5713 this.runners.push(runner);
5714 this.ids.push(id);
5715 return this;
5716 }
5717
5718 clearBefore(id) {
5719 const deleteCnt = this.ids.indexOf(id + 1) || 1;
5720 this.ids.splice(0, deleteCnt, 0);
5721 this.runners.splice(0, deleteCnt, new FakeRunner()).forEach(r => r.clearTransformsFromQueue());
5722 return this;
5723 }
5724
5725 edit(id, newRunner) {
5726 const index = this.ids.indexOf(id + 1);
5727 this.ids.splice(index, 1, id + 1);
5728 this.runners.splice(index, 1, newRunner);
5729 return this;
5730 }
5731
5732 getByID(id) {
5733 return this.runners[this.ids.indexOf(id + 1)];
5734 }
5735
5736 length() {
5737 return this.ids.length;
5738 }
5739
5740 merge() {
5741 let lastRunner = null;
5742
5743 for (let i = 0; i < this.runners.length; ++i) {
5744 const runner = this.runners[i];
5745 const condition = lastRunner && runner.done && lastRunner.done // don't merge runner when persisted on timeline
5746 && (!runner._timeline || !runner._timeline._runnerIds.includes(runner.id)) && (!lastRunner._timeline || !lastRunner._timeline._runnerIds.includes(lastRunner.id));
5747
5748 if (condition) {
5749 // the +1 happens in the function
5750 this.remove(runner.id);
5751 const newRunner = runner.mergeWith(lastRunner);
5752 this.edit(lastRunner.id, newRunner);
5753 lastRunner = newRunner;
5754 --i;
5755 } else {
5756 lastRunner = runner;
5757 }
5758 }
5759
5760 return this;
5761 }
5762
5763 remove(id) {
5764 const index = this.ids.indexOf(id + 1);
5765 this.ids.splice(index, 1);
5766 this.runners.splice(index, 1);
5767 return this;
5768 }
5769
5770 }
5771 registerMethods({
5772 Element: {
5773 animate(duration, delay, when) {
5774 const o = Runner.sanitise(duration, delay, when);
5775 const timeline = this.timeline();
5776 return new Runner(o.duration).loop(o).element(this).timeline(timeline.play()).schedule(o.delay, o.when);
5777 },
5778
5779 delay(by, when) {
5780 return this.animate(0, by, when);
5781 },
5782
5783 // this function searches for all runners on the element and deletes the ones
5784 // which run before the current one. This is because absolute transformations
5785 // overwfrite anything anyway so there is no need to waste time computing
5786 // other runners
5787 _clearTransformRunnersBefore(currentRunner) {
5788 this._transformationRunners.clearBefore(currentRunner.id);
5789 },
5790
5791 _currentTransform(current) {
5792 return this._transformationRunners.runners // we need the equal sign here to make sure, that also transformations
5793 // on the same runner which execute before the current transformation are
5794 // taken into account
5795 .filter(runner => runner.id <= current.id).map(getRunnerTransform).reduce(lmultiply, new Matrix());
5796 },
5797
5798 _addRunner(runner) {
5799 this._transformationRunners.add(runner); // Make sure that the runner merge is executed at the very end of
5800 // all Animator functions. Thats why we use immediate here to execute
5801 // the merge right after all frames are run
5802
5803
5804 Animator.cancelImmediate(this._frameId);
5805 this._frameId = Animator.immediate(mergeTransforms.bind(this));
5806 },
5807
5808 _prepareRunner() {
5809 if (this._frameId == null) {
5810 this._transformationRunners = new RunnerArray().add(new FakeRunner(new Matrix(this)));
5811 }
5812 }
5813
5814 }
5815 }); // Will output the elements from array A that are not in the array B
5816
5817 const difference = (a, b) => a.filter(x => !b.includes(x));
5818
5819 extend(Runner, {
5820 attr(a, v) {
5821 return this.styleAttr('attr', a, v);
5822 },
5823
5824 // Add animatable styles
5825 css(s, v) {
5826 return this.styleAttr('css', s, v);
5827 },
5828
5829 styleAttr(type, nameOrAttrs, val) {
5830 if (typeof nameOrAttrs === 'string') {
5831 return this.styleAttr(type, {
5832 [nameOrAttrs]: val
5833 });
5834 }
5835
5836 let attrs = nameOrAttrs;
5837 if (this._tryRetarget(type, attrs)) return this;
5838 let morpher = new Morphable(this._stepper).to(attrs);
5839 let keys = Object.keys(attrs);
5840 this.queue(function () {
5841 morpher = morpher.from(this.element()[type](keys));
5842 }, function (pos) {
5843 this.element()[type](morpher.at(pos).valueOf());
5844 return morpher.done();
5845 }, function (newToAttrs) {
5846 // Check if any new keys were added
5847 const newKeys = Object.keys(newToAttrs);
5848 const differences = difference(newKeys, keys); // If their are new keys, initialize them and add them to morpher
5849
5850 if (differences.length) {
5851 // Get the values
5852 const addedFromAttrs = this.element()[type](differences); // Get the already initialized values
5853
5854 const oldFromAttrs = new ObjectBag(morpher.from()).valueOf(); // Merge old and new
5855
5856 Object.assign(oldFromAttrs, addedFromAttrs);
5857 morpher.from(oldFromAttrs);
5858 } // Get the object from the morpher
5859
5860
5861 const oldToAttrs = new ObjectBag(morpher.to()).valueOf(); // Merge in new attributes
5862
5863 Object.assign(oldToAttrs, newToAttrs); // Change morpher target
5864
5865 morpher.to(oldToAttrs); // Make sure that we save the work we did so we don't need it to do again
5866
5867 keys = newKeys;
5868 attrs = newToAttrs;
5869 });
5870
5871 this._rememberMorpher(type, morpher);
5872
5873 return this;
5874 },
5875
5876 zoom(level, point) {
5877 if (this._tryRetarget('zoom', level, point)) return this;
5878 let morpher = new Morphable(this._stepper).to(new SVGNumber(level));
5879 this.queue(function () {
5880 morpher = morpher.from(this.element().zoom());
5881 }, function (pos) {
5882 this.element().zoom(morpher.at(pos), point);
5883 return morpher.done();
5884 }, function (newLevel, newPoint) {
5885 point = newPoint;
5886 morpher.to(newLevel);
5887 });
5888
5889 this._rememberMorpher('zoom', morpher);
5890
5891 return this;
5892 },
5893
5894 /**
5895 ** absolute transformations
5896 **/
5897 //
5898 // M v -----|-----(D M v = F v)------|-----> T v
5899 //
5900 // 1. define the final state (T) and decompose it (once)
5901 // t = [tx, ty, the, lam, sy, sx]
5902 // 2. on every frame: pull the current state of all previous transforms
5903 // (M - m can change)
5904 // and then write this as m = [tx0, ty0, the0, lam0, sy0, sx0]
5905 // 3. Find the interpolated matrix F(pos) = m + pos * (t - m)
5906 // - Note F(0) = M
5907 // - Note F(1) = T
5908 // 4. Now you get the delta matrix as a result: D = F * inv(M)
5909 transform(transforms, relative, affine) {
5910 // If we have a declarative function, we should retarget it if possible
5911 relative = transforms.relative || relative;
5912
5913 if (this._isDeclarative && !relative && this._tryRetarget('transform', transforms)) {
5914 return this;
5915 } // Parse the parameters
5916
5917
5918 const isMatrix = Matrix.isMatrixLike(transforms);
5919 affine = transforms.affine != null ? transforms.affine : affine != null ? affine : !isMatrix; // Create a morepher and set its type
5920
5921 const morpher = new Morphable(this._stepper).type(affine ? TransformBag : Matrix);
5922 let origin;
5923 let element;
5924 let current;
5925 let currentAngle;
5926 let startTransform;
5927
5928 function setup() {
5929 // make sure element and origin is defined
5930 element = element || this.element();
5931 origin = origin || getOrigin(transforms, element);
5932 startTransform = new Matrix(relative ? undefined : element); // add the runner to the element so it can merge transformations
5933
5934 element._addRunner(this); // Deactivate all transforms that have run so far if we are absolute
5935
5936
5937 if (!relative) {
5938 element._clearTransformRunnersBefore(this);
5939 }
5940 }
5941
5942 function run(pos) {
5943 // clear all other transforms before this in case something is saved
5944 // on this runner. We are absolute. We dont need these!
5945 if (!relative) this.clearTransform();
5946 const {
5947 x,
5948 y
5949 } = new Point(origin).transform(element._currentTransform(this));
5950 let target = new Matrix({ ...transforms,
5951 origin: [x, y]
5952 });
5953 let start = this._isDeclarative && current ? current : startTransform;
5954
5955 if (affine) {
5956 target = target.decompose(x, y);
5957 start = start.decompose(x, y); // Get the current and target angle as it was set
5958
5959 const rTarget = target.rotate;
5960 const rCurrent = start.rotate; // Figure out the shortest path to rotate directly
5961
5962 const possibilities = [rTarget - 360, rTarget, rTarget + 360];
5963 const distances = possibilities.map(a => Math.abs(a - rCurrent));
5964 const shortest = Math.min(...distances);
5965 const index = distances.indexOf(shortest);
5966 target.rotate = possibilities[index];
5967 }
5968
5969 if (relative) {
5970 // we have to be careful here not to overwrite the rotation
5971 // with the rotate method of Matrix
5972 if (!isMatrix) {
5973 target.rotate = transforms.rotate || 0;
5974 }
5975
5976 if (this._isDeclarative && currentAngle) {
5977 start.rotate = currentAngle;
5978 }
5979 }
5980
5981 morpher.from(start);
5982 morpher.to(target);
5983 const affineParameters = morpher.at(pos);
5984 currentAngle = affineParameters.rotate;
5985 current = new Matrix(affineParameters);
5986 this.addTransform(current);
5987
5988 element._addRunner(this);
5989
5990 return morpher.done();
5991 }
5992
5993 function retarget(newTransforms) {
5994 // only get a new origin if it changed since the last call
5995 if ((newTransforms.origin || 'center').toString() !== (transforms.origin || 'center').toString()) {
5996 origin = getOrigin(newTransforms, element);
5997 } // overwrite the old transformations with the new ones
5998
5999
6000 transforms = { ...newTransforms,
6001 origin
6002 };
6003 }
6004
6005 this.queue(setup, run, retarget, true);
6006 this._isDeclarative && this._rememberMorpher('transform', morpher);
6007 return this;
6008 },
6009
6010 // Animatable x-axis
6011 x(x, relative) {
6012 return this._queueNumber('x', x);
6013 },
6014
6015 // Animatable y-axis
6016 y(y) {
6017 return this._queueNumber('y', y);
6018 },
6019
6020 dx(x = 0) {
6021 return this._queueNumberDelta('x', x);
6022 },
6023
6024 dy(y = 0) {
6025 return this._queueNumberDelta('y', y);
6026 },
6027
6028 dmove(x, y) {
6029 return this.dx(x).dy(y);
6030 },
6031
6032 _queueNumberDelta(method, to) {
6033 to = new SVGNumber(to); // Try to change the target if we have this method already registerd
6034
6035 if (this._tryRetarget(method, to)) return this; // Make a morpher and queue the animation
6036
6037 const morpher = new Morphable(this._stepper).to(to);
6038 let from = null;
6039 this.queue(function () {
6040 from = this.element()[method]();
6041 morpher.from(from);
6042 morpher.to(from + to);
6043 }, function (pos) {
6044 this.element()[method](morpher.at(pos));
6045 return morpher.done();
6046 }, function (newTo) {
6047 morpher.to(from + new SVGNumber(newTo));
6048 }); // Register the morpher so that if it is changed again, we can retarget it
6049
6050 this._rememberMorpher(method, morpher);
6051
6052 return this;
6053 },
6054
6055 _queueObject(method, to) {
6056 // Try to change the target if we have this method already registerd
6057 if (this._tryRetarget(method, to)) return this; // Make a morpher and queue the animation
6058
6059 const morpher = new Morphable(this._stepper).to(to);
6060 this.queue(function () {
6061 morpher.from(this.element()[method]());
6062 }, function (pos) {
6063 this.element()[method](morpher.at(pos));
6064 return morpher.done();
6065 }); // Register the morpher so that if it is changed again, we can retarget it
6066
6067 this._rememberMorpher(method, morpher);
6068
6069 return this;
6070 },
6071
6072 _queueNumber(method, value) {
6073 return this._queueObject(method, new SVGNumber(value));
6074 },
6075
6076 // Animatable center x-axis
6077 cx(x) {
6078 return this._queueNumber('cx', x);
6079 },
6080
6081 // Animatable center y-axis
6082 cy(y) {
6083 return this._queueNumber('cy', y);
6084 },
6085
6086 // Add animatable move
6087 move(x, y) {
6088 return this.x(x).y(y);
6089 },
6090
6091 // Add animatable center
6092 center(x, y) {
6093 return this.cx(x).cy(y);
6094 },
6095
6096 // Add animatable size
6097 size(width, height) {
6098 // animate bbox based size for all other elements
6099 let box;
6100
6101 if (!width || !height) {
6102 box = this._element.bbox();
6103 }
6104
6105 if (!width) {
6106 width = box.width / box.height * height;
6107 }
6108
6109 if (!height) {
6110 height = box.height / box.width * width;
6111 }
6112
6113 return this.width(width).height(height);
6114 },
6115
6116 // Add animatable width
6117 width(width) {
6118 return this._queueNumber('width', width);
6119 },
6120
6121 // Add animatable height
6122 height(height) {
6123 return this._queueNumber('height', height);
6124 },
6125
6126 // Add animatable plot
6127 plot(a, b, c, d) {
6128 // Lines can be plotted with 4 arguments
6129 if (arguments.length === 4) {
6130 return this.plot([a, b, c, d]);
6131 }
6132
6133 if (this._tryRetarget('plot', a)) return this;
6134 const morpher = new Morphable(this._stepper).type(this._element.MorphArray).to(a);
6135 this.queue(function () {
6136 morpher.from(this._element.array());
6137 }, function (pos) {
6138 this._element.plot(morpher.at(pos));
6139
6140 return morpher.done();
6141 });
6142
6143 this._rememberMorpher('plot', morpher);
6144
6145 return this;
6146 },
6147
6148 // Add leading method
6149 leading(value) {
6150 return this._queueNumber('leading', value);
6151 },
6152
6153 // Add animatable viewbox
6154 viewbox(x, y, width, height) {
6155 return this._queueObject('viewbox', new Box(x, y, width, height));
6156 },
6157
6158 update(o) {
6159 if (typeof o !== 'object') {
6160 return this.update({
6161 offset: arguments[0],
6162 color: arguments[1],
6163 opacity: arguments[2]
6164 });
6165 }
6166
6167 if (o.opacity != null) this.attr('stop-opacity', o.opacity);
6168 if (o.color != null) this.attr('stop-color', o.color);
6169 if (o.offset != null) this.attr('offset', o.offset);
6170 return this;
6171 }
6172
6173 });
6174 extend(Runner, {
6175 rx,
6176 ry,
6177 from,
6178 to
6179 });
6180 register(Runner, 'Runner');
6181
6182 class Svg extends Container {
6183 constructor(node, attrs = node) {
6184 super(nodeOrNew('svg', node), attrs);
6185 this.namespace();
6186 } // Creates and returns defs element
6187
6188
6189 defs() {
6190 if (!this.isRoot()) return this.root().defs();
6191 return adopt(this.node.querySelector('defs')) || this.put(new Defs());
6192 }
6193
6194 isRoot() {
6195 return !this.node.parentNode || !(this.node.parentNode instanceof globals.window.SVGElement) && this.node.parentNode.nodeName !== '#document-fragment';
6196 } // Add namespaces
6197
6198
6199 namespace() {
6200 if (!this.isRoot()) return this.root().namespace();
6201 return this.attr({
6202 xmlns: svg,
6203 version: '1.1'
6204 }).attr('xmlns:xlink', xlink, xmlns).attr('xmlns:svgjs', svgjs, xmlns);
6205 }
6206
6207 removeNamespace() {
6208 return this.attr({
6209 xmlns: null,
6210 version: null
6211 }).attr('xmlns:xlink', null, xmlns).attr('xmlns:svgjs', null, xmlns);
6212 } // Check if this is a root svg
6213 // If not, call root() from this element
6214
6215
6216 root() {
6217 if (this.isRoot()) return this;
6218 return super.root();
6219 }
6220
6221 }
6222 registerMethods({
6223 Container: {
6224 // Create nested svg document
6225 nested: wrapWithAttrCheck(function () {
6226 return this.put(new Svg());
6227 })
6228 }
6229 });
6230 register(Svg, 'Svg', true);
6231
6232 class Symbol extends Container {
6233 // Initialize node
6234 constructor(node, attrs = node) {
6235 super(nodeOrNew('symbol', node), attrs);
6236 }
6237
6238 }
6239 registerMethods({
6240 Container: {
6241 symbol: wrapWithAttrCheck(function () {
6242 return this.put(new Symbol());
6243 })
6244 }
6245 });
6246 register(Symbol, 'Symbol');
6247
6248 function plain(text) {
6249 // clear if build mode is disabled
6250 if (this._build === false) {
6251 this.clear();
6252 } // create text node
6253
6254
6255 this.node.appendChild(globals.document.createTextNode(text));
6256 return this;
6257 } // Get length of text element
6258
6259 function length() {
6260 return this.node.getComputedTextLength();
6261 } // Move over x-axis
6262 // Text is moved by its bounding box
6263 // text-anchor does NOT matter
6264
6265 function x$1(x, box = this.bbox()) {
6266 if (x == null) {
6267 return box.x;
6268 }
6269
6270 return this.attr('x', this.attr('x') + x - box.x);
6271 } // Move over y-axis
6272
6273 function y$1(y, box = this.bbox()) {
6274 if (y == null) {
6275 return box.y;
6276 }
6277
6278 return this.attr('y', this.attr('y') + y - box.y);
6279 }
6280 function move$1(x, y, box = this.bbox()) {
6281 return this.x(x, box).y(y, box);
6282 } // Move center over x-axis
6283
6284 function cx(x, box = this.bbox()) {
6285 if (x == null) {
6286 return box.cx;
6287 }
6288
6289 return this.attr('x', this.attr('x') + x - box.cx);
6290 } // Move center over y-axis
6291
6292 function cy(y, box = this.bbox()) {
6293 if (y == null) {
6294 return box.cy;
6295 }
6296
6297 return this.attr('y', this.attr('y') + y - box.cy);
6298 }
6299 function center(x, y, box = this.bbox()) {
6300 return this.cx(x, box).cy(y, box);
6301 }
6302 function ax(x) {
6303 return this.attr('x', x);
6304 }
6305 function ay(y) {
6306 return this.attr('y', y);
6307 }
6308 function amove(x, y) {
6309 return this.ax(x).ay(y);
6310 } // Enable / disable build mode
6311
6312 function build(build) {
6313 this._build = !!build;
6314 return this;
6315 }
6316
6317 var textable = {
6318 __proto__: null,
6319 plain: plain,
6320 length: length,
6321 x: x$1,
6322 y: y$1,
6323 move: move$1,
6324 cx: cx,
6325 cy: cy,
6326 center: center,
6327 ax: ax,
6328 ay: ay,
6329 amove: amove,
6330 build: build
6331 };
6332
6333 class Text extends Shape {
6334 // Initialize node
6335 constructor(node, attrs = node) {
6336 super(nodeOrNew('text', node), attrs);
6337 this.dom.leading = new SVGNumber(1.3); // store leading value for rebuilding
6338
6339 this._rebuild = true; // enable automatic updating of dy values
6340
6341 this._build = false; // disable build mode for adding multiple lines
6342 } // Set / get leading
6343
6344
6345 leading(value) {
6346 // act as getter
6347 if (value == null) {
6348 return this.dom.leading;
6349 } // act as setter
6350
6351
6352 this.dom.leading = new SVGNumber(value);
6353 return this.rebuild();
6354 } // Rebuild appearance type
6355
6356
6357 rebuild(rebuild) {
6358 // store new rebuild flag if given
6359 if (typeof rebuild === 'boolean') {
6360 this._rebuild = rebuild;
6361 } // define position of all lines
6362
6363
6364 if (this._rebuild) {
6365 const self = this;
6366 let blankLineOffset = 0;
6367 const leading = this.dom.leading;
6368 this.each(function (i) {
6369 const fontSize = globals.window.getComputedStyle(this.node).getPropertyValue('font-size');
6370 const dy = leading * new SVGNumber(fontSize);
6371
6372 if (this.dom.newLined) {
6373 this.attr('x', self.attr('x'));
6374
6375 if (this.text() === '\n') {
6376 blankLineOffset += dy;
6377 } else {
6378 this.attr('dy', i ? dy + blankLineOffset : 0);
6379 blankLineOffset = 0;
6380 }
6381 }
6382 });
6383 this.fire('rebuild');
6384 }
6385
6386 return this;
6387 } // overwrite method from parent to set data properly
6388
6389
6390 setData(o) {
6391 this.dom = o;
6392 this.dom.leading = new SVGNumber(o.leading || 1.3);
6393 return this;
6394 } // Set the text content
6395
6396
6397 text(text) {
6398 // act as getter
6399 if (text === undefined) {
6400 const children = this.node.childNodes;
6401 let firstLine = 0;
6402 text = '';
6403
6404 for (let i = 0, len = children.length; i < len; ++i) {
6405 // skip textPaths - they are no lines
6406 if (children[i].nodeName === 'textPath') {
6407 if (i === 0) firstLine = 1;
6408 continue;
6409 } // add newline if its not the first child and newLined is set to true
6410
6411
6412 if (i !== firstLine && children[i].nodeType !== 3 && adopt(children[i]).dom.newLined === true) {
6413 text += '\n';
6414 } // add content of this node
6415
6416
6417 text += children[i].textContent;
6418 }
6419
6420 return text;
6421 } // remove existing content
6422
6423
6424 this.clear().build(true);
6425
6426 if (typeof text === 'function') {
6427 // call block
6428 text.call(this, this);
6429 } else {
6430 // store text and make sure text is not blank
6431 text = (text + '').split('\n'); // build new lines
6432
6433 for (let j = 0, jl = text.length; j < jl; j++) {
6434 this.newLine(text[j]);
6435 }
6436 } // disable build mode and rebuild lines
6437
6438
6439 return this.build(false).rebuild();
6440 }
6441
6442 }
6443 extend(Text, textable);
6444 registerMethods({
6445 Container: {
6446 // Create text element
6447 text: wrapWithAttrCheck(function (text = '') {
6448 return this.put(new Text()).text(text);
6449 }),
6450 // Create plain text element
6451 plain: wrapWithAttrCheck(function (text = '') {
6452 return this.put(new Text()).plain(text);
6453 })
6454 }
6455 });
6456 register(Text, 'Text');
6457
6458 class Tspan extends Shape {
6459 // Initialize node
6460 constructor(node, attrs = node) {
6461 super(nodeOrNew('tspan', node), attrs);
6462 this._build = false; // disable build mode for adding multiple lines
6463 } // Shortcut dx
6464
6465
6466 dx(dx) {
6467 return this.attr('dx', dx);
6468 } // Shortcut dy
6469
6470
6471 dy(dy) {
6472 return this.attr('dy', dy);
6473 } // Create new line
6474
6475
6476 newLine() {
6477 // mark new line
6478 this.dom.newLined = true; // fetch parent
6479
6480 const text = this.parent(); // early return in case we are not in a text element
6481
6482 if (!(text instanceof Text)) {
6483 return this;
6484 }
6485
6486 const i = text.index(this);
6487 const fontSize = globals.window.getComputedStyle(this.node).getPropertyValue('font-size');
6488 const dy = text.dom.leading * new SVGNumber(fontSize); // apply new position
6489
6490 return this.dy(i ? dy : 0).attr('x', text.x());
6491 } // Set text content
6492
6493
6494 text(text) {
6495 if (text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '');
6496
6497 if (typeof text === 'function') {
6498 this.clear().build(true);
6499 text.call(this, this);
6500 this.build(false);
6501 } else {
6502 this.plain(text);
6503 }
6504
6505 return this;
6506 }
6507
6508 }
6509 extend(Tspan, textable);
6510 registerMethods({
6511 Tspan: {
6512 tspan: wrapWithAttrCheck(function (text = '') {
6513 const tspan = new Tspan(); // clear if build mode is disabled
6514
6515 if (!this._build) {
6516 this.clear();
6517 } // add new tspan
6518
6519
6520 return this.put(tspan).text(text);
6521 })
6522 },
6523 Text: {
6524 newLine: function (text = '') {
6525 return this.tspan(text).newLine();
6526 }
6527 }
6528 });
6529 register(Tspan, 'Tspan');
6530
6531 class Circle extends Shape {
6532 constructor(node, attrs = node) {
6533 super(nodeOrNew('circle', node), attrs);
6534 }
6535
6536 radius(r) {
6537 return this.attr('r', r);
6538 } // Radius x value
6539
6540
6541 rx(rx) {
6542 return this.attr('r', rx);
6543 } // Alias radius x value
6544
6545
6546 ry(ry) {
6547 return this.rx(ry);
6548 }
6549
6550 size(size) {
6551 return this.radius(new SVGNumber(size).divide(2));
6552 }
6553
6554 }
6555 extend(Circle, {
6556 x: x$3,
6557 y: y$3,
6558 cx: cx$1,
6559 cy: cy$1,
6560 width: width$2,
6561 height: height$2
6562 });
6563 registerMethods({
6564 Container: {
6565 // Create circle element
6566 circle: wrapWithAttrCheck(function (size = 0) {
6567 return this.put(new Circle()).size(size).move(0, 0);
6568 })
6569 }
6570 });
6571 register(Circle, 'Circle');
6572
6573 class ClipPath extends Container {
6574 constructor(node, attrs = node) {
6575 super(nodeOrNew('clipPath', node), attrs);
6576 } // Unclip all clipped elements and remove itself
6577
6578
6579 remove() {
6580 // unclip all targets
6581 this.targets().forEach(function (el) {
6582 el.unclip();
6583 }); // remove clipPath from parent
6584
6585 return super.remove();
6586 }
6587
6588 targets() {
6589 return baseFind('svg [clip-path*="' + this.id() + '"]');
6590 }
6591
6592 }
6593 registerMethods({
6594 Container: {
6595 // Create clipping element
6596 clip: wrapWithAttrCheck(function () {
6597 return this.defs().put(new ClipPath());
6598 })
6599 },
6600 Element: {
6601 // Distribute clipPath to svg element
6602 clipper() {
6603 return this.reference('clip-path');
6604 },
6605
6606 clipWith(element) {
6607 // use given clip or create a new one
6608 const clipper = element instanceof ClipPath ? element : this.parent().clip().add(element); // apply mask
6609
6610 return this.attr('clip-path', 'url("#' + clipper.id() + '")');
6611 },
6612
6613 // Unclip element
6614 unclip() {
6615 return this.attr('clip-path', null);
6616 }
6617
6618 }
6619 });
6620 register(ClipPath, 'ClipPath');
6621
6622 class ForeignObject extends Element {
6623 constructor(node, attrs = node) {
6624 super(nodeOrNew('foreignObject', node), attrs);
6625 }
6626
6627 }
6628 registerMethods({
6629 Container: {
6630 foreignObject: wrapWithAttrCheck(function (width, height) {
6631 return this.put(new ForeignObject()).size(width, height);
6632 })
6633 }
6634 });
6635 register(ForeignObject, 'ForeignObject');
6636
6637 function dmove(dx, dy) {
6638 this.children().forEach((child, i) => {
6639 let bbox; // We have to wrap this for elements that dont have a bbox
6640 // e.g. title and other descriptive elements
6641
6642 try {
6643 // Get the childs bbox
6644 bbox = child.bbox();
6645 } catch (e) {
6646 return;
6647 } // Get childs matrix
6648
6649
6650 const m = new Matrix(child); // Translate childs matrix by amount and
6651 // transform it back into parents space
6652
6653 const matrix = m.translate(dx, dy).transform(m.inverse()); // Calculate new x and y from old box
6654
6655 const p = new Point(bbox.x, bbox.y).transform(matrix); // Move element
6656
6657 child.move(p.x, p.y);
6658 });
6659 return this;
6660 }
6661 function dx(dx) {
6662 return this.dmove(dx, 0);
6663 }
6664 function dy(dy) {
6665 return this.dmove(0, dy);
6666 }
6667 function height(height, box = this.bbox()) {
6668 if (height == null) return box.height;
6669 return this.size(box.width, height, box);
6670 }
6671 function move(x = 0, y = 0, box = this.bbox()) {
6672 const dx = x - box.x;
6673 const dy = y - box.y;
6674 return this.dmove(dx, dy);
6675 }
6676 function size(width, height, box = this.bbox()) {
6677 const p = proportionalSize(this, width, height, box);
6678 const scaleX = p.width / box.width;
6679 const scaleY = p.height / box.height;
6680 this.children().forEach((child, i) => {
6681 const o = new Point(box).transform(new Matrix(child).inverse());
6682 child.scale(scaleX, scaleY, o.x, o.y);
6683 });
6684 return this;
6685 }
6686 function width(width, box = this.bbox()) {
6687 if (width == null) return box.width;
6688 return this.size(width, box.height, box);
6689 }
6690 function x(x, box = this.bbox()) {
6691 if (x == null) return box.x;
6692 return this.move(x, box.y, box);
6693 }
6694 function y(y, box = this.bbox()) {
6695 if (y == null) return box.y;
6696 return this.move(box.x, y, box);
6697 }
6698
6699 var containerGeometry = {
6700 __proto__: null,
6701 dmove: dmove,
6702 dx: dx,
6703 dy: dy,
6704 height: height,
6705 move: move,
6706 size: size,
6707 width: width,
6708 x: x,
6709 y: y
6710 };
6711
6712 class G extends Container {
6713 constructor(node, attrs = node) {
6714 super(nodeOrNew('g', node), attrs);
6715 }
6716
6717 }
6718 extend(G, containerGeometry);
6719 registerMethods({
6720 Container: {
6721 // Create a group element
6722 group: wrapWithAttrCheck(function () {
6723 return this.put(new G());
6724 })
6725 }
6726 });
6727 register(G, 'G');
6728
6729 class A extends Container {
6730 constructor(node, attrs = node) {
6731 super(nodeOrNew('a', node), attrs);
6732 } // Link target attribute
6733
6734
6735 target(target) {
6736 return this.attr('target', target);
6737 } // Link url
6738
6739
6740 to(url) {
6741 return this.attr('href', url, xlink);
6742 }
6743
6744 }
6745 extend(A, containerGeometry);
6746 registerMethods({
6747 Container: {
6748 // Create a hyperlink element
6749 link: wrapWithAttrCheck(function (url) {
6750 return this.put(new A()).to(url);
6751 })
6752 },
6753 Element: {
6754 unlink() {
6755 const link = this.linker();
6756 if (!link) return this;
6757 const parent = link.parent();
6758
6759 if (!parent) {
6760 return this.remove();
6761 }
6762
6763 const index = parent.index(link);
6764 parent.add(this, index);
6765 link.remove();
6766 return this;
6767 },
6768
6769 linkTo(url) {
6770 // reuse old link if possible
6771 let link = this.linker();
6772
6773 if (!link) {
6774 link = new A();
6775 this.wrap(link);
6776 }
6777
6778 if (typeof url === 'function') {
6779 url.call(link, link);
6780 } else {
6781 link.to(url);
6782 }
6783
6784 return this;
6785 },
6786
6787 linker() {
6788 const link = this.parent();
6789
6790 if (link && link.node.nodeName.toLowerCase() === 'a') {
6791 return link;
6792 }
6793
6794 return null;
6795 }
6796
6797 }
6798 });
6799 register(A, 'A');
6800
6801 class Mask extends Container {
6802 // Initialize node
6803 constructor(node, attrs = node) {
6804 super(nodeOrNew('mask', node), attrs);
6805 } // Unmask all masked elements and remove itself
6806
6807
6808 remove() {
6809 // unmask all targets
6810 this.targets().forEach(function (el) {
6811 el.unmask();
6812 }); // remove mask from parent
6813
6814 return super.remove();
6815 }
6816
6817 targets() {
6818 return baseFind('svg [mask*="' + this.id() + '"]');
6819 }
6820
6821 }
6822 registerMethods({
6823 Container: {
6824 mask: wrapWithAttrCheck(function () {
6825 return this.defs().put(new Mask());
6826 })
6827 },
6828 Element: {
6829 // Distribute mask to svg element
6830 masker() {
6831 return this.reference('mask');
6832 },
6833
6834 maskWith(element) {
6835 // use given mask or create a new one
6836 const masker = element instanceof Mask ? element : this.parent().mask().add(element); // apply mask
6837
6838 return this.attr('mask', 'url("#' + masker.id() + '")');
6839 },
6840
6841 // Unmask element
6842 unmask() {
6843 return this.attr('mask', null);
6844 }
6845
6846 }
6847 });
6848 register(Mask, 'Mask');
6849
6850 class Stop extends Element {
6851 constructor(node, attrs = node) {
6852 super(nodeOrNew('stop', node), attrs);
6853 } // add color stops
6854
6855
6856 update(o) {
6857 if (typeof o === 'number' || o instanceof SVGNumber) {
6858 o = {
6859 offset: arguments[0],
6860 color: arguments[1],
6861 opacity: arguments[2]
6862 };
6863 } // set attributes
6864
6865
6866 if (o.opacity != null) this.attr('stop-opacity', o.opacity);
6867 if (o.color != null) this.attr('stop-color', o.color);
6868 if (o.offset != null) this.attr('offset', new SVGNumber(o.offset));
6869 return this;
6870 }
6871
6872 }
6873 registerMethods({
6874 Gradient: {
6875 // Add a color stop
6876 stop: function (offset, color, opacity) {
6877 return this.put(new Stop()).update(offset, color, opacity);
6878 }
6879 }
6880 });
6881 register(Stop, 'Stop');
6882
6883 function cssRule(selector, rule) {
6884 if (!selector) return '';
6885 if (!rule) return selector;
6886 let ret = selector + '{';
6887
6888 for (const i in rule) {
6889 ret += unCamelCase(i) + ':' + rule[i] + ';';
6890 }
6891
6892 ret += '}';
6893 return ret;
6894 }
6895
6896 class Style extends Element {
6897 constructor(node, attrs = node) {
6898 super(nodeOrNew('style', node), attrs);
6899 }
6900
6901 addText(w = '') {
6902 this.node.textContent += w;
6903 return this;
6904 }
6905
6906 font(name, src, params = {}) {
6907 return this.rule('@font-face', {
6908 fontFamily: name,
6909 src: src,
6910 ...params
6911 });
6912 }
6913
6914 rule(selector, obj) {
6915 return this.addText(cssRule(selector, obj));
6916 }
6917
6918 }
6919 registerMethods('Dom', {
6920 style(selector, obj) {
6921 return this.put(new Style()).rule(selector, obj);
6922 },
6923
6924 fontface(name, src, params) {
6925 return this.put(new Style()).font(name, src, params);
6926 }
6927
6928 });
6929 register(Style, 'Style');
6930
6931 class TextPath extends Text {
6932 // Initialize node
6933 constructor(node, attrs = node) {
6934 super(nodeOrNew('textPath', node), attrs);
6935 } // return the array of the path track element
6936
6937
6938 array() {
6939 const track = this.track();
6940 return track ? track.array() : null;
6941 } // Plot path if any
6942
6943
6944 plot(d) {
6945 const track = this.track();
6946 let pathArray = null;
6947
6948 if (track) {
6949 pathArray = track.plot(d);
6950 }
6951
6952 return d == null ? pathArray : this;
6953 } // Get the path element
6954
6955
6956 track() {
6957 return this.reference('href');
6958 }
6959
6960 }
6961 registerMethods({
6962 Container: {
6963 textPath: wrapWithAttrCheck(function (text, path) {
6964 // Convert text to instance if needed
6965 if (!(text instanceof Text)) {
6966 text = this.text(text);
6967 }
6968
6969 return text.path(path);
6970 })
6971 },
6972 Text: {
6973 // Create path for text to run on
6974 path: wrapWithAttrCheck(function (track, importNodes = true) {
6975 const textPath = new TextPath(); // if track is a path, reuse it
6976
6977 if (!(track instanceof Path)) {
6978 // create path element
6979 track = this.defs().path(track);
6980 } // link textPath to path and add content
6981
6982
6983 textPath.attr('href', '#' + track, xlink); // Transplant all nodes from text to textPath
6984
6985 let node;
6986
6987 if (importNodes) {
6988 while (node = this.node.firstChild) {
6989 textPath.node.appendChild(node);
6990 }
6991 } // add textPath element as child node and return textPath
6992
6993
6994 return this.put(textPath);
6995 }),
6996
6997 // Get the textPath children
6998 textPath() {
6999 return this.findOne('textPath');
7000 }
7001
7002 },
7003 Path: {
7004 // creates a textPath from this path
7005 text: wrapWithAttrCheck(function (text) {
7006 // Convert text to instance if needed
7007 if (!(text instanceof Text)) {
7008 text = new Text().addTo(this.parent()).text(text);
7009 } // Create textPath from text and path and return
7010
7011
7012 return text.path(this);
7013 }),
7014
7015 targets() {
7016 return baseFind('svg textPath').filter(node => {
7017 return (node.attr('href') || '').includes(this.id());
7018 }); // Does not work in IE11. Use when IE support is dropped
7019 // return baseFind('svg textPath[*|href*="' + this.id() + '"]')
7020 }
7021
7022 }
7023 });
7024 TextPath.prototype.MorphArray = PathArray;
7025 register(TextPath, 'TextPath');
7026
7027 class Use extends Shape {
7028 constructor(node, attrs = node) {
7029 super(nodeOrNew('use', node), attrs);
7030 } // Use element as a reference
7031
7032
7033 use(element, file) {
7034 // Set lined element
7035 return this.attr('href', (file || '') + '#' + element, xlink);
7036 }
7037
7038 }
7039 registerMethods({
7040 Container: {
7041 // Create a use element
7042 use: wrapWithAttrCheck(function (element, file) {
7043 return this.put(new Use()).use(element, file);
7044 })
7045 }
7046 });
7047 register(Use, 'Use');
7048
7049 /* Optional Modules */
7050 const SVG$1 = makeInstance;
7051 extend([Svg, Symbol, Image, Pattern, Marker], getMethodsFor('viewbox'));
7052 extend([Line, Polyline, Polygon, Path], getMethodsFor('marker'));
7053 extend(Text, getMethodsFor('Text'));
7054 extend(Path, getMethodsFor('Path'));
7055 extend(Defs, getMethodsFor('Defs'));
7056 extend([Text, Tspan], getMethodsFor('Tspan'));
7057 extend([Rect, Ellipse, Gradient, Runner], getMethodsFor('radius'));
7058 extend(EventTarget, getMethodsFor('EventTarget'));
7059 extend(Dom, getMethodsFor('Dom'));
7060 extend(Element, getMethodsFor('Element'));
7061 extend(Shape, getMethodsFor('Shape'));
7062 extend([Container, Fragment], getMethodsFor('Container'));
7063 extend(Gradient, getMethodsFor('Gradient'));
7064 extend(Runner, getMethodsFor('Runner'));
7065 List.extend(getMethodNames());
7066 registerMorphableType([SVGNumber, Color, Box, Matrix, SVGArray, PointArray, PathArray, Point]);
7067 makeMorphable();
7068
7069 var svgMembers = {
7070 __proto__: null,
7071 Morphable: Morphable,
7072 registerMorphableType: registerMorphableType,
7073 makeMorphable: makeMorphable,
7074 TransformBag: TransformBag,
7075 ObjectBag: ObjectBag,
7076 NonMorphable: NonMorphable,
7077 defaults: defaults,
7078 utils: utils,
7079 namespaces: namespaces,
7080 regex: regex,
7081 SVG: SVG$1,
7082 parser: parser,
7083 find: baseFind,
7084 getWindow: getWindow,
7085 registerWindow: registerWindow,
7086 restoreWindow: restoreWindow,
7087 saveWindow: saveWindow,
7088 withWindow: withWindow,
7089 Animator: Animator,
7090 Controller: Controller,
7091 Ease: Ease,
7092 PID: PID,
7093 Spring: Spring,
7094 easing: easing,
7095 Queue: Queue,
7096 Runner: Runner,
7097 Timeline: Timeline,
7098 Array: SVGArray,
7099 Box: Box,
7100 Color: Color,
7101 EventTarget: EventTarget,
7102 Matrix: Matrix,
7103 Number: SVGNumber,
7104 PathArray: PathArray,
7105 Point: Point,
7106 PointArray: PointArray,
7107 List: List,
7108 Circle: Circle,
7109 ClipPath: ClipPath,
7110 Container: Container,
7111 Defs: Defs,
7112 Dom: Dom,
7113 Element: Element,
7114 Ellipse: Ellipse,
7115 ForeignObject: ForeignObject,
7116 Fragment: Fragment,
7117 Gradient: Gradient,
7118 G: G,
7119 A: A,
7120 Image: Image,
7121 Line: Line,
7122 Marker: Marker,
7123 Mask: Mask,
7124 Path: Path,
7125 Pattern: Pattern,
7126 Polygon: Polygon,
7127 Polyline: Polyline,
7128 Rect: Rect,
7129 Shape: Shape,
7130 Stop: Stop,
7131 Style: Style,
7132 Svg: Svg,
7133 Symbol: Symbol,
7134 Text: Text,
7135 TextPath: TextPath,
7136 Tspan: Tspan,
7137 Use: Use,
7138 windowEvents: windowEvents,
7139 getEvents: getEvents,
7140 getEventTarget: getEventTarget,
7141 clearEvents: clearEvents,
7142 on: on,
7143 off: off,
7144 dispatch: dispatch,
7145 root: root,
7146 create: create,
7147 makeInstance: makeInstance,
7148 nodeOrNew: nodeOrNew,
7149 adopt: adopt,
7150 mockAdopt: mockAdopt,
7151 register: register,
7152 getClass: getClass,
7153 eid: eid,
7154 assignNewId: assignNewId,
7155 extend: extend,
7156 wrapWithAttrCheck: wrapWithAttrCheck
7157 };
7158
7159 function SVG(element, isHTML) {
7160 return makeInstance(element, isHTML);
7161 }
7162 Object.assign(SVG, svgMembers);
7163
7164 return SVG;
7165
7166 })();
7167 //# sourceMappingURL=svg.js.map