PluginProbe
APCu Manager / trunk
APCu Manager vtrunk
4.6.0 4.6.1 4.5.4 4.5.2 4.5.3 4.5.1 trunk 1.0.0 1.1.0 1.2.0 1.2.1 1.2.2 1.2.3 1.3.0 2.0.0 2.1.0 2.2.0 2.3.0 2.4.0 2.4.1 2.5.0 2.6.0 3.0.0 3.0.1 3.1.0 All 49 releases
apcu-manager / admin / js / chartist.js

chartist.js in APCu Manager trunk, at admin/js/chartist.js

4,516 lines 208.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function (root, factory) {
2 if (typeof define === 'function' && define.amd) {
3 // AMD. Register as an anonymous module unless amdModuleId is set
4 define('Chartist', [], function () {
5 return (root['Chartist'] = factory());
6 });
7 } else if (typeof module === 'object' && module.exports) {
8 // Node. Does not work with strict CommonJS, but
9 // only CommonJS-like environments that support module.exports,
10 // like Node.
11 module.exports = factory();
12 } else {
13 root['Chartist'] = factory();
14 }
15 }(this, function () {
16
17 /* Chartist.js 0.11.4
18 * Copyright © 2019 Gion Kunz
19 * Free to use under either the WTFPL license or the MIT license.
20 * https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-WTFPL
21 * https://raw.githubusercontent.com/gionkunz/chartist-js/master/LICENSE-MIT
22 */
23 /**
24 * The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.
25 *
26 * @module Chartist.Core
27 */
28 var Chartist = {
29 version: '0.11.4'
30 };
31
32 (function (globalRoot, Chartist) {
33 'use strict';
34
35 var window = globalRoot.window;
36 var document = globalRoot.document;
37
38 /**
39 * This object contains all namespaces used within Chartist.
40 *
41 * @memberof Chartist.Core
42 * @type {{svg: string, xmlns: string, xhtml: string, xlink: string, ct: string}}
43 */
44 Chartist.namespaces = {
45 svg: 'http://www.w3.org/2000/svg',
46 xmlns: 'http://www.w3.org/2000/xmlns/',
47 xhtml: 'http://www.w3.org/1999/xhtml',
48 xlink: 'http://www.w3.org/1999/xlink',
49 ct: 'http://gionkunz.github.com/chartist-js/ct'
50 };
51
52 /**
53 * Helps to simplify functional style code
54 *
55 * @memberof Chartist.Core
56 * @param {*} n This exact value will be returned by the noop function
57 * @return {*} The same value that was provided to the n parameter
58 */
59 Chartist.noop = function (n) {
60 return n;
61 };
62
63 /**
64 * Generates a-z from a number 0 to 26
65 *
66 * @memberof Chartist.Core
67 * @param {Number} n A number from 0 to 26 that will result in a letter a-z
68 * @return {String} A character from a-z based on the input number n
69 */
70 Chartist.alphaNumerate = function (n) {
71 // Limit to a-z
72 return String.fromCharCode(97 + n % 26);
73 };
74
75 /**
76 * Simple recursive object extend
77 *
78 * @memberof Chartist.Core
79 * @param {Object} target Target object where the source will be merged into
80 * @param {Object...} sources This object (objects) will be merged into target and then target is returned
81 * @return {Object} An object that has the same reference as target but is extended and merged with the properties of source
82 */
83 Chartist.extend = function (target) {
84 var i, source, sourceProp;
85 target = target || {};
86
87 for (i = 1; i < arguments.length; i++) {
88 source = arguments[i];
89 for (var prop in source) {
90 sourceProp = source[prop];
91 if (typeof sourceProp === 'object' && sourceProp !== null && !(sourceProp instanceof Array)) {
92 target[prop] = Chartist.extend(target[prop], sourceProp);
93 } else {
94 target[prop] = sourceProp;
95 }
96 }
97 }
98
99 return target;
100 };
101
102 /**
103 * Replaces all occurrences of subStr in str with newSubStr and returns a new string.
104 *
105 * @memberof Chartist.Core
106 * @param {String} str
107 * @param {String} subStr
108 * @param {String} newSubStr
109 * @return {String}
110 */
111 Chartist.replaceAll = function(str, subStr, newSubStr) {
112 return str.replace(new RegExp(subStr, 'g'), newSubStr);
113 };
114
115 /**
116 * Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.
117 *
118 * @memberof Chartist.Core
119 * @param {Number} value
120 * @param {String} unit
121 * @return {String} Returns the passed number value with unit.
122 */
123 Chartist.ensureUnit = function(value, unit) {
124 if(typeof value === 'number') {
125 value = value + unit;
126 }
127
128 return value;
129 };
130
131 /**
132 * Converts a number or string to a quantity object.
133 *
134 * @memberof Chartist.Core
135 * @param {String|Number} input
136 * @return {Object} Returns an object containing the value as number and the unit as string.
137 */
138 Chartist.quantity = function(input) {
139 if (typeof input === 'string') {
140 var match = (/^(\d+)\s*(.*)$/g).exec(input);
141 return {
142 value : +match[1],
143 unit: match[2] || undefined
144 };
145 }
146 return { value: input };
147 };
148
149 /**
150 * This is a wrapper around document.querySelector that will return the query if it's already of type Node
151 *
152 * @memberof Chartist.Core
153 * @param {String|Node} query The query to use for selecting a Node or a DOM node that will be returned directly
154 * @return {Node}
155 */
156 Chartist.querySelector = function(query) {
157 return query instanceof Node ? query : document.querySelector(query);
158 };
159
160 /**
161 * Functional style helper to produce array with given length initialized with undefined values
162 *
163 * @memberof Chartist.Core
164 * @param length
165 * @return {Array}
166 */
167 Chartist.times = function(length) {
168 return Array.apply(null, new Array(length));
169 };
170
171 /**
172 * Sum helper to be used in reduce functions
173 *
174 * @memberof Chartist.Core
175 * @param previous
176 * @param current
177 * @return {*}
178 */
179 Chartist.sum = function(previous, current) {
180 return previous + (current ? current : 0);
181 };
182
183 /**
184 * Multiply helper to be used in `Array.map` for multiplying each value of an array with a factor.
185 *
186 * @memberof Chartist.Core
187 * @param {Number} factor
188 * @returns {Function} Function that can be used in `Array.map` to multiply each value in an array
189 */
190 Chartist.mapMultiply = function(factor) {
191 return function(num) {
192 return num * factor;
193 };
194 };
195
196 /**
197 * Add helper to be used in `Array.map` for adding a addend to each value of an array.
198 *
199 * @memberof Chartist.Core
200 * @param {Number} addend
201 * @returns {Function} Function that can be used in `Array.map` to add a addend to each value in an array
202 */
203 Chartist.mapAdd = function(addend) {
204 return function(num) {
205 return num + addend;
206 };
207 };
208
209 /**
210 * Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).
211 *
212 * @memberof Chartist.Core
213 * @param arr
214 * @param cb
215 * @return {Array}
216 */
217 Chartist.serialMap = function(arr, cb) {
218 var result = [],
219 length = Math.max.apply(null, arr.map(function(e) {
220 return e.length;
221 }));
222
223 Chartist.times(length).forEach(function(e, index) {
224 var args = arr.map(function(e) {
225 return e[index];
226 });
227
228 result[index] = cb.apply(null, args);
229 });
230
231 return result;
232 };
233
234 /**
235 * This helper function can be used to round values with certain precision level after decimal. This is used to prevent rounding errors near float point precision limit.
236 *
237 * @memberof Chartist.Core
238 * @param {Number} value The value that should be rounded with precision
239 * @param {Number} [digits] The number of digits after decimal used to do the rounding
240 * @returns {number} Rounded value
241 */
242 Chartist.roundWithPrecision = function(value, digits) {
243 var precision = Math.pow(10, digits || Chartist.precision);
244 return Math.round(value * precision) / precision;
245 };
246
247 /**
248 * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.
249 *
250 * @memberof Chartist.Core
251 * @type {number}
252 */
253 Chartist.precision = 8;
254
255 /**
256 * A map with characters to escape for strings to be safely used as attribute values.
257 *
258 * @memberof Chartist.Core
259 * @type {Object}
260 */
261 Chartist.escapingMap = {
262 '&': '&amp;',
263 '<': '&lt;',
264 '>': '&gt;',
265 '"': '&quot;',
266 '\'': '&#039;'
267 };
268
269 /**
270 * This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap.
271 * If called with null or undefined the function will return immediately with null or undefined.
272 *
273 * @memberof Chartist.Core
274 * @param {Number|String|Object} data
275 * @return {String}
276 */
277 Chartist.serialize = function(data) {
278 if(data === null || data === undefined) {
279 return data;
280 } else if(typeof data === 'number') {
281 data = ''+data;
282 } else if(typeof data === 'object') {
283 data = JSON.stringify({data: data});
284 }
285
286 return Object.keys(Chartist.escapingMap).reduce(function(result, key) {
287 return Chartist.replaceAll(result, key, Chartist.escapingMap[key]);
288 }, data);
289 };
290
291 /**
292 * This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.
293 *
294 * @memberof Chartist.Core
295 * @param {String} data
296 * @return {String|Number|Object}
297 */
298 Chartist.deserialize = function(data) {
299 if(typeof data !== 'string') {
300 return data;
301 }
302
303 data = Object.keys(Chartist.escapingMap).reduce(function(result, key) {
304 return Chartist.replaceAll(result, Chartist.escapingMap[key], key);
305 }, data);
306
307 try {
308 data = JSON.parse(data);
309 data = data.data !== undefined ? data.data : data;
310 } catch(e) {}
311
312 return data;
313 };
314
315 /**
316 * Create or reinitialize the SVG element for the chart
317 *
318 * @memberof Chartist.Core
319 * @param {Node} container The containing DOM Node object that will be used to plant the SVG element
320 * @param {String} width Set the width of the SVG element. Default is 100%
321 * @param {String} height Set the height of the SVG element. Default is 100%
322 * @param {String} className Specify a class to be added to the SVG element
323 * @return {Object} The created/reinitialized SVG element
324 */
325 Chartist.createSvg = function (container, width, height, className) {
326 var svg;
327
328 width = width || '100%';
329 height = height || '100%';
330
331 // Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it
332 // Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/
333 Array.prototype.slice.call(container.querySelectorAll('svg')).filter(function filterChartistSvgObjects(svg) {
334 return svg.getAttributeNS(Chartist.namespaces.xmlns, 'ct');
335 }).forEach(function removePreviousElement(svg) {
336 container.removeChild(svg);
337 });
338
339 // Create svg object with width and height or use 100% as default
340 svg = new Chartist.Svg('svg').attr({
341 width: width,
342 height: height
343 }).addClass(className);
344
345 svg._node.style.width = width;
346 svg._node.style.height = height;
347
348 // Add the DOM node to our container
349 container.appendChild(svg._node);
350
351 return svg;
352 };
353
354 /**
355 * Ensures that the data object passed as second argument to the charts is present and correctly initialized.
356 *
357 * @param {Object} data The data object that is passed as second argument to the charts
358 * @return {Object} The normalized data object
359 */
360 Chartist.normalizeData = function(data, reverse, multi) {
361 var labelCount;
362 var output = {
363 raw: data,
364 normalized: {}
365 };
366
367 // Check if we should generate some labels based on existing series data
368 output.normalized.series = Chartist.getDataArray({
369 series: data.series || []
370 }, reverse, multi);
371
372 // If all elements of the normalized data array are arrays we're dealing with
373 // multi series data and we need to find the largest series if they are un-even
374 if (output.normalized.series.every(function(value) {
375 return value instanceof Array;
376 })) {
377 // Getting the series with the the most elements
378 labelCount = Math.max.apply(null, output.normalized.series.map(function(series) {
379 return series.length;
380 }));
381 } else {
382 // We're dealing with Pie data so we just take the normalized array length
383 labelCount = output.normalized.series.length;
384 }
385
386 output.normalized.labels = (data.labels || []).slice();
387 // Padding the labels to labelCount with empty strings
388 Array.prototype.push.apply(
389 output.normalized.labels,
390 Chartist.times(Math.max(0, labelCount - output.normalized.labels.length)).map(function() {
391 return '';
392 })
393 );
394
395 if(reverse) {
396 Chartist.reverseData(output.normalized);
397 }
398
399 return output;
400 };
401
402 /**
403 * This function safely checks if an objects has an owned property.
404 *
405 * @param {Object} object The object where to check for a property
406 * @param {string} property The property name
407 * @returns {boolean} Returns true if the object owns the specified property
408 */
409 Chartist.safeHasProperty = function(object, property) {
410 return object !== null &&
411 typeof object === 'object' &&
412 object.hasOwnProperty(property);
413 };
414
415 /**
416 * Checks if a value is considered a hole in the data series.
417 *
418 * @param {*} value
419 * @returns {boolean} True if the value is considered a data hole
420 */
421 Chartist.isDataHoleValue = function(value) {
422 return value === null ||
423 value === undefined ||
424 (typeof value === 'number' && isNaN(value));
425 };
426
427 /**
428 * Reverses the series, labels and series data arrays.
429 *
430 * @memberof Chartist.Core
431 * @param data
432 */
433 Chartist.reverseData = function(data) {
434 data.labels.reverse();
435 data.series.reverse();
436 for (var i = 0; i < data.series.length; i++) {
437 if(typeof(data.series[i]) === 'object' && data.series[i].data !== undefined) {
438 data.series[i].data.reverse();
439 } else if(data.series[i] instanceof Array) {
440 data.series[i].reverse();
441 }
442 }
443 };
444
445 /**
446 * Convert data series into plain array
447 *
448 * @memberof Chartist.Core
449 * @param {Object} data The series object that contains the data to be visualized in the chart
450 * @param {Boolean} [reverse] If true the whole data is reversed by the getDataArray call. This will modify the data object passed as first parameter. The labels as well as the series order is reversed. The whole series data arrays are reversed too.
451 * @param {Boolean} [multi] Create a multi dimensional array from a series data array where a value object with `x` and `y` values will be created.
452 * @return {Array} A plain array that contains the data to be visualized in the chart
453 */
454 Chartist.getDataArray = function(data, reverse, multi) {
455 // Recursively walks through nested arrays and convert string values to numbers and objects with value properties
456 // to values. Check the tests in data core -> data normalization for a detailed specification of expected values
457 function recursiveConvert(value) {
458 if(Chartist.safeHasProperty(value, 'value')) {
459 // We are dealing with value object notation so we need to recurse on value property
460 return recursiveConvert(value.value);
461 } else if(Chartist.safeHasProperty(value, 'data')) {
462 // We are dealing with series object notation so we need to recurse on data property
463 return recursiveConvert(value.data);
464 } else if(value instanceof Array) {
465 // Data is of type array so we need to recurse on the series
466 return value.map(recursiveConvert);
467 } else if(Chartist.isDataHoleValue(value)) {
468 // We're dealing with a hole in the data and therefore need to return undefined
469 // We're also returning undefined for multi value output
470 return undefined;
471 } else {
472 // We need to prepare multi value output (x and y data)
473 if(multi) {
474 var multiValue = {};
475
476 // Single series value arrays are assumed to specify the Y-Axis value
477 // For example: [1, 2] => [{x: undefined, y: 1}, {x: undefined, y: 2}]
478 // If multi is a string then it's assumed that it specified which dimension should be filled as default
479 if(typeof multi === 'string') {
480 multiValue[multi] = Chartist.getNumberOrUndefined(value);
481 } else {
482 multiValue.y = Chartist.getNumberOrUndefined(value);
483 }
484
485 multiValue.x = value.hasOwnProperty('x') ? Chartist.getNumberOrUndefined(value.x) : multiValue.x;
486 multiValue.y = value.hasOwnProperty('y') ? Chartist.getNumberOrUndefined(value.y) : multiValue.y;
487
488 return multiValue;
489
490 } else {
491 // We can return simple data
492 return Chartist.getNumberOrUndefined(value);
493 }
494 }
495 }
496
497 return data.series.map(recursiveConvert);
498 };
499
500 /**
501 * Converts a number into a padding object.
502 *
503 * @memberof Chartist.Core
504 * @param {Object|Number} padding
505 * @param {Number} [fallback] This value is used to fill missing values if a incomplete padding object was passed
506 * @returns {Object} Returns a padding object containing top, right, bottom, left properties filled with the padding number passed in as argument. If the argument is something else than a number (presumably already a correct padding object) then this argument is directly returned.
507 */
508 Chartist.normalizePadding = function(padding, fallback) {
509 fallback = fallback || 0;
510
511 return typeof padding === 'number' ? {
512 top: padding,
513 right: padding,
514 bottom: padding,
515 left: padding
516 } : {
517 top: typeof padding.top === 'number' ? padding.top : fallback,
518 right: typeof padding.right === 'number' ? padding.right : fallback,
519 bottom: typeof padding.bottom === 'number' ? padding.bottom : fallback,
520 left: typeof padding.left === 'number' ? padding.left : fallback
521 };
522 };
523
524 Chartist.getMetaData = function(series, index) {
525 var value = series.data ? series.data[index] : series[index];
526 return value ? value.meta : undefined;
527 };
528
529 /**
530 * Calculate the order of magnitude for the chart scale
531 *
532 * @memberof Chartist.Core
533 * @param {Number} value The value Range of the chart
534 * @return {Number} The order of magnitude
535 */
536 Chartist.orderOfMagnitude = function (value) {
537 return Math.floor(Math.log(Math.abs(value)) / Math.LN10);
538 };
539
540 /**
541 * Project a data length into screen coordinates (pixels)
542 *
543 * @memberof Chartist.Core
544 * @param {Object} axisLength The svg element for the chart
545 * @param {Number} length Single data value from a series array
546 * @param {Object} bounds All the values to set the bounds of the chart
547 * @return {Number} The projected data length in pixels
548 */
549 Chartist.projectLength = function (axisLength, length, bounds) {
550 return length / bounds.range * axisLength;
551 };
552
553 /**
554 * Get the height of the area in the chart for the data series
555 *
556 * @memberof Chartist.Core
557 * @param {Object} svg The svg element for the chart
558 * @param {Object} options The Object that contains all the optional values for the chart
559 * @return {Number} The height of the area in the chart for the data series
560 */
561 Chartist.getAvailableHeight = function (svg, options) {
562 return Math.max((Chartist.quantity(options.height).value || svg.height()) - (options.chartPadding.top + options.chartPadding.bottom) - options.axisX.offset, 0);
563 };
564
565 /**
566 * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
567 *
568 * @memberof Chartist.Core
569 * @param {Array} data The array that contains the data to be visualized in the chart
570 * @param {Object} options The Object that contains the chart options
571 * @param {String} dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration
572 * @return {Object} An object that contains the highest and lowest value that will be visualized on the chart.
573 */
574 Chartist.getHighLow = function (data, options, dimension) {
575 // TODO: Remove workaround for deprecated global high / low config. Axis high / low configuration is preferred
576 options = Chartist.extend({}, options, dimension ? options['axis' + dimension.toUpperCase()] : {});
577
578 var highLow = {
579 high: options.high === undefined ? -Number.MAX_VALUE : +options.high,
580 low: options.low === undefined ? Number.MAX_VALUE : +options.low
581 };
582 var findHigh = options.high === undefined;
583 var findLow = options.low === undefined;
584
585 // Function to recursively walk through arrays and find highest and lowest number
586 function recursiveHighLow(data) {
587 if(data === undefined) {
588 return undefined;
589 } else if(data instanceof Array) {
590 for (var i = 0; i < data.length; i++) {
591 recursiveHighLow(data[i]);
592 }
593 } else {
594 var value = dimension ? +data[dimension] : +data;
595
596 if (findHigh && value > highLow.high) {
597 highLow.high = value;
598 }
599
600 if (findLow && value < highLow.low) {
601 highLow.low = value;
602 }
603 }
604 }
605
606 // Start to find highest and lowest number recursively
607 if(findHigh || findLow) {
608 recursiveHighLow(data);
609 }
610
611 // Overrides of high / low based on reference value, it will make sure that the invisible reference value is
612 // used to generate the chart. This is useful when the chart always needs to contain the position of the
613 // invisible reference value in the view i.e. for bipolar scales.
614 if (options.referenceValue || options.referenceValue === 0) {
615 highLow.high = Math.max(options.referenceValue, highLow.high);
616 highLow.low = Math.min(options.referenceValue, highLow.low);
617 }
618
619 // If high and low are the same because of misconfiguration or flat data (only the same value) we need
620 // to set the high or low to 0 depending on the polarity
621 if (highLow.high <= highLow.low) {
622 // If both values are 0 we set high to 1
623 if (highLow.low === 0) {
624 highLow.high = 1;
625 } else if (highLow.low < 0) {
626 // If we have the same negative value for the bounds we set bounds.high to 0
627 highLow.high = 0;
628 } else if (highLow.high > 0) {
629 // If we have the same positive value for the bounds we set bounds.low to 0
630 highLow.low = 0;
631 } else {
632 // If data array was empty, values are Number.MAX_VALUE and -Number.MAX_VALUE. Set bounds to prevent errors
633 highLow.high = 1;
634 highLow.low = 0;
635 }
636 }
637
638 return highLow;
639 };
640
641 /**
642 * Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite.
643 *
644 * @memberof Chartist.Core
645 * @param value
646 * @returns {Boolean}
647 */
648 Chartist.isNumeric = function(value) {
649 return value === null ? false : isFinite(value);
650 };
651
652 /**
653 * Returns true on all falsey values except the numeric value 0.
654 *
655 * @memberof Chartist.Core
656 * @param value
657 * @returns {boolean}
658 */
659 Chartist.isFalseyButZero = function(value) {
660 return !value && value !== 0;
661 };
662
663 /**
664 * Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined.
665 *
666 * @memberof Chartist.Core
667 * @param value
668 * @returns {*}
669 */
670 Chartist.getNumberOrUndefined = function(value) {
671 return Chartist.isNumeric(value) ? +value : undefined;
672 };
673
674 /**
675 * Checks if provided value object is multi value (contains x or y properties)
676 *
677 * @memberof Chartist.Core
678 * @param value
679 */
680 Chartist.isMultiValue = function(value) {
681 return typeof value === 'object' && ('x' in value || 'y' in value);
682 };
683
684 /**
685 * Gets a value from a dimension `value.x` or `value.y` while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return `defaultValue`.
686 *
687 * @memberof Chartist.Core
688 * @param value
689 * @param dimension
690 * @param defaultValue
691 * @returns {*}
692 */
693 Chartist.getMultiValue = function(value, dimension) {
694 if(Chartist.isMultiValue(value)) {
695 return Chartist.getNumberOrUndefined(value[dimension || 'y']);
696 } else {
697 return Chartist.getNumberOrUndefined(value);
698 }
699 };
700
701 /**
702 * Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex.
703 *
704 * @memberof Chartist.Core
705 * @param {Number} num An integer number where the smallest factor should be searched for
706 * @returns {Number} The smallest integer factor of the parameter num.
707 */
708 Chartist.rho = function(num) {
709 if(num === 1) {
710 return num;
711 }
712
713 function gcd(p, q) {
714 if (p % q === 0) {
715 return q;
716 } else {
717 return gcd(q, p % q);
718 }
719 }
720
721 function f(x) {
722 return x * x + 1;
723 }
724
725 var x1 = 2, x2 = 2, divisor;
726 if (num % 2 === 0) {
727 return 2;
728 }
729
730 do {
731 x1 = f(x1) % num;
732 x2 = f(f(x2)) % num;
733 divisor = gcd(Math.abs(x1 - x2), num);
734 } while (divisor === 1);
735
736 return divisor;
737 };
738
739 /**
740 * Calculate and retrieve all the bounds for the chart and return them in one array
741 *
742 * @memberof Chartist.Core
743 * @param {Number} axisLength The length of the Axis used for
744 * @param {Object} highLow An object containing a high and low property indicating the value range of the chart.
745 * @param {Number} scaleMinSpace The minimum projected length a step should result in
746 * @param {Boolean} onlyInteger
747 * @return {Object} All the values to set the bounds of the chart
748 */
749 Chartist.getBounds = function (axisLength, highLow, scaleMinSpace, onlyInteger) {
750 var i,
751 optimizationCounter = 0,
752 newMin,
753 newMax,
754 bounds = {
755 high: highLow.high,
756 low: highLow.low
757 };
758
759 bounds.valueRange = bounds.high - bounds.low;
760 bounds.oom = Chartist.orderOfMagnitude(bounds.valueRange);
761 bounds.step = Math.pow(10, bounds.oom);
762 bounds.min = Math.floor(bounds.low / bounds.step) * bounds.step;
763 bounds.max = Math.ceil(bounds.high / bounds.step) * bounds.step;
764 bounds.range = bounds.max - bounds.min;
765 bounds.numberOfSteps = Math.round(bounds.range / bounds.step);
766
767 // Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
768 // If we are already below the scaleMinSpace value we will scale up
769 var length = Chartist.projectLength(axisLength, bounds.step, bounds);
770 var scaleUp = length < scaleMinSpace;
771 var smallestFactor = onlyInteger ? Chartist.rho(bounds.range) : 0;
772
773 // First check if we should only use integer steps and if step 1 is still larger than scaleMinSpace so we can use 1
774 if(onlyInteger && Chartist.projectLength(axisLength, 1, bounds) >= scaleMinSpace) {
775 bounds.step = 1;
776 } else if(onlyInteger && smallestFactor < bounds.step && Chartist.projectLength(axisLength, smallestFactor, bounds) >= scaleMinSpace) {
777 // If step 1 was too small, we can try the smallest factor of range
778 // If the smallest factor is smaller than the current bounds.step and the projected length of smallest factor
779 // is larger than the scaleMinSpace we should go for it.
780 bounds.step = smallestFactor;
781 } else {
782 // Trying to divide or multiply by 2 and find the best step value
783 while (true) {
784 if (scaleUp && Chartist.projectLength(axisLength, bounds.step, bounds) <= scaleMinSpace) {
785 bounds.step *= 2;
786 } else if (!scaleUp && Chartist.projectLength(axisLength, bounds.step / 2, bounds) >= scaleMinSpace) {
787 bounds.step /= 2;
788 if(onlyInteger && bounds.step % 1 !== 0) {
789 bounds.step *= 2;
790 break;
791 }
792 } else {
793 break;
794 }
795
796 if(optimizationCounter++ > 1000) {
797 throw new Error('Exceeded maximum number of iterations while optimizing scale step!');
798 }
799 }
800 }
801
802 var EPSILON = 2.221E-16;
803 bounds.step = Math.max(bounds.step, EPSILON);
804 function safeIncrement(value, increment) {
805 // If increment is too small use *= (1+EPSILON) as a simple nextafter
806 if (value === (value += increment)) {
807 value *= (1 + (increment > 0 ? EPSILON : -EPSILON));
808 }
809 return value;
810 }
811
812 // Narrow min and max based on new step
813 newMin = bounds.min;
814 newMax = bounds.max;
815 while (newMin + bounds.step <= bounds.low) {
816 newMin = safeIncrement(newMin, bounds.step);
817 }
818 while (newMax - bounds.step >= bounds.high) {
819 newMax = safeIncrement(newMax, -bounds.step);
820 }
821 bounds.min = newMin;
822 bounds.max = newMax;
823 bounds.range = bounds.max - bounds.min;
824
825 var values = [];
826 for (i = bounds.min; i <= bounds.max; i = safeIncrement(i, bounds.step)) {
827 var value = Chartist.roundWithPrecision(i);
828 if (value !== values[values.length - 1]) {
829 values.push(value);
830 }
831 }
832 bounds.values = values;
833 return bounds;
834 };
835
836 /**
837 * Calculate cartesian coordinates of polar coordinates
838 *
839 * @memberof Chartist.Core
840 * @param {Number} centerX X-axis coordinates of center point of circle segment
841 * @param {Number} centerY X-axis coordinates of center point of circle segment
842 * @param {Number} radius Radius of circle segment
843 * @param {Number} angleInDegrees Angle of circle segment in degrees
844 * @return {{x:Number, y:Number}} Coordinates of point on circumference
845 */
846 Chartist.polarToCartesian = function (centerX, centerY, radius, angleInDegrees) {
847 var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
848
849 return {
850 x: centerX + (radius * Math.cos(angleInRadians)),
851 y: centerY + (radius * Math.sin(angleInRadians))
852 };
853 };
854
855 /**
856 * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
857 *
858 * @memberof Chartist.Core
859 * @param {Object} svg The svg element for the chart
860 * @param {Object} options The Object that contains all the optional values for the chart
861 * @param {Number} [fallbackPadding] The fallback padding if partial padding objects are used
862 * @return {Object} The chart rectangles coordinates inside the svg element plus the rectangles measurements
863 */
864 Chartist.createChartRect = function (svg, options, fallbackPadding) {
865 var hasAxis = !!(options.axisX || options.axisY);
866 var yAxisOffset = hasAxis ? options.axisY.offset : 0;
867 var xAxisOffset = hasAxis ? options.axisX.offset : 0;
868 // If width or height results in invalid value (including 0) we fallback to the unitless settings or even 0
869 var width = svg.width() || Chartist.quantity(options.width).value || 0;
870 var height = svg.height() || Chartist.quantity(options.height).value || 0;
871 var normalizedPadding = Chartist.normalizePadding(options.chartPadding, fallbackPadding);
872
873 // If settings were to small to cope with offset (legacy) and padding, we'll adjust
874 width = Math.max(width, yAxisOffset + normalizedPadding.left + normalizedPadding.right);
875 height = Math.max(height, xAxisOffset + normalizedPadding.top + normalizedPadding.bottom);
876
877 var chartRect = {
878 padding: normalizedPadding,
879 width: function () {
880 return this.x2 - this.x1;
881 },
882 height: function () {
883 return this.y1 - this.y2;
884 }
885 };
886
887 if(hasAxis) {
888 if (options.axisX.position === 'start') {
889 chartRect.y2 = normalizedPadding.top + xAxisOffset;
890 chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
891 } else {
892 chartRect.y2 = normalizedPadding.top;
893 chartRect.y1 = Math.max(height - normalizedPadding.bottom - xAxisOffset, chartRect.y2 + 1);
894 }
895
896 if (options.axisY.position === 'start') {
897 chartRect.x1 = normalizedPadding.left + yAxisOffset;
898 chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
899 } else {
900 chartRect.x1 = normalizedPadding.left;
901 chartRect.x2 = Math.max(width - normalizedPadding.right - yAxisOffset, chartRect.x1 + 1);
902 }
903 } else {
904 chartRect.x1 = normalizedPadding.left;
905 chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
906 chartRect.y2 = normalizedPadding.top;
907 chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
908 }
909
910 return chartRect;
911 };
912
913 /**
914 * Creates a grid line based on a projected value.
915 *
916 * @memberof Chartist.Core
917 * @param position
918 * @param index
919 * @param axis
920 * @param offset
921 * @param length
922 * @param group
923 * @param classes
924 * @param eventEmitter
925 */
926 Chartist.createGrid = function(position, index, axis, offset, length, group, classes, eventEmitter) {
927 var positionalData = {};
928 positionalData[axis.units.pos + '1'] = position;
929 positionalData[axis.units.pos + '2'] = position;
930 positionalData[axis.counterUnits.pos + '1'] = offset;
931 positionalData[axis.counterUnits.pos + '2'] = offset + length;
932
933 var gridElement = group.elem('line', positionalData, classes.join(' '));
934
935 // Event for grid draw
936 eventEmitter.emit('draw',
937 Chartist.extend({
938 type: 'grid',
939 axis: axis,
940 index: index,
941 group: group,
942 element: gridElement
943 }, positionalData)
944 );
945 };
946
947 /**
948 * Creates a grid background rect and emits the draw event.
949 *
950 * @memberof Chartist.Core
951 * @param gridGroup
952 * @param chartRect
953 * @param className
954 * @param eventEmitter
955 */
956 Chartist.createGridBackground = function (gridGroup, chartRect, className, eventEmitter) {
957 var gridBackground = gridGroup.elem('rect', {
958 x: chartRect.x1,
959 y: chartRect.y2,
960 width: chartRect.width(),
961 height: chartRect.height(),
962 }, className, true);
963
964 // Event for grid background draw
965 eventEmitter.emit('draw', {
966 type: 'gridBackground',
967 group: gridGroup,
968 element: gridBackground
969 });
970 };
971
972 /**
973 * Creates a label based on a projected value and an axis.
974 *
975 * @memberof Chartist.Core
976 * @param position
977 * @param length
978 * @param index
979 * @param labels
980 * @param axis
981 * @param axisOffset
982 * @param labelOffset
983 * @param group
984 * @param classes
985 * @param useForeignObject
986 * @param eventEmitter
987 */
988 Chartist.createLabel = function(position, length, index, labels, axis, axisOffset, labelOffset, group, classes, useForeignObject, eventEmitter) {
989 var labelElement;
990 var positionalData = {};
991
992 positionalData[axis.units.pos] = position + labelOffset[axis.units.pos];
993 positionalData[axis.counterUnits.pos] = labelOffset[axis.counterUnits.pos];
994 positionalData[axis.units.len] = length;
995 positionalData[axis.counterUnits.len] = Math.max(0, axisOffset - 10);
996
997 if(useForeignObject) {
998 // We need to set width and height explicitly to px as span will not expand with width and height being
999 // 100% in all browsers
1000 var content = document.createElement('span');
1001 content.className = classes.join(' ');
1002 content.setAttribute('xmlns', Chartist.namespaces.xhtml);
1003 content.innerText = labels[index];
1004 content.style[axis.units.len] = Math.round(positionalData[axis.units.len]) + 'px';
1005 content.style[axis.counterUnits.len] = Math.round(positionalData[axis.counterUnits.len]) + 'px';
1006
1007 labelElement = group.foreignObject(content, Chartist.extend({
1008 style: 'overflow: visible;'
1009 }, positionalData));
1010 } else {
1011 labelElement = group.elem('text', positionalData, classes.join(' ')).text(labels[index]);
1012 }
1013
1014 eventEmitter.emit('draw', Chartist.extend({
1015 type: 'label',
1016 axis: axis,
1017 index: index,
1018 group: group,
1019 element: labelElement,
1020 text: labels[index]
1021 }, positionalData));
1022 };
1023
1024 /**
1025 * Helper to read series specific options from options object. It automatically falls back to the global option if
1026 * there is no option in the series options.
1027 *
1028 * @param {Object} series Series object
1029 * @param {Object} options Chartist options object
1030 * @param {string} key The options key that should be used to obtain the options
1031 * @returns {*}
1032 */
1033 Chartist.getSeriesOption = function(series, options, key) {
1034 if(series.name && options.series && options.series[series.name]) {
1035 var seriesOptions = options.series[series.name];
1036 return seriesOptions.hasOwnProperty(key) ? seriesOptions[key] : options[key];
1037 } else {
1038 return options[key];
1039 }
1040 };
1041
1042 /**
1043 * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
1044 *
1045 * @memberof Chartist.Core
1046 * @param {Object} options Options set by user
1047 * @param {Array} responsiveOptions Optional functions to add responsive behavior to chart
1048 * @param {Object} eventEmitter The event emitter that will be used to emit the options changed events
1049 * @return {Object} The consolidated options object from the defaults, base and matching responsive options
1050 */
1051 Chartist.optionsProvider = function (options, responsiveOptions, eventEmitter) {
1052 var baseOptions = Chartist.extend({}, options),
1053 currentOptions,
1054 mediaQueryListeners = [],
1055 i;
1056
1057 function updateCurrentOptions(mediaEvent) {
1058 var previousOptions = currentOptions;
1059 currentOptions = Chartist.extend({}, baseOptions);
1060
1061 if (responsiveOptions) {
1062 for (i = 0; i < responsiveOptions.length; i++) {
1063 var mql = window.matchMedia(responsiveOptions[i][0]);
1064 if (mql.matches) {
1065 currentOptions = Chartist.extend(currentOptions, responsiveOptions[i][1]);
1066 }
1067 }
1068 }
1069
1070 if(eventEmitter && mediaEvent) {
1071 eventEmitter.emit('optionsChanged', {
1072 previousOptions: previousOptions,
1073 currentOptions: currentOptions
1074 });
1075 }
1076 }
1077
1078 function removeMediaQueryListeners() {
1079 mediaQueryListeners.forEach(function(mql) {
1080 mql.removeListener(updateCurrentOptions);
1081 });
1082 }
1083
1084 if (!window.matchMedia) {
1085 throw 'window.matchMedia not found! Make sure you\'re using a polyfill.';
1086 } else if (responsiveOptions) {
1087
1088 for (i = 0; i < responsiveOptions.length; i++) {
1089 var mql = window.matchMedia(responsiveOptions[i][0]);
1090 mql.addListener(updateCurrentOptions);
1091 mediaQueryListeners.push(mql);
1092 }
1093 }
1094 // Execute initially without an event argument so we get the correct options
1095 updateCurrentOptions();
1096
1097 return {
1098 removeMediaQueryListeners: removeMediaQueryListeners,
1099 getCurrentOptions: function getCurrentOptions() {
1100 return Chartist.extend({}, currentOptions);
1101 }
1102 };
1103 };
1104
1105
1106 /**
1107 * Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates
1108 * valueData property describing the segment.
1109 *
1110 * With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any
1111 * points with undefined values are discarded.
1112 *
1113 * **Options**
1114 * The following options are used to determine how segments are formed
1115 * ```javascript
1116 * var options = {
1117 * // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment.
1118 * fillHoles: false,
1119 * // If increasingX is true, the coordinates in all segments have strictly increasing x-values.
1120 * increasingX: false
1121 * };
1122 * ```
1123 *
1124 * @memberof Chartist.Core
1125 * @param {Array} pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn]
1126 * @param {Array} values List of associated point values in the form [v1, v2 .. vn]
1127 * @param {Object} options Options set by user
1128 * @return {Array} List of segments, each containing a pathCoordinates and valueData property.
1129 */
1130 Chartist.splitIntoSegments = function(pathCoordinates, valueData, options) {
1131 var defaultOptions = {
1132 increasingX: false,
1133 fillHoles: false
1134 };
1135
1136 options = Chartist.extend({}, defaultOptions, options);
1137
1138 var segments = [];
1139 var hole = true;
1140
1141 for(var i = 0; i < pathCoordinates.length; i += 2) {
1142 // If this value is a "hole" we set the hole flag
1143 if(Chartist.getMultiValue(valueData[i / 2].value) === undefined) {
1144 // if(valueData[i / 2].value === undefined) {
1145 if(!options.fillHoles) {
1146 hole = true;
1147 }
1148 } else {
1149 if(options.increasingX && i >= 2 && pathCoordinates[i] <= pathCoordinates[i-2]) {
1150 // X is not increasing, so we need to make sure we start a new segment
1151 hole = true;
1152 }
1153
1154
1155 // If it's a valid value we need to check if we're coming out of a hole and create a new empty segment
1156 if(hole) {
1157 segments.push({
1158 pathCoordinates: [],
1159 valueData: []
1160 });
1161 // As we have a valid value now, we are not in a "hole" anymore
1162 hole = false;
1163 }
1164
1165 // Add to the segment pathCoordinates and valueData
1166 segments[segments.length - 1].pathCoordinates.push(pathCoordinates[i], pathCoordinates[i + 1]);
1167 segments[segments.length - 1].valueData.push(valueData[i / 2]);
1168 }
1169 }
1170
1171 return segments;
1172 };
1173 }(this || global, Chartist));
1174 ;/**
1175 * Chartist path interpolation functions.
1176 *
1177 * @module Chartist.Interpolation
1178 */
1179 /* global Chartist */
1180 (function(globalRoot, Chartist) {
1181 'use strict';
1182
1183 Chartist.Interpolation = {};
1184
1185 /**
1186 * This interpolation function does not smooth the path and the result is only containing lines and no curves.
1187 *
1188 * @example
1189 * var chart = new Chartist.Line('.ct-chart', {
1190 * labels: [1, 2, 3, 4, 5],
1191 * series: [[1, 2, 8, 1, 7]]
1192 * }, {
1193 * lineSmooth: Chartist.Interpolation.none({
1194 * fillHoles: false
1195 * })
1196 * });
1197 *
1198 *
1199 * @memberof Chartist.Interpolation
1200 * @return {Function}
1201 */
1202 Chartist.Interpolation.none = function(options) {
1203 var defaultOptions = {
1204 fillHoles: false
1205 };
1206 options = Chartist.extend({}, defaultOptions, options);
1207 return function none(pathCoordinates, valueData) {
1208 var path = new Chartist.Svg.Path();
1209 var hole = true;
1210
1211 for(var i = 0; i < pathCoordinates.length; i += 2) {
1212 var currX = pathCoordinates[i];
1213 var currY = pathCoordinates[i + 1];
1214 var currData = valueData[i / 2];
1215
1216 if(Chartist.getMultiValue(currData.value) !== undefined) {
1217
1218 if(hole) {
1219 path.move(currX, currY, false, currData);
1220 } else {
1221 path.line(currX, currY, false, currData);
1222 }
1223
1224 hole = false;
1225 } else if(!options.fillHoles) {
1226 hole = true;
1227 }
1228 }
1229
1230 return path;
1231 };
1232 };
1233
1234 /**
1235 * Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing.
1236 *
1237 * Simple smoothing can be used instead of `Chartist.Smoothing.cardinal` if you'd like to get rid of the artifacts it produces sometimes. Simple smoothing produces less flowing lines but is accurate by hitting the points and it also doesn't swing below or above the given data point.
1238 *
1239 * All smoothing functions within Chartist are factory functions that accept an options parameter. The simple interpolation function accepts one configuration parameter `divisor`, between 1 and ∞, which controls the smoothing characteristics.
1240 *
1241 * @example
1242 * var chart = new Chartist.Line('.ct-chart', {
1243 * labels: [1, 2, 3, 4, 5],
1244 * series: [[1, 2, 8, 1, 7]]
1245 * }, {
1246 * lineSmooth: Chartist.Interpolation.simple({
1247 * divisor: 2,
1248 * fillHoles: false
1249 * })
1250 * });
1251 *
1252 *
1253 * @memberof Chartist.Interpolation
1254 * @param {Object} options The options of the simple interpolation factory function.
1255 * @return {Function}
1256 */
1257 Chartist.Interpolation.simple = function(options) {
1258 var defaultOptions = {
1259 divisor: 2,
1260 fillHoles: false
1261 };
1262 options = Chartist.extend({}, defaultOptions, options);
1263
1264 var d = 1 / Math.max(1, options.divisor);
1265
1266 return function simple(pathCoordinates, valueData) {
1267 var path = new Chartist.Svg.Path();
1268 var prevX, prevY, prevData;
1269
1270 for(var i = 0; i < pathCoordinates.length; i += 2) {
1271 var currX = pathCoordinates[i];
1272 var currY = pathCoordinates[i + 1];
1273 var length = (currX - prevX) * d;
1274 var currData = valueData[i / 2];
1275
1276 if(currData.value !== undefined) {
1277
1278 if(prevData === undefined) {
1279 path.move(currX, currY, false, currData);
1280 } else {
1281 path.curve(
1282 prevX + length,
1283 prevY,
1284 currX - length,
1285 currY,
1286 currX,
1287 currY,
1288 false,
1289 currData
1290 );
1291 }
1292
1293 prevX = currX;
1294 prevY = currY;
1295 prevData = currData;
1296 } else if(!options.fillHoles) {
1297 prevX = currX = prevData = undefined;
1298 }
1299 }
1300
1301 return path;
1302 };
1303 };
1304
1305 /**
1306 * Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results.
1307 *
1308 * Cardinal splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
1309 *
1310 * All smoothing functions within Chartist are factory functions that accept an options parameter. The cardinal interpolation function accepts one configuration parameter `tension`, between 0 and 1, which controls the smoothing intensity.
1311 *
1312 * @example
1313 * var chart = new Chartist.Line('.ct-chart', {
1314 * labels: [1, 2, 3, 4, 5],
1315 * series: [[1, 2, 8, 1, 7]]
1316 * }, {
1317 * lineSmooth: Chartist.Interpolation.cardinal({
1318 * tension: 1,
1319 * fillHoles: false
1320 * })
1321 * });
1322 *
1323 * @memberof Chartist.Interpolation
1324 * @param {Object} options The options of the cardinal factory function.
1325 * @return {Function}
1326 */
1327 Chartist.Interpolation.cardinal = function(options) {
1328 var defaultOptions = {
1329 tension: 1,
1330 fillHoles: false
1331 };
1332
1333 options = Chartist.extend({}, defaultOptions, options);
1334
1335 var t = Math.min(1, Math.max(0, options.tension)),
1336 c = 1 - t;
1337
1338 return function cardinal(pathCoordinates, valueData) {
1339 // First we try to split the coordinates into segments
1340 // This is necessary to treat "holes" in line charts
1341 var segments = Chartist.splitIntoSegments(pathCoordinates, valueData, {
1342 fillHoles: options.fillHoles
1343 });
1344
1345 if(!segments.length) {
1346 // If there were no segments return 'Chartist.Interpolation.none'
1347 return Chartist.Interpolation.none()([]);
1348 } else if(segments.length > 1) {
1349 // If the split resulted in more that one segment we need to interpolate each segment individually and join them
1350 // afterwards together into a single path.
1351 var paths = [];
1352 // For each segment we will recurse the cardinal function
1353 segments.forEach(function(segment) {
1354 paths.push(cardinal(segment.pathCoordinates, segment.valueData));
1355 });
1356 // Join the segment path data into a single path and return
1357 return Chartist.Svg.Path.join(paths);
1358 } else {
1359 // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
1360 // segment
1361 pathCoordinates = segments[0].pathCoordinates;
1362 valueData = segments[0].valueData;
1363
1364 // If less than two points we need to fallback to no smoothing
1365 if(pathCoordinates.length <= 4) {
1366 return Chartist.Interpolation.none()(pathCoordinates, valueData);
1367 }
1368
1369 var path = new Chartist.Svg.Path().move(pathCoordinates[0], pathCoordinates[1], false, valueData[0]),
1370 z;
1371
1372 for (var i = 0, iLen = pathCoordinates.length; iLen - 2 * !z > i; i += 2) {
1373 var p = [
1374 {x: +pathCoordinates[i - 2], y: +pathCoordinates[i - 1]},
1375 {x: +pathCoordinates[i], y: +pathCoordinates[i + 1]},
1376 {x: +pathCoordinates[i + 2], y: +pathCoordinates[i + 3]},
1377 {x: +pathCoordinates[i + 4], y: +pathCoordinates[i + 5]}
1378 ];
1379 if (z) {
1380 if (!i) {
1381 p[0] = {x: +pathCoordinates[iLen - 2], y: +pathCoordinates[iLen - 1]};
1382 } else if (iLen - 4 === i) {
1383 p[3] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
1384 } else if (iLen - 2 === i) {
1385 p[2] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
1386 p[3] = {x: +pathCoordinates[2], y: +pathCoordinates[3]};
1387 }
1388 } else {
1389 if (iLen - 4 === i) {
1390 p[3] = p[2];
1391 } else if (!i) {
1392 p[0] = {x: +pathCoordinates[i], y: +pathCoordinates[i + 1]};
1393 }
1394 }
1395
1396 path.curve(
1397 (t * (-p[0].x + 6 * p[1].x + p[2].x) / 6) + (c * p[2].x),
1398 (t * (-p[0].y + 6 * p[1].y + p[2].y) / 6) + (c * p[2].y),
1399 (t * (p[1].x + 6 * p[2].x - p[3].x) / 6) + (c * p[2].x),
1400 (t * (p[1].y + 6 * p[2].y - p[3].y) / 6) + (c * p[2].y),
1401 p[2].x,
1402 p[2].y,
1403 false,
1404 valueData[(i + 2) / 2]
1405 );
1406 }
1407
1408 return path;
1409 }
1410 };
1411 };
1412
1413 /**
1414 * Monotone Cubic spline interpolation produces a smooth curve which preserves monotonicity. Unlike cardinal splines, the curve will not extend beyond the range of y-values of the original data points.
1415 *
1416 * Monotone Cubic splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`.
1417 *
1418 * The x-values of subsequent points must be increasing to fit a Monotone Cubic spline. If this condition is not met for a pair of adjacent points, then there will be a break in the curve between those data points.
1419 *
1420 * All smoothing functions within Chartist are factory functions that accept an options parameter.
1421 *
1422 * @example
1423 * var chart = new Chartist.Line('.ct-chart', {
1424 * labels: [1, 2, 3, 4, 5],
1425 * series: [[1, 2, 8, 1, 7]]
1426 * }, {
1427 * lineSmooth: Chartist.Interpolation.monotoneCubic({
1428 * fillHoles: false
1429 * })
1430 * });
1431 *
1432 * @memberof Chartist.Interpolation
1433 * @param {Object} options The options of the monotoneCubic factory function.
1434 * @return {Function}
1435 */
1436 Chartist.Interpolation.monotoneCubic = function(options) {
1437 var defaultOptions = {
1438 fillHoles: false
1439 };
1440
1441 options = Chartist.extend({}, defaultOptions, options);
1442
1443 return function monotoneCubic(pathCoordinates, valueData) {
1444 // First we try to split the coordinates into segments
1445 // This is necessary to treat "holes" in line charts
1446 var segments = Chartist.splitIntoSegments(pathCoordinates, valueData, {
1447 fillHoles: options.fillHoles,
1448 increasingX: true
1449 });
1450
1451 if(!segments.length) {
1452 // If there were no segments return 'Chartist.Interpolation.none'
1453 return Chartist.Interpolation.none()([]);
1454 } else if(segments.length > 1) {
1455 // If the split resulted in more that one segment we need to interpolate each segment individually and join them
1456 // afterwards together into a single path.
1457 var paths = [];
1458 // For each segment we will recurse the monotoneCubic fn function
1459 segments.forEach(function(segment) {
1460 paths.push(monotoneCubic(segment.pathCoordinates, segment.valueData));
1461 });
1462 // Join the segment path data into a single path and return
1463 return Chartist.Svg.Path.join(paths);
1464 } else {
1465 // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
1466 // segment
1467 pathCoordinates = segments[0].pathCoordinates;
1468 valueData = segments[0].valueData;
1469
1470 // If less than three points we need to fallback to no smoothing
1471 if(pathCoordinates.length <= 4) {
1472 return Chartist.Interpolation.none()(pathCoordinates, valueData);
1473 }
1474
1475 var xs = [],
1476 ys = [],
1477 i,
1478 n = pathCoordinates.length / 2,
1479 ms = [],
1480 ds = [], dys = [], dxs = [],
1481 path;
1482
1483 // Populate x and y coordinates into separate arrays, for readability
1484
1485 for(i = 0; i < n; i++) {
1486 xs[i] = pathCoordinates[i * 2];
1487 ys[i] = pathCoordinates[i * 2 + 1];
1488 }
1489
1490 // Calculate deltas and derivative
1491
1492 for(i = 0; i < n - 1; i++) {
1493 dys[i] = ys[i + 1] - ys[i];
1494 dxs[i] = xs[i + 1] - xs[i];
1495 ds[i] = dys[i] / dxs[i];
1496 }
1497
1498 // Determine desired slope (m) at each point using Fritsch-Carlson method
1499 // See: http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation
1500
1501 ms[0] = ds[0];
1502 ms[n - 1] = ds[n - 2];
1503
1504 for(i = 1; i < n - 1; i++) {
1505 if(ds[i] === 0 || ds[i - 1] === 0 || (ds[i - 1] > 0) !== (ds[i] > 0)) {
1506 ms[i] = 0;
1507 } else {
1508 ms[i] = 3 * (dxs[i - 1] + dxs[i]) / (
1509 (2 * dxs[i] + dxs[i - 1]) / ds[i - 1] +
1510 (dxs[i] + 2 * dxs[i - 1]) / ds[i]);
1511
1512 if(!isFinite(ms[i])) {
1513 ms[i] = 0;
1514 }
1515 }
1516 }
1517
1518 // Now build a path from the slopes
1519
1520 path = new Chartist.Svg.Path().move(xs[0], ys[0], false, valueData[0]);
1521
1522 for(i = 0; i < n - 1; i++) {
1523 path.curve(
1524 // First control point
1525 xs[i] + dxs[i] / 3,
1526 ys[i] + ms[i] * dxs[i] / 3,
1527 // Second control point
1528 xs[i + 1] - dxs[i] / 3,
1529 ys[i + 1] - ms[i + 1] * dxs[i] / 3,
1530 // End point
1531 xs[i + 1],
1532 ys[i + 1],
1533
1534 false,
1535 valueData[i + 1]
1536 );
1537 }
1538
1539 return path;
1540 }
1541 };
1542 };
1543
1544 /**
1545 * Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the `showPoint` option is enabled.
1546 *
1547 * All smoothing functions within Chartist are factory functions that accept an options parameter. The step interpolation function accepts one configuration parameter `postpone`, that can be `true` or `false`. The default value is `true` and will cause the step to occur where the value actually changes. If a different behaviour is needed where the step is shifted to the left and happens before the actual value, this option can be set to `false`.
1548 *
1549 * @example
1550 * var chart = new Chartist.Line('.ct-chart', {
1551 * labels: [1, 2, 3, 4, 5],
1552 * series: [[1, 2, 8, 1, 7]]
1553 * }, {
1554 * lineSmooth: Chartist.Interpolation.step({
1555 * postpone: true,
1556 * fillHoles: false
1557 * })
1558 * });
1559 *
1560 * @memberof Chartist.Interpolation
1561 * @param options
1562 * @returns {Function}
1563 */
1564 Chartist.Interpolation.step = function(options) {
1565 var defaultOptions = {
1566 postpone: true,
1567 fillHoles: false
1568 };
1569
1570 options = Chartist.extend({}, defaultOptions, options);
1571
1572 return function step(pathCoordinates, valueData) {
1573 var path = new Chartist.Svg.Path();
1574
1575 var prevX, prevY, prevData;
1576
1577 for (var i = 0; i < pathCoordinates.length; i += 2) {
1578 var currX = pathCoordinates[i];
1579 var currY = pathCoordinates[i + 1];
1580 var currData = valueData[i / 2];
1581
1582 // If the current point is also not a hole we can draw the step lines
1583 if(currData.value !== undefined) {
1584 if(prevData === undefined) {
1585 path.move(currX, currY, false, currData);
1586 } else {
1587 if(options.postpone) {
1588 // If postponed we should draw the step line with the value of the previous value
1589 path.line(currX, prevY, false, prevData);
1590 } else {
1591 // If not postponed we should draw the step line with the value of the current value
1592 path.line(prevX, currY, false, currData);
1593 }
1594 // Line to the actual point (this should only be a Y-Axis movement
1595 path.line(currX, currY, false, currData);
1596 }
1597
1598 prevX = currX;
1599 prevY = currY;
1600 prevData = currData;
1601 } else if(!options.fillHoles) {
1602 prevX = prevY = prevData = undefined;
1603 }
1604 }
1605
1606 return path;
1607 };
1608 };
1609
1610 }(this || global, Chartist));
1611 ;/**
1612 * A very basic event module that helps to generate and catch events.
1613 *
1614 * @module Chartist.Event
1615 */
1616 /* global Chartist */
1617 (function (globalRoot, Chartist) {
1618 'use strict';
1619
1620 Chartist.EventEmitter = function () {
1621 var handlers = [];
1622
1623 /**
1624 * Add an event handler for a specific event
1625 *
1626 * @memberof Chartist.Event
1627 * @param {String} event The event name
1628 * @param {Function} handler A event handler function
1629 */
1630 function addEventHandler(event, handler) {
1631 handlers[event] = handlers[event] || [];
1632 handlers[event].push(handler);
1633 }
1634
1635 /**
1636 * Remove an event handler of a specific event name or remove all event handlers for a specific event.
1637 *
1638 * @memberof Chartist.Event
1639 * @param {String} event The event name where a specific or all handlers should be removed
1640 * @param {Function} [handler] An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed.
1641 */
1642 function removeEventHandler(event, handler) {
1643 // Only do something if there are event handlers with this name existing
1644 if(handlers[event]) {
1645 // If handler is set we will look for a specific handler and only remove this
1646 if(handler) {
1647 handlers[event].splice(handlers[event].indexOf(handler), 1);
1648 if(handlers[event].length === 0) {
1649 delete handlers[event];
1650 }
1651 } else {
1652 // If no handler is specified we remove all handlers for this event
1653 delete handlers[event];
1654 }
1655 }
1656 }
1657
1658 /**
1659 * Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.
1660 *
1661 * @memberof Chartist.Event
1662 * @param {String} event The event name that should be triggered
1663 * @param {*} data Arbitrary data that will be passed to the event handler callback functions
1664 */
1665 function emit(event, data) {
1666 // Only do something if there are event handlers with this name existing
1667 if(handlers[event]) {
1668 handlers[event].forEach(function(handler) {
1669 handler(data);
1670 });
1671 }
1672
1673 // Emit event to star event handlers
1674 if(handlers['*']) {
1675 handlers['*'].forEach(function(starHandler) {
1676 starHandler(event, data);
1677 });
1678 }
1679 }
1680
1681 return {
1682 addEventHandler: addEventHandler,
1683 removeEventHandler: removeEventHandler,
1684 emit: emit
1685 };
1686 };
1687
1688 }(this || global, Chartist));
1689 ;/**
1690 * This module provides some basic prototype inheritance utilities.
1691 *
1692 * @module Chartist.Class
1693 */
1694 /* global Chartist */
1695 (function(globalRoot, Chartist) {
1696 'use strict';
1697
1698 function listToArray(list) {
1699 var arr = [];
1700 if (list.length) {
1701 for (var i = 0; i < list.length; i++) {
1702 arr.push(list[i]);
1703 }
1704 }
1705 return arr;
1706 }
1707
1708 /**
1709 * Method to extend from current prototype.
1710 *
1711 * @memberof Chartist.Class
1712 * @param {Object} properties The object that serves as definition for the prototype that gets created for the new class. This object should always contain a constructor property that is the desired constructor for the newly created class.
1713 * @param {Object} [superProtoOverride] By default extens will use the current class prototype or Chartist.class. With this parameter you can specify any super prototype that will be used.
1714 * @return {Function} Constructor function of the new class
1715 *
1716 * @example
1717 * var Fruit = Class.extend({
1718 * color: undefined,
1719 * sugar: undefined,
1720 *
1721 * constructor: function(color, sugar) {
1722 * this.color = color;
1723 * this.sugar = sugar;
1724 * },
1725 *
1726 * eat: function() {
1727 * this.sugar = 0;
1728 * return this;
1729 * }
1730 * });
1731 *
1732 * var Banana = Fruit.extend({
1733 * length: undefined,
1734 *
1735 * constructor: function(length, sugar) {
1736 * Banana['super'].constructor.call(this, 'Yellow', sugar);
1737 * this.length = length;
1738 * }
1739 * });
1740 *
1741 * var banana = new Banana(20, 40);
1742 * console.log('banana instanceof Fruit', banana instanceof Fruit);
1743 * console.log('Fruit is prototype of banana', Fruit.prototype.isPrototypeOf(banana));
1744 * console.log('bananas prototype is Fruit', Object.getPrototypeOf(banana) === Fruit.prototype);
1745 * console.log(banana.sugar);
1746 * console.log(banana.eat().sugar);
1747 * console.log(banana.color);
1748 */
1749 function extend(properties, superProtoOverride) {
1750 var superProto = superProtoOverride || this.prototype || Chartist.Class;
1751 var proto = Object.create(superProto);
1752
1753 Chartist.Class.cloneDefinitions(proto, properties);
1754
1755 var constr = function() {
1756 var fn = proto.constructor || function () {},
1757 instance;
1758
1759 // If this is linked to the Chartist namespace the constructor was not called with new
1760 // To provide a fallback we will instantiate here and return the instance
1761 instance = this === Chartist ? Object.create(proto) : this;
1762 fn.apply(instance, Array.prototype.slice.call(arguments, 0));
1763
1764 // If this constructor was not called with new we need to return the instance
1765 // This will not harm when the constructor has been called with new as the returned value is ignored
1766 return instance;
1767 };
1768
1769 constr.prototype = proto;
1770 constr['super'] = superProto;
1771 constr.extend = this.extend;
1772
1773 return constr;
1774 }
1775
1776 // Variable argument list clones args > 0 into args[0] and retruns modified args[0]
1777 function cloneDefinitions() {
1778 var args = listToArray(arguments);
1779 var target = args[0];
1780
1781 args.splice(1, args.length - 1).forEach(function (source) {
1782 Object.getOwnPropertyNames(source).forEach(function (propName) {
1783 // If this property already exist in target we delete it first
1784 delete target[propName];
1785 // Define the property with the descriptor from source
1786 Object.defineProperty(target, propName,
1787 Object.getOwnPropertyDescriptor(source, propName));
1788 });
1789 });
1790
1791 return target;
1792 }
1793
1794 Chartist.Class = {
1795 extend: extend,
1796 cloneDefinitions: cloneDefinitions
1797 };
1798
1799 }(this || global, Chartist));
1800 ;/**
1801 * Base for all chart types. The methods in Chartist.Base are inherited to all chart types.
1802 *
1803 * @module Chartist.Base
1804 */
1805 /* global Chartist */
1806 (function(globalRoot, Chartist) {
1807 'use strict';
1808
1809 var window = globalRoot.window;
1810
1811 // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.
1812 // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not
1813 // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.
1814 // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html
1815 // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj
1816 // The problem is with the label offsets that can't be converted into percentage and affecting the chart container
1817 /**
1818 * Updates the chart which currently does a full reconstruction of the SVG DOM
1819 *
1820 * @param {Object} [data] Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart.
1821 * @param {Object} [options] Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart.
1822 * @param {Boolean} [override] If set to true, the passed options will be used to extend the options that have been configured already. Otherwise the chart default options will be used as the base
1823 * @memberof Chartist.Base
1824 */
1825 function update(data, options, override) {
1826 if(data) {
1827 this.data = data || {};
1828 this.data.labels = this.data.labels || [];
1829 this.data.series = this.data.series || [];
1830 // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
1831 this.eventEmitter.emit('data', {
1832 type: 'update',
1833 data: this.data
1834 });
1835 }
1836
1837 if(options) {
1838 this.options = Chartist.extend({}, override ? this.options : this.defaultOptions, options);
1839
1840 // If chartist was not initialized yet, we just set the options and leave the rest to the initialization
1841 // Otherwise we re-create the optionsProvider at this point
1842 if(!this.initializeTimeoutId) {
1843 this.optionsProvider.removeMediaQueryListeners();
1844 this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
1845 }
1846 }
1847
1848 // Only re-created the chart if it has been initialized yet
1849 if(!this.initializeTimeoutId) {
1850 this.createChart(this.optionsProvider.getCurrentOptions());
1851 }
1852
1853 // Return a reference to the chart object to chain up calls
1854 return this;
1855 }
1856
1857 /**
1858 * This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.
1859 *
1860 * @memberof Chartist.Base
1861 */
1862 function detach() {
1863 // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore
1864 // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout
1865 if(!this.initializeTimeoutId) {
1866 window.removeEventListener('resize', this.resizeListener);
1867 this.optionsProvider.removeMediaQueryListeners();
1868 } else {
1869 window.clearTimeout(this.initializeTimeoutId);
1870 }
1871
1872 return this;
1873 }
1874
1875 /**
1876 * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
1877 *
1878 * @memberof Chartist.Base
1879 * @param {String} event Name of the event. Check the examples for supported events.
1880 * @param {Function} handler The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details.
1881 */
1882 function on(event, handler) {
1883 this.eventEmitter.addEventHandler(event, handler);
1884 return this;
1885 }
1886
1887 /**
1888 * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.
1889 *
1890 * @memberof Chartist.Base
1891 * @param {String} event Name of the event for which a handler should be removed
1892 * @param {Function} [handler] The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list.
1893 */
1894 function off(event, handler) {
1895 this.eventEmitter.removeEventHandler(event, handler);
1896 return this;
1897 }
1898
1899 function initialize() {
1900 // Add window resize listener that re-creates the chart
1901 window.addEventListener('resize', this.resizeListener);
1902
1903 // Obtain current options based on matching media queries (if responsive options are given)
1904 // This will also register a listener that is re-creating the chart based on media changes
1905 this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
1906 // Register options change listener that will trigger a chart update
1907 this.eventEmitter.addEventHandler('optionsChanged', function() {
1908 this.update();
1909 }.bind(this));
1910
1911 // Before the first chart creation we need to register us with all plugins that are configured
1912 // Initialize all relevant plugins with our chart object and the plugin options specified in the config
1913 if(this.options.plugins) {
1914 this.options.plugins.forEach(function(plugin) {
1915 if(plugin instanceof Array) {
1916 plugin[0](this, plugin[1]);
1917 } else {
1918 plugin(this);
1919 }
1920 }.bind(this));
1921 }
1922
1923 // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
1924 this.eventEmitter.emit('data', {
1925 type: 'initial',
1926 data: this.data
1927 });
1928
1929 // Create the first chart
1930 this.createChart(this.optionsProvider.getCurrentOptions());
1931
1932 // As chart is initialized from the event loop now we can reset our timeout reference
1933 // This is important if the chart gets initialized on the same element twice
1934 this.initializeTimeoutId = undefined;
1935 }
1936
1937 /**
1938 * Constructor of chart base class.
1939 *
1940 * @param query
1941 * @param data
1942 * @param defaultOptions
1943 * @param options
1944 * @param responsiveOptions
1945 * @constructor
1946 */
1947 function Base(query, data, defaultOptions, options, responsiveOptions) {
1948 this.container = Chartist.querySelector(query);
1949 this.data = data || {};
1950 this.data.labels = this.data.labels || [];
1951 this.data.series = this.data.series || [];
1952 this.defaultOptions = defaultOptions;
1953 this.options = options;
1954 this.responsiveOptions = responsiveOptions;
1955 this.eventEmitter = Chartist.EventEmitter();
1956 this.supportsForeignObject = Chartist.Svg.isSupported('Extensibility');
1957 this.supportsAnimations = Chartist.Svg.isSupported('AnimationEventsAttribute');
1958 this.resizeListener = function resizeListener(){
1959 this.update();
1960 }.bind(this);
1961
1962 if(this.container) {
1963 // If chartist was already initialized in this container we are detaching all event listeners first
1964 if(this.container.__chartist__) {
1965 this.container.__chartist__.detach();
1966 }
1967
1968 this.container.__chartist__ = this;
1969 }
1970
1971 // Using event loop for first draw to make it possible to register event listeners in the same call stack where
1972 // the chart was created.
1973 this.initializeTimeoutId = setTimeout(initialize.bind(this), 0);
1974 }
1975
1976 // Creating the chart base class
1977 Chartist.Base = Chartist.Class.extend({
1978 constructor: Base,
1979 optionsProvider: undefined,
1980 container: undefined,
1981 svg: undefined,
1982 eventEmitter: undefined,
1983 createChart: function() {
1984 throw new Error('Base chart type can\'t be instantiated!');
1985 },
1986 update: update,
1987 detach: detach,
1988 on: on,
1989 off: off,
1990 version: Chartist.version,
1991 supportsForeignObject: false
1992 });
1993
1994 }(this || global, Chartist));
1995 ;/**
1996 * Chartist SVG module for simple SVG DOM abstraction
1997 *
1998 * @module Chartist.Svg
1999 */
2000 /* global Chartist */
2001 (function(globalRoot, Chartist) {
2002 'use strict';
2003
2004 var document = globalRoot.document;
2005
2006 /**
2007 * Chartist.Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them.
2008 *
2009 * @memberof Chartist.Svg
2010 * @constructor
2011 * @param {String|Element} name The name of the SVG element to create or an SVG dom element which should be wrapped into Chartist.Svg
2012 * @param {Object} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
2013 * @param {String} className This class or class list will be added to the SVG element
2014 * @param {Object} parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child
2015 * @param {Boolean} insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
2016 */
2017 function Svg(name, attributes, className, parent, insertFirst) {
2018 // If Svg is getting called with an SVG element we just return the wrapper
2019 if(name instanceof Element) {
2020 this._node = name;
2021 } else {
2022 this._node = document.createElementNS(Chartist.namespaces.svg, name);
2023
2024 // If this is an SVG element created then custom namespace
2025 if(name === 'svg') {
2026 this.attr({
2027 'xmlns:ct': Chartist.namespaces.ct
2028 });
2029 }
2030 }
2031
2032 if(attributes) {
2033 this.attr(attributes);
2034 }
2035
2036 if(className) {
2037 this.addClass(className);
2038 }
2039
2040 if(parent) {
2041 if (insertFirst && parent._node.firstChild) {
2042 parent._node.insertBefore(this._node, parent._node.firstChild);
2043 } else {
2044 parent._node.appendChild(this._node);
2045 }
2046 }
2047 }
2048
2049 /**
2050 * Set attributes on the current SVG element of the wrapper you're currently working on.
2051 *
2052 * @memberof Chartist.Svg
2053 * @param {Object|String} attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value.
2054 * @param {String} [ns] If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object.
2055 * @return {Object|String} The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function.
2056 */
2057 function attr(attributes, ns) {
2058 if(typeof attributes === 'string') {
2059 if(ns) {
2060 return this._node.getAttributeNS(ns, attributes);
2061 } else {
2062 return this._node.getAttribute(attributes);
2063 }
2064 }
2065
2066 Object.keys(attributes).forEach(function(key) {
2067 // If the attribute value is undefined we can skip this one
2068 if(attributes[key] === undefined) {
2069 return;
2070 }
2071
2072 if (key.indexOf(':') !== -1) {
2073 var namespacedAttribute = key.split(':');
2074 this._node.setAttributeNS(Chartist.namespaces[namespacedAttribute[0]], key, attributes[key]);
2075 } else {
2076 this._node.setAttribute(key, attributes[key]);
2077 }
2078 }.bind(this));
2079
2080 return this;
2081 }
2082
2083 /**
2084 * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.
2085 *
2086 * @memberof Chartist.Svg
2087 * @param {String} name The name of the SVG element that should be created as child element of the currently selected element wrapper
2088 * @param {Object} [attributes] An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added.
2089 * @param {String} [className] This class or class list will be added to the SVG element
2090 * @param {Boolean} [insertFirst] If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element
2091 * @return {Chartist.Svg} Returns a Chartist.Svg wrapper object that can be used to modify the containing SVG data
2092 */
2093 function elem(name, attributes, className, insertFirst) {
2094 return new Chartist.Svg(name, attributes, className, this, insertFirst);
2095 }
2096
2097 /**
2098 * Returns the parent Chartist.SVG wrapper object
2099 *
2100 * @memberof Chartist.Svg
2101 * @return {Chartist.Svg} Returns a Chartist.Svg wrapper around the parent node of the current node. If the parent node is not existing or it's not an SVG node then this function will return null.
2102 */
2103 function parent() {
2104 return this._node.parentNode instanceof SVGElement ? new Chartist.Svg(this._node.parentNode) : null;
2105 }
2106
2107 /**
2108 * This method returns a Chartist.Svg wrapper around the root SVG element of the current tree.
2109 *
2110 * @memberof Chartist.Svg
2111 * @return {Chartist.Svg} The root SVG element wrapped in a Chartist.Svg element
2112 */
2113 function root() {
2114 var node = this._node;
2115 while(node.nodeName !== 'svg') {
2116 node = node.parentNode;
2117 }
2118 return new Chartist.Svg(node);
2119 }
2120
2121 /**
2122 * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper.
2123 *
2124 * @memberof Chartist.Svg
2125 * @param {String} selector A CSS selector that is used to query for child SVG elements
2126 * @return {Chartist.Svg} The SVG wrapper for the element found or null if no element was found
2127 */
2128 function querySelector(selector) {
2129 var foundNode = this._node.querySelector(selector);
2130 return foundNode ? new Chartist.Svg(foundNode) : null;
2131 }
2132
2133 /**
2134 * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper.
2135 *
2136 * @memberof Chartist.Svg
2137 * @param {String} selector A CSS selector that is used to query for child SVG elements
2138 * @return {Chartist.Svg.List} The SVG wrapper list for the element found or null if no element was found
2139 */
2140 function querySelectorAll(selector) {
2141 var foundNodes = this._node.querySelectorAll(selector);
2142 return foundNodes.length ? new Chartist.Svg.List(foundNodes) : null;
2143 }
2144
2145 /**
2146 * Returns the underlying SVG node for the current element.
2147 *
2148 * @memberof Chartist.Svg
2149 * @returns {Node}
2150 */
2151 function getNode() {
2152 return this._node;
2153 }
2154
2155 /**
2156 * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM.
2157 *
2158 * @memberof Chartist.Svg
2159 * @param {Node|String} content The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject
2160 * @param {String} [attributes] An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added.
2161 * @param {String} [className] This class or class list will be added to the SVG element
2162 * @param {Boolean} [insertFirst] Specifies if the foreignObject should be inserted as first child
2163 * @return {Chartist.Svg} New wrapper object that wraps the foreignObject element
2164 */
2165 function foreignObject(content, attributes, className, insertFirst) {
2166 // If content is string then we convert it to DOM
2167 // TODO: Handle case where content is not a string nor a DOM Node
2168 if(typeof content === 'string') {
2169 var container = document.createElement('div');
2170 container.innerHTML = content;
2171 content = container.firstChild;
2172 }
2173
2174 // Adding namespace to content element
2175 content.setAttribute('xmlns', Chartist.namespaces.xmlns);
2176
2177 // Creating the foreignObject without required extension attribute (as described here
2178 // http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement)
2179 var fnObj = this.elem('foreignObject', attributes, className, insertFirst);
2180
2181 // Add content to foreignObjectElement
2182 fnObj._node.appendChild(content);
2183
2184 return fnObj;
2185 }
2186
2187 /**
2188 * This method adds a new text element to the current Chartist.Svg wrapper.
2189 *
2190 * @memberof Chartist.Svg
2191 * @param {String} t The text that should be added to the text element that is created
2192 * @return {Chartist.Svg} The same wrapper object that was used to add the newly created element
2193 */
2194 function text(t) {
2195 this._node.appendChild(document.createTextNode(t));
2196 return this;
2197 }
2198
2199 /**
2200 * This method will clear all child nodes of the current wrapper object.
2201 *
2202 * @memberof Chartist.Svg
2203 * @return {Chartist.Svg} The same wrapper object that got emptied
2204 */
2205 function empty() {
2206 while (this._node.firstChild) {
2207 this._node.removeChild(this._node.firstChild);
2208 }
2209
2210 return this;
2211 }
2212
2213 /**
2214 * This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure.
2215 *
2216 * @memberof Chartist.Svg
2217 * @return {Chartist.Svg} The parent wrapper object of the element that got removed
2218 */
2219 function remove() {
2220 this._node.parentNode.removeChild(this._node);
2221 return this.parent();
2222 }
2223
2224 /**
2225 * This method will replace the element with a new element that can be created outside of the current DOM.
2226 *
2227 * @memberof Chartist.Svg
2228 * @param {Chartist.Svg} newElement The new Chartist.Svg object that will be used to replace the current wrapper object
2229 * @return {Chartist.Svg} The wrapper of the new element
2230 */
2231 function replace(newElement) {
2232 this._node.parentNode.replaceChild(newElement._node, this._node);
2233 return newElement;
2234 }
2235
2236 /**
2237 * This method will append an element to the current element as a child.
2238 *
2239 * @memberof Chartist.Svg
2240 * @param {Chartist.Svg} element The Chartist.Svg element that should be added as a child
2241 * @param {Boolean} [insertFirst] Specifies if the element should be inserted as first child
2242 * @return {Chartist.Svg} The wrapper of the appended object
2243 */
2244 function append(element, insertFirst) {
2245 if(insertFirst && this._node.firstChild) {
2246 this._node.insertBefore(element._node, this._node.firstChild);
2247 } else {
2248 this._node.appendChild(element._node);
2249 }
2250
2251 return this;
2252 }
2253
2254 /**
2255 * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.
2256 *
2257 * @memberof Chartist.Svg
2258 * @return {Array} A list of classes or an empty array if there are no classes on the current element
2259 */
2260 function classes() {
2261 return this._node.getAttribute('class') ? this._node.getAttribute('class').trim().split(/\s+/) : [];
2262 }
2263
2264 /**
2265 * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.
2266 *
2267 * @memberof Chartist.Svg
2268 * @param {String} names A white space separated list of class names
2269 * @return {Chartist.Svg} The wrapper of the current element
2270 */
2271 function addClass(names) {
2272 this._node.setAttribute('class',
2273 this.classes(this._node)
2274 .concat(names.trim().split(/\s+/))
2275 .filter(function(elem, pos, self) {
2276 return self.indexOf(elem) === pos;
2277 }).join(' ')
2278 );
2279
2280 return this;
2281 }
2282
2283 /**
2284 * Removes one or a space separated list of classes from the current element.
2285 *
2286 * @memberof Chartist.Svg
2287 * @param {String} names A white space separated list of class names
2288 * @return {Chartist.Svg} The wrapper of the current element
2289 */
2290 function removeClass(names) {
2291 var removedClasses = names.trim().split(/\s+/);
2292
2293 this._node.setAttribute('class', this.classes(this._node).filter(function(name) {
2294 return removedClasses.indexOf(name) === -1;
2295 }).join(' '));
2296
2297 return this;
2298 }
2299
2300 /**
2301 * Removes all classes from the current element.
2302 *
2303 * @memberof Chartist.Svg
2304 * @return {Chartist.Svg} The wrapper of the current element
2305 */
2306 function removeAllClasses() {
2307 this._node.setAttribute('class', '');
2308
2309 return this;
2310 }
2311
2312 /**
2313 * Get element height using `getBoundingClientRect`
2314 *
2315 * @memberof Chartist.Svg
2316 * @return {Number} The elements height in pixels
2317 */
2318 function height() {
2319 return this._node.getBoundingClientRect().height;
2320 }
2321
2322 /**
2323 * Get element width using `getBoundingClientRect`
2324 *
2325 * @memberof Chartist.Core
2326 * @return {Number} The elements width in pixels
2327 */
2328 function width() {
2329 return this._node.getBoundingClientRect().width;
2330 }
2331
2332 /**
2333 * The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in `Chartist.Svg.Easing` or an array with four numbers specifying a cubic Bézier curve.
2334 * **An animations object could look like this:**
2335 * ```javascript
2336 * element.animate({
2337 * opacity: {
2338 * dur: 1000,
2339 * from: 0,
2340 * to: 1
2341 * },
2342 * x1: {
2343 * dur: '1000ms',
2344 * from: 100,
2345 * to: 200,
2346 * easing: 'easeOutQuart'
2347 * },
2348 * y1: {
2349 * dur: '2s',
2350 * from: 0,
2351 * to: 100
2352 * }
2353 * });
2354 * ```
2355 * **Automatic unit conversion**
2356 * For the `dur` and the `begin` animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds.
2357 * **Guided mode**
2358 * The default behavior of SMIL animations with offset using the `begin` attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation `from` value even before the animation starts. Also if you don't specify `fill="freeze"` on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Chartist.Svg will also use the `begin` property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it.
2359 * If guided mode is enabled the following behavior is added:
2360 * - Before the animation starts (even when delayed with `begin`) the animated attribute will be set already to the `from` value of the animation
2361 * - `begin` is explicitly set to `indefinite` so it can be started manually without relying on document begin time (creation)
2362 * - The animate element will be forced to use `fill="freeze"`
2363 * - The animation will be triggered with `beginElement()` in a timeout where `begin` of the definition object is interpreted in milli seconds. If no `begin` was specified the timeout is triggered immediately.
2364 * - After the animation the element attribute value will be set to the `to` value of the animation
2365 * - The animate element is deleted from the DOM
2366 *
2367 * @memberof Chartist.Svg
2368 * @param {Object} animations An animations object where the property keys are the attributes you'd like to animate. The properties should be objects again that contain the SMIL animation attributes (usually begin, dur, from, and to). The property begin and dur is auto converted (see Automatic unit conversion). You can also schedule multiple animations for the same attribute by passing an Array of SMIL definition objects. Attributes that contain an array of SMIL definition objects will not be executed in guided mode.
2369 * @param {Boolean} guided Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated.
2370 * @param {Object} eventEmitter If specified, this event emitter will be notified when an animation starts or ends.
2371 * @return {Chartist.Svg} The current element where the animation was added
2372 */
2373 function animate(animations, guided, eventEmitter) {
2374 if(guided === undefined) {
2375 guided = true;
2376 }
2377
2378 Object.keys(animations).forEach(function createAnimateForAttributes(attribute) {
2379
2380 function createAnimate(animationDefinition, guided) {
2381 var attributeProperties = {},
2382 animate,
2383 timeout,
2384 easing;
2385
2386 // Check if an easing is specified in the definition object and delete it from the object as it will not
2387 // be part of the animate element attributes.
2388 if(animationDefinition.easing) {
2389 // If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object
2390 easing = animationDefinition.easing instanceof Array ?
2391 animationDefinition.easing :
2392 Chartist.Svg.Easing[animationDefinition.easing];
2393 delete animationDefinition.easing;
2394 }
2395
2396 // If numeric dur or begin was provided we assume milli seconds
2397 animationDefinition.begin = Chartist.ensureUnit(animationDefinition.begin, 'ms');
2398 animationDefinition.dur = Chartist.ensureUnit(animationDefinition.dur, 'ms');
2399
2400 if(easing) {
2401 animationDefinition.calcMode = 'spline';
2402 animationDefinition.keySplines = easing.join(' ');
2403 animationDefinition.keyTimes = '0;1';
2404 }
2405
2406 // Adding "fill: freeze" if we are in guided mode and set initial attribute values
2407 if(guided) {
2408 animationDefinition.fill = 'freeze';
2409 // Animated property on our element should already be set to the animation from value in guided mode
2410 attributeProperties[attribute] = animationDefinition.from;
2411 this.attr(attributeProperties);
2412
2413 // In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin
2414 // which needs to be in ms aside
2415 timeout = Chartist.quantity(animationDefinition.begin || 0).value;
2416 animationDefinition.begin = 'indefinite';
2417 }
2418
2419 animate = this.elem('animate', Chartist.extend({
2420 attributeName: attribute
2421 }, animationDefinition));
2422
2423 if(guided) {
2424 // If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout
2425 setTimeout(function() {
2426 // If beginElement fails we set the animated attribute to the end position and remove the animate element
2427 // This happens if the SMIL ElementTimeControl interface is not supported or any other problems occured in
2428 // the browser. (Currently FF 34 does not support animate elements in foreignObjects)
2429 try {
2430 animate._node.beginElement();
2431 } catch(err) {
2432 // Set animated attribute to current animated value
2433 attributeProperties[attribute] = animationDefinition.to;
2434 this.attr(attributeProperties);
2435 // Remove the animate element as it's no longer required
2436 animate.remove();
2437 }
2438 }.bind(this), timeout);
2439 }
2440
2441 if(eventEmitter) {
2442 animate._node.addEventListener('beginEvent', function handleBeginEvent() {
2443 eventEmitter.emit('animationBegin', {
2444 element: this,
2445 animate: animate._node,
2446 params: animationDefinition
2447 });
2448 }.bind(this));
2449 }
2450
2451 animate._node.addEventListener('endEvent', function handleEndEvent() {
2452 if(eventEmitter) {
2453 eventEmitter.emit('animationEnd', {
2454 element: this,
2455 animate: animate._node,
2456 params: animationDefinition
2457 });
2458 }
2459
2460 if(guided) {
2461 // Set animated attribute to current animated value
2462 attributeProperties[attribute] = animationDefinition.to;
2463 this.attr(attributeProperties);
2464 // Remove the animate element as it's no longer required
2465 animate.remove();
2466 }
2467 }.bind(this));
2468 }
2469
2470 // If current attribute is an array of definition objects we create an animate for each and disable guided mode
2471 if(animations[attribute] instanceof Array) {
2472 animations[attribute].forEach(function(animationDefinition) {
2473 createAnimate.bind(this)(animationDefinition, false);
2474 }.bind(this));
2475 } else {
2476 createAnimate.bind(this)(animations[attribute], guided);
2477 }
2478
2479 }.bind(this));
2480
2481 return this;
2482 }
2483
2484 Chartist.Svg = Chartist.Class.extend({
2485 constructor: Svg,
2486 attr: attr,
2487 elem: elem,
2488 parent: parent,
2489 root: root,
2490 querySelector: querySelector,
2491 querySelectorAll: querySelectorAll,
2492 getNode: getNode,
2493 foreignObject: foreignObject,
2494 text: text,
2495 empty: empty,
2496 remove: remove,
2497 replace: replace,
2498 append: append,
2499 classes: classes,
2500 addClass: addClass,
2501 removeClass: removeClass,
2502 removeAllClasses: removeAllClasses,
2503 height: height,
2504 width: width,
2505 animate: animate
2506 });
2507
2508 /**
2509 * This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list.
2510 *
2511 * @memberof Chartist.Svg
2512 * @param {String} feature The SVG 1.1 feature that should be checked for support.
2513 * @return {Boolean} True of false if the feature is supported or not
2514 */
2515 Chartist.Svg.isSupported = function(feature) {
2516 return document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#' + feature, '1.1');
2517 };
2518
2519 /**
2520 * This Object contains some standard easing cubic bezier curves. Then can be used with their name in the `Chartist.Svg.animate`. You can also extend the list and use your own name in the `animate` function. Click the show code button to see the available bezier functions.
2521 *
2522 * @memberof Chartist.Svg
2523 */
2524 var easingCubicBeziers = {
2525 easeInSine: [0.47, 0, 0.745, 0.715],
2526 easeOutSine: [0.39, 0.575, 0.565, 1],
2527 easeInOutSine: [0.445, 0.05, 0.55, 0.95],
2528 easeInQuad: [0.55, 0.085, 0.68, 0.53],
2529 easeOutQuad: [0.25, 0.46, 0.45, 0.94],
2530 easeInOutQuad: [0.455, 0.03, 0.515, 0.955],
2531 easeInCubic: [0.55, 0.055, 0.675, 0.19],
2532 easeOutCubic: [0.215, 0.61, 0.355, 1],
2533 easeInOutCubic: [0.645, 0.045, 0.355, 1],
2534 easeInQuart: [0.895, 0.03, 0.685, 0.22],
2535 easeOutQuart: [0.165, 0.84, 0.44, 1],
2536 easeInOutQuart: [0.77, 0, 0.175, 1],
2537 easeInQuint: [0.755, 0.05, 0.855, 0.06],
2538 easeOutQuint: [0.23, 1, 0.32, 1],
2539 easeInOutQuint: [0.86, 0, 0.07, 1],
2540 easeInExpo: [0.95, 0.05, 0.795, 0.035],
2541 easeOutExpo: [0.19, 1, 0.22, 1],
2542 easeInOutExpo: [1, 0, 0, 1],
2543 easeInCirc: [0.6, 0.04, 0.98, 0.335],
2544 easeOutCirc: [0.075, 0.82, 0.165, 1],
2545 easeInOutCirc: [0.785, 0.135, 0.15, 0.86],
2546 easeInBack: [0.6, -0.28, 0.735, 0.045],
2547 easeOutBack: [0.175, 0.885, 0.32, 1.275],
2548 easeInOutBack: [0.68, -0.55, 0.265, 1.55]
2549 };
2550
2551 Chartist.Svg.Easing = easingCubicBeziers;
2552
2553 /**
2554 * This helper class is to wrap multiple `Chartist.Svg` elements into a list where you can call the `Chartist.Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Chartist.Svg` on multiple elements.
2555 * An instance of this class is also returned by `Chartist.Svg.querySelectorAll`.
2556 *
2557 * @memberof Chartist.Svg
2558 * @param {Array<Node>|NodeList} nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll)
2559 * @constructor
2560 */
2561 function SvgList(nodeList) {
2562 var list = this;
2563
2564 this.svgElements = [];
2565 for(var i = 0; i < nodeList.length; i++) {
2566 this.svgElements.push(new Chartist.Svg(nodeList[i]));
2567 }
2568
2569 // Add delegation methods for Chartist.Svg
2570 Object.keys(Chartist.Svg.prototype).filter(function(prototypeProperty) {
2571 return ['constructor',
2572 'parent',
2573 'querySelector',
2574 'querySelectorAll',
2575 'replace',
2576 'append',
2577 'classes',
2578 'height',
2579 'width'].indexOf(prototypeProperty) === -1;
2580 }).forEach(function(prototypeProperty) {
2581 list[prototypeProperty] = function() {
2582 var args = Array.prototype.slice.call(arguments, 0);
2583 list.svgElements.forEach(function(element) {
2584 Chartist.Svg.prototype[prototypeProperty].apply(element, args);
2585 });
2586 return list;
2587 };
2588 });
2589 }
2590
2591 Chartist.Svg.List = Chartist.Class.extend({
2592 constructor: SvgList
2593 });
2594 }(this || global, Chartist));
2595 ;/**
2596 * Chartist SVG path module for SVG path description creation and modification.
2597 *
2598 * @module Chartist.Svg.Path
2599 */
2600 /* global Chartist */
2601 (function(globalRoot, Chartist) {
2602 'use strict';
2603
2604 /**
2605 * Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported.
2606 *
2607 * @memberof Chartist.Svg.Path
2608 * @type {Object}
2609 */
2610 var elementDescriptions = {
2611 m: ['x', 'y'],
2612 l: ['x', 'y'],
2613 c: ['x1', 'y1', 'x2', 'y2', 'x', 'y'],
2614 a: ['rx', 'ry', 'xAr', 'lAf', 'sf', 'x', 'y']
2615 };
2616
2617 /**
2618 * Default options for newly created SVG path objects.
2619 *
2620 * @memberof Chartist.Svg.Path
2621 * @type {Object}
2622 */
2623 var defaultOptions = {
2624 // The accuracy in digit count after the decimal point. This will be used to round numbers in the SVG path. If this option is set to false then no rounding will be performed.
2625 accuracy: 3
2626 };
2627
2628 function element(command, params, pathElements, pos, relative, data) {
2629 var pathElement = Chartist.extend({
2630 command: relative ? command.toLowerCase() : command.toUpperCase()
2631 }, params, data ? { data: data } : {} );
2632
2633 pathElements.splice(pos, 0, pathElement);
2634 }
2635
2636 function forEachParam(pathElements, cb) {
2637 pathElements.forEach(function(pathElement, pathElementIndex) {
2638 elementDescriptions[pathElement.command.toLowerCase()].forEach(function(paramName, paramIndex) {
2639 cb(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
2640 });
2641 });
2642 }
2643
2644 /**
2645 * Used to construct a new path object.
2646 *
2647 * @memberof Chartist.Svg.Path
2648 * @param {Boolean} close If set to true then this path will be closed when stringified (with a Z at the end)
2649 * @param {Object} options Options object that overrides the default objects. See default options for more details.
2650 * @constructor
2651 */
2652 function SvgPath(close, options) {
2653 this.pathElements = [];
2654 this.pos = 0;
2655 this.close = close;
2656 this.options = Chartist.extend({}, defaultOptions, options);
2657 }
2658
2659 /**
2660 * Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor.
2661 *
2662 * @memberof Chartist.Svg.Path
2663 * @param {Number} [pos] If a number is passed then the cursor is set to this position in the path element array.
2664 * @return {Chartist.Svg.Path|Number} If the position parameter was passed then the return value will be the path object for easy call chaining. If no position parameter was passed then the current position is returned.
2665 */
2666 function position(pos) {
2667 if(pos !== undefined) {
2668 this.pos = Math.max(0, Math.min(this.pathElements.length, pos));
2669 return this;
2670 } else {
2671 return this.pos;
2672 }
2673 }
2674
2675 /**
2676 * Removes elements from the path starting at the current position.
2677 *
2678 * @memberof Chartist.Svg.Path
2679 * @param {Number} count Number of path elements that should be removed from the current position.
2680 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2681 */
2682 function remove(count) {
2683 this.pathElements.splice(this.pos, count);
2684 return this;
2685 }
2686
2687 /**
2688 * Use this function to add a new move SVG path element.
2689 *
2690 * @memberof Chartist.Svg.Path
2691 * @param {Number} x The x coordinate for the move element.
2692 * @param {Number} y The y coordinate for the move element.
2693 * @param {Boolean} [relative] If set to true the move element will be created with relative coordinates (lowercase letter)
2694 * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
2695 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2696 */
2697 function move(x, y, relative, data) {
2698 element('M', {
2699 x: +x,
2700 y: +y
2701 }, this.pathElements, this.pos++, relative, data);
2702 return this;
2703 }
2704
2705 /**
2706 * Use this function to add a new line SVG path element.
2707 *
2708 * @memberof Chartist.Svg.Path
2709 * @param {Number} x The x coordinate for the line element.
2710 * @param {Number} y The y coordinate for the line element.
2711 * @param {Boolean} [relative] If set to true the line element will be created with relative coordinates (lowercase letter)
2712 * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
2713 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2714 */
2715 function line(x, y, relative, data) {
2716 element('L', {
2717 x: +x,
2718 y: +y
2719 }, this.pathElements, this.pos++, relative, data);
2720 return this;
2721 }
2722
2723 /**
2724 * Use this function to add a new curve SVG path element.
2725 *
2726 * @memberof Chartist.Svg.Path
2727 * @param {Number} x1 The x coordinate for the first control point of the bezier curve.
2728 * @param {Number} y1 The y coordinate for the first control point of the bezier curve.
2729 * @param {Number} x2 The x coordinate for the second control point of the bezier curve.
2730 * @param {Number} y2 The y coordinate for the second control point of the bezier curve.
2731 * @param {Number} x The x coordinate for the target point of the curve element.
2732 * @param {Number} y The y coordinate for the target point of the curve element.
2733 * @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
2734 * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
2735 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2736 */
2737 function curve(x1, y1, x2, y2, x, y, relative, data) {
2738 element('C', {
2739 x1: +x1,
2740 y1: +y1,
2741 x2: +x2,
2742 y2: +y2,
2743 x: +x,
2744 y: +y
2745 }, this.pathElements, this.pos++, relative, data);
2746 return this;
2747 }
2748
2749 /**
2750 * Use this function to add a new non-bezier curve SVG path element.
2751 *
2752 * @memberof Chartist.Svg.Path
2753 * @param {Number} rx The radius to be used for the x-axis of the arc.
2754 * @param {Number} ry The radius to be used for the y-axis of the arc.
2755 * @param {Number} xAr Defines the orientation of the arc
2756 * @param {Number} lAf Large arc flag
2757 * @param {Number} sf Sweep flag
2758 * @param {Number} x The x coordinate for the target point of the curve element.
2759 * @param {Number} y The y coordinate for the target point of the curve element.
2760 * @param {Boolean} [relative] If set to true the curve element will be created with relative coordinates (lowercase letter)
2761 * @param {*} [data] Any data that should be stored with the element object that will be accessible in pathElement
2762 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2763 */
2764 function arc(rx, ry, xAr, lAf, sf, x, y, relative, data) {
2765 element('A', {
2766 rx: +rx,
2767 ry: +ry,
2768 xAr: +xAr,
2769 lAf: +lAf,
2770 sf: +sf,
2771 x: +x,
2772 y: +y
2773 }, this.pathElements, this.pos++, relative, data);
2774 return this;
2775 }
2776
2777 /**
2778 * Parses an SVG path seen in the d attribute of path elements, and inserts the parsed elements into the existing path object at the current cursor position. Any closing path indicators (Z at the end of the path) will be ignored by the parser as this is provided by the close option in the options of the path object.
2779 *
2780 * @memberof Chartist.Svg.Path
2781 * @param {String} path Any SVG path that contains move (m), line (l) or curve (c) components.
2782 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2783 */
2784 function parse(path) {
2785 // Parsing the SVG path string into an array of arrays [['M', '10', '10'], ['L', '100', '100']]
2786 var chunks = path.replace(/([A-Za-z])([0-9])/g, '$1 $2')
2787 .replace(/([0-9])([A-Za-z])/g, '$1 $2')
2788 .split(/[\s,]+/)
2789 .reduce(function(result, element) {
2790 if(element.match(/[A-Za-z]/)) {
2791 result.push([]);
2792 }
2793
2794 result[result.length - 1].push(element);
2795 return result;
2796 }, []);
2797
2798 // If this is a closed path we remove the Z at the end because this is determined by the close option
2799 if(chunks[chunks.length - 1][0].toUpperCase() === 'Z') {
2800 chunks.pop();
2801 }
2802
2803 // Using svgPathElementDescriptions to map raw path arrays into objects that contain the command and the parameters
2804 // For example {command: 'M', x: '10', y: '10'}
2805 var elements = chunks.map(function(chunk) {
2806 var command = chunk.shift(),
2807 description = elementDescriptions[command.toLowerCase()];
2808
2809 return Chartist.extend({
2810 command: command
2811 }, description.reduce(function(result, paramName, index) {
2812 result[paramName] = +chunk[index];
2813 return result;
2814 }, {}));
2815 });
2816
2817 // Preparing a splice call with the elements array as var arg params and insert the parsed elements at the current position
2818 var spliceArgs = [this.pos, 0];
2819 Array.prototype.push.apply(spliceArgs, elements);
2820 Array.prototype.splice.apply(this.pathElements, spliceArgs);
2821 // Increase the internal position by the element count
2822 this.pos += elements.length;
2823
2824 return this;
2825 }
2826
2827 /**
2828 * This function renders to current SVG path object into a final SVG string that can be used in the d attribute of SVG path elements. It uses the accuracy option to round big decimals. If the close parameter was set in the constructor of this path object then a path closing Z will be appended to the output string.
2829 *
2830 * @memberof Chartist.Svg.Path
2831 * @return {String}
2832 */
2833 function stringify() {
2834 var accuracyMultiplier = Math.pow(10, this.options.accuracy);
2835
2836 return this.pathElements.reduce(function(path, pathElement) {
2837 var params = elementDescriptions[pathElement.command.toLowerCase()].map(function(paramName) {
2838 return this.options.accuracy ?
2839 (Math.round(pathElement[paramName] * accuracyMultiplier) / accuracyMultiplier) :
2840 pathElement[paramName];
2841 }.bind(this));
2842
2843 return path + pathElement.command + params.join(',');
2844 }.bind(this), '') + (this.close ? 'Z' : '');
2845 }
2846
2847 /**
2848 * Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves, affecting the given coordinate.
2849 *
2850 * @memberof Chartist.Svg.Path
2851 * @param {Number} x The number which will be used to scale the x, x1 and x2 of all path elements.
2852 * @param {Number} y The number which will be used to scale the y, y1 and y2 of all path elements.
2853 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2854 */
2855 function scale(x, y) {
2856 forEachParam(this.pathElements, function(pathElement, paramName) {
2857 pathElement[paramName] *= paramName[0] === 'x' ? x : y;
2858 });
2859 return this;
2860 }
2861
2862 /**
2863 * Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate.
2864 *
2865 * @memberof Chartist.Svg.Path
2866 * @param {Number} x The number which will be used to translate the x, x1 and x2 of all path elements.
2867 * @param {Number} y The number which will be used to translate the y, y1 and y2 of all path elements.
2868 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2869 */
2870 function translate(x, y) {
2871 forEachParam(this.pathElements, function(pathElement, paramName) {
2872 pathElement[paramName] += paramName[0] === 'x' ? x : y;
2873 });
2874 return this;
2875 }
2876
2877 /**
2878 * This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path.
2879 * The method signature of the callback function looks like this:
2880 * ```javascript
2881 * function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)
2882 * ```
2883 * If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate.
2884 *
2885 * @memberof Chartist.Svg.Path
2886 * @param {Function} transformFnc The callback function for the transformation. Check the signature in the function description.
2887 * @return {Chartist.Svg.Path} The current path object for easy call chaining.
2888 */
2889 function transform(transformFnc) {
2890 forEachParam(this.pathElements, function(pathElement, paramName, pathElementIndex, paramIndex, pathElements) {
2891 var transformed = transformFnc(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
2892 if(transformed || transformed === 0) {
2893 pathElement[paramName] = transformed;
2894 }
2895 });
2896 return this;
2897 }
2898
2899 /**
2900 * This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.
2901 *
2902 * @memberof Chartist.Svg.Path
2903 * @param {Boolean} [close] Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used.
2904 * @return {Chartist.Svg.Path}
2905 */
2906 function clone(close) {
2907 var c = new Chartist.Svg.Path(close || this.close);
2908 c.pos = this.pos;
2909 c.pathElements = this.pathElements.slice().map(function cloneElements(pathElement) {
2910 return Chartist.extend({}, pathElement);
2911 });
2912 c.options = Chartist.extend({}, this.options);
2913 return c;
2914 }
2915
2916 /**
2917 * Split a Svg.Path object by a specific command in the path chain. The path chain will be split and an array of newly created paths objects will be returned. This is useful if you'd like to split an SVG path by it's move commands, for example, in order to isolate chunks of drawings.
2918 *
2919 * @memberof Chartist.Svg.Path
2920 * @param {String} command The command you'd like to use to split the path
2921 * @return {Array<Chartist.Svg.Path>}
2922 */
2923 function splitByCommand(command) {
2924 var split = [
2925 new Chartist.Svg.Path()
2926 ];
2927
2928 this.pathElements.forEach(function(pathElement) {
2929 if(pathElement.command === command.toUpperCase() && split[split.length - 1].pathElements.length !== 0) {
2930 split.push(new Chartist.Svg.Path());
2931 }
2932
2933 split[split.length - 1].pathElements.push(pathElement);
2934 });
2935
2936 return split;
2937 }
2938
2939 /**
2940 * This static function on `Chartist.Svg.Path` is joining multiple paths together into one paths.
2941 *
2942 * @memberof Chartist.Svg.Path
2943 * @param {Array<Chartist.Svg.Path>} paths A list of paths to be joined together. The order is important.
2944 * @param {boolean} close If the newly created path should be a closed path
2945 * @param {Object} options Path options for the newly created path.
2946 * @return {Chartist.Svg.Path}
2947 */
2948
2949 function join(paths, close, options) {
2950 var joinedPath = new Chartist.Svg.Path(close, options);
2951 for(var i = 0; i < paths.length; i++) {
2952 var path = paths[i];
2953 for(var j = 0; j < path.pathElements.length; j++) {
2954 joinedPath.pathElements.push(path.pathElements[j]);
2955 }
2956 }
2957 return joinedPath;
2958 }
2959
2960 Chartist.Svg.Path = Chartist.Class.extend({
2961 constructor: SvgPath,
2962 position: position,
2963 remove: remove,
2964 move: move,
2965 line: line,
2966 curve: curve,
2967 arc: arc,
2968 scale: scale,
2969 translate: translate,
2970 transform: transform,
2971 parse: parse,
2972 stringify: stringify,
2973 clone: clone,
2974 splitByCommand: splitByCommand
2975 });
2976
2977 Chartist.Svg.Path.elementDescriptions = elementDescriptions;
2978 Chartist.Svg.Path.join = join;
2979 }(this || global, Chartist));
2980 ;/* global Chartist */
2981 (function (globalRoot, Chartist) {
2982 'use strict';
2983
2984 var window = globalRoot.window;
2985 var document = globalRoot.document;
2986
2987 var axisUnits = {
2988 x: {
2989 pos: 'x',
2990 len: 'width',
2991 dir: 'horizontal',
2992 rectStart: 'x1',
2993 rectEnd: 'x2',
2994 rectOffset: 'y2'
2995 },
2996 y: {
2997 pos: 'y',
2998 len: 'height',
2999 dir: 'vertical',
3000 rectStart: 'y2',
3001 rectEnd: 'y1',
3002 rectOffset: 'x1'
3003 }
3004 };
3005
3006 function Axis(units, chartRect, ticks, options) {
3007 this.units = units;
3008 this.counterUnits = units === axisUnits.x ? axisUnits.y : axisUnits.x;
3009 this.chartRect = chartRect;
3010 this.axisLength = chartRect[units.rectEnd] - chartRect[units.rectStart];
3011 this.gridOffset = chartRect[units.rectOffset];
3012 this.ticks = ticks;
3013 this.options = options;
3014 }
3015
3016 function createGridAndLabels(gridGroup, labelGroup, useForeignObject, chartOptions, eventEmitter) {
3017 var axisOptions = chartOptions['axis' + this.units.pos.toUpperCase()];
3018 var projectedValues = this.ticks.map(this.projectValue.bind(this));
3019 var labelValues = this.ticks.map(axisOptions.labelInterpolationFnc);
3020
3021 projectedValues.forEach(function(projectedValue, index) {
3022 var labelOffset = {
3023 x: 0,
3024 y: 0
3025 };
3026
3027 // TODO: Find better solution for solving this problem
3028 // Calculate how much space we have available for the label
3029 var labelLength;
3030 if(projectedValues[index + 1]) {
3031 // If we still have one label ahead, we can calculate the distance to the next tick / label
3032 labelLength = projectedValues[index + 1] - projectedValue;
3033 } else {
3034 // If we don't have a label ahead and we have only two labels in total, we just take the remaining distance to
3035 // on the whole axis length. We limit that to a minimum of 30 pixel, so that labels close to the border will
3036 // still be visible inside of the chart padding.
3037 labelLength = Math.max(this.axisLength - projectedValue, 30);
3038 }
3039
3040 // Skip grid lines and labels where interpolated label values are falsey (execpt for 0)
3041 if(Chartist.isFalseyButZero(labelValues[index]) && labelValues[index] !== '') {
3042 return;
3043 }
3044
3045 // Transform to global coordinates using the chartRect
3046 // We also need to set the label offset for the createLabel function
3047 if(this.units.pos === 'x') {
3048 projectedValue = this.chartRect.x1 + projectedValue;
3049 labelOffset.x = chartOptions.axisX.labelOffset.x;
3050
3051 // If the labels should be positioned in start position (top side for vertical axis) we need to set a
3052 // different offset as for positioned with end (bottom)
3053 if(chartOptions.axisX.position === 'start') {
3054 labelOffset.y = this.chartRect.padding.top + chartOptions.axisX.labelOffset.y + (useForeignObject ? 5 : 20);
3055 } else {
3056 labelOffset.y = this.chartRect.y1 + chartOptions.axisX.labelOffset.y + (useForeignObject ? 5 : 20);
3057 }
3058 } else {
3059 projectedValue = this.chartRect.y1 - projectedValue;
3060 labelOffset.y = chartOptions.axisY.labelOffset.y - (useForeignObject ? labelLength : 0);
3061
3062 // If the labels should be positioned in start position (left side for horizontal axis) we need to set a
3063 // different offset as for positioned with end (right side)
3064 if(chartOptions.axisY.position === 'start') {
3065 labelOffset.x = useForeignObject ? this.chartRect.padding.left + chartOptions.axisY.labelOffset.x : this.chartRect.x1 - 10;
3066 } else {
3067 labelOffset.x = this.chartRect.x2 + chartOptions.axisY.labelOffset.x + 10;
3068 }
3069 }
3070
3071 if(axisOptions.showGrid) {
3072 Chartist.createGrid(projectedValue, index, this, this.gridOffset, this.chartRect[this.counterUnits.len](), gridGroup, [
3073 chartOptions.classNames.grid,
3074 chartOptions.classNames[this.units.dir]
3075 ], eventEmitter);
3076 }
3077
3078 if(axisOptions.showLabel) {
3079 Chartist.createLabel(projectedValue, labelLength, index, labelValues, this, axisOptions.offset, labelOffset, labelGroup, [
3080 chartOptions.classNames.label,
3081 chartOptions.classNames[this.units.dir],
3082 (axisOptions.position === 'start' ? chartOptions.classNames[axisOptions.position] : chartOptions.classNames['end'])
3083 ], useForeignObject, eventEmitter);
3084 }
3085 }.bind(this));
3086 }
3087
3088 Chartist.Axis = Chartist.Class.extend({
3089 constructor: Axis,
3090 createGridAndLabels: createGridAndLabels,
3091 projectValue: function(value, index, data) {
3092 throw new Error('Base axis can\'t be instantiated!');
3093 }
3094 });
3095
3096 Chartist.Axis.units = axisUnits;
3097
3098 }(this || global, Chartist));
3099 ;/**
3100 * The auto scale axis uses standard linear scale projection of values along an axis. It uses order of magnitude to find a scale automatically and evaluates the available space in order to find the perfect amount of ticks for your chart.
3101 * **Options**
3102 * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
3103 * ```javascript
3104 * var options = {
3105 * // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
3106 * high: 100,
3107 * // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
3108 * low: 0,
3109 * // This option will be used when finding the right scale division settings. The amount of ticks on the scale will be determined so that as many ticks as possible will be displayed, while not violating this minimum required space (in pixel).
3110 * scaleMinSpace: 20,
3111 * // Can be set to true or false. If set to true, the scale will be generated with whole numbers only.
3112 * onlyInteger: true,
3113 * // The reference value can be used to make sure that this value will always be on the chart. This is especially useful on bipolar charts where the bipolar center always needs to be part of the chart.
3114 * referenceValue: 5
3115 * };
3116 * ```
3117 *
3118 * @module Chartist.AutoScaleAxis
3119 */
3120 /* global Chartist */
3121 (function (globalRoot, Chartist) {
3122 'use strict';
3123
3124 var window = globalRoot.window;
3125 var document = globalRoot.document;
3126
3127 function AutoScaleAxis(axisUnit, data, chartRect, options) {
3128 // Usually we calculate highLow based on the data but this can be overriden by a highLow object in the options
3129 var highLow = options.highLow || Chartist.getHighLow(data, options, axisUnit.pos);
3130 this.bounds = Chartist.getBounds(chartRect[axisUnit.rectEnd] - chartRect[axisUnit.rectStart], highLow, options.scaleMinSpace || 20, options.onlyInteger);
3131 this.range = {
3132 min: this.bounds.min,
3133 max: this.bounds.max
3134 };
3135
3136 Chartist.AutoScaleAxis['super'].constructor.call(this,
3137 axisUnit,
3138 chartRect,
3139 this.bounds.values,
3140 options);
3141 }
3142
3143 function projectValue(value) {
3144 return this.axisLength * (+Chartist.getMultiValue(value, this.units.pos) - this.bounds.min) / this.bounds.range;
3145 }
3146
3147 Chartist.AutoScaleAxis = Chartist.Axis.extend({
3148 constructor: AutoScaleAxis,
3149 projectValue: projectValue
3150 });
3151
3152 }(this || global, Chartist));
3153 ;/**
3154 * The fixed scale axis uses standard linear projection of values along an axis. It makes use of a divisor option to divide the range provided from the minimum and maximum value or the options high and low that will override the computed minimum and maximum.
3155 * **Options**
3156 * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
3157 * ```javascript
3158 * var options = {
3159 * // If high is specified then the axis will display values explicitly up to this value and the computed maximum from the data is ignored
3160 * high: 100,
3161 * // If low is specified then the axis will display values explicitly down to this value and the computed minimum from the data is ignored
3162 * low: 0,
3163 * // If specified then the value range determined from minimum to maximum (or low and high) will be divided by this number and ticks will be generated at those division points. The default divisor is 1.
3164 * divisor: 4,
3165 * // If ticks is explicitly set, then the axis will not compute the ticks with the divisor, but directly use the data in ticks to determine at what points on the axis a tick need to be generated.
3166 * ticks: [1, 10, 20, 30]
3167 * };
3168 * ```
3169 *
3170 * @module Chartist.FixedScaleAxis
3171 */
3172 /* global Chartist */
3173 (function (globalRoot, Chartist) {
3174 'use strict';
3175
3176 var window = globalRoot.window;
3177 var document = globalRoot.document;
3178
3179 function FixedScaleAxis(axisUnit, data, chartRect, options) {
3180 var highLow = options.highLow || Chartist.getHighLow(data, options, axisUnit.pos);
3181 this.divisor = options.divisor || 1;
3182 this.ticks = options.ticks || Chartist.times(this.divisor).map(function(value, index) {
3183 return highLow.low + (highLow.high - highLow.low) / this.divisor * index;
3184 }.bind(this));
3185 this.ticks.sort(function(a, b) {
3186 return a - b;
3187 });
3188 this.range = {
3189 min: highLow.low,
3190 max: highLow.high
3191 };
3192
3193 Chartist.FixedScaleAxis['super'].constructor.call(this,
3194 axisUnit,
3195 chartRect,
3196 this.ticks,
3197 options);
3198
3199 this.stepLength = this.axisLength / this.divisor;
3200 }
3201
3202 function projectValue(value) {
3203 return this.axisLength * (+Chartist.getMultiValue(value, this.units.pos) - this.range.min) / (this.range.max - this.range.min);
3204 }
3205
3206 Chartist.FixedScaleAxis = Chartist.Axis.extend({
3207 constructor: FixedScaleAxis,
3208 projectValue: projectValue
3209 });
3210
3211 }(this || global, Chartist));
3212 ;/**
3213 * The step axis for step based charts like bar chart or step based line charts. It uses a fixed amount of ticks that will be equally distributed across the whole axis length. The projection is done using the index of the data value rather than the value itself and therefore it's only useful for distribution purpose.
3214 * **Options**
3215 * The following options are used by this axis in addition to the default axis options outlined in the axis configuration of the chart default settings.
3216 * ```javascript
3217 * var options = {
3218 * // Ticks to be used to distribute across the axis length. As this axis type relies on the index of the value rather than the value, arbitrary data that can be converted to a string can be used as ticks.
3219 * ticks: ['One', 'Two', 'Three'],
3220 * // If set to true the full width will be used to distribute the values where the last value will be at the maximum of the axis length. If false the spaces between the ticks will be evenly distributed instead.
3221 * stretch: true
3222 * };
3223 * ```
3224 *
3225 * @module Chartist.StepAxis
3226 */
3227 /* global Chartist */
3228 (function (globalRoot, Chartist) {
3229 'use strict';
3230
3231 var window = globalRoot.window;
3232 var document = globalRoot.document;
3233
3234 function StepAxis(axisUnit, data, chartRect, options) {
3235 Chartist.StepAxis['super'].constructor.call(this,
3236 axisUnit,
3237 chartRect,
3238 options.ticks,
3239 options);
3240
3241 var calc = Math.max(1, options.ticks.length - (options.stretch ? 1 : 0));
3242 this.stepLength = this.axisLength / calc;
3243 }
3244
3245 function projectValue(value, index) {
3246 return this.stepLength * index;
3247 }
3248
3249 Chartist.StepAxis = Chartist.Axis.extend({
3250 constructor: StepAxis,
3251 projectValue: projectValue
3252 });
3253
3254 }(this || global, Chartist));
3255 ;/**
3256 * The Chartist line chart can be used to draw Line or Scatter charts. If used in the browser you can access the global `Chartist` namespace where you find the `Line` function as a main entry point.
3257 *
3258 * For examples on how to use the line chart please check the examples of the `Chartist.Line` method.
3259 *
3260 * @module Chartist.Line
3261 */
3262 /* global Chartist */
3263 (function(globalRoot, Chartist){
3264 'use strict';
3265
3266 var window = globalRoot.window;
3267 var document = globalRoot.document;
3268
3269 /**
3270 * Default options in line charts. Expand the code view to see a detailed list of options with comments.
3271 *
3272 * @memberof Chartist.Line
3273 */
3274 var defaultOptions = {
3275 // Options for X-Axis
3276 axisX: {
3277 // The offset of the labels to the chart area
3278 offset: 30,
3279 // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
3280 position: 'end',
3281 // Allows you to correct label positioning on this axis by positive or negative x and y offset.
3282 labelOffset: {
3283 x: 0,
3284 y: 0
3285 },
3286 // If labels should be shown or not
3287 showLabel: true,
3288 // If the axis grid should be drawn or not
3289 showGrid: true,
3290 // Interpolation function that allows you to intercept the value from the axis label
3291 labelInterpolationFnc: Chartist.noop,
3292 // Set the axis type to be used to project values on this axis. If not defined, Chartist.StepAxis will be used for the X-Axis, where the ticks option will be set to the labels in the data and the stretch option will be set to the global fullWidth option. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
3293 type: undefined
3294 },
3295 // Options for Y-Axis
3296 axisY: {
3297 // The offset of the labels to the chart area
3298 offset: 40,
3299 // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
3300 position: 'start',
3301 // Allows you to correct label positioning on this axis by positive or negative x and y offset.
3302 labelOffset: {
3303 x: 0,
3304 y: 0
3305 },
3306 // If labels should be shown or not
3307 showLabel: true,
3308 // If the axis grid should be drawn or not
3309 showGrid: true,
3310 // Interpolation function that allows you to intercept the value from the axis label
3311 labelInterpolationFnc: Chartist.noop,
3312 // Set the axis type to be used to project values on this axis. If not defined, Chartist.AutoScaleAxis will be used for the Y-Axis, where the high and low options will be set to the global high and low options. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here.
3313 type: undefined,
3314 // This value specifies the minimum height in pixel of the scale steps
3315 scaleMinSpace: 20,
3316 // Use only integer values (whole numbers) for the scale steps
3317 onlyInteger: false
3318 },
3319 // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
3320 width: undefined,
3321 // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
3322 height: undefined,
3323 // If the line should be drawn or not
3324 showLine: true,
3325 // If dots should be drawn or not
3326 showPoint: true,
3327 // If the line chart should draw an area
3328 showArea: false,
3329 // The base for the area chart that will be used to close the area shape (is normally 0)
3330 areaBase: 0,
3331 // Specify if the lines should be smoothed. This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. Check the examples for a brief description.
3332 lineSmooth: true,
3333 // If the line chart should add a background fill to the .ct-grids group.
3334 showGridBackground: false,
3335 // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
3336 low: undefined,
3337 // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
3338 high: undefined,
3339 // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
3340 chartPadding: {
3341 top: 15,
3342 right: 15,
3343 bottom: 5,
3344 left: 10
3345 },
3346 // When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler.
3347 fullWidth: false,
3348 // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
3349 reverseData: false,
3350 // Override the class names that get used to generate the SVG structure of the chart
3351 classNames: {
3352 chart: 'ct-chart-line',
3353 label: 'ct-label',
3354 labelGroup: 'ct-labels',
3355 series: 'ct-series',
3356 line: 'ct-line',
3357 point: 'ct-point',
3358 area: 'ct-area',
3359 grid: 'ct-grid',
3360 gridGroup: 'ct-grids',
3361 gridBackground: 'ct-grid-background',
3362 vertical: 'ct-vertical',
3363 horizontal: 'ct-horizontal',
3364 start: 'ct-start',
3365 end: 'ct-end'
3366 }
3367 };
3368
3369 /**
3370 * Creates a new chart
3371 *
3372 */
3373 function createChart(options) {
3374 var data = Chartist.normalizeData(this.data, options.reverseData, true);
3375
3376 // Create new svg object
3377 this.svg = Chartist.createSvg(this.container, options.width, options.height, options.classNames.chart);
3378 // Create groups for labels, grid and series
3379 var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);
3380 var seriesGroup = this.svg.elem('g');
3381 var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);
3382
3383 var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
3384 var axisX, axisY;
3385
3386 if(options.axisX.type === undefined) {
3387 axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
3388 ticks: data.normalized.labels,
3389 stretch: options.fullWidth
3390 }));
3391 } else {
3392 axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);
3393 }
3394
3395 if(options.axisY.type === undefined) {
3396 axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
3397 high: Chartist.isNumeric(options.high) ? options.high : options.axisY.high,
3398 low: Chartist.isNumeric(options.low) ? options.low : options.axisY.low
3399 }));
3400 } else {
3401 axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);
3402 }
3403
3404 axisX.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
3405 axisY.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
3406
3407 if (options.showGridBackground) {
3408 Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
3409 }
3410
3411 // Draw the series
3412 data.raw.series.forEach(function(series, seriesIndex) {
3413 var seriesElement = seriesGroup.elem('g');
3414
3415 // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
3416 seriesElement.attr({
3417 'ct:series-name': series.name,
3418 'ct:meta': Chartist.serialize(series.meta)
3419 });
3420
3421 // Use series class from series data or if not set generate one
3422 seriesElement.addClass([
3423 options.classNames.series,
3424 (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))
3425 ].join(' '));
3426
3427 var pathCoordinates = [],
3428 pathData = [];
3429
3430 data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {
3431 var p = {
3432 x: chartRect.x1 + axisX.projectValue(value, valueIndex, data.normalized.series[seriesIndex]),
3433 y: chartRect.y1 - axisY.projectValue(value, valueIndex, data.normalized.series[seriesIndex])
3434 };
3435 pathCoordinates.push(p.x, p.y);
3436 pathData.push({
3437 value: value,
3438 valueIndex: valueIndex,
3439 meta: Chartist.getMetaData(series, valueIndex)
3440 });
3441 }.bind(this));
3442
3443 var seriesOptions = {
3444 lineSmooth: Chartist.getSeriesOption(series, options, 'lineSmooth'),
3445 showPoint: Chartist.getSeriesOption(series, options, 'showPoint'),
3446 showLine: Chartist.getSeriesOption(series, options, 'showLine'),
3447 showArea: Chartist.getSeriesOption(series, options, 'showArea'),
3448 areaBase: Chartist.getSeriesOption(series, options, 'areaBase')
3449 };
3450
3451 var smoothing = typeof seriesOptions.lineSmooth === 'function' ?
3452 seriesOptions.lineSmooth : (seriesOptions.lineSmooth ? Chartist.Interpolation.monotoneCubic() : Chartist.Interpolation.none());
3453 // Interpolating path where pathData will be used to annotate each path element so we can trace back the original
3454 // index, value and meta data
3455 var path = smoothing(pathCoordinates, pathData);
3456
3457 // If we should show points we need to create them now to avoid secondary loop
3458 // Points are drawn from the pathElements returned by the interpolation function
3459 // Small offset for Firefox to render squares correctly
3460 if (seriesOptions.showPoint) {
3461
3462 path.pathElements.forEach(function(pathElement) {
3463 var point = seriesElement.elem('line', {
3464 x1: pathElement.x,
3465 y1: pathElement.y,
3466 x2: pathElement.x + 0.01,
3467 y2: pathElement.y
3468 }, options.classNames.point).attr({
3469 'ct:value': [pathElement.data.value.x, pathElement.data.value.y].filter(Chartist.isNumeric).join(','),
3470 'ct:meta': Chartist.serialize(pathElement.data.meta)
3471 });
3472
3473 this.eventEmitter.emit('draw', {
3474 type: 'point',
3475 value: pathElement.data.value,
3476 index: pathElement.data.valueIndex,
3477 meta: pathElement.data.meta,
3478 series: series,
3479 seriesIndex: seriesIndex,
3480 axisX: axisX,
3481 axisY: axisY,
3482 group: seriesElement,
3483 element: point,
3484 x: pathElement.x,
3485 y: pathElement.y
3486 });
3487 }.bind(this));
3488 }
3489
3490 if(seriesOptions.showLine) {
3491 var line = seriesElement.elem('path', {
3492 d: path.stringify()
3493 }, options.classNames.line, true);
3494
3495 this.eventEmitter.emit('draw', {
3496 type: 'line',
3497 values: data.normalized.series[seriesIndex],
3498 path: path.clone(),
3499 chartRect: chartRect,
3500 index: seriesIndex,
3501 series: series,
3502 seriesIndex: seriesIndex,
3503 seriesMeta: series.meta,
3504 axisX: axisX,
3505 axisY: axisY,
3506 group: seriesElement,
3507 element: line
3508 });
3509 }
3510
3511 // Area currently only works with axes that support a range!
3512 if(seriesOptions.showArea && axisY.range) {
3513 // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that
3514 // the area is not drawn outside the chart area.
3515 var areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);
3516
3517 // We project the areaBase value into screen coordinates
3518 var areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);
3519
3520 // In order to form the area we'll first split the path by move commands so we can chunk it up into segments
3521 path.splitByCommand('M').filter(function onlySolidSegments(pathSegment) {
3522 // We filter only "solid" segments that contain more than one point. Otherwise there's no need for an area
3523 return pathSegment.pathElements.length > 1;
3524 }).map(function convertToArea(solidPathSegments) {
3525 // Receiving the filtered solid path segments we can now convert those segments into fill areas
3526 var firstElement = solidPathSegments.pathElements[0];
3527 var lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];
3528
3529 // Cloning the solid path segment with closing option and removing the first move command from the clone
3530 // We then insert a new move that should start at the area base and draw a straight line up or down
3531 // at the end of the path we add an additional straight line to the projected area base value
3532 // As the closing option is set our path will be automatically closed
3533 return solidPathSegments.clone(true)
3534 .position(0)
3535 .remove(1)
3536 .move(firstElement.x, areaBaseProjected)
3537 .line(firstElement.x, firstElement.y)
3538 .position(solidPathSegments.pathElements.length + 1)
3539 .line(lastElement.x, areaBaseProjected);
3540
3541 }).forEach(function createArea(areaPath) {
3542 // For each of our newly created area paths, we'll now create path elements by stringifying our path objects
3543 // and adding the created DOM elements to the correct series group
3544 var area = seriesElement.elem('path', {
3545 d: areaPath.stringify()
3546 }, options.classNames.area, true);
3547
3548 // Emit an event for each area that was drawn
3549 this.eventEmitter.emit('draw', {
3550 type: 'area',
3551 values: data.normalized.series[seriesIndex],
3552 path: areaPath.clone(),
3553 series: series,
3554 seriesIndex: seriesIndex,
3555 axisX: axisX,
3556 axisY: axisY,
3557 chartRect: chartRect,
3558 index: seriesIndex,
3559 group: seriesElement,
3560 element: area
3561 });
3562 }.bind(this));
3563 }
3564 }.bind(this));
3565
3566 this.eventEmitter.emit('created', {
3567 bounds: axisY.bounds,
3568 chartRect: chartRect,
3569 axisX: axisX,
3570 axisY: axisY,
3571 svg: this.svg,
3572 options: options
3573 });
3574 }
3575
3576 /**
3577 * This method creates a new line chart.
3578 *
3579 * @memberof Chartist.Line
3580 * @param {String|Node} query A selector query string or directly a DOM element
3581 * @param {Object} data The data object that needs to consist of a labels and a series array
3582 * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
3583 * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
3584 * @return {Object} An object which exposes the API for the created chart
3585 *
3586 * @example
3587 * // Create a simple line chart
3588 * var data = {
3589 * // A labels array that can contain any sort of values
3590 * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
3591 * // Our series array that contains series objects or in this case series data arrays
3592 * series: [
3593 * [5, 2, 4, 2, 0]
3594 * ]
3595 * };
3596 *
3597 * // As options we currently only set a static size of 300x200 px
3598 * var options = {
3599 * width: '300px',
3600 * height: '200px'
3601 * };
3602 *
3603 * // In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options
3604 * new Chartist.Line('.ct-chart', data, options);
3605 *
3606 * @example
3607 * // Use specific interpolation function with configuration from the Chartist.Interpolation module
3608 *
3609 * var chart = new Chartist.Line('.ct-chart', {
3610 * labels: [1, 2, 3, 4, 5],
3611 * series: [
3612 * [1, 1, 8, 1, 7]
3613 * ]
3614 * }, {
3615 * lineSmooth: Chartist.Interpolation.cardinal({
3616 * tension: 0.2
3617 * })
3618 * });
3619 *
3620 * @example
3621 * // Create a line chart with responsive options
3622 *
3623 * var data = {
3624 * // A labels array that can contain any sort of values
3625 * labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
3626 * // Our series array that contains series objects or in this case series data arrays
3627 * series: [
3628 * [5, 2, 4, 2, 0]
3629 * ]
3630 * };
3631 *
3632 * // In addition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries.
3633 * var responsiveOptions = [
3634 * ['screen and (min-width: 641px) and (max-width: 1024px)', {
3635 * showPoint: false,
3636 * axisX: {
3637 * labelInterpolationFnc: function(value) {
3638 * // Will return Mon, Tue, Wed etc. on medium screens
3639 * return value.slice(0, 3);
3640 * }
3641 * }
3642 * }],
3643 * ['screen and (max-width: 640px)', {
3644 * showLine: false,
3645 * axisX: {
3646 * labelInterpolationFnc: function(value) {
3647 * // Will return M, T, W etc. on small screens
3648 * return value[0];
3649 * }
3650 * }
3651 * }]
3652 * ];
3653 *
3654 * new Chartist.Line('.ct-chart', data, null, responsiveOptions);
3655 *
3656 */
3657 function Line(query, data, options, responsiveOptions) {
3658 Chartist.Line['super'].constructor.call(this,
3659 query,
3660 data,
3661 defaultOptions,
3662 Chartist.extend({}, defaultOptions, options),
3663 responsiveOptions);
3664 }
3665
3666 // Creating line chart type in Chartist namespace
3667 Chartist.Line = Chartist.Base.extend({
3668 constructor: Line,
3669 createChart: createChart
3670 });
3671
3672 }(this || global, Chartist));
3673 ;/**
3674 * The bar chart module of Chartist that can be used to draw unipolar or bipolar bar and grouped bar charts.
3675 *
3676 * @module Chartist.Bar
3677 */
3678 /* global Chartist */
3679 (function(globalRoot, Chartist){
3680 'use strict';
3681
3682 var window = globalRoot.window;
3683 var document = globalRoot.document;
3684
3685 /**
3686 * Default options in bar charts. Expand the code view to see a detailed list of options with comments.
3687 *
3688 * @memberof Chartist.Bar
3689 */
3690 var defaultOptions = {
3691 // Options for X-Axis
3692 axisX: {
3693 // The offset of the chart drawing area to the border of the container
3694 offset: 30,
3695 // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
3696 position: 'end',
3697 // Allows you to correct label positioning on this axis by positive or negative x and y offset.
3698 labelOffset: {
3699 x: 0,
3700 y: 0
3701 },
3702 // If labels should be shown or not
3703 showLabel: true,
3704 // If the axis grid should be drawn or not
3705 showGrid: true,
3706 // Interpolation function that allows you to intercept the value from the axis label
3707 labelInterpolationFnc: Chartist.noop,
3708 // This value specifies the minimum width in pixel of the scale steps
3709 scaleMinSpace: 30,
3710 // Use only integer values (whole numbers) for the scale steps
3711 onlyInteger: false
3712 },
3713 // Options for Y-Axis
3714 axisY: {
3715 // The offset of the chart drawing area to the border of the container
3716 offset: 40,
3717 // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis.
3718 position: 'start',
3719 // Allows you to correct label positioning on this axis by positive or negative x and y offset.
3720 labelOffset: {
3721 x: 0,
3722 y: 0
3723 },
3724 // If labels should be shown or not
3725 showLabel: true,
3726 // If the axis grid should be drawn or not
3727 showGrid: true,
3728 // Interpolation function that allows you to intercept the value from the axis label
3729 labelInterpolationFnc: Chartist.noop,
3730 // This value specifies the minimum height in pixel of the scale steps
3731 scaleMinSpace: 20,
3732 // Use only integer values (whole numbers) for the scale steps
3733 onlyInteger: false
3734 },
3735 // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
3736 width: undefined,
3737 // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
3738 height: undefined,
3739 // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
3740 high: undefined,
3741 // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
3742 low: undefined,
3743 // Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale.
3744 referenceValue: 0,
3745 // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
3746 chartPadding: {
3747 top: 15,
3748 right: 15,
3749 bottom: 5,
3750 left: 10
3751 },
3752 // Specify the distance in pixel of bars in a group
3753 seriesBarDistance: 15,
3754 // If set to true this property will cause the series bars to be stacked. Check the `stackMode` option for further stacking options.
3755 stackBars: false,
3756 // If set to 'overlap' this property will force the stacked bars to draw from the zero line.
3757 // If set to 'accumulate' this property will form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect.
3758 stackMode: 'accumulate',
3759 // Inverts the axes of the bar chart in order to draw a horizontal bar chart. Be aware that you also need to invert your axis settings as the Y Axis will now display the labels and the X Axis the values.
3760 horizontalBars: false,
3761 // If set to true then each bar will represent a series and the data array is expected to be a one dimensional array of data values rather than a series array of series. This is useful if the bar chart should represent a profile rather than some data over time.
3762 distributeSeries: false,
3763 // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
3764 reverseData: false,
3765 // If the bar chart should add a background fill to the .ct-grids group.
3766 showGridBackground: false,
3767 // Override the class names that get used to generate the SVG structure of the chart
3768 classNames: {
3769 chart: 'ct-chart-bar',
3770 horizontalBars: 'ct-horizontal-bars',
3771 label: 'ct-label',
3772 labelGroup: 'ct-labels',
3773 series: 'ct-series',
3774 bar: 'ct-bar',
3775 grid: 'ct-grid',
3776 gridGroup: 'ct-grids',
3777 gridBackground: 'ct-grid-background',
3778 vertical: 'ct-vertical',
3779 horizontal: 'ct-horizontal',
3780 start: 'ct-start',
3781 end: 'ct-end'
3782 }
3783 };
3784
3785 /**
3786 * Creates a new chart
3787 *
3788 */
3789 function createChart(options) {
3790 var data;
3791 var highLow;
3792
3793 if(options.distributeSeries) {
3794 data = Chartist.normalizeData(this.data, options.reverseData, options.horizontalBars ? 'x' : 'y');
3795 data.normalized.series = data.normalized.series.map(function(value) {
3796 return [value];
3797 });
3798 } else {
3799 data = Chartist.normalizeData(this.data, options.reverseData, options.horizontalBars ? 'x' : 'y');
3800 }
3801
3802 // Create new svg element
3803 this.svg = Chartist.createSvg(
3804 this.container,
3805 options.width,
3806 options.height,
3807 options.classNames.chart + (options.horizontalBars ? ' ' + options.classNames.horizontalBars : '')
3808 );
3809
3810 // Drawing groups in correct order
3811 var gridGroup = this.svg.elem('g').addClass(options.classNames.gridGroup);
3812 var seriesGroup = this.svg.elem('g');
3813 var labelGroup = this.svg.elem('g').addClass(options.classNames.labelGroup);
3814
3815 if(options.stackBars && data.normalized.series.length !== 0) {
3816
3817 // If stacked bars we need to calculate the high low from stacked values from each series
3818 var serialSums = Chartist.serialMap(data.normalized.series, function serialSums() {
3819 return Array.prototype.slice.call(arguments).map(function(value) {
3820 return value;
3821 }).reduce(function(prev, curr) {
3822 return {
3823 x: prev.x + (curr && curr.x) || 0,
3824 y: prev.y + (curr && curr.y) || 0
3825 };
3826 }, {x: 0, y: 0});
3827 });
3828
3829 highLow = Chartist.getHighLow([serialSums], options, options.horizontalBars ? 'x' : 'y');
3830
3831 } else {
3832
3833 highLow = Chartist.getHighLow(data.normalized.series, options, options.horizontalBars ? 'x' : 'y');
3834 }
3835
3836 // Overrides of high / low from settings
3837 highLow.high = +options.high || (options.high === 0 ? 0 : highLow.high);
3838 highLow.low = +options.low || (options.low === 0 ? 0 : highLow.low);
3839
3840 var chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
3841
3842 var valueAxis,
3843 labelAxisTicks,
3844 labelAxis,
3845 axisX,
3846 axisY;
3847
3848 // We need to set step count based on some options combinations
3849 if(options.distributeSeries && options.stackBars) {
3850 // If distributed series are enabled and bars need to be stacked, we'll only have one bar and therefore should
3851 // use only the first label for the step axis
3852 labelAxisTicks = data.normalized.labels.slice(0, 1);
3853 } else {
3854 // If distributed series are enabled but stacked bars aren't, we should use the series labels
3855 // If we are drawing a regular bar chart with two dimensional series data, we just use the labels array
3856 // as the bars are normalized
3857 labelAxisTicks = data.normalized.labels;
3858 }
3859
3860 // Set labelAxis and valueAxis based on the horizontalBars setting. This setting will flip the axes if necessary.
3861 if(options.horizontalBars) {
3862 if(options.axisX.type === undefined) {
3863 valueAxis = axisX = new Chartist.AutoScaleAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
3864 highLow: highLow,
3865 referenceValue: 0
3866 }));
3867 } else {
3868 valueAxis = axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, Chartist.extend({}, options.axisX, {
3869 highLow: highLow,
3870 referenceValue: 0
3871 }));
3872 }
3873
3874 if(options.axisY.type === undefined) {
3875 labelAxis = axisY = new Chartist.StepAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, {
3876 ticks: labelAxisTicks
3877 });
3878 } else {
3879 labelAxis = axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, options.axisY);
3880 }
3881 } else {
3882 if(options.axisX.type === undefined) {
3883 labelAxis = axisX = new Chartist.StepAxis(Chartist.Axis.units.x, data.normalized.series, chartRect, {
3884 ticks: labelAxisTicks
3885 });
3886 } else {
3887 labelAxis = axisX = options.axisX.type.call(Chartist, Chartist.Axis.units.x, data.normalized.series, chartRect, options.axisX);
3888 }
3889
3890 if(options.axisY.type === undefined) {
3891 valueAxis = axisY = new Chartist.AutoScaleAxis(Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
3892 highLow: highLow,
3893 referenceValue: 0
3894 }));
3895 } else {
3896 valueAxis = axisY = options.axisY.type.call(Chartist, Chartist.Axis.units.y, data.normalized.series, chartRect, Chartist.extend({}, options.axisY, {
3897 highLow: highLow,
3898 referenceValue: 0
3899 }));
3900 }
3901 }
3902
3903 // Projected 0 point
3904 var zeroPoint = options.horizontalBars ? (chartRect.x1 + valueAxis.projectValue(0)) : (chartRect.y1 - valueAxis.projectValue(0));
3905 // Used to track the screen coordinates of stacked bars
3906 var stackedBarValues = [];
3907
3908 labelAxis.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
3909 valueAxis.createGridAndLabels(gridGroup, labelGroup, this.supportsForeignObject, options, this.eventEmitter);
3910
3911 if (options.showGridBackground) {
3912 Chartist.createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
3913 }
3914
3915 // Draw the series
3916 data.raw.series.forEach(function(series, seriesIndex) {
3917 // Calculating bi-polar value of index for seriesOffset. For i = 0..4 biPol will be -1.5, -0.5, 0.5, 1.5 etc.
3918 var biPol = seriesIndex - (data.raw.series.length - 1) / 2;
3919 // Half of the period width between vertical grid lines used to position bars
3920 var periodHalfLength;
3921 // Current series SVG element
3922 var seriesElement;
3923
3924 // We need to set periodHalfLength based on some options combinations
3925 if(options.distributeSeries && !options.stackBars) {
3926 // If distributed series are enabled but stacked bars aren't, we need to use the length of the normaizedData array
3927 // which is the series count and divide by 2
3928 periodHalfLength = labelAxis.axisLength / data.normalized.series.length / 2;
3929 } else if(options.distributeSeries && options.stackBars) {
3930 // If distributed series and stacked bars are enabled we'll only get one bar so we should just divide the axis
3931 // length by 2
3932 periodHalfLength = labelAxis.axisLength / 2;
3933 } else {
3934 // On regular bar charts we should just use the series length
3935 periodHalfLength = labelAxis.axisLength / data.normalized.series[seriesIndex].length / 2;
3936 }
3937
3938 // Adding the series group to the series element
3939 seriesElement = seriesGroup.elem('g');
3940
3941 // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
3942 seriesElement.attr({
3943 'ct:series-name': series.name,
3944 'ct:meta': Chartist.serialize(series.meta)
3945 });
3946
3947 // Use series class from series data or if not set generate one
3948 seriesElement.addClass([
3949 options.classNames.series,
3950 (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(seriesIndex))
3951 ].join(' '));
3952
3953 data.normalized.series[seriesIndex].forEach(function(value, valueIndex) {
3954 var projected,
3955 bar,
3956 previousStack,
3957 labelAxisValueIndex;
3958
3959 // We need to set labelAxisValueIndex based on some options combinations
3960 if(options.distributeSeries && !options.stackBars) {
3961 // If distributed series are enabled but stacked bars aren't, we can use the seriesIndex for later projection
3962 // on the step axis for label positioning
3963 labelAxisValueIndex = seriesIndex;
3964 } else if(options.distributeSeries && options.stackBars) {
3965 // If distributed series and stacked bars are enabled, we will only get one bar and therefore always use
3966 // 0 for projection on the label step axis
3967 labelAxisValueIndex = 0;
3968 } else {
3969 // On regular bar charts we just use the value index to project on the label step axis
3970 labelAxisValueIndex = valueIndex;
3971 }
3972
3973 // We need to transform coordinates differently based on the chart layout
3974 if(options.horizontalBars) {
3975 projected = {
3976 x: chartRect.x1 + valueAxis.projectValue(value && value.x ? value.x : 0, valueIndex, data.normalized.series[seriesIndex]),
3977 y: chartRect.y1 - labelAxis.projectValue(value && value.y ? value.y : 0, labelAxisValueIndex, data.normalized.series[seriesIndex])
3978 };
3979 } else {
3980 projected = {
3981 x: chartRect.x1 + labelAxis.projectValue(value && value.x ? value.x : 0, labelAxisValueIndex, data.normalized.series[seriesIndex]),
3982 y: chartRect.y1 - valueAxis.projectValue(value && value.y ? value.y : 0, valueIndex, data.normalized.series[seriesIndex])
3983 }
3984 }
3985
3986 // If the label axis is a step based axis we will offset the bar into the middle of between two steps using
3987 // the periodHalfLength value. Also we do arrange the different series so that they align up to each other using
3988 // the seriesBarDistance. If we don't have a step axis, the bar positions can be chosen freely so we should not
3989 // add any automated positioning.
3990 if(labelAxis instanceof Chartist.StepAxis) {
3991 // Offset to center bar between grid lines, but only if the step axis is not stretched
3992 if(!labelAxis.options.stretch) {
3993 projected[labelAxis.units.pos] += periodHalfLength * (options.horizontalBars ? -1 : 1);
3994 }
3995 // Using bi-polar offset for multiple series if no stacked bars or series distribution is used
3996 projected[labelAxis.units.pos] += (options.stackBars || options.distributeSeries) ? 0 : biPol * options.seriesBarDistance * (options.horizontalBars ? -1 : 1);
3997 }
3998
3999 // Enter value in stacked bar values used to remember previous screen value for stacking up bars
4000 previousStack = stackedBarValues[valueIndex] || zeroPoint;
4001 stackedBarValues[valueIndex] = previousStack - (zeroPoint - projected[labelAxis.counterUnits.pos]);
4002
4003 // Skip if value is undefined
4004 if(value === undefined) {
4005 return;
4006 }
4007
4008 var positions = {};
4009 positions[labelAxis.units.pos + '1'] = projected[labelAxis.units.pos];
4010 positions[labelAxis.units.pos + '2'] = projected[labelAxis.units.pos];
4011
4012 if(options.stackBars && (options.stackMode === 'accumulate' || !options.stackMode)) {
4013 // Stack mode: accumulate (default)
4014 // If bars are stacked we use the stackedBarValues reference and otherwise base all bars off the zero line
4015 // We want backwards compatibility, so the expected fallback without the 'stackMode' option
4016 // to be the original behaviour (accumulate)
4017 positions[labelAxis.counterUnits.pos + '1'] = previousStack;
4018 positions[labelAxis.counterUnits.pos + '2'] = stackedBarValues[valueIndex];
4019 } else {
4020 // Draw from the zero line normally
4021 // This is also the same code for Stack mode: overlap
4022 positions[labelAxis.counterUnits.pos + '1'] = zeroPoint;
4023 positions[labelAxis.counterUnits.pos + '2'] = projected[labelAxis.counterUnits.pos];
4024 }
4025
4026 // Limit x and y so that they are within the chart rect
4027 positions.x1 = Math.min(Math.max(positions.x1, chartRect.x1), chartRect.x2);
4028 positions.x2 = Math.min(Math.max(positions.x2, chartRect.x1), chartRect.x2);
4029 positions.y1 = Math.min(Math.max(positions.y1, chartRect.y2), chartRect.y1);
4030 positions.y2 = Math.min(Math.max(positions.y2, chartRect.y2), chartRect.y1);
4031
4032 var metaData = Chartist.getMetaData(series, valueIndex);
4033
4034 // Create bar element
4035 bar = seriesElement.elem('line', positions, options.classNames.bar).attr({
4036 'ct:value': [value.x, value.y].filter(Chartist.isNumeric).join(','),
4037 'ct:meta': Chartist.serialize(metaData)
4038 });
4039
4040 this.eventEmitter.emit('draw', Chartist.extend({
4041 type: 'bar',
4042 value: value,
4043 index: valueIndex,
4044 meta: metaData,
4045 series: series,
4046 seriesIndex: seriesIndex,
4047 axisX: axisX,
4048 axisY: axisY,
4049 chartRect: chartRect,
4050 group: seriesElement,
4051 element: bar
4052 }, positions));
4053 }.bind(this));
4054 }.bind(this));
4055
4056 this.eventEmitter.emit('created', {
4057 bounds: valueAxis.bounds,
4058 chartRect: chartRect,
4059 axisX: axisX,
4060 axisY: axisY,
4061 svg: this.svg,
4062 options: options
4063 });
4064 }
4065
4066 /**
4067 * This method creates a new bar chart and returns API object that you can use for later changes.
4068 *
4069 * @memberof Chartist.Bar
4070 * @param {String|Node} query A selector query string or directly a DOM element
4071 * @param {Object} data The data object that needs to consist of a labels and a series array
4072 * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
4073 * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
4074 * @return {Object} An object which exposes the API for the created chart
4075 *
4076 * @example
4077 * // Create a simple bar chart
4078 * var data = {
4079 * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
4080 * series: [
4081 * [5, 2, 4, 2, 0]
4082 * ]
4083 * };
4084 *
4085 * // In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object.
4086 * new Chartist.Bar('.ct-chart', data);
4087 *
4088 * @example
4089 * // This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10
4090 * new Chartist.Bar('.ct-chart', {
4091 * labels: [1, 2, 3, 4, 5, 6, 7],
4092 * series: [
4093 * [1, 3, 2, -5, -3, 1, -6],
4094 * [-5, -2, -4, -1, 2, -3, 1]
4095 * ]
4096 * }, {
4097 * seriesBarDistance: 12,
4098 * low: -10,
4099 * high: 10
4100 * });
4101 *
4102 */
4103 function Bar(query, data, options, responsiveOptions) {
4104 Chartist.Bar['super'].constructor.call(this,
4105 query,
4106 data,
4107 defaultOptions,
4108 Chartist.extend({}, defaultOptions, options),
4109 responsiveOptions);
4110 }
4111
4112 // Creating bar chart type in Chartist namespace
4113 Chartist.Bar = Chartist.Base.extend({
4114 constructor: Bar,
4115 createChart: createChart
4116 });
4117
4118 }(this || global, Chartist));
4119 ;/**
4120 * The pie chart module of Chartist that can be used to draw pie, donut or gauge charts
4121 *
4122 * @module Chartist.Pie
4123 */
4124 /* global Chartist */
4125 (function(globalRoot, Chartist) {
4126 'use strict';
4127
4128 var window = globalRoot.window;
4129 var document = globalRoot.document;
4130
4131 /**
4132 * Default options in line charts. Expand the code view to see a detailed list of options with comments.
4133 *
4134 * @memberof Chartist.Pie
4135 */
4136 var defaultOptions = {
4137 // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
4138 width: undefined,
4139 // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
4140 height: undefined,
4141 // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
4142 chartPadding: 5,
4143 // Override the class names that are used to generate the SVG structure of the chart
4144 classNames: {
4145 chartPie: 'ct-chart-pie',
4146 chartDonut: 'ct-chart-donut',
4147 series: 'ct-series',
4148 slicePie: 'ct-slice-pie',
4149 sliceDonut: 'ct-slice-donut',
4150 sliceDonutSolid: 'ct-slice-donut-solid',
4151 label: 'ct-label'
4152 },
4153 // The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise.
4154 startAngle: 0,
4155 // An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts.
4156 total: undefined,
4157 // If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices.
4158 donut: false,
4159 // If specified the donut segments will be drawn as shapes instead of strokes.
4160 donutSolid: false,
4161 // Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future.
4162 // This option can be set as number or string to specify a relative width (i.e. 100 or '30%').
4163 donutWidth: 60,
4164 // If a label should be shown or not
4165 showLabel: true,
4166 // Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center.
4167 labelOffset: 0,
4168 // This option can be set to 'inside', 'outside' or 'center'. Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. The 'center' option only makes sense in conjunction with the 'labelOffset' option.
4169 labelPosition: 'inside',
4170 // An interpolation function for the label value
4171 labelInterpolationFnc: Chartist.noop,
4172 // Label direction can be 'neutral', 'explode' or 'implode'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center.
4173 labelDirection: 'neutral',
4174 // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
4175 reverseData: false,
4176 // If true empty values will be ignored to avoid drawing unncessary slices and labels
4177 ignoreEmptyValues: false
4178 };
4179
4180 /**
4181 * Determines SVG anchor position based on direction and center parameter
4182 *
4183 * @param center
4184 * @param label
4185 * @param direction
4186 * @return {string}
4187 */
4188 function determineAnchorPosition(center, label, direction) {
4189 var toTheRight = label.x > center.x;
4190
4191 if(toTheRight && direction === 'explode' ||
4192 !toTheRight && direction === 'implode') {
4193 return 'start';
4194 } else if(toTheRight && direction === 'implode' ||
4195 !toTheRight && direction === 'explode') {
4196 return 'end';
4197 } else {
4198 return 'middle';
4199 }
4200 }
4201
4202 /**
4203 * Creates the pie chart
4204 *
4205 * @param options
4206 */
4207 function createChart(options) {
4208 var data = Chartist.normalizeData(this.data);
4209 var seriesGroups = [],
4210 labelsGroup,
4211 chartRect,
4212 radius,
4213 labelRadius,
4214 totalDataSum,
4215 startAngle = options.startAngle;
4216
4217 // Create SVG.js draw
4218 this.svg = Chartist.createSvg(this.container, options.width, options.height,options.donut ? options.classNames.chartDonut : options.classNames.chartPie);
4219 // Calculate charting rect
4220 chartRect = Chartist.createChartRect(this.svg, options, defaultOptions.padding);
4221 // Get biggest circle radius possible within chartRect
4222 radius = Math.min(chartRect.width() / 2, chartRect.height() / 2);
4223 // Calculate total of all series to get reference value or use total reference from optional options
4224 totalDataSum = options.total || data.normalized.series.reduce(function(previousValue, currentValue) {
4225 return previousValue + currentValue;
4226 }, 0);
4227
4228 var donutWidth = Chartist.quantity(options.donutWidth);
4229 if (donutWidth.unit === '%') {
4230 donutWidth.value *= radius / 100;
4231 }
4232
4233 // If this is a donut chart we need to adjust our radius to enable strokes to be drawn inside
4234 // Unfortunately this is not possible with the current SVG Spec
4235 // See this proposal for more details: http://lists.w3.org/Archives/Public/www-svg/2003Oct/0000.html
4236 radius -= options.donut && !options.donutSolid ? donutWidth.value / 2 : 0;
4237
4238 // If labelPosition is set to `outside` or a donut chart is drawn then the label position is at the radius,
4239 // if regular pie chart it's half of the radius
4240 if(options.labelPosition === 'outside' || options.donut && !options.donutSolid) {
4241 labelRadius = radius;
4242 } else if(options.labelPosition === 'center') {
4243 // If labelPosition is center we start with 0 and will later wait for the labelOffset
4244 labelRadius = 0;
4245 } else if(options.donutSolid) {
4246 labelRadius = radius - donutWidth.value / 2;
4247 } else {
4248 // Default option is 'inside' where we use half the radius so the label will be placed in the center of the pie
4249 // slice
4250 labelRadius = radius / 2;
4251 }
4252 // Add the offset to the labelRadius where a negative offset means closed to the center of the chart
4253 labelRadius += options.labelOffset;
4254
4255 // Calculate end angle based on total sum and current data value and offset with padding
4256 var center = {
4257 x: chartRect.x1 + chartRect.width() / 2,
4258 y: chartRect.y2 + chartRect.height() / 2
4259 };
4260
4261 // Check if there is only one non-zero value in the series array.
4262 var hasSingleValInSeries = data.raw.series.filter(function(val) {
4263 return val.hasOwnProperty('value') ? val.value !== 0 : val !== 0;
4264 }).length === 1;
4265
4266 // Creating the series groups
4267 data.raw.series.forEach(function(series, index) {
4268 seriesGroups[index] = this.svg.elem('g', null, null);
4269 }.bind(this));
4270 //if we need to show labels we create the label group now
4271 if(options.showLabel) {
4272 labelsGroup = this.svg.elem('g', null, null);
4273 }
4274
4275 // Draw the series
4276 // initialize series groups
4277 data.raw.series.forEach(function(series, index) {
4278 // If current value is zero and we are ignoring empty values then skip to next value
4279 if (data.normalized.series[index] === 0 && options.ignoreEmptyValues) return;
4280
4281 // If the series is an object and contains a name or meta data we add a custom attribute
4282 seriesGroups[index].attr({
4283 'ct:series-name': series.name
4284 });
4285
4286 // Use series class from series data or if not set generate one
4287 seriesGroups[index].addClass([
4288 options.classNames.series,
4289 (series.className || options.classNames.series + '-' + Chartist.alphaNumerate(index))
4290 ].join(' '));
4291
4292 // If the whole dataset is 0 endAngle should be zero. Can't divide by 0.
4293 var endAngle = (totalDataSum > 0 ? startAngle + data.normalized.series[index] / totalDataSum * 360 : 0);
4294
4295 // Use slight offset so there are no transparent hairline issues
4296 var overlappigStartAngle = Math.max(0, startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2));
4297
4298 // If we need to draw the arc for all 360 degrees we need to add a hack where we close the circle
4299 // with Z and use 359.99 degrees
4300 if(endAngle - overlappigStartAngle >= 359.99) {
4301 endAngle = overlappigStartAngle + 359.99;
4302 }
4303
4304 var start = Chartist.polarToCartesian(center.x, center.y, radius, overlappigStartAngle),
4305 end = Chartist.polarToCartesian(center.x, center.y, radius, endAngle);
4306
4307 var innerStart,
4308 innerEnd,
4309 donutSolidRadius;
4310
4311 // Create a new path element for the pie chart. If this isn't a donut chart we should close the path for a correct stroke
4312 var path = new Chartist.Svg.Path(!options.donut || options.donutSolid)
4313 .move(end.x, end.y)
4314 .arc(radius, radius, 0, endAngle - startAngle > 180, 0, start.x, start.y);
4315
4316 // If regular pie chart (no donut) we add a line to the center of the circle for completing the pie
4317 if(!options.donut) {
4318 path.line(center.x, center.y);
4319 } else if (options.donutSolid) {
4320 donutSolidRadius = radius - donutWidth.value;
4321 innerStart = Chartist.polarToCartesian(center.x, center.y, donutSolidRadius, startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2));
4322 innerEnd = Chartist.polarToCartesian(center.x, center.y, donutSolidRadius, endAngle);
4323 path.line(innerStart.x, innerStart.y);
4324 path.arc(donutSolidRadius, donutSolidRadius, 0, endAngle - startAngle > 180, 1, innerEnd.x, innerEnd.y);
4325 }
4326
4327 // Create the SVG path
4328 // If this is a donut chart we add the donut class, otherwise just a regular slice
4329 var pathClassName = options.classNames.slicePie;
4330 if (options.donut) {
4331 pathClassName = options.classNames.sliceDonut;
4332 if (options.donutSolid) {
4333 pathClassName = options.classNames.sliceDonutSolid;
4334 }
4335 }
4336 var pathElement = seriesGroups[index].elem('path', {
4337 d: path.stringify()
4338 }, pathClassName);
4339
4340 // Adding the pie series value to the path
4341 pathElement.attr({
4342 'ct:value': data.normalized.series[index],
4343 'ct:meta': Chartist.serialize(series.meta)
4344 });
4345
4346 // If this is a donut, we add the stroke-width as style attribute
4347 if(options.donut && !options.donutSolid) {
4348 pathElement._node.style.strokeWidth = donutWidth.value + 'px';
4349 }
4350
4351 // Fire off draw event
4352 this.eventEmitter.emit('draw', {
4353 type: 'slice',
4354 value: data.normalized.series[index],
4355 totalDataSum: totalDataSum,
4356 index: index,
4357 meta: series.meta,
4358 series: series,
4359 group: seriesGroups[index],
4360 element: pathElement,
4361 path: path.clone(),
4362 center: center,
4363 radius: radius,
4364 startAngle: startAngle,
4365 endAngle: endAngle
4366 });
4367
4368 // If we need to show labels we need to add the label for this slice now
4369 if(options.showLabel) {
4370 var labelPosition;
4371 if(data.raw.series.length === 1) {
4372 // If we have only 1 series, we can position the label in the center of the pie
4373 labelPosition = {
4374 x: center.x,
4375 y: center.y
4376 };
4377 } else {
4378 // Position at the labelRadius distance from center and between start and end angle
4379 labelPosition = Chartist.polarToCartesian(
4380 center.x,
4381 center.y,
4382 labelRadius,
4383 startAngle + (endAngle - startAngle) / 2
4384 );
4385 }
4386
4387 var rawValue;
4388 if(data.normalized.labels && !Chartist.isFalseyButZero(data.normalized.labels[index])) {
4389 rawValue = data.normalized.labels[index];
4390 } else {
4391 rawValue = data.normalized.series[index];
4392 }
4393
4394 var interpolatedValue = options.labelInterpolationFnc(rawValue, index);
4395
4396 if(interpolatedValue || interpolatedValue === 0) {
4397 var labelElement = labelsGroup.elem('text', {
4398 dx: labelPosition.x,
4399 dy: labelPosition.y,
4400 'text-anchor': determineAnchorPosition(center, labelPosition, options.labelDirection)
4401 }, options.classNames.label).text('' + interpolatedValue);
4402
4403 // Fire off draw event
4404 this.eventEmitter.emit('draw', {
4405 type: 'label',
4406 index: index,
4407 group: labelsGroup,
4408 element: labelElement,
4409 text: '' + interpolatedValue,
4410 x: labelPosition.x,
4411 y: labelPosition.y
4412 });
4413 }
4414 }
4415
4416 // Set next startAngle to current endAngle.
4417 // (except for last slice)
4418 startAngle = endAngle;
4419 }.bind(this));
4420
4421 this.eventEmitter.emit('created', {
4422 chartRect: chartRect,
4423 svg: this.svg,
4424 options: options
4425 });
4426 }
4427
4428 /**
4429 * This method creates a new pie chart and returns an object that can be used to redraw the chart.
4430 *
4431 * @memberof Chartist.Pie
4432 * @param {String|Node} query A selector query string or directly a DOM element
4433 * @param {Object} data The data object in the pie chart needs to have a series property with a one dimensional data array. The values will be normalized against each other and don't necessarily need to be in percentage. The series property can also be an array of value objects that contain a value property and a className property to override the CSS class name for the series group.
4434 * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list.
4435 * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
4436 * @return {Object} An object with a version and an update method to manually redraw the chart
4437 *
4438 * @example
4439 * // Simple pie chart example with four series
4440 * new Chartist.Pie('.ct-chart', {
4441 * series: [10, 2, 4, 3]
4442 * });
4443 *
4444 * @example
4445 * // Drawing a donut chart
4446 * new Chartist.Pie('.ct-chart', {
4447 * series: [10, 2, 4, 3]
4448 * }, {
4449 * donut: true
4450 * });
4451 *
4452 * @example
4453 * // Using donut, startAngle and total to draw a gauge chart
4454 * new Chartist.Pie('.ct-chart', {
4455 * series: [20, 10, 30, 40]
4456 * }, {
4457 * donut: true,
4458 * donutWidth: 20,
4459 * startAngle: 270,
4460 * total: 200
4461 * });
4462 *
4463 * @example
4464 * // Drawing a pie chart with padding and labels that are outside the pie
4465 * new Chartist.Pie('.ct-chart', {
4466 * series: [20, 10, 30, 40]
4467 * }, {
4468 * chartPadding: 30,
4469 * labelOffset: 50,
4470 * labelDirection: 'explode'
4471 * });
4472 *
4473 * @example
4474 * // Overriding the class names for individual series as well as a name and meta data.
4475 * // The name will be written as ct:series-name attribute and the meta data will be serialized and written
4476 * // to a ct:meta attribute.
4477 * new Chartist.Pie('.ct-chart', {
4478 * series: [{
4479 * value: 20,
4480 * name: 'Series 1',
4481 * className: 'my-custom-class-one',
4482 * meta: 'Meta One'
4483 * }, {
4484 * value: 10,
4485 * name: 'Series 2',
4486 * className: 'my-custom-class-two',
4487 * meta: 'Meta Two'
4488 * }, {
4489 * value: 70,
4490 * name: 'Series 3',
4491 * className: 'my-custom-class-three',
4492 * meta: 'Meta Three'
4493 * }]
4494 * });
4495 */
4496 function Pie(query, data, options, responsiveOptions) {
4497 Chartist.Pie['super'].constructor.call(this,
4498 query,
4499 data,
4500 defaultOptions,
4501 Chartist.extend({}, defaultOptions, options),
4502 responsiveOptions);
4503 }
4504
4505 // Creating pie chart type in Chartist namespace
4506 Chartist.Pie = Chartist.Base.extend({
4507 constructor: Pie,
4508 createChart: createChart,
4509 determineAnchorPosition: determineAnchorPosition
4510 });
4511
4512 }(this || global, Chartist));
4513
4514 return Chartist;
4515
4516 }));