chartist 0.11.4 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/LICENSE-WTFPL +5 -5
  2. package/README.md +142 -32
  3. package/dist/axes/AutoScaleAxis.d.ts +12 -0
  4. package/dist/axes/AutoScaleAxis.d.ts.map +1 -0
  5. package/dist/axes/Axis.d.ts +40 -0
  6. package/dist/axes/Axis.d.ts.map +1 -0
  7. package/dist/axes/FixedScaleAxis.d.ts +11 -0
  8. package/dist/axes/FixedScaleAxis.d.ts.map +1 -0
  9. package/dist/axes/StepAxis.d.ts +9 -0
  10. package/dist/axes/StepAxis.d.ts.map +1 -0
  11. package/dist/axes/index.d.ts +6 -0
  12. package/dist/axes/index.d.ts.map +1 -0
  13. package/dist/axes/types.d.ts +5 -0
  14. package/dist/axes/types.d.ts.map +1 -0
  15. package/dist/charts/BarChart/BarChart.d.ts +47 -0
  16. package/dist/charts/BarChart/BarChart.d.ts.map +1 -0
  17. package/dist/charts/BarChart/BarChart.types.d.ts +40 -0
  18. package/dist/charts/BarChart/BarChart.types.d.ts.map +1 -0
  19. package/dist/charts/BarChart/index.d.ts +3 -0
  20. package/dist/charts/BarChart/index.d.ts.map +1 -0
  21. package/dist/charts/BaseChart.d.ts +47 -0
  22. package/dist/charts/BaseChart.d.ts.map +1 -0
  23. package/dist/charts/LineChart/LineChart.d.ts +92 -0
  24. package/dist/charts/LineChart/LineChart.d.ts.map +1 -0
  25. package/dist/charts/LineChart/LineChart.types.d.ts +53 -0
  26. package/dist/charts/LineChart/LineChart.types.d.ts.map +1 -0
  27. package/dist/charts/LineChart/index.d.ts +3 -0
  28. package/dist/charts/LineChart/index.d.ts.map +1 -0
  29. package/dist/charts/PieChart/PieChart.d.ts +83 -0
  30. package/dist/charts/PieChart/PieChart.d.ts.map +1 -0
  31. package/dist/charts/PieChart/PieChart.types.d.ts +53 -0
  32. package/dist/charts/PieChart/PieChart.types.d.ts.map +1 -0
  33. package/dist/charts/PieChart/index.d.ts +3 -0
  34. package/dist/charts/PieChart/index.d.ts.map +1 -0
  35. package/dist/charts/index.d.ts +6 -0
  36. package/dist/charts/index.d.ts.map +1 -0
  37. package/dist/charts/types.d.ts +11 -0
  38. package/dist/charts/types.d.ts.map +1 -0
  39. package/dist/core/constants.d.ts +13 -0
  40. package/dist/core/constants.d.ts.map +1 -0
  41. package/dist/core/creation.d.ts +61 -0
  42. package/dist/core/creation.d.ts.map +1 -0
  43. package/dist/core/data/bounds.d.ts +14 -0
  44. package/dist/core/data/bounds.d.ts.map +1 -0
  45. package/dist/core/data/data.d.ts +23 -0
  46. package/dist/core/data/data.d.ts.map +1 -0
  47. package/dist/core/data/highLow.d.ts +13 -0
  48. package/dist/core/data/highLow.d.ts.map +1 -0
  49. package/dist/core/data/index.d.ts +7 -0
  50. package/dist/core/data/index.d.ts.map +1 -0
  51. package/dist/core/data/normalize.d.ts +11 -0
  52. package/dist/core/data/normalize.d.ts.map +1 -0
  53. package/dist/core/data/segments.d.ts +29 -0
  54. package/dist/core/data/segments.d.ts.map +1 -0
  55. package/dist/core/data/serialize.d.ts +12 -0
  56. package/dist/core/data/serialize.d.ts.map +1 -0
  57. package/dist/core/index.d.ts +8 -0
  58. package/dist/core/index.d.ts.map +1 -0
  59. package/dist/core/lang.d.ts +23 -0
  60. package/dist/core/lang.d.ts.map +1 -0
  61. package/dist/core/math.d.ts +42 -0
  62. package/dist/core/math.d.ts.map +1 -0
  63. package/dist/core/optionsProvider.d.ts +15 -0
  64. package/dist/core/optionsProvider.d.ts.map +1 -0
  65. package/dist/core/types.d.ts +205 -0
  66. package/dist/core/types.d.ts.map +1 -0
  67. package/dist/event/EventEmitter.d.ts +27 -0
  68. package/dist/event/EventEmitter.d.ts.map +1 -0
  69. package/dist/event/index.d.ts +2 -0
  70. package/dist/event/index.d.ts.map +1 -0
  71. package/dist/index.cjs +3557 -0
  72. package/dist/index.cjs.map +1 -0
  73. package/dist/index.css +2 -0
  74. package/dist/index.css.map +1 -0
  75. package/dist/index.d.ts +8 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +3497 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/index.umd.js +2 -0
  80. package/dist/index.umd.js.map +1 -0
  81. package/dist/interpolation/cardinal.d.ts +28 -0
  82. package/dist/interpolation/cardinal.d.ts.map +1 -0
  83. package/dist/interpolation/index.d.ts +6 -0
  84. package/dist/interpolation/index.d.ts.map +1 -0
  85. package/dist/interpolation/monotoneCubic.d.ts +28 -0
  86. package/dist/interpolation/monotoneCubic.d.ts.map +1 -0
  87. package/dist/interpolation/none.d.ts +20 -0
  88. package/dist/interpolation/none.d.ts.map +1 -0
  89. package/dist/interpolation/simple.d.ts +28 -0
  90. package/dist/interpolation/simple.d.ts.map +1 -0
  91. package/dist/interpolation/step.d.ts +24 -0
  92. package/dist/interpolation/step.d.ts.map +1 -0
  93. package/dist/svg/Svg.d.ts +201 -0
  94. package/dist/svg/Svg.d.ts.map +1 -0
  95. package/dist/svg/SvgList.d.ts +31 -0
  96. package/dist/svg/SvgList.d.ts.map +1 -0
  97. package/dist/svg/SvgPath.d.ts +125 -0
  98. package/dist/svg/SvgPath.d.ts.map +1 -0
  99. package/dist/svg/animation.d.ts +37 -0
  100. package/dist/svg/animation.d.ts.map +1 -0
  101. package/dist/svg/index.d.ts +6 -0
  102. package/dist/svg/index.d.ts.map +1 -0
  103. package/dist/svg/types.d.ts +54 -0
  104. package/dist/svg/types.d.ts.map +1 -0
  105. package/dist/utils/extend.d.ts +10 -0
  106. package/dist/utils/extend.d.ts.map +1 -0
  107. package/dist/utils/functional.d.ts +30 -0
  108. package/dist/utils/functional.d.ts.map +1 -0
  109. package/dist/utils/index.d.ts +5 -0
  110. package/dist/utils/index.d.ts.map +1 -0
  111. package/dist/utils/types.d.ts +7 -0
  112. package/dist/utils/types.d.ts.map +1 -0
  113. package/dist/utils/utils.d.ts +27 -0
  114. package/dist/utils/utils.d.ts.map +1 -0
  115. package/package.json +39 -76
  116. package/CHANGELOG.md +0 -232
  117. package/dist/chartist.css +0 -615
  118. package/dist/chartist.css.map +0 -10
  119. package/dist/chartist.js +0 -4516
  120. package/dist/chartist.min.css +0 -1
  121. package/dist/chartist.min.js +0 -10
  122. package/dist/chartist.min.js.map +0 -1
  123. package/dist/scss/chartist.scss +0 -241
  124. package/dist/scss/settings/_chartist-settings.scss +0 -88
package/dist/index.js ADDED
@@ -0,0 +1,3497 @@
1
+ /**
2
+ * This object contains all namespaces used within Chartist.
3
+ */ const namespaces = {
4
+ svg: "http://www.w3.org/2000/svg",
5
+ xmlns: "http://www.w3.org/2000/xmlns/",
6
+ xhtml: "http://www.w3.org/1999/xhtml",
7
+ xlink: "http://www.w3.org/1999/xlink",
8
+ ct: "http://gionkunz.github.com/chartist-js/ct"
9
+ };
10
+ /**
11
+ * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.
12
+ */ const precision = 8;
13
+ /**
14
+ * A map with characters to escape for strings to be safely used as attribute values.
15
+ */ const escapingMap = {
16
+ "&": "&",
17
+ "<": "&lt;",
18
+ ">": "&gt;",
19
+ '"': "&quot;",
20
+ "'": "&#039;"
21
+ };
22
+
23
+ /**
24
+ * Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.
25
+ * @return Returns the passed number value with unit.
26
+ */ function ensureUnit(value, unit) {
27
+ if (typeof value === "number") {
28
+ return value + unit;
29
+ }
30
+ return value;
31
+ }
32
+ /**
33
+ * Converts a number or string to a quantity object.
34
+ * @return Returns an object containing the value as number and the unit as string.
35
+ */ function quantity(input) {
36
+ if (typeof input === "string") {
37
+ const match = /^(\d+)\s*(.*)$/g.exec(input);
38
+ return {
39
+ value: match ? +match[1] : 0,
40
+ unit: (match === null || match === void 0 ? void 0 : match[2]) || undefined
41
+ };
42
+ }
43
+ return {
44
+ value: Number(input)
45
+ };
46
+ }
47
+ /**
48
+ * Generates a-z from a number 0 to 26
49
+ * @param n A number from 0 to 26 that will result in a letter a-z
50
+ * @return A character from a-z based on the input number n
51
+ */ function alphaNumerate(n) {
52
+ // Limit to a-z
53
+ return String.fromCharCode(97 + n % 26);
54
+ }
55
+
56
+ const EPSILON = 2.221e-16;
57
+ /**
58
+ * Calculate the order of magnitude for the chart scale
59
+ * @param value The value Range of the chart
60
+ * @return The order of magnitude
61
+ */ function orderOfMagnitude(value) {
62
+ return Math.floor(Math.log(Math.abs(value)) / Math.LN10);
63
+ }
64
+ /**
65
+ * Project a data length into screen coordinates (pixels)
66
+ * @param axisLength The svg element for the chart
67
+ * @param length Single data value from a series array
68
+ * @param bounds All the values to set the bounds of the chart
69
+ * @return The projected data length in pixels
70
+ */ function projectLength(axisLength, length, bounds) {
71
+ return length / bounds.range * axisLength;
72
+ }
73
+ /**
74
+ * 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.
75
+ * @param value The value that should be rounded with precision
76
+ * @param [digits] The number of digits after decimal used to do the rounding
77
+ * @returns Rounded value
78
+ */ function roundWithPrecision(value, digits) {
79
+ const precision$1 = Math.pow(10, digits || precision);
80
+ return Math.round(value * precision$1) / precision$1;
81
+ }
82
+ /**
83
+ * 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.
84
+ * @param num An integer number where the smallest factor should be searched for
85
+ * @returns The smallest integer factor of the parameter num.
86
+ */ function rho(num) {
87
+ if (num === 1) {
88
+ return num;
89
+ }
90
+ function gcd(p, q) {
91
+ if (p % q === 0) {
92
+ return q;
93
+ } else {
94
+ return gcd(q, p % q);
95
+ }
96
+ }
97
+ function f(x) {
98
+ return x * x + 1;
99
+ }
100
+ let x1 = 2;
101
+ let x2 = 2;
102
+ let divisor;
103
+ if (num % 2 === 0) {
104
+ return 2;
105
+ }
106
+ do {
107
+ x1 = f(x1) % num;
108
+ x2 = f(f(x2)) % num;
109
+ divisor = gcd(Math.abs(x1 - x2), num);
110
+ }while (divisor === 1);
111
+ return divisor;
112
+ }
113
+ /**
114
+ * Calculate cartesian coordinates of polar coordinates
115
+ * @param centerX X-axis coordinates of center point of circle segment
116
+ * @param centerY X-axis coordinates of center point of circle segment
117
+ * @param radius Radius of circle segment
118
+ * @param angleInDegrees Angle of circle segment in degrees
119
+ * @return Coordinates of point on circumference
120
+ */ function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
121
+ const angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
122
+ return {
123
+ x: centerX + radius * Math.cos(angleInRadians),
124
+ y: centerY + radius * Math.sin(angleInRadians)
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Calculate and retrieve all the bounds for the chart and return them in one array
130
+ * @param axisLength The length of the Axis used for
131
+ * @param highLow An object containing a high and low property indicating the value range of the chart.
132
+ * @param scaleMinSpace The minimum projected length a step should result in
133
+ * @param onlyInteger
134
+ * @return All the values to set the bounds of the chart
135
+ */ function getBounds(axisLength, highLow, scaleMinSpace) {
136
+ let onlyInteger = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
137
+ const bounds = {
138
+ high: highLow.high,
139
+ low: highLow.low,
140
+ valueRange: 0,
141
+ oom: 0,
142
+ step: 0,
143
+ min: 0,
144
+ max: 0,
145
+ range: 0,
146
+ numberOfSteps: 0,
147
+ values: []
148
+ };
149
+ bounds.valueRange = bounds.high - bounds.low;
150
+ bounds.oom = orderOfMagnitude(bounds.valueRange);
151
+ bounds.step = Math.pow(10, bounds.oom);
152
+ bounds.min = Math.floor(bounds.low / bounds.step) * bounds.step;
153
+ bounds.max = Math.ceil(bounds.high / bounds.step) * bounds.step;
154
+ bounds.range = bounds.max - bounds.min;
155
+ bounds.numberOfSteps = Math.round(bounds.range / bounds.step);
156
+ // Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
157
+ // If we are already below the scaleMinSpace value we will scale up
158
+ const length = projectLength(axisLength, bounds.step, bounds);
159
+ const scaleUp = length < scaleMinSpace;
160
+ const smallestFactor = onlyInteger ? rho(bounds.range) : 0;
161
+ // First check if we should only use integer steps and if step 1 is still larger than scaleMinSpace so we can use 1
162
+ if (onlyInteger && projectLength(axisLength, 1, bounds) >= scaleMinSpace) {
163
+ bounds.step = 1;
164
+ } else if (onlyInteger && smallestFactor < bounds.step && projectLength(axisLength, smallestFactor, bounds) >= scaleMinSpace) {
165
+ // If step 1 was too small, we can try the smallest factor of range
166
+ // If the smallest factor is smaller than the current bounds.step and the projected length of smallest factor
167
+ // is larger than the scaleMinSpace we should go for it.
168
+ bounds.step = smallestFactor;
169
+ } else {
170
+ // Trying to divide or multiply by 2 and find the best step value
171
+ let optimizationCounter = 0;
172
+ for(;;){
173
+ if (scaleUp && projectLength(axisLength, bounds.step, bounds) <= scaleMinSpace) {
174
+ bounds.step *= 2;
175
+ } else if (!scaleUp && projectLength(axisLength, bounds.step / 2, bounds) >= scaleMinSpace) {
176
+ bounds.step /= 2;
177
+ if (onlyInteger && bounds.step % 1 !== 0) {
178
+ bounds.step *= 2;
179
+ break;
180
+ }
181
+ } else {
182
+ break;
183
+ }
184
+ if (optimizationCounter++ > 1000) {
185
+ throw new Error("Exceeded maximum number of iterations while optimizing scale step!");
186
+ }
187
+ }
188
+ }
189
+ bounds.step = Math.max(bounds.step, EPSILON);
190
+ function safeIncrement(value, increment) {
191
+ // If increment is too small use *= (1+EPSILON) as a simple nextafter
192
+ if (value === (value += increment)) {
193
+ value *= 1 + (increment > 0 ? EPSILON : -EPSILON);
194
+ }
195
+ return value;
196
+ }
197
+ // Narrow min and max based on new step
198
+ let newMin = bounds.min;
199
+ let newMax = bounds.max;
200
+ while(newMin + bounds.step <= bounds.low){
201
+ newMin = safeIncrement(newMin, bounds.step);
202
+ }
203
+ while(newMax - bounds.step >= bounds.high){
204
+ newMax = safeIncrement(newMax, -bounds.step);
205
+ }
206
+ bounds.min = newMin;
207
+ bounds.max = newMax;
208
+ bounds.range = bounds.max - bounds.min;
209
+ const values = [];
210
+ for(let i = bounds.min; i <= bounds.max; i = safeIncrement(i, bounds.step)){
211
+ const value = roundWithPrecision(i);
212
+ if (value !== values[values.length - 1]) {
213
+ values.push(value);
214
+ }
215
+ }
216
+ bounds.values = values;
217
+ return bounds;
218
+ }
219
+
220
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
221
+ function extend() {
222
+ let target = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
223
+ for(var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
224
+ sources[_key - 1] = arguments[_key];
225
+ }
226
+ for(let i = 0; i < sources.length; i++){
227
+ const source = sources[i];
228
+ for(const prop in source){
229
+ const sourceProp = source[prop];
230
+ if (typeof sourceProp === "object" && sourceProp !== null && !(sourceProp instanceof Array)) {
231
+ target[prop] = extend(target[prop], sourceProp);
232
+ } else {
233
+ target[prop] = sourceProp;
234
+ }
235
+ }
236
+ }
237
+ return target;
238
+ }
239
+
240
+ /**
241
+ * Helps to simplify functional style code
242
+ * @param n This exact value will be returned by the noop function
243
+ * @return The same value that was provided to the n parameter
244
+ */ const noop = (n)=>n
245
+ ;
246
+ /**
247
+ * Functional style helper to produce array with given length initialized with undefined values
248
+ */ const times = (length)=>Array.from({
249
+ length
250
+ })
251
+ ;
252
+ /**
253
+ * Sum helper to be used in reduce functions
254
+ */ const sum = (previous, current)=>previous + (current ? current : 0)
255
+ ;
256
+ /**
257
+ * 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).
258
+ *
259
+ * For example:
260
+ * @example
261
+ * ```javascript
262
+ * const data = [[1, 2], [3], []];
263
+ * serialMap(data, cb);
264
+ *
265
+ * // where cb will be called 2 times
266
+ * // 1. call arguments: (1, 3, undefined)
267
+ * // 2. call arguments: (2, undefined, undefined)
268
+ * ```
269
+ */ const serialMap = (array, callback)=>times(Math.max(...array.map((element)=>element.length
270
+ ))).map((_inner, index)=>callback(...array.map((element)=>element[index]
271
+ ))
272
+ )
273
+ ;
274
+
275
+ function safeHasProperty(target, property) {
276
+ return target !== null && typeof target === "object" && Reflect.has(target, property);
277
+ }
278
+ function isNumeric(value) {
279
+ return value !== null && isFinite(value);
280
+ }
281
+ /**
282
+ * Returns true on all falsey values except the numeric value 0.
283
+ */ function isFalseyButZero(value) {
284
+ return !value && value !== 0;
285
+ }
286
+ function getNumberOrUndefined(value) {
287
+ return isNumeric(value) ? Number(value) : undefined;
288
+ }
289
+ /**
290
+ * Checks if value is array of arrays or not.
291
+ */ function isArrayOfArrays(data) {
292
+ if (!Array.isArray(data)) {
293
+ return false;
294
+ }
295
+ return data.every(Array.isArray);
296
+ }
297
+
298
+ /**
299
+ * Get meta data of a specific value in a series.
300
+ */ function getMetaData(seriesData, index) {
301
+ const value = Array.isArray(seriesData) ? seriesData[index] : safeHasProperty(seriesData, "data") ? seriesData.data[index] : null;
302
+ return safeHasProperty(value, "meta") ? value.meta : undefined;
303
+ }
304
+ function isDataHoleValue(value) {
305
+ return value === null || value === undefined || typeof value === "number" && isNaN(value);
306
+ }
307
+ /**
308
+ * Checks if value is array of series objects.
309
+ */ function isArrayOfSeries(value) {
310
+ return Array.isArray(value) && value.every((_)=>Array.isArray(_) || safeHasProperty(_, "data")
311
+ );
312
+ }
313
+ /**
314
+ * Checks if provided value object is multi value (contains x or y properties)
315
+ */ function isMultiValue(value) {
316
+ return typeof value === "object" && value !== null && (Reflect.has(value, "x") || Reflect.has(value, "y"));
317
+ }
318
+ /**
319
+ * 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`.
320
+ */ function getMultiValue(value) {
321
+ let dimension = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "y";
322
+ if (isMultiValue(value) && safeHasProperty(value, dimension)) {
323
+ return getNumberOrUndefined(value[dimension]);
324
+ } else {
325
+ return getNumberOrUndefined(value);
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
331
+ * @param data The array that contains the data to be visualized in the chart
332
+ * @param options The Object that contains the chart options
333
+ * @param dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration
334
+ * @return An object that contains the highest and lowest value that will be visualized on the chart.
335
+ */ function getHighLow(data, options, dimension) {
336
+ // TODO: Remove workaround for deprecated global high / low config. Axis high / low configuration is preferred
337
+ options = {
338
+ ...options,
339
+ ...dimension ? dimension === "x" ? options.axisX : options.axisY : {}
340
+ };
341
+ const highLow = {
342
+ high: options.high === undefined ? -Number.MAX_VALUE : +options.high,
343
+ low: options.low === undefined ? Number.MAX_VALUE : +options.low
344
+ };
345
+ const findHigh = options.high === undefined;
346
+ const findLow = options.low === undefined;
347
+ // Function to recursively walk through arrays and find highest and lowest number
348
+ function recursiveHighLow(sourceData) {
349
+ if (isDataHoleValue(sourceData)) {
350
+ return;
351
+ } else if (Array.isArray(sourceData)) {
352
+ for(let i = 0; i < sourceData.length; i++){
353
+ recursiveHighLow(sourceData[i]);
354
+ }
355
+ } else {
356
+ const value = Number(dimension && safeHasProperty(sourceData, dimension) ? sourceData[dimension] : sourceData);
357
+ if (findHigh && value > highLow.high) {
358
+ highLow.high = value;
359
+ }
360
+ if (findLow && value < highLow.low) {
361
+ highLow.low = value;
362
+ }
363
+ }
364
+ }
365
+ // Start to find highest and lowest number recursively
366
+ if (findHigh || findLow) {
367
+ recursiveHighLow(data);
368
+ }
369
+ // Overrides of high / low based on reference value, it will make sure that the invisible reference value is
370
+ // used to generate the chart. This is useful when the chart always needs to contain the position of the
371
+ // invisible reference value in the view i.e. for bipolar scales.
372
+ if (options.referenceValue || options.referenceValue === 0) {
373
+ highLow.high = Math.max(options.referenceValue, highLow.high);
374
+ highLow.low = Math.min(options.referenceValue, highLow.low);
375
+ }
376
+ // If high and low are the same because of misconfiguration or flat data (only the same value) we need
377
+ // to set the high or low to 0 depending on the polarity
378
+ if (highLow.high <= highLow.low) {
379
+ // If both values are 0 we set high to 1
380
+ if (highLow.low === 0) {
381
+ highLow.high = 1;
382
+ } else if (highLow.low < 0) {
383
+ // If we have the same negative value for the bounds we set bounds.high to 0
384
+ highLow.high = 0;
385
+ } else if (highLow.high > 0) {
386
+ // If we have the same positive value for the bounds we set bounds.low to 0
387
+ highLow.low = 0;
388
+ } else {
389
+ // If data array was empty, values are Number.MAX_VALUE and -Number.MAX_VALUE. Set bounds to prevent errors
390
+ highLow.high = 1;
391
+ highLow.low = 0;
392
+ }
393
+ }
394
+ return highLow;
395
+ }
396
+
397
+ function normalizeData(data) {
398
+ let reverse = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false, multi = arguments.length > 2 ? arguments[2] : void 0, distributed = arguments.length > 3 ? arguments[3] : void 0;
399
+ let labelCount;
400
+ const normalized = {
401
+ labels: [],
402
+ series: normalizeSeries(data.series, multi, distributed)
403
+ };
404
+ // If all elements of the normalized data array are arrays we're dealing with
405
+ // multi series data and we need to find the largest series if they are un-even
406
+ if (isArrayOfArrays(normalized.series)) {
407
+ // Getting the series with the the most elements
408
+ labelCount = Math.max(...normalized.series.map((series)=>series.length
409
+ ));
410
+ } else {
411
+ // We're dealing with Pie data so we just take the normalized array length
412
+ labelCount = normalized.series.length;
413
+ }
414
+ normalized.labels = (data.labels || []).slice();
415
+ // Padding the labels to labelCount with empty strings
416
+ normalized.labels.push(...times(Math.max(0, labelCount - normalized.labels.length)).map(()=>""
417
+ ));
418
+ if (reverse) {
419
+ reverseData(normalized);
420
+ }
421
+ return normalized;
422
+ }
423
+ /**
424
+ * Reverses the series, labels and series data arrays.
425
+ */ function reverseData(data) {
426
+ var ref;
427
+ (ref = data.labels) === null || ref === void 0 ? void 0 : ref.reverse();
428
+ data.series.reverse();
429
+ for (const series of data.series){
430
+ if (safeHasProperty(series, "data")) {
431
+ series.data.reverse();
432
+ } else if (Array.isArray(series)) {
433
+ series.reverse();
434
+ }
435
+ }
436
+ }
437
+ function normalizeMulti(value, multi) {
438
+ // We need to prepare multi value output (x and y data)
439
+ let x;
440
+ let y;
441
+ // Single series value arrays are assumed to specify the Y-Axis value
442
+ // For example: [1, 2] => [{x: undefined, y: 1}, {x: undefined, y: 2}]
443
+ // If multi is a string then it's assumed that it specified which dimension should be filled as default
444
+ if (typeof value !== "object") {
445
+ const num = getNumberOrUndefined(value);
446
+ if (multi === "x") {
447
+ x = num;
448
+ } else {
449
+ y = num;
450
+ }
451
+ } else {
452
+ if (safeHasProperty(value, "x")) {
453
+ x = getNumberOrUndefined(value.x);
454
+ }
455
+ if (safeHasProperty(value, "y")) {
456
+ y = getNumberOrUndefined(value.y);
457
+ }
458
+ }
459
+ if (x === undefined && y === undefined) {
460
+ return undefined;
461
+ }
462
+ return {
463
+ x,
464
+ y
465
+ };
466
+ }
467
+ function normalizePrimitive(value, multi) {
468
+ if (isDataHoleValue(value)) {
469
+ // We're dealing with a hole in the data and therefore need to return undefined
470
+ // We're also returning undefined for multi value output
471
+ return undefined;
472
+ }
473
+ if (multi) {
474
+ return normalizeMulti(value, multi);
475
+ }
476
+ return getNumberOrUndefined(value);
477
+ }
478
+ function normalizeSingleSeries(series, multi) {
479
+ if (!Array.isArray(series)) {
480
+ // We are dealing with series object notation so we need to recurse on data property
481
+ return normalizeSingleSeries(series.data, multi);
482
+ }
483
+ return series.map((value)=>{
484
+ if (safeHasProperty(value, "value")) {
485
+ // We are dealing with value object notation so we need to recurse on value property
486
+ return normalizePrimitive(value.value, multi);
487
+ }
488
+ return normalizePrimitive(value, multi);
489
+ });
490
+ }
491
+ function normalizeSeries(series, multi, distributed) {
492
+ if (isArrayOfSeries(series)) {
493
+ return series.map((_)=>normalizeSingleSeries(_, multi)
494
+ );
495
+ }
496
+ const normalizedSeries = normalizeSingleSeries(series, multi);
497
+ if (distributed) {
498
+ return normalizedSeries.map((value)=>[
499
+ value
500
+ ]
501
+ );
502
+ }
503
+ return normalizedSeries;
504
+ }
505
+
506
+ /**
507
+ * Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates
508
+ * valueData property describing the segment.
509
+ *
510
+ * With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any
511
+ * points with undefined values are discarded.
512
+ *
513
+ * **Options**
514
+ * The following options are used to determine how segments are formed
515
+ * ```javascript
516
+ * var options = {
517
+ * // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment.
518
+ * fillHoles: false,
519
+ * // If increasingX is true, the coordinates in all segments have strictly increasing x-values.
520
+ * increasingX: false
521
+ * };
522
+ * ```
523
+ *
524
+ * @param pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn]
525
+ * @param valueData List of associated point values in the form [v1, v2 .. vn]
526
+ * @param options Options set by user
527
+ * @return List of segments, each containing a pathCoordinates and valueData property.
528
+ */ function splitIntoSegments(pathCoordinates, valueData, options) {
529
+ const finalOptions = {
530
+ increasingX: false,
531
+ fillHoles: false,
532
+ ...options
533
+ };
534
+ const segments = [];
535
+ let hole = true;
536
+ for(let i = 0; i < pathCoordinates.length; i += 2){
537
+ // If this value is a "hole" we set the hole flag
538
+ if (getMultiValue(valueData[i / 2].value) === undefined) {
539
+ // if(valueData[i / 2].value === undefined) {
540
+ if (!finalOptions.fillHoles) {
541
+ hole = true;
542
+ }
543
+ } else {
544
+ if (finalOptions.increasingX && i >= 2 && pathCoordinates[i] <= pathCoordinates[i - 2]) {
545
+ // X is not increasing, so we need to make sure we start a new segment
546
+ hole = true;
547
+ }
548
+ // If it's a valid value we need to check if we're coming out of a hole and create a new empty segment
549
+ if (hole) {
550
+ segments.push({
551
+ pathCoordinates: [],
552
+ valueData: []
553
+ });
554
+ // As we have a valid value now, we are not in a "hole" anymore
555
+ hole = false;
556
+ }
557
+ // Add to the segment pathCoordinates and valueData
558
+ segments[segments.length - 1].pathCoordinates.push(pathCoordinates[i], pathCoordinates[i + 1]);
559
+ segments[segments.length - 1].valueData.push(valueData[i / 2]);
560
+ }
561
+ }
562
+ return segments;
563
+ }
564
+
565
+ function serialize(data) {
566
+ let serialized = "";
567
+ if (data === null || data === undefined) {
568
+ return data;
569
+ } else if (typeof data === "number") {
570
+ serialized = "" + data;
571
+ } else if (typeof data === "object") {
572
+ serialized = JSON.stringify({
573
+ data: data
574
+ });
575
+ } else {
576
+ serialized = String(data);
577
+ }
578
+ return Object.keys(escapingMap).reduce((result, key)=>result.replaceAll(key, escapingMap[key])
579
+ , serialized);
580
+ }
581
+ function deserialize(data) {
582
+ if (typeof data !== "string") {
583
+ return data;
584
+ }
585
+ if (data === "NaN") {
586
+ return NaN;
587
+ }
588
+ data = Object.keys(escapingMap).reduce((result, key)=>result.replaceAll(escapingMap[key], key)
589
+ , data);
590
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
591
+ let parsedData = data;
592
+ if (typeof data === "string") {
593
+ try {
594
+ parsedData = JSON.parse(data);
595
+ parsedData = parsedData.data !== undefined ? parsedData.data : parsedData;
596
+ } catch (e) {
597
+ /* Ingore */ }
598
+ }
599
+ return parsedData;
600
+ }
601
+
602
+ /**
603
+ * This helper class is to wrap multiple `Svg` elements into a list where you can call the `Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Svg` on multiple elements.
604
+ * An instance of this class is also returned by `Svg.querySelectorAll`.
605
+ */ class SvgList {
606
+ call(method, args) {
607
+ this.svgElements.forEach((element)=>Reflect.apply(element[method], element, args)
608
+ );
609
+ return this;
610
+ }
611
+ attr() {
612
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
613
+ args[_key] = arguments[_key];
614
+ }
615
+ return this.call("attr", args);
616
+ }
617
+ elem() {
618
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
619
+ args[_key] = arguments[_key];
620
+ }
621
+ return this.call("elem", args);
622
+ }
623
+ root() {
624
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
625
+ args[_key] = arguments[_key];
626
+ }
627
+ return this.call("root", args);
628
+ }
629
+ getNode() {
630
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
631
+ args[_key] = arguments[_key];
632
+ }
633
+ return this.call("getNode", args);
634
+ }
635
+ foreignObject() {
636
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
637
+ args[_key] = arguments[_key];
638
+ }
639
+ return this.call("foreignObject", args);
640
+ }
641
+ text() {
642
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
643
+ args[_key] = arguments[_key];
644
+ }
645
+ return this.call("text", args);
646
+ }
647
+ empty() {
648
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
649
+ args[_key] = arguments[_key];
650
+ }
651
+ return this.call("empty", args);
652
+ }
653
+ remove() {
654
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
655
+ args[_key] = arguments[_key];
656
+ }
657
+ return this.call("remove", args);
658
+ }
659
+ addClass() {
660
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
661
+ args[_key] = arguments[_key];
662
+ }
663
+ return this.call("addClass", args);
664
+ }
665
+ removeClass() {
666
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
667
+ args[_key] = arguments[_key];
668
+ }
669
+ return this.call("removeClass", args);
670
+ }
671
+ removeAllClasses() {
672
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
673
+ args[_key] = arguments[_key];
674
+ }
675
+ return this.call("removeAllClasses", args);
676
+ }
677
+ animate() {
678
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
679
+ args[_key] = arguments[_key];
680
+ }
681
+ return this.call("animate", args);
682
+ }
683
+ /**
684
+ * @param nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll)
685
+ */ constructor(nodeList){
686
+ this.svgElements = [];
687
+ for(let i = 0; i < nodeList.length; i++){
688
+ this.svgElements.push(new Svg(nodeList[i]));
689
+ }
690
+ }
691
+ }
692
+
693
+ /**
694
+ * This Object contains some standard easing cubic bezier curves.
695
+ * Then can be used with their name in the `Svg.animate`.
696
+ * You can also extend the list and use your own name in the `animate` function.
697
+ * Click the show code button to see the available bezier functions.
698
+ */ const easings = {
699
+ easeInSine: [
700
+ 0.47,
701
+ 0,
702
+ 0.745,
703
+ 0.715
704
+ ],
705
+ easeOutSine: [
706
+ 0.39,
707
+ 0.575,
708
+ 0.565,
709
+ 1
710
+ ],
711
+ easeInOutSine: [
712
+ 0.445,
713
+ 0.05,
714
+ 0.55,
715
+ 0.95
716
+ ],
717
+ easeInQuad: [
718
+ 0.55,
719
+ 0.085,
720
+ 0.68,
721
+ 0.53
722
+ ],
723
+ easeOutQuad: [
724
+ 0.25,
725
+ 0.46,
726
+ 0.45,
727
+ 0.94
728
+ ],
729
+ easeInOutQuad: [
730
+ 0.455,
731
+ 0.03,
732
+ 0.515,
733
+ 0.955
734
+ ],
735
+ easeInCubic: [
736
+ 0.55,
737
+ 0.055,
738
+ 0.675,
739
+ 0.19
740
+ ],
741
+ easeOutCubic: [
742
+ 0.215,
743
+ 0.61,
744
+ 0.355,
745
+ 1
746
+ ],
747
+ easeInOutCubic: [
748
+ 0.645,
749
+ 0.045,
750
+ 0.355,
751
+ 1
752
+ ],
753
+ easeInQuart: [
754
+ 0.895,
755
+ 0.03,
756
+ 0.685,
757
+ 0.22
758
+ ],
759
+ easeOutQuart: [
760
+ 0.165,
761
+ 0.84,
762
+ 0.44,
763
+ 1
764
+ ],
765
+ easeInOutQuart: [
766
+ 0.77,
767
+ 0,
768
+ 0.175,
769
+ 1
770
+ ],
771
+ easeInQuint: [
772
+ 0.755,
773
+ 0.05,
774
+ 0.855,
775
+ 0.06
776
+ ],
777
+ easeOutQuint: [
778
+ 0.23,
779
+ 1,
780
+ 0.32,
781
+ 1
782
+ ],
783
+ easeInOutQuint: [
784
+ 0.86,
785
+ 0,
786
+ 0.07,
787
+ 1
788
+ ],
789
+ easeInExpo: [
790
+ 0.95,
791
+ 0.05,
792
+ 0.795,
793
+ 0.035
794
+ ],
795
+ easeOutExpo: [
796
+ 0.19,
797
+ 1,
798
+ 0.22,
799
+ 1
800
+ ],
801
+ easeInOutExpo: [
802
+ 1,
803
+ 0,
804
+ 0,
805
+ 1
806
+ ],
807
+ easeInCirc: [
808
+ 0.6,
809
+ 0.04,
810
+ 0.98,
811
+ 0.335
812
+ ],
813
+ easeOutCirc: [
814
+ 0.075,
815
+ 0.82,
816
+ 0.165,
817
+ 1
818
+ ],
819
+ easeInOutCirc: [
820
+ 0.785,
821
+ 0.135,
822
+ 0.15,
823
+ 0.86
824
+ ],
825
+ easeInBack: [
826
+ 0.6,
827
+ -0.28,
828
+ 0.735,
829
+ 0.045
830
+ ],
831
+ easeOutBack: [
832
+ 0.175,
833
+ 0.885,
834
+ 0.32,
835
+ 1.275
836
+ ],
837
+ easeInOutBack: [
838
+ 0.68,
839
+ -0.55,
840
+ 0.265,
841
+ 1.55
842
+ ]
843
+ };
844
+ function createAnimation(element, attribute, animationDefinition) {
845
+ let createGuided = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false, eventEmitter = arguments.length > 4 ? arguments[4] : void 0;
846
+ const { easing , ...def } = animationDefinition;
847
+ const attributeProperties = {};
848
+ let animationEasing;
849
+ let timeout;
850
+ // Check if an easing is specified in the definition object and delete it from the object as it will not
851
+ // be part of the animate element attributes.
852
+ if (easing) {
853
+ // If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object
854
+ animationEasing = Array.isArray(easing) ? easing : easings[easing];
855
+ }
856
+ // If numeric dur or begin was provided we assume milli seconds
857
+ def.begin = ensureUnit(def.begin, "ms");
858
+ def.dur = ensureUnit(def.dur, "ms");
859
+ if (animationEasing) {
860
+ def.calcMode = "spline";
861
+ def.keySplines = animationEasing.join(" ");
862
+ def.keyTimes = "0;1";
863
+ }
864
+ // Adding "fill: freeze" if we are in guided mode and set initial attribute values
865
+ if (createGuided) {
866
+ def.fill = "freeze";
867
+ // Animated property on our element should already be set to the animation from value in guided mode
868
+ attributeProperties[attribute] = def.from;
869
+ element.attr(attributeProperties);
870
+ // In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin
871
+ // which needs to be in ms aside
872
+ timeout = quantity(def.begin || 0).value;
873
+ def.begin = "indefinite";
874
+ }
875
+ const animate = element.elem("animate", {
876
+ attributeName: attribute,
877
+ ...def
878
+ });
879
+ if (createGuided) {
880
+ // If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout
881
+ setTimeout(()=>{
882
+ // If beginElement fails we set the animated attribute to the end position and remove the animate element
883
+ // This happens if the SMIL ElementTimeControl interface is not supported or any other problems occurred in
884
+ // the browser. (Currently FF 34 does not support animate elements in foreignObjects)
885
+ try {
886
+ // @ts-expect-error Try legacy API.
887
+ animate._node.beginElement();
888
+ } catch (err) {
889
+ // Set animated attribute to current animated value
890
+ attributeProperties[attribute] = def.to;
891
+ element.attr(attributeProperties);
892
+ // Remove the animate element as it's no longer required
893
+ animate.remove();
894
+ }
895
+ }, timeout);
896
+ }
897
+ const animateNode = animate.getNode();
898
+ if (eventEmitter) {
899
+ animateNode.addEventListener("beginEvent", ()=>eventEmitter.emit("animationBegin", {
900
+ element: element,
901
+ animate: animateNode,
902
+ params: animationDefinition
903
+ })
904
+ );
905
+ }
906
+ animateNode.addEventListener("endEvent", ()=>{
907
+ if (eventEmitter) {
908
+ eventEmitter.emit("animationEnd", {
909
+ element: element,
910
+ animate: animateNode,
911
+ params: animationDefinition
912
+ });
913
+ }
914
+ if (createGuided) {
915
+ // Set animated attribute to current animated value
916
+ attributeProperties[attribute] = def.to;
917
+ element.attr(attributeProperties);
918
+ // Remove the animate element as it's no longer required
919
+ animate.remove();
920
+ }
921
+ });
922
+ }
923
+
924
+ /**
925
+ * Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them.
926
+ */ class Svg {
927
+ attr(attributes, ns) {
928
+ if (typeof attributes === "string") {
929
+ if (ns) {
930
+ return this._node.getAttributeNS(ns, attributes);
931
+ } else {
932
+ return this._node.getAttribute(attributes);
933
+ }
934
+ }
935
+ Object.keys(attributes).forEach((key)=>{
936
+ // If the attribute value is undefined we can skip this one
937
+ if (attributes[key] === undefined) {
938
+ return;
939
+ }
940
+ if (key.indexOf(":") !== -1) {
941
+ const namespacedAttribute = key.split(":");
942
+ this._node.setAttributeNS(namespaces[namespacedAttribute[0]], key, String(attributes[key]));
943
+ } else {
944
+ this._node.setAttribute(key, String(attributes[key]));
945
+ }
946
+ });
947
+ return this;
948
+ }
949
+ /**
950
+ * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.
951
+ * @param name The name of the SVG element that should be created as child element of the currently selected element wrapper
952
+ * @param 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.
953
+ * @param className This class or class list will be added to the SVG element
954
+ * @param 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
955
+ * @return Returns a Svg wrapper object that can be used to modify the containing SVG data
956
+ */ elem(name, attributes, className) {
957
+ let insertFirst = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
958
+ return new Svg(name, attributes, className, this, insertFirst);
959
+ }
960
+ /**
961
+ * Returns the parent Chartist.SVG wrapper object
962
+ * @return Returns a 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.
963
+ */ parent() {
964
+ return this._node.parentNode instanceof SVGElement ? new Svg(this._node.parentNode) : null;
965
+ }
966
+ /**
967
+ * This method returns a Svg wrapper around the root SVG element of the current tree.
968
+ * @return The root SVG element wrapped in a Svg element
969
+ */ root() {
970
+ let node = this._node;
971
+ while(node.nodeName !== "svg"){
972
+ if (node.parentElement) {
973
+ node = node.parentElement;
974
+ } else {
975
+ break;
976
+ }
977
+ }
978
+ return new Svg(node);
979
+ }
980
+ /**
981
+ * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Svg wrapper.
982
+ * @param selector A CSS selector that is used to query for child SVG elements
983
+ * @return The SVG wrapper for the element found or null if no element was found
984
+ */ querySelector(selector) {
985
+ const foundNode = this._node.querySelector(selector);
986
+ return foundNode ? new Svg(foundNode) : null;
987
+ }
988
+ /**
989
+ * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Svg.List wrapper.
990
+ * @param selector A CSS selector that is used to query for child SVG elements
991
+ * @return The SVG wrapper list for the element found or null if no element was found
992
+ */ querySelectorAll(selector) {
993
+ const foundNodes = this._node.querySelectorAll(selector);
994
+ return new SvgList(foundNodes);
995
+ }
996
+ /**
997
+ * Returns the underlying SVG node for the current element.
998
+ */ getNode() {
999
+ return this._node;
1000
+ }
1001
+ /**
1002
+ * 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.
1003
+ * @param 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
1004
+ * @param 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.
1005
+ * @param className This class or class list will be added to the SVG element
1006
+ * @param insertFirst Specifies if the foreignObject should be inserted as first child
1007
+ * @return New wrapper object that wraps the foreignObject element
1008
+ */ foreignObject(content, attributes, className) {
1009
+ let insertFirst = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false;
1010
+ let contentNode;
1011
+ // If content is string then we convert it to DOM
1012
+ // TODO: Handle case where content is not a string nor a DOM Node
1013
+ if (typeof content === "string") {
1014
+ const container = document.createElement("div");
1015
+ container.innerHTML = content;
1016
+ contentNode = container.firstChild;
1017
+ } else {
1018
+ contentNode = content;
1019
+ }
1020
+ if (contentNode instanceof Element) {
1021
+ // Adding namespace to content element
1022
+ contentNode.setAttribute("xmlns", namespaces.xmlns);
1023
+ }
1024
+ // Creating the foreignObject without required extension attribute (as described here
1025
+ // http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement)
1026
+ const fnObj = this.elem("foreignObject", attributes, className, insertFirst);
1027
+ // Add content to foreignObjectElement
1028
+ fnObj._node.appendChild(contentNode);
1029
+ return fnObj;
1030
+ }
1031
+ /**
1032
+ * This method adds a new text element to the current Svg wrapper.
1033
+ * @param t The text that should be added to the text element that is created
1034
+ * @return The same wrapper object that was used to add the newly created element
1035
+ */ text(t) {
1036
+ this._node.appendChild(document.createTextNode(t));
1037
+ return this;
1038
+ }
1039
+ /**
1040
+ * This method will clear all child nodes of the current wrapper object.
1041
+ * @return The same wrapper object that got emptied
1042
+ */ empty() {
1043
+ while(this._node.firstChild){
1044
+ this._node.removeChild(this._node.firstChild);
1045
+ }
1046
+ return this;
1047
+ }
1048
+ /**
1049
+ * 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.
1050
+ * @return The parent wrapper object of the element that got removed
1051
+ */ remove() {
1052
+ var ref;
1053
+ (ref = this._node.parentNode) === null || ref === void 0 ? void 0 : ref.removeChild(this._node);
1054
+ return this.parent();
1055
+ }
1056
+ /**
1057
+ * This method will replace the element with a new element that can be created outside of the current DOM.
1058
+ * @param newElement The new Svg object that will be used to replace the current wrapper object
1059
+ * @return The wrapper of the new element
1060
+ */ replace(newElement) {
1061
+ var ref;
1062
+ (ref = this._node.parentNode) === null || ref === void 0 ? void 0 : ref.replaceChild(newElement._node, this._node);
1063
+ return newElement;
1064
+ }
1065
+ /**
1066
+ * This method will append an element to the current element as a child.
1067
+ * @param element The Svg element that should be added as a child
1068
+ * @param insertFirst Specifies if the element should be inserted as first child
1069
+ * @return The wrapper of the appended object
1070
+ */ append(element) {
1071
+ let insertFirst = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
1072
+ if (insertFirst && this._node.firstChild) {
1073
+ this._node.insertBefore(element._node, this._node.firstChild);
1074
+ } else {
1075
+ this._node.appendChild(element._node);
1076
+ }
1077
+ return this;
1078
+ }
1079
+ /**
1080
+ * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.
1081
+ * @return A list of classes or an empty array if there are no classes on the current element
1082
+ */ classes() {
1083
+ const classNames = this._node.getAttribute("class");
1084
+ return classNames ? classNames.trim().split(/\s+/) : [];
1085
+ }
1086
+ /**
1087
+ * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.
1088
+ * @param names A white space separated list of class names
1089
+ * @return The wrapper of the current element
1090
+ */ addClass(names) {
1091
+ this._node.setAttribute("class", this.classes().concat(names.trim().split(/\s+/)).filter(function(elem, pos, self) {
1092
+ return self.indexOf(elem) === pos;
1093
+ }).join(" "));
1094
+ return this;
1095
+ }
1096
+ /**
1097
+ * Removes one or a space separated list of classes from the current element.
1098
+ * @param names A white space separated list of class names
1099
+ * @return The wrapper of the current element
1100
+ */ removeClass(names) {
1101
+ const removedClasses = names.trim().split(/\s+/);
1102
+ this._node.setAttribute("class", this.classes().filter((name)=>removedClasses.indexOf(name) === -1
1103
+ ).join(" "));
1104
+ return this;
1105
+ }
1106
+ /**
1107
+ * Removes all classes from the current element.
1108
+ * @return The wrapper of the current element
1109
+ */ removeAllClasses() {
1110
+ this._node.setAttribute("class", "");
1111
+ return this;
1112
+ }
1113
+ /**
1114
+ * Get element height using `getBoundingClientRect`
1115
+ * @return The elements height in pixels
1116
+ */ height() {
1117
+ return this._node.getBoundingClientRect().height;
1118
+ }
1119
+ /**
1120
+ * Get element width using `getBoundingClientRect`
1121
+ * @return The elements width in pixels
1122
+ */ width() {
1123
+ return this._node.getBoundingClientRect().width;
1124
+ }
1125
+ /**
1126
+ * 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 `Svg.Easing` or an array with four numbers specifying a cubic Bézier curve.
1127
+ * **An animations object could look like this:**
1128
+ * ```javascript
1129
+ * element.animate({
1130
+ * opacity: {
1131
+ * dur: 1000,
1132
+ * from: 0,
1133
+ * to: 1
1134
+ * },
1135
+ * x1: {
1136
+ * dur: '1000ms',
1137
+ * from: 100,
1138
+ * to: 200,
1139
+ * easing: 'easeOutQuart'
1140
+ * },
1141
+ * y1: {
1142
+ * dur: '2s',
1143
+ * from: 0,
1144
+ * to: 100
1145
+ * }
1146
+ * });
1147
+ * ```
1148
+ * **Automatic unit conversion**
1149
+ * 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.
1150
+ * **Guided mode**
1151
+ * 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 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.
1152
+ * If guided mode is enabled the following behavior is added:
1153
+ * - Before the animation starts (even when delayed with `begin`) the animated attribute will be set already to the `from` value of the animation
1154
+ * - `begin` is explicitly set to `indefinite` so it can be started manually without relying on document begin time (creation)
1155
+ * - The animate element will be forced to use `fill="freeze"`
1156
+ * - 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.
1157
+ * - After the animation the element attribute value will be set to the `to` value of the animation
1158
+ * - The animate element is deleted from the DOM
1159
+ * @param 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.
1160
+ * @param guided Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated.
1161
+ * @param eventEmitter If specified, this event emitter will be notified when an animation starts or ends.
1162
+ * @return The current element where the animation was added
1163
+ */ animate(animations) {
1164
+ let guided = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true, eventEmitter = arguments.length > 2 ? arguments[2] : void 0;
1165
+ Object.keys(animations).forEach((attribute)=>{
1166
+ const attributeAnimation = animations[attribute];
1167
+ // If current attribute is an array of definition objects we create an animate for each and disable guided mode
1168
+ if (Array.isArray(attributeAnimation)) {
1169
+ attributeAnimation.forEach((animationDefinition)=>createAnimation(this, attribute, animationDefinition, false, eventEmitter)
1170
+ );
1171
+ } else {
1172
+ createAnimation(this, attribute, attributeAnimation, guided, eventEmitter);
1173
+ }
1174
+ });
1175
+ return this;
1176
+ }
1177
+ /**
1178
+ * @param name The name of the SVG element to create or an SVG dom element which should be wrapped into Svg
1179
+ * @param 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.
1180
+ * @param className This class or class list will be added to the SVG element
1181
+ * @param parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child
1182
+ * @param 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
1183
+ */ constructor(name, attributes, className, parent, insertFirst = false){
1184
+ // If Svg is getting called with an SVG element we just return the wrapper
1185
+ if (name instanceof Element) {
1186
+ this._node = name;
1187
+ } else {
1188
+ this._node = document.createElementNS(namespaces.svg, name);
1189
+ // If this is an SVG element created then custom namespace
1190
+ if (name === "svg") {
1191
+ this.attr({
1192
+ "xmlns:ct": namespaces.ct
1193
+ });
1194
+ }
1195
+ }
1196
+ if (attributes) {
1197
+ this.attr(attributes);
1198
+ }
1199
+ if (className) {
1200
+ this.addClass(className);
1201
+ }
1202
+ if (parent) {
1203
+ if (insertFirst && parent._node.firstChild) {
1204
+ parent._node.insertBefore(this._node, parent._node.firstChild);
1205
+ } else {
1206
+ parent._node.appendChild(this._node);
1207
+ }
1208
+ }
1209
+ }
1210
+ }
1211
+ /**
1212
+ * @todo Only there for chartist <1 compatibility. Remove after deprecation warining.
1213
+ * @deprecated Use the animation module export `easings` directly.
1214
+ */ Svg.Easing = easings;
1215
+
1216
+ /**
1217
+ * Create or reinitialize the SVG element for the chart
1218
+ * @param container The containing DOM Node object that will be used to plant the SVG element
1219
+ * @param width Set the width of the SVG element. Default is 100%
1220
+ * @param height Set the height of the SVG element. Default is 100%
1221
+ * @param className Specify a class to be added to the SVG element
1222
+ * @return The created/reinitialized SVG element
1223
+ */ function createSvg(container) {
1224
+ let width = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "100%", height = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "100%", className = arguments.length > 3 ? arguments[3] : void 0;
1225
+ // Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it
1226
+ // Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/
1227
+ Array.from(container.querySelectorAll("svg")).filter((svg)=>svg.getAttributeNS(namespaces.xmlns, "ct")
1228
+ ).forEach((svg)=>container.removeChild(svg)
1229
+ );
1230
+ // Create svg object with width and height or use 100% as default
1231
+ const svg1 = new Svg("svg").attr({
1232
+ width,
1233
+ height
1234
+ }).attr({
1235
+ // TODO: Check better solution (browser support) and remove inline styles due to CSP
1236
+ style: "width: ".concat(width, "; height: ").concat(height, ";")
1237
+ });
1238
+ if (className) {
1239
+ svg1.addClass(className);
1240
+ }
1241
+ // Add the DOM node to our container
1242
+ container.appendChild(svg1.getNode());
1243
+ return svg1;
1244
+ }
1245
+ /**
1246
+ * Converts a number into a padding object.
1247
+ * @param padding
1248
+ * @param fallback This value is used to fill missing values if a incomplete padding object was passed
1249
+ * @returns 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.
1250
+ */ function normalizePadding(padding) {
1251
+ return typeof padding === "number" ? {
1252
+ top: padding,
1253
+ right: padding,
1254
+ bottom: padding,
1255
+ left: padding
1256
+ } : padding === undefined ? {
1257
+ top: 0,
1258
+ right: 0,
1259
+ bottom: 0,
1260
+ left: 0
1261
+ } : {
1262
+ top: typeof padding.top === "number" ? padding.top : 0,
1263
+ right: typeof padding.right === "number" ? padding.right : 0,
1264
+ bottom: typeof padding.bottom === "number" ? padding.bottom : 0,
1265
+ left: typeof padding.left === "number" ? padding.left : 0
1266
+ };
1267
+ }
1268
+ /**
1269
+ * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
1270
+ * @param svg The svg element for the chart
1271
+ * @param options The Object that contains all the optional values for the chart
1272
+ * @return The chart rectangles coordinates inside the svg element plus the rectangles measurements
1273
+ */ function createChartRect(svg, options) {
1274
+ var ref, ref1, ref2, ref3;
1275
+ const hasAxis = Boolean(options.axisX || options.axisY);
1276
+ const yAxisOffset = ((ref = options.axisY) === null || ref === void 0 ? void 0 : ref.offset) || 0;
1277
+ const xAxisOffset = ((ref1 = options.axisX) === null || ref1 === void 0 ? void 0 : ref1.offset) || 0;
1278
+ const yAxisPosition = (ref2 = options.axisY) === null || ref2 === void 0 ? void 0 : ref2.position;
1279
+ const xAxisPosition = (ref3 = options.axisX) === null || ref3 === void 0 ? void 0 : ref3.position;
1280
+ // If width or height results in invalid value (including 0) we fallback to the unitless settings or even 0
1281
+ let width = svg.width() || quantity(options.width).value || 0;
1282
+ let height = svg.height() || quantity(options.height).value || 0;
1283
+ const normalizedPadding = normalizePadding(options.chartPadding);
1284
+ // If settings were to small to cope with offset (legacy) and padding, we'll adjust
1285
+ width = Math.max(width, yAxisOffset + normalizedPadding.left + normalizedPadding.right);
1286
+ height = Math.max(height, xAxisOffset + normalizedPadding.top + normalizedPadding.bottom);
1287
+ const chartRect = {
1288
+ x1: 0,
1289
+ x2: 0,
1290
+ y1: 0,
1291
+ y2: 0,
1292
+ padding: normalizedPadding,
1293
+ width () {
1294
+ return this.x2 - this.x1;
1295
+ },
1296
+ height () {
1297
+ return this.y1 - this.y2;
1298
+ }
1299
+ };
1300
+ if (hasAxis) {
1301
+ if (xAxisPosition === "start") {
1302
+ chartRect.y2 = normalizedPadding.top + xAxisOffset;
1303
+ chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
1304
+ } else {
1305
+ chartRect.y2 = normalizedPadding.top;
1306
+ chartRect.y1 = Math.max(height - normalizedPadding.bottom - xAxisOffset, chartRect.y2 + 1);
1307
+ }
1308
+ if (yAxisPosition === "start") {
1309
+ chartRect.x1 = normalizedPadding.left + yAxisOffset;
1310
+ chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
1311
+ } else {
1312
+ chartRect.x1 = normalizedPadding.left;
1313
+ chartRect.x2 = Math.max(width - normalizedPadding.right - yAxisOffset, chartRect.x1 + 1);
1314
+ }
1315
+ } else {
1316
+ chartRect.x1 = normalizedPadding.left;
1317
+ chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1);
1318
+ chartRect.y2 = normalizedPadding.top;
1319
+ chartRect.y1 = Math.max(height - normalizedPadding.bottom, chartRect.y2 + 1);
1320
+ }
1321
+ return chartRect;
1322
+ }
1323
+ /**
1324
+ * Creates a grid line based on a projected value.
1325
+ */ function createGrid(position, index, axis, offset, length, group, classes, eventEmitter) {
1326
+ const positionalData = {
1327
+ ["".concat(axis.units.pos, "1")]: position,
1328
+ ["".concat(axis.units.pos, "2")]: position,
1329
+ ["".concat(axis.counterUnits.pos, "1")]: offset,
1330
+ ["".concat(axis.counterUnits.pos, "2")]: offset + length
1331
+ };
1332
+ const gridElement = group.elem("line", positionalData, classes.join(" "));
1333
+ // Event for grid draw
1334
+ eventEmitter.emit("draw", {
1335
+ type: "grid",
1336
+ axis,
1337
+ index,
1338
+ group,
1339
+ element: gridElement,
1340
+ ...positionalData
1341
+ });
1342
+ }
1343
+ /**
1344
+ * Creates a grid background rect and emits the draw event.
1345
+ */ function createGridBackground(gridGroup, chartRect, className, eventEmitter) {
1346
+ const gridBackground = gridGroup.elem("rect", {
1347
+ x: chartRect.x1,
1348
+ y: chartRect.y2,
1349
+ width: chartRect.width(),
1350
+ height: chartRect.height()
1351
+ }, className, true);
1352
+ // Event for grid background draw
1353
+ eventEmitter.emit("draw", {
1354
+ type: "gridBackground",
1355
+ group: gridGroup,
1356
+ element: gridBackground
1357
+ });
1358
+ }
1359
+ /**
1360
+ * Creates a label based on a projected value and an axis.
1361
+ */ function createLabel(position, length, index, label, axis, axisOffset, labelOffset, group, classes, eventEmitter) {
1362
+ const positionalData = {
1363
+ [axis.units.pos]: position + labelOffset[axis.units.pos],
1364
+ [axis.counterUnits.pos]: labelOffset[axis.counterUnits.pos],
1365
+ [axis.units.len]: length,
1366
+ [axis.counterUnits.len]: Math.max(0, axisOffset - 10)
1367
+ };
1368
+ // We need to set width and height explicitly to px as span will not expand with width and height being
1369
+ // 100% in all browsers
1370
+ const stepLength = Math.round(positionalData[axis.units.len]);
1371
+ const stepCounterLength = Math.round(positionalData[axis.counterUnits.len]);
1372
+ const content = document.createElement("span");
1373
+ content.className = classes.join(" ");
1374
+ content.style[axis.units.len] = stepLength + "px";
1375
+ content.style[axis.counterUnits.len] = stepCounterLength + "px";
1376
+ content.textContent = String(label);
1377
+ const labelElement = group.foreignObject(content, {
1378
+ style: "overflow: visible;",
1379
+ ...positionalData
1380
+ });
1381
+ eventEmitter.emit("draw", {
1382
+ type: "label",
1383
+ axis,
1384
+ index,
1385
+ group,
1386
+ element: labelElement,
1387
+ text: label,
1388
+ ...positionalData
1389
+ });
1390
+ }
1391
+
1392
+ /**
1393
+ * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
1394
+ * @param options Options set by user
1395
+ * @param responsiveOptions Optional functions to add responsive behavior to chart
1396
+ * @param eventEmitter The event emitter that will be used to emit the options changed events
1397
+ * @return The consolidated options object from the defaults, base and matching responsive options
1398
+ */ function optionsProvider(options, responsiveOptions, eventEmitter) {
1399
+ let currentOptions;
1400
+ const mediaQueryListeners = [];
1401
+ function updateCurrentOptions(mediaEvent) {
1402
+ const previousOptions = currentOptions;
1403
+ currentOptions = extend({}, options);
1404
+ if (responsiveOptions) {
1405
+ responsiveOptions.forEach((responsiveOption)=>{
1406
+ const mql = window.matchMedia(responsiveOption[0]);
1407
+ if (mql.matches) {
1408
+ currentOptions = extend(currentOptions, responsiveOption[1]);
1409
+ }
1410
+ });
1411
+ }
1412
+ if (eventEmitter && mediaEvent) {
1413
+ eventEmitter.emit("optionsChanged", {
1414
+ previousOptions,
1415
+ currentOptions
1416
+ });
1417
+ }
1418
+ }
1419
+ function removeMediaQueryListeners() {
1420
+ mediaQueryListeners.forEach((mql)=>mql.removeEventListener("change", updateCurrentOptions)
1421
+ );
1422
+ }
1423
+ if (!window.matchMedia) {
1424
+ throw new Error("window.matchMedia not found! Make sure you're using a polyfill.");
1425
+ } else if (responsiveOptions) {
1426
+ responsiveOptions.forEach((responsiveOption)=>{
1427
+ const mql = window.matchMedia(responsiveOption[0]);
1428
+ mql.addEventListener("change", updateCurrentOptions);
1429
+ mediaQueryListeners.push(mql);
1430
+ });
1431
+ }
1432
+ // Execute initially without an event argument so we get the correct options
1433
+ updateCurrentOptions();
1434
+ return {
1435
+ removeMediaQueryListeners,
1436
+ getCurrentOptions () {
1437
+ return currentOptions;
1438
+ }
1439
+ };
1440
+ }
1441
+
1442
+ /**
1443
+ * Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported.
1444
+ */ const elementDescriptions = {
1445
+ m: [
1446
+ "x",
1447
+ "y"
1448
+ ],
1449
+ l: [
1450
+ "x",
1451
+ "y"
1452
+ ],
1453
+ c: [
1454
+ "x1",
1455
+ "y1",
1456
+ "x2",
1457
+ "y2",
1458
+ "x",
1459
+ "y"
1460
+ ],
1461
+ a: [
1462
+ "rx",
1463
+ "ry",
1464
+ "xAr",
1465
+ "lAf",
1466
+ "sf",
1467
+ "x",
1468
+ "y"
1469
+ ]
1470
+ };
1471
+ /**
1472
+ * Default options for newly created SVG path objects.
1473
+ */ const defaultOptions$3 = {
1474
+ // 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.
1475
+ accuracy: 3
1476
+ };
1477
+ function element(command, params, pathElements, pos, relative, data) {
1478
+ const pathElement = {
1479
+ command: relative ? command.toLowerCase() : command.toUpperCase(),
1480
+ ...params,
1481
+ ...data ? {
1482
+ data
1483
+ } : {}
1484
+ };
1485
+ pathElements.splice(pos, 0, pathElement);
1486
+ }
1487
+ function forEachParam(pathElements, cb) {
1488
+ pathElements.forEach((pathElement, pathElementIndex)=>{
1489
+ elementDescriptions[pathElement.command.toLowerCase()].forEach((paramName, paramIndex)=>{
1490
+ cb(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
1491
+ });
1492
+ });
1493
+ }
1494
+ class SvgPath {
1495
+ /**
1496
+ * This static function on `SvgPath` is joining multiple paths together into one paths.
1497
+ * @param paths A list of paths to be joined together. The order is important.
1498
+ * @param close If the newly created path should be a closed path
1499
+ * @param options Path options for the newly created path.
1500
+ */ static join(paths) {
1501
+ let close = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false, options = arguments.length > 2 ? arguments[2] : void 0;
1502
+ const joinedPath = new SvgPath(close, options);
1503
+ for(let i = 0; i < paths.length; i++){
1504
+ const path = paths[i];
1505
+ for(let j = 0; j < path.pathElements.length; j++){
1506
+ joinedPath.pathElements.push(path.pathElements[j]);
1507
+ }
1508
+ }
1509
+ return joinedPath;
1510
+ }
1511
+ position(pos) {
1512
+ if (pos !== undefined) {
1513
+ this.pos = Math.max(0, Math.min(this.pathElements.length, pos));
1514
+ return this;
1515
+ } else {
1516
+ return this.pos;
1517
+ }
1518
+ }
1519
+ /**
1520
+ * Removes elements from the path starting at the current position.
1521
+ * @param count Number of path elements that should be removed from the current position.
1522
+ * @return The current path object for easy call chaining.
1523
+ */ remove(count) {
1524
+ this.pathElements.splice(this.pos, count);
1525
+ return this;
1526
+ }
1527
+ /**
1528
+ * Use this function to add a new move SVG path element.
1529
+ * @param x The x coordinate for the move element.
1530
+ * @param y The y coordinate for the move element.
1531
+ * @param relative If set to true the move element will be created with relative coordinates (lowercase letter)
1532
+ * @param data Any data that should be stored with the element object that will be accessible in pathElement
1533
+ * @return The current path object for easy call chaining.
1534
+ */ move(x, y) {
1535
+ let relative = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false, data = arguments.length > 3 ? arguments[3] : void 0;
1536
+ element("M", {
1537
+ x: +x,
1538
+ y: +y
1539
+ }, this.pathElements, this.pos++, relative, data);
1540
+ return this;
1541
+ }
1542
+ /**
1543
+ * Use this function to add a new line SVG path element.
1544
+ * @param x The x coordinate for the line element.
1545
+ * @param y The y coordinate for the line element.
1546
+ * @param relative If set to true the line element will be created with relative coordinates (lowercase letter)
1547
+ * @param data Any data that should be stored with the element object that will be accessible in pathElement
1548
+ * @return The current path object for easy call chaining.
1549
+ */ line(x, y) {
1550
+ let relative = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false, data = arguments.length > 3 ? arguments[3] : void 0;
1551
+ element("L", {
1552
+ x: +x,
1553
+ y: +y
1554
+ }, this.pathElements, this.pos++, relative, data);
1555
+ return this;
1556
+ }
1557
+ /**
1558
+ * Use this function to add a new curve SVG path element.
1559
+ * @param x1 The x coordinate for the first control point of the bezier curve.
1560
+ * @param y1 The y coordinate for the first control point of the bezier curve.
1561
+ * @param x2 The x coordinate for the second control point of the bezier curve.
1562
+ * @param y2 The y coordinate for the second control point of the bezier curve.
1563
+ * @param x The x coordinate for the target point of the curve element.
1564
+ * @param y The y coordinate for the target point of the curve element.
1565
+ * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter)
1566
+ * @param data Any data that should be stored with the element object that will be accessible in pathElement
1567
+ * @return The current path object for easy call chaining.
1568
+ */ curve(x1, y1, x2, y2, x, y) {
1569
+ let relative = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : false, data = arguments.length > 7 ? arguments[7] : void 0;
1570
+ element("C", {
1571
+ x1: +x1,
1572
+ y1: +y1,
1573
+ x2: +x2,
1574
+ y2: +y2,
1575
+ x: +x,
1576
+ y: +y
1577
+ }, this.pathElements, this.pos++, relative, data);
1578
+ return this;
1579
+ }
1580
+ /**
1581
+ * Use this function to add a new non-bezier curve SVG path element.
1582
+ * @param rx The radius to be used for the x-axis of the arc.
1583
+ * @param ry The radius to be used for the y-axis of the arc.
1584
+ * @param xAr Defines the orientation of the arc
1585
+ * @param lAf Large arc flag
1586
+ * @param sf Sweep flag
1587
+ * @param x The x coordinate for the target point of the curve element.
1588
+ * @param y The y coordinate for the target point of the curve element.
1589
+ * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter)
1590
+ * @param data Any data that should be stored with the element object that will be accessible in pathElement
1591
+ * @return The current path object for easy call chaining.
1592
+ */ arc(rx, ry, xAr, lAf, sf, x, y) {
1593
+ let relative = arguments.length > 7 && arguments[7] !== void 0 ? arguments[7] : false, data = arguments.length > 8 ? arguments[8] : void 0;
1594
+ element("A", {
1595
+ rx,
1596
+ ry,
1597
+ xAr,
1598
+ lAf,
1599
+ sf,
1600
+ x,
1601
+ y
1602
+ }, this.pathElements, this.pos++, relative, data);
1603
+ return this;
1604
+ }
1605
+ /**
1606
+ * 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.
1607
+ * @param path Any SVG path that contains move (m), line (l) or curve (c) components.
1608
+ * @return The current path object for easy call chaining.
1609
+ */ parse(path) {
1610
+ // Parsing the SVG path string into an array of arrays [['M', '10', '10'], ['L', '100', '100']]
1611
+ const chunks = path.replace(/([A-Za-z])([0-9])/g, "$1 $2").replace(/([0-9])([A-Za-z])/g, "$1 $2").split(/[\s,]+/).reduce((result, pathElement)=>{
1612
+ if (pathElement.match(/[A-Za-z]/)) {
1613
+ result.push([]);
1614
+ }
1615
+ result[result.length - 1].push(pathElement);
1616
+ return result;
1617
+ }, []);
1618
+ // If this is a closed path we remove the Z at the end because this is determined by the close option
1619
+ if (chunks[chunks.length - 1][0].toUpperCase() === "Z") {
1620
+ chunks.pop();
1621
+ }
1622
+ // Using svgPathElementDescriptions to map raw path arrays into objects that contain the command and the parameters
1623
+ // For example {command: 'M', x: '10', y: '10'}
1624
+ const elements = chunks.map((chunk)=>{
1625
+ const command = chunk.shift();
1626
+ const description = elementDescriptions[command.toLowerCase()];
1627
+ return {
1628
+ command,
1629
+ ...description.reduce((result, paramName, index)=>{
1630
+ result[paramName] = +chunk[index];
1631
+ return result;
1632
+ }, {})
1633
+ };
1634
+ });
1635
+ // Preparing a splice call with the elements array as var arg params and insert the parsed elements at the current position
1636
+ this.pathElements.splice(this.pos, 0, ...elements);
1637
+ // Increase the internal position by the element count
1638
+ this.pos += elements.length;
1639
+ return this;
1640
+ }
1641
+ /**
1642
+ * 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.
1643
+ */ stringify() {
1644
+ const accuracyMultiplier = Math.pow(10, this.options.accuracy);
1645
+ return this.pathElements.reduce((path, pathElement)=>{
1646
+ const params = elementDescriptions[pathElement.command.toLowerCase()].map((paramName)=>{
1647
+ const value = pathElement[paramName];
1648
+ return this.options.accuracy ? Math.round(value * accuracyMultiplier) / accuracyMultiplier : value;
1649
+ });
1650
+ return path + pathElement.command + params.join(",");
1651
+ }, "") + (this.close ? "Z" : "");
1652
+ }
1653
+ /**
1654
+ * 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.
1655
+ * @param x The number which will be used to scale the x, x1 and x2 of all path elements.
1656
+ * @param y The number which will be used to scale the y, y1 and y2 of all path elements.
1657
+ * @return The current path object for easy call chaining.
1658
+ */ scale(x, y) {
1659
+ forEachParam(this.pathElements, (pathElement, paramName)=>{
1660
+ pathElement[paramName] *= paramName[0] === "x" ? x : y;
1661
+ });
1662
+ return this;
1663
+ }
1664
+ /**
1665
+ * 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.
1666
+ * @param x The number which will be used to translate the x, x1 and x2 of all path elements.
1667
+ * @param y The number which will be used to translate the y, y1 and y2 of all path elements.
1668
+ * @return The current path object for easy call chaining.
1669
+ */ translate(x, y) {
1670
+ forEachParam(this.pathElements, (pathElement, paramName)=>{
1671
+ pathElement[paramName] += paramName[0] === "x" ? x : y;
1672
+ });
1673
+ return this;
1674
+ }
1675
+ /**
1676
+ * 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.
1677
+ * The method signature of the callback function looks like this:
1678
+ * ```javascript
1679
+ * function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)
1680
+ * ```
1681
+ * 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.
1682
+ * @param transformFnc The callback function for the transformation. Check the signature in the function description.
1683
+ * @return The current path object for easy call chaining.
1684
+ */ transform(transformFnc) {
1685
+ forEachParam(this.pathElements, (pathElement, paramName, pathElementIndex, paramIndex, pathElements)=>{
1686
+ const transformed = transformFnc(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
1687
+ if (transformed || transformed === 0) {
1688
+ pathElement[paramName] = transformed;
1689
+ }
1690
+ });
1691
+ return this;
1692
+ }
1693
+ /**
1694
+ * This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.
1695
+ * @param close Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used.
1696
+ */ clone() {
1697
+ let close = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
1698
+ const clone = new SvgPath(close || this.close);
1699
+ clone.pos = this.pos;
1700
+ clone.pathElements = this.pathElements.slice().map((pathElement)=>({
1701
+ ...pathElement
1702
+ })
1703
+ );
1704
+ clone.options = {
1705
+ ...this.options
1706
+ };
1707
+ return clone;
1708
+ }
1709
+ /**
1710
+ * 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.
1711
+ * @param command The command you'd like to use to split the path
1712
+ */ splitByCommand(command) {
1713
+ const split = [
1714
+ new SvgPath()
1715
+ ];
1716
+ this.pathElements.forEach((pathElement)=>{
1717
+ if (pathElement.command === command.toUpperCase() && split[split.length - 1].pathElements.length !== 0) {
1718
+ split.push(new SvgPath());
1719
+ }
1720
+ split[split.length - 1].pathElements.push(pathElement);
1721
+ });
1722
+ return split;
1723
+ }
1724
+ /**
1725
+ * Used to construct a new path object.
1726
+ * @param close If set to true then this path will be closed when stringified (with a Z at the end)
1727
+ * @param options Options object that overrides the default objects. See default options for more details.
1728
+ */ constructor(close = false, options){
1729
+ this.close = close;
1730
+ this.pathElements = [];
1731
+ this.pos = 0;
1732
+ this.options = {
1733
+ ...defaultOptions$3,
1734
+ ...options
1735
+ };
1736
+ }
1737
+ }
1738
+
1739
+ /**
1740
+ * This interpolation function does not smooth the path and the result is only containing lines and no curves.
1741
+ *
1742
+ * @example
1743
+ * const chart = new LineChart('.ct-chart', {
1744
+ * labels: [1, 2, 3, 4, 5],
1745
+ * series: [[1, 2, 8, 1, 7]]
1746
+ * }, {
1747
+ * lineSmooth: Interpolation.none({
1748
+ * fillHoles: false
1749
+ * })
1750
+ * });
1751
+ */ function none(options) {
1752
+ const finalOptions = {
1753
+ fillHoles: false,
1754
+ ...options
1755
+ };
1756
+ return function noneInterpolation(pathCoordinates, valueData) {
1757
+ const path = new SvgPath();
1758
+ let hole = true;
1759
+ for(let i = 0; i < pathCoordinates.length; i += 2){
1760
+ const currX = pathCoordinates[i];
1761
+ const currY = pathCoordinates[i + 1];
1762
+ const currData = valueData[i / 2];
1763
+ if (getMultiValue(currData.value) !== undefined) {
1764
+ if (hole) {
1765
+ path.move(currX, currY, false, currData);
1766
+ } else {
1767
+ path.line(currX, currY, false, currData);
1768
+ }
1769
+ hole = false;
1770
+ } else if (!finalOptions.fillHoles) {
1771
+ hole = true;
1772
+ }
1773
+ }
1774
+ return path;
1775
+ };
1776
+ }
1777
+
1778
+ /**
1779
+ * 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.
1780
+ *
1781
+ * 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.
1782
+ *
1783
+ * 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.
1784
+ *
1785
+ * @example
1786
+ * const chart = new LineChart('.ct-chart', {
1787
+ * labels: [1, 2, 3, 4, 5],
1788
+ * series: [[1, 2, 8, 1, 7]]
1789
+ * }, {
1790
+ * lineSmooth: Interpolation.simple({
1791
+ * divisor: 2,
1792
+ * fillHoles: false
1793
+ * })
1794
+ * });
1795
+ *
1796
+ * @param options The options of the simple interpolation factory function.
1797
+ */ function simple(options) {
1798
+ const finalOptions = {
1799
+ divisor: 2,
1800
+ fillHoles: false,
1801
+ ...options
1802
+ };
1803
+ const d = 1 / Math.max(1, finalOptions.divisor);
1804
+ return function simpleInterpolation(pathCoordinates, valueData) {
1805
+ const path = new SvgPath();
1806
+ let prevX = 0;
1807
+ let prevY = 0;
1808
+ let prevData;
1809
+ for(let i = 0; i < pathCoordinates.length; i += 2){
1810
+ const currX = pathCoordinates[i];
1811
+ const currY = pathCoordinates[i + 1];
1812
+ const length = (currX - prevX) * d;
1813
+ const currData = valueData[i / 2];
1814
+ if (currData.value !== undefined) {
1815
+ if (prevData === undefined) {
1816
+ path.move(currX, currY, false, currData);
1817
+ } else {
1818
+ path.curve(prevX + length, prevY, currX - length, currY, currX, currY, false, currData);
1819
+ }
1820
+ prevX = currX;
1821
+ prevY = currY;
1822
+ prevData = currData;
1823
+ } else if (!finalOptions.fillHoles) {
1824
+ prevX = prevY = 0;
1825
+ prevData = undefined;
1826
+ }
1827
+ }
1828
+ return path;
1829
+ };
1830
+ }
1831
+
1832
+ /**
1833
+ * 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.
1834
+ *
1835
+ * 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`.
1836
+ *
1837
+ * @example
1838
+ * var chart = new Chartist.Line('.ct-chart', {
1839
+ * labels: [1, 2, 3, 4, 5],
1840
+ * series: [[1, 2, 8, 1, 7]]
1841
+ * }, {
1842
+ * lineSmooth: Interpolation.step({
1843
+ * postpone: true,
1844
+ * fillHoles: false
1845
+ * })
1846
+ * });
1847
+ */ function step(options) {
1848
+ const finalOptions = {
1849
+ postpone: true,
1850
+ fillHoles: false,
1851
+ ...options
1852
+ };
1853
+ return function stepInterpolation(pathCoordinates, valueData) {
1854
+ const path = new SvgPath();
1855
+ let prevX = 0;
1856
+ let prevY = 0;
1857
+ let prevData;
1858
+ for(let i = 0; i < pathCoordinates.length; i += 2){
1859
+ const currX = pathCoordinates[i];
1860
+ const currY = pathCoordinates[i + 1];
1861
+ const currData = valueData[i / 2];
1862
+ // If the current point is also not a hole we can draw the step lines
1863
+ if (currData.value !== undefined) {
1864
+ if (prevData === undefined) {
1865
+ path.move(currX, currY, false, currData);
1866
+ } else {
1867
+ if (finalOptions.postpone) {
1868
+ // If postponed we should draw the step line with the value of the previous value
1869
+ path.line(currX, prevY, false, prevData);
1870
+ } else {
1871
+ // If not postponed we should draw the step line with the value of the current value
1872
+ path.line(prevX, currY, false, currData);
1873
+ }
1874
+ // Line to the actual point (this should only be a Y-Axis movement
1875
+ path.line(currX, currY, false, currData);
1876
+ }
1877
+ prevX = currX;
1878
+ prevY = currY;
1879
+ prevData = currData;
1880
+ } else if (!finalOptions.fillHoles) {
1881
+ prevX = prevY = 0;
1882
+ prevData = undefined;
1883
+ }
1884
+ }
1885
+ return path;
1886
+ };
1887
+ }
1888
+
1889
+ /**
1890
+ * 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.
1891
+ *
1892
+ * 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`.
1893
+ *
1894
+ * 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.
1895
+ *
1896
+ * @example
1897
+ * const chart = new LineChart('.ct-chart', {
1898
+ * labels: [1, 2, 3, 4, 5],
1899
+ * series: [[1, 2, 8, 1, 7]]
1900
+ * }, {
1901
+ * lineSmooth: Interpolation.cardinal({
1902
+ * tension: 1,
1903
+ * fillHoles: false
1904
+ * })
1905
+ * });
1906
+ *
1907
+ * @param options The options of the cardinal factory function.
1908
+ */ function cardinal(options) {
1909
+ const finalOptions = {
1910
+ tension: 1,
1911
+ fillHoles: false,
1912
+ ...options
1913
+ };
1914
+ const t = Math.min(1, Math.max(0, finalOptions.tension));
1915
+ const c = 1 - t;
1916
+ return function cardinalInterpolation(pathCoordinates, valueData) {
1917
+ // First we try to split the coordinates into segments
1918
+ // This is necessary to treat "holes" in line charts
1919
+ const segments = splitIntoSegments(pathCoordinates, valueData, {
1920
+ fillHoles: finalOptions.fillHoles
1921
+ });
1922
+ if (!segments.length) {
1923
+ // If there were no segments return 'none' interpolation
1924
+ return none()([], []);
1925
+ } else if (segments.length > 1) {
1926
+ // If the split resulted in more that one segment we need to interpolate each segment individually and join them
1927
+ // afterwards together into a single path.
1928
+ // For each segment we will recurse the cardinal function
1929
+ // Join the segment path data into a single path and return
1930
+ return SvgPath.join(segments.map((segment)=>cardinalInterpolation(segment.pathCoordinates, segment.valueData)
1931
+ ));
1932
+ } else {
1933
+ // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
1934
+ // segment
1935
+ pathCoordinates = segments[0].pathCoordinates;
1936
+ valueData = segments[0].valueData;
1937
+ // If less than two points we need to fallback to no smoothing
1938
+ if (pathCoordinates.length <= 4) {
1939
+ return none()(pathCoordinates, valueData);
1940
+ }
1941
+ const path = new SvgPath().move(pathCoordinates[0], pathCoordinates[1], false, valueData[0]);
1942
+ const z = false;
1943
+ for(let i = 0, iLen = pathCoordinates.length; iLen - 2 * Number(!z) > i; i += 2){
1944
+ const p = [
1945
+ {
1946
+ x: +pathCoordinates[i - 2],
1947
+ y: +pathCoordinates[i - 1]
1948
+ },
1949
+ {
1950
+ x: +pathCoordinates[i],
1951
+ y: +pathCoordinates[i + 1]
1952
+ },
1953
+ {
1954
+ x: +pathCoordinates[i + 2],
1955
+ y: +pathCoordinates[i + 3]
1956
+ },
1957
+ {
1958
+ x: +pathCoordinates[i + 4],
1959
+ y: +pathCoordinates[i + 5]
1960
+ }
1961
+ ];
1962
+ {
1963
+ if (iLen - 4 === i) {
1964
+ p[3] = p[2];
1965
+ } else if (!i) {
1966
+ p[0] = {
1967
+ x: +pathCoordinates[i],
1968
+ y: +pathCoordinates[i + 1]
1969
+ };
1970
+ }
1971
+ }
1972
+ path.curve(t * (-p[0].x + 6 * p[1].x + p[2].x) / 6 + c * p[2].x, t * (-p[0].y + 6 * p[1].y + p[2].y) / 6 + c * p[2].y, t * (p[1].x + 6 * p[2].x - p[3].x) / 6 + c * p[2].x, t * (p[1].y + 6 * p[2].y - p[3].y) / 6 + c * p[2].y, p[2].x, p[2].y, false, valueData[(i + 2) / 2]);
1973
+ }
1974
+ return path;
1975
+ }
1976
+ };
1977
+ }
1978
+
1979
+ /**
1980
+ * 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.
1981
+ *
1982
+ * 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`.
1983
+ *
1984
+ * 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.
1985
+ *
1986
+ * All smoothing functions within Chartist are factory functions that accept an options parameter.
1987
+ *
1988
+ * @example
1989
+ * const chart = new LineChart('.ct-chart', {
1990
+ * labels: [1, 2, 3, 4, 5],
1991
+ * series: [[1, 2, 8, 1, 7]]
1992
+ * }, {
1993
+ * lineSmooth: Interpolation.monotoneCubic({
1994
+ * fillHoles: false
1995
+ * })
1996
+ * });
1997
+ *
1998
+ * @param options The options of the monotoneCubic factory function.
1999
+ */ function monotoneCubic(options) {
2000
+ const finalOptions = {
2001
+ fillHoles: false,
2002
+ ...options
2003
+ };
2004
+ return function monotoneCubicInterpolation(pathCoordinates, valueData) {
2005
+ // First we try to split the coordinates into segments
2006
+ // This is necessary to treat "holes" in line charts
2007
+ const segments = splitIntoSegments(pathCoordinates, valueData, {
2008
+ fillHoles: finalOptions.fillHoles,
2009
+ increasingX: true
2010
+ });
2011
+ if (!segments.length) {
2012
+ // If there were no segments return 'Chartist.Interpolation.none'
2013
+ return none()([], []);
2014
+ } else if (segments.length > 1) {
2015
+ // If the split resulted in more that one segment we need to interpolate each segment individually and join them
2016
+ // afterwards together into a single path.
2017
+ // For each segment we will recurse the monotoneCubic fn function
2018
+ // Join the segment path data into a single path and return
2019
+ return SvgPath.join(segments.map((segment)=>monotoneCubicInterpolation(segment.pathCoordinates, segment.valueData)
2020
+ ));
2021
+ } else {
2022
+ // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first
2023
+ // segment
2024
+ pathCoordinates = segments[0].pathCoordinates;
2025
+ valueData = segments[0].valueData;
2026
+ // If less than three points we need to fallback to no smoothing
2027
+ if (pathCoordinates.length <= 4) {
2028
+ return none()(pathCoordinates, valueData);
2029
+ }
2030
+ const xs = [];
2031
+ const ys = [];
2032
+ const n = pathCoordinates.length / 2;
2033
+ const ms = [];
2034
+ const ds = [];
2035
+ const dys = [];
2036
+ const dxs = [];
2037
+ // Populate x and y coordinates into separate arrays, for readability
2038
+ for(let i = 0; i < n; i++){
2039
+ xs[i] = pathCoordinates[i * 2];
2040
+ ys[i] = pathCoordinates[i * 2 + 1];
2041
+ }
2042
+ // Calculate deltas and derivative
2043
+ for(let i1 = 0; i1 < n - 1; i1++){
2044
+ dys[i1] = ys[i1 + 1] - ys[i1];
2045
+ dxs[i1] = xs[i1 + 1] - xs[i1];
2046
+ ds[i1] = dys[i1] / dxs[i1];
2047
+ }
2048
+ // Determine desired slope (m) at each point using Fritsch-Carlson method
2049
+ // See: http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation
2050
+ ms[0] = ds[0];
2051
+ ms[n - 1] = ds[n - 2];
2052
+ for(let i2 = 1; i2 < n - 1; i2++){
2053
+ if (ds[i2] === 0 || ds[i2 - 1] === 0 || ds[i2 - 1] > 0 !== ds[i2] > 0) {
2054
+ ms[i2] = 0;
2055
+ } else {
2056
+ ms[i2] = 3 * (dxs[i2 - 1] + dxs[i2]) / ((2 * dxs[i2] + dxs[i2 - 1]) / ds[i2 - 1] + (dxs[i2] + 2 * dxs[i2 - 1]) / ds[i2]);
2057
+ if (!isFinite(ms[i2])) {
2058
+ ms[i2] = 0;
2059
+ }
2060
+ }
2061
+ }
2062
+ // Now build a path from the slopes
2063
+ const path = new SvgPath().move(xs[0], ys[0], false, valueData[0]);
2064
+ for(let i3 = 0; i3 < n - 1; i3++){
2065
+ path.curve(// First control point
2066
+ xs[i3] + dxs[i3] / 3, ys[i3] + ms[i3] * dxs[i3] / 3, // Second control point
2067
+ xs[i3 + 1] - dxs[i3] / 3, ys[i3 + 1] - ms[i3 + 1] * dxs[i3] / 3, // End point
2068
+ xs[i3 + 1], ys[i3 + 1], false, valueData[i3 + 1]);
2069
+ }
2070
+ return path;
2071
+ }
2072
+ };
2073
+ }
2074
+
2075
+ var index = /*#__PURE__*/Object.freeze({
2076
+ __proto__: null,
2077
+ none: none,
2078
+ simple: simple,
2079
+ step: step,
2080
+ cardinal: cardinal,
2081
+ monotoneCubic: monotoneCubic
2082
+ });
2083
+
2084
+ class EventEmitter {
2085
+ on(event, listener) {
2086
+ const { allListeners , listeners } = this;
2087
+ if (event === "*") {
2088
+ allListeners.add(listener);
2089
+ } else {
2090
+ if (!listeners.has(event)) {
2091
+ listeners.set(event, new Set());
2092
+ }
2093
+ listeners.get(event).add(listener);
2094
+ }
2095
+ }
2096
+ off(event, listener) {
2097
+ const { allListeners , listeners } = this;
2098
+ if (event === "*") {
2099
+ if (listener) {
2100
+ allListeners.delete(listener);
2101
+ } else {
2102
+ allListeners.clear();
2103
+ }
2104
+ } else if (listeners.has(event)) {
2105
+ const eventListeners = listeners.get(event);
2106
+ if (listener) {
2107
+ eventListeners.delete(listener);
2108
+ } else {
2109
+ eventListeners.clear();
2110
+ }
2111
+ if (!eventListeners.size) {
2112
+ listeners.delete(event);
2113
+ }
2114
+ }
2115
+ }
2116
+ /**
2117
+ * Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.
2118
+ * @param event The event name that should be triggered
2119
+ * @param data Arbitrary data that will be passed to the event handler callback functions
2120
+ */ emit(event, data) {
2121
+ const { allListeners , listeners } = this;
2122
+ // Only do something if there are event handlers with this name existing
2123
+ if (listeners.has(event)) {
2124
+ listeners.get(event).forEach((listener)=>listener(data)
2125
+ );
2126
+ }
2127
+ // Emit event to star event handlers
2128
+ allListeners.forEach((listener)=>listener(event, data)
2129
+ );
2130
+ }
2131
+ constructor(){
2132
+ this.listeners = new Map();
2133
+ this.allListeners = new Set();
2134
+ }
2135
+ }
2136
+
2137
+ const instances = new WeakMap();
2138
+ class BaseChart {
2139
+ // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance.
2140
+ // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not
2141
+ // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage.
2142
+ // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html
2143
+ // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj
2144
+ // The problem is with the label offsets that can't be converted into percentage and affecting the chart container
2145
+ /**
2146
+ * Updates the chart which currently does a full reconstruction of the SVG DOM
2147
+ * @param 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.
2148
+ * @param 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.
2149
+ * @param 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
2150
+ */ update(data, options) {
2151
+ let override = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
2152
+ if (data) {
2153
+ this.data = data || {};
2154
+ this.data.labels = this.data.labels || [];
2155
+ this.data.series = this.data.series || [];
2156
+ // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
2157
+ this.eventEmitter.emit("data", {
2158
+ type: "update",
2159
+ data: this.data
2160
+ });
2161
+ }
2162
+ if (options) {
2163
+ this.options = extend({}, override ? this.options : this.defaultOptions, options);
2164
+ // If chartist was not initialized yet, we just set the options and leave the rest to the initialization
2165
+ // Otherwise we re-create the optionsProvider at this point
2166
+ if (!this.initializeTimeoutId) {
2167
+ var ref;
2168
+ (ref = this.optionsProvider) === null || ref === void 0 ? void 0 : ref.removeMediaQueryListeners();
2169
+ this.optionsProvider = optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
2170
+ }
2171
+ }
2172
+ // Only re-created the chart if it has been initialized yet
2173
+ if (!this.initializeTimeoutId && this.optionsProvider) {
2174
+ this.createChart(this.optionsProvider.getCurrentOptions());
2175
+ }
2176
+ // Return a reference to the chart object to chain up calls
2177
+ return this;
2178
+ }
2179
+ /**
2180
+ * 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.
2181
+ */ detach() {
2182
+ // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore
2183
+ // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout
2184
+ if (!this.initializeTimeoutId) {
2185
+ var ref;
2186
+ window.removeEventListener("resize", this.resizeListener);
2187
+ (ref = this.optionsProvider) === null || ref === void 0 ? void 0 : ref.removeMediaQueryListeners();
2188
+ } else {
2189
+ window.clearTimeout(this.initializeTimeoutId);
2190
+ }
2191
+ instances.delete(this.container);
2192
+ return this;
2193
+ }
2194
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2195
+ on(event, listener) {
2196
+ this.eventEmitter.on(event, listener);
2197
+ return this;
2198
+ }
2199
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2200
+ off(event, listener) {
2201
+ this.eventEmitter.off(event, listener);
2202
+ return this;
2203
+ }
2204
+ initialize() {
2205
+ // Add window resize listener that re-creates the chart
2206
+ window.addEventListener("resize", this.resizeListener);
2207
+ // Obtain current options based on matching media queries (if responsive options are given)
2208
+ // This will also register a listener that is re-creating the chart based on media changes
2209
+ this.optionsProvider = optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
2210
+ // Register options change listener that will trigger a chart update
2211
+ this.eventEmitter.on("optionsChanged", ()=>this.update()
2212
+ );
2213
+ // Before the first chart creation we need to register us with all plugins that are configured
2214
+ // Initialize all relevant plugins with our chart object and the plugin options specified in the config
2215
+ if (this.options.plugins) {
2216
+ this.options.plugins.forEach((plugin)=>{
2217
+ if (Array.isArray(plugin)) {
2218
+ plugin[0](this, plugin[1]);
2219
+ } else {
2220
+ plugin(this);
2221
+ }
2222
+ });
2223
+ }
2224
+ // Event for data transformation that allows to manipulate the data before it gets rendered in the charts
2225
+ this.eventEmitter.emit("data", {
2226
+ type: "initial",
2227
+ data: this.data
2228
+ });
2229
+ // Create the first chart
2230
+ this.createChart(this.optionsProvider.getCurrentOptions());
2231
+ // As chart is initialized from the event loop now we can reset our timeout reference
2232
+ // This is important if the chart gets initialized on the same element twice
2233
+ this.initializeTimeoutId = null;
2234
+ }
2235
+ constructor(query, data, defaultOptions, options, responsiveOptions){
2236
+ this.data = data;
2237
+ this.defaultOptions = defaultOptions;
2238
+ this.options = options;
2239
+ this.responsiveOptions = responsiveOptions;
2240
+ this.eventEmitter = new EventEmitter();
2241
+ this.resizeListener = ()=>this.update()
2242
+ ;
2243
+ this.initializeTimeoutId = setTimeout(()=>this.initialize()
2244
+ , 0);
2245
+ const container = typeof query === "string" ? document.querySelector(query) : query;
2246
+ if (!container) {
2247
+ throw new Error("Target element is not found");
2248
+ }
2249
+ this.container = container;
2250
+ const prevInstance = instances.get(container);
2251
+ // If chartist was already initialized in this container we are detaching all event listeners first
2252
+ if (prevInstance) {
2253
+ prevInstance.detach();
2254
+ }
2255
+ instances.set(container, this);
2256
+ }
2257
+ }
2258
+
2259
+ const axisUnits = {
2260
+ x: {
2261
+ pos: "x",
2262
+ len: "width",
2263
+ dir: "horizontal",
2264
+ rectStart: "x1",
2265
+ rectEnd: "x2",
2266
+ rectOffset: "y2"
2267
+ },
2268
+ y: {
2269
+ pos: "y",
2270
+ len: "height",
2271
+ dir: "vertical",
2272
+ rectStart: "y2",
2273
+ rectEnd: "y1",
2274
+ rectOffset: "x1"
2275
+ }
2276
+ };
2277
+ class Axis {
2278
+ createGridAndLabels(gridGroup, labelGroup, chartOptions, eventEmitter) {
2279
+ const axisOptions = this.units.pos === "x" ? chartOptions.axisX : chartOptions.axisY;
2280
+ const projectedValues = this.ticks.map((tick, i)=>this.projectValue(tick, i)
2281
+ );
2282
+ const labelValues = this.ticks.map(axisOptions.labelInterpolationFnc);
2283
+ projectedValues.forEach((projectedValue, index)=>{
2284
+ const labelValue = labelValues[index];
2285
+ const labelOffset = {
2286
+ x: 0,
2287
+ y: 0
2288
+ };
2289
+ // TODO: Find better solution for solving this problem
2290
+ // Calculate how much space we have available for the label
2291
+ let labelLength;
2292
+ if (projectedValues[index + 1]) {
2293
+ // If we still have one label ahead, we can calculate the distance to the next tick / label
2294
+ labelLength = projectedValues[index + 1] - projectedValue;
2295
+ } else {
2296
+ // If we don't have a label ahead and we have only two labels in total, we just take the remaining distance to
2297
+ // on the whole axis length. We limit that to a minimum of 30 pixel, so that labels close to the border will
2298
+ // still be visible inside of the chart padding.
2299
+ labelLength = Math.max(this.axisLength - projectedValue, 30);
2300
+ }
2301
+ // Skip grid lines and labels where interpolated label values are falsey (except for 0)
2302
+ if (labelValue !== "" && isFalseyButZero(labelValue)) {
2303
+ return;
2304
+ }
2305
+ // Transform to global coordinates using the chartRect
2306
+ // We also need to set the label offset for the createLabel function
2307
+ if (this.units.pos === "x") {
2308
+ projectedValue = this.chartRect.x1 + projectedValue;
2309
+ labelOffset.x = chartOptions.axisX.labelOffset.x;
2310
+ // If the labels should be positioned in start position (top side for vertical axis) we need to set a
2311
+ // different offset as for positioned with end (bottom)
2312
+ if (chartOptions.axisX.position === "start") {
2313
+ labelOffset.y = this.chartRect.padding.top + chartOptions.axisX.labelOffset.y + 5;
2314
+ } else {
2315
+ labelOffset.y = this.chartRect.y1 + chartOptions.axisX.labelOffset.y + 5;
2316
+ }
2317
+ } else {
2318
+ projectedValue = this.chartRect.y1 - projectedValue;
2319
+ labelOffset.y = chartOptions.axisY.labelOffset.y - labelLength;
2320
+ // If the labels should be positioned in start position (left side for horizontal axis) we need to set a
2321
+ // different offset as for positioned with end (right side)
2322
+ if (chartOptions.axisY.position === "start") {
2323
+ labelOffset.x = this.chartRect.padding.left + chartOptions.axisY.labelOffset.x;
2324
+ } else {
2325
+ labelOffset.x = this.chartRect.x2 + chartOptions.axisY.labelOffset.x + 10;
2326
+ }
2327
+ }
2328
+ if (axisOptions.showGrid) {
2329
+ createGrid(projectedValue, index, this, this.gridOffset, this.chartRect[this.counterUnits.len](), gridGroup, [
2330
+ chartOptions.classNames.grid,
2331
+ chartOptions.classNames[this.units.dir]
2332
+ ], eventEmitter);
2333
+ }
2334
+ if (axisOptions.showLabel) {
2335
+ createLabel(projectedValue, labelLength, index, labelValue, this, axisOptions.offset, labelOffset, labelGroup, [
2336
+ chartOptions.classNames.label,
2337
+ chartOptions.classNames[this.units.dir],
2338
+ axisOptions.position === "start" ? chartOptions.classNames[axisOptions.position] : chartOptions.classNames.end
2339
+ ], eventEmitter);
2340
+ }
2341
+ });
2342
+ }
2343
+ constructor(units, chartRect, ticks){
2344
+ this.units = units;
2345
+ this.chartRect = chartRect;
2346
+ this.ticks = ticks;
2347
+ this.counterUnits = units === axisUnits.x ? axisUnits.y : axisUnits.x;
2348
+ this.axisLength = chartRect[this.units.rectEnd] - chartRect[this.units.rectStart];
2349
+ this.gridOffset = chartRect[this.units.rectOffset];
2350
+ }
2351
+ }
2352
+
2353
+ class AutoScaleAxis extends Axis {
2354
+ projectValue(value) {
2355
+ const finalValue = Number(getMultiValue(value, this.units.pos));
2356
+ return this.axisLength * (finalValue - this.bounds.min) / this.bounds.range;
2357
+ }
2358
+ constructor(axisUnit, data, chartRect, options){
2359
+ // Usually we calculate highLow based on the data but this can be overriden by a highLow object in the options
2360
+ const highLow = options.highLow || getHighLow(data, options, axisUnit.pos);
2361
+ const bounds = getBounds(chartRect[axisUnit.rectEnd] - chartRect[axisUnit.rectStart], highLow, options.scaleMinSpace || 20, options.onlyInteger);
2362
+ const range = {
2363
+ min: bounds.min,
2364
+ max: bounds.max
2365
+ };
2366
+ super(axisUnit, chartRect, bounds.values);
2367
+ this.bounds = bounds;
2368
+ this.range = range;
2369
+ }
2370
+ }
2371
+
2372
+ class FixedScaleAxis extends Axis {
2373
+ projectValue(value) {
2374
+ const finalValue = Number(getMultiValue(value, this.units.pos));
2375
+ return this.axisLength * (finalValue - this.range.min) / (this.range.max - this.range.min);
2376
+ }
2377
+ constructor(axisUnit, data, chartRect, options){
2378
+ const highLow = options.highLow || getHighLow(data, options, axisUnit.pos);
2379
+ const divisor = options.divisor || 1;
2380
+ const ticks = (options.ticks || times(divisor).map((_value, index)=>highLow.low + (highLow.high - highLow.low) / divisor * index
2381
+ )).sort((a, b)=>Number(a) - Number(b)
2382
+ );
2383
+ const range = {
2384
+ min: highLow.low,
2385
+ max: highLow.high
2386
+ };
2387
+ super(axisUnit, chartRect, ticks);
2388
+ this.range = range;
2389
+ }
2390
+ }
2391
+
2392
+ class StepAxis extends Axis {
2393
+ projectValue(_value, index) {
2394
+ return this.stepLength * index;
2395
+ }
2396
+ constructor(axisUnit, _data, chartRect, options){
2397
+ const ticks = options.ticks || [];
2398
+ super(axisUnit, chartRect, ticks);
2399
+ const calc = Math.max(1, ticks.length - (options.stretch ? 1 : 0));
2400
+ this.stepLength = this.axisLength / calc;
2401
+ this.stretch = Boolean(options.stretch);
2402
+ }
2403
+ }
2404
+
2405
+ function getSeriesOption(series, options, key) {
2406
+ var ref;
2407
+ if (safeHasProperty(series, "name") && series.name && ((ref = options.series) === null || ref === void 0 ? void 0 : ref[series.name])) {
2408
+ const seriesOptions = options === null || options === void 0 ? void 0 : options.series[series.name];
2409
+ const value = seriesOptions[key];
2410
+ const result = value === undefined ? options[key] : value;
2411
+ return result;
2412
+ } else {
2413
+ return options[key];
2414
+ }
2415
+ }
2416
+ /**
2417
+ * Default options in line charts. Expand the code view to see a detailed list of options with comments.
2418
+ */ const defaultOptions$2 = {
2419
+ // Options for X-Axis
2420
+ axisX: {
2421
+ // The offset of the labels to the chart area
2422
+ offset: 30,
2423
+ // 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.
2424
+ position: "end",
2425
+ // Allows you to correct label positioning on this axis by positive or negative x and y offset.
2426
+ labelOffset: {
2427
+ x: 0,
2428
+ y: 0
2429
+ },
2430
+ // If labels should be shown or not
2431
+ showLabel: true,
2432
+ // If the axis grid should be drawn or not
2433
+ showGrid: true,
2434
+ // Interpolation function that allows you to intercept the value from the axis label
2435
+ labelInterpolationFnc: noop,
2436
+ // 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.
2437
+ type: undefined
2438
+ },
2439
+ // Options for Y-Axis
2440
+ axisY: {
2441
+ // The offset of the labels to the chart area
2442
+ offset: 40,
2443
+ // 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.
2444
+ position: "start",
2445
+ // Allows you to correct label positioning on this axis by positive or negative x and y offset.
2446
+ labelOffset: {
2447
+ x: 0,
2448
+ y: 0
2449
+ },
2450
+ // If labels should be shown or not
2451
+ showLabel: true,
2452
+ // If the axis grid should be drawn or not
2453
+ showGrid: true,
2454
+ // Interpolation function that allows you to intercept the value from the axis label
2455
+ labelInterpolationFnc: noop,
2456
+ // 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.
2457
+ type: undefined,
2458
+ // This value specifies the minimum height in pixel of the scale steps
2459
+ scaleMinSpace: 20,
2460
+ // Use only integer values (whole numbers) for the scale steps
2461
+ onlyInteger: false
2462
+ },
2463
+ // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
2464
+ width: undefined,
2465
+ // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
2466
+ height: undefined,
2467
+ // If the line should be drawn or not
2468
+ showLine: true,
2469
+ // If dots should be drawn or not
2470
+ showPoint: true,
2471
+ // If the line chart should draw an area
2472
+ showArea: false,
2473
+ // The base for the area chart that will be used to close the area shape (is normally 0)
2474
+ areaBase: 0,
2475
+ // 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.
2476
+ lineSmooth: true,
2477
+ // If the line chart should add a background fill to the .ct-grids group.
2478
+ showGridBackground: false,
2479
+ // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
2480
+ low: undefined,
2481
+ // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
2482
+ high: undefined,
2483
+ // 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}
2484
+ chartPadding: {
2485
+ top: 15,
2486
+ right: 15,
2487
+ bottom: 5,
2488
+ left: 10
2489
+ },
2490
+ // 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.
2491
+ fullWidth: false,
2492
+ // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
2493
+ reverseData: false,
2494
+ // Override the class names that get used to generate the SVG structure of the chart
2495
+ classNames: {
2496
+ chart: "ct-chart-line",
2497
+ label: "ct-label",
2498
+ labelGroup: "ct-labels",
2499
+ series: "ct-series",
2500
+ line: "ct-line",
2501
+ point: "ct-point",
2502
+ area: "ct-area",
2503
+ grid: "ct-grid",
2504
+ gridGroup: "ct-grids",
2505
+ gridBackground: "ct-grid-background",
2506
+ vertical: "ct-vertical",
2507
+ horizontal: "ct-horizontal",
2508
+ start: "ct-start",
2509
+ end: "ct-end"
2510
+ }
2511
+ };
2512
+ class LineChart extends BaseChart {
2513
+ /**
2514
+ * Creates a new chart
2515
+ */ createChart(options) {
2516
+ const { data } = this;
2517
+ const normalizedData = normalizeData(data, options.reverseData, true);
2518
+ // Create new svg object
2519
+ const svg = createSvg(this.container, options.width, options.height, options.classNames.chart);
2520
+ this.svg = svg;
2521
+ // Create groups for labels, grid and series
2522
+ const gridGroup = svg.elem("g").addClass(options.classNames.gridGroup);
2523
+ const seriesGroup = svg.elem("g");
2524
+ const labelGroup = svg.elem("g").addClass(options.classNames.labelGroup);
2525
+ const chartRect = createChartRect(svg, options);
2526
+ let axisX;
2527
+ let axisY;
2528
+ if (options.axisX.type === undefined) {
2529
+ axisX = new StepAxis(axisUnits.x, normalizedData.series, chartRect, {
2530
+ ...options.axisX,
2531
+ ticks: normalizedData.labels,
2532
+ stretch: options.fullWidth
2533
+ });
2534
+ } else {
2535
+ // eslint-disable-next-line new-cap
2536
+ axisX = new options.axisX.type(axisUnits.x, normalizedData.series, chartRect, options.axisX);
2537
+ }
2538
+ if (options.axisY.type === undefined) {
2539
+ axisY = new AutoScaleAxis(axisUnits.y, normalizedData.series, chartRect, {
2540
+ ...options.axisY,
2541
+ high: isNumeric(options.high) ? options.high : options.axisY.high,
2542
+ low: isNumeric(options.low) ? options.low : options.axisY.low
2543
+ });
2544
+ } else {
2545
+ // eslint-disable-next-line new-cap
2546
+ axisY = new options.axisY.type(axisUnits.y, normalizedData.series, chartRect, options.axisY);
2547
+ }
2548
+ axisX.createGridAndLabels(gridGroup, labelGroup, options, this.eventEmitter);
2549
+ axisY.createGridAndLabels(gridGroup, labelGroup, options, this.eventEmitter);
2550
+ if (options.showGridBackground) {
2551
+ createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
2552
+ }
2553
+ // Draw the series
2554
+ data.series.forEach((series, seriesIndex)=>{
2555
+ const seriesElement = seriesGroup.elem("g");
2556
+ const seriesName = safeHasProperty(series, "name") && series.name;
2557
+ const seriesClassName = safeHasProperty(series, "className") && series.className;
2558
+ const seriesMeta = safeHasProperty(series, "meta") ? series.meta : undefined;
2559
+ // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
2560
+ if (seriesName) {
2561
+ seriesElement.attr({
2562
+ "ct:series-name": seriesName
2563
+ });
2564
+ }
2565
+ if (seriesMeta) {
2566
+ seriesElement.attr({
2567
+ "ct:meta": serialize(seriesMeta)
2568
+ });
2569
+ }
2570
+ // Use series class from series data or if not set generate one
2571
+ seriesElement.addClass([
2572
+ options.classNames.series,
2573
+ seriesClassName || "".concat(options.classNames.series, "-").concat(alphaNumerate(seriesIndex))
2574
+ ].join(" "));
2575
+ const pathCoordinates = [];
2576
+ const pathData = [];
2577
+ normalizedData.series[seriesIndex].forEach((value, valueIndex)=>{
2578
+ const p = {
2579
+ x: chartRect.x1 + axisX.projectValue(value, valueIndex, normalizedData.series[seriesIndex]),
2580
+ y: chartRect.y1 - axisY.projectValue(value, valueIndex, normalizedData.series[seriesIndex])
2581
+ };
2582
+ pathCoordinates.push(p.x, p.y);
2583
+ pathData.push({
2584
+ value,
2585
+ valueIndex,
2586
+ meta: getMetaData(series, valueIndex)
2587
+ });
2588
+ });
2589
+ const seriesOptions = {
2590
+ lineSmooth: getSeriesOption(series, options, "lineSmooth"),
2591
+ showPoint: getSeriesOption(series, options, "showPoint"),
2592
+ showLine: getSeriesOption(series, options, "showLine"),
2593
+ showArea: getSeriesOption(series, options, "showArea"),
2594
+ areaBase: getSeriesOption(series, options, "areaBase")
2595
+ };
2596
+ let smoothing;
2597
+ if (typeof seriesOptions.lineSmooth === "function") {
2598
+ smoothing = seriesOptions.lineSmooth;
2599
+ } else {
2600
+ smoothing = seriesOptions.lineSmooth ? monotoneCubic() : none();
2601
+ }
2602
+ // Interpolating path where pathData will be used to annotate each path element so we can trace back the original
2603
+ // index, value and meta data
2604
+ const path = smoothing(pathCoordinates, pathData);
2605
+ // If we should show points we need to create them now to avoid secondary loop
2606
+ // Points are drawn from the pathElements returned by the interpolation function
2607
+ // Small offset for Firefox to render squares correctly
2608
+ if (seriesOptions.showPoint) {
2609
+ path.pathElements.forEach((pathElement)=>{
2610
+ const { data: pathElementData } = pathElement;
2611
+ const point = seriesElement.elem("line", {
2612
+ x1: pathElement.x,
2613
+ y1: pathElement.y,
2614
+ x2: pathElement.x + 0.01,
2615
+ y2: pathElement.y
2616
+ }, options.classNames.point);
2617
+ if (pathElementData) {
2618
+ let x;
2619
+ let y;
2620
+ if (safeHasProperty(pathElementData.value, "x")) {
2621
+ x = pathElementData.value.x;
2622
+ }
2623
+ if (safeHasProperty(pathElementData.value, "y")) {
2624
+ y = pathElementData.value.y;
2625
+ }
2626
+ point.attr({
2627
+ "ct:value": [
2628
+ x,
2629
+ y
2630
+ ].filter(isNumeric).join(","),
2631
+ "ct:meta": serialize(pathElementData.meta)
2632
+ });
2633
+ }
2634
+ this.eventEmitter.emit("draw", {
2635
+ type: "point",
2636
+ value: pathElementData === null || pathElementData === void 0 ? void 0 : pathElementData.value,
2637
+ index: (pathElementData === null || pathElementData === void 0 ? void 0 : pathElementData.valueIndex) || 0,
2638
+ meta: pathElementData === null || pathElementData === void 0 ? void 0 : pathElementData.meta,
2639
+ series,
2640
+ seriesIndex,
2641
+ axisX,
2642
+ axisY,
2643
+ group: seriesElement,
2644
+ element: point,
2645
+ x: pathElement.x,
2646
+ y: pathElement.y,
2647
+ chartRect
2648
+ });
2649
+ });
2650
+ }
2651
+ if (seriesOptions.showLine) {
2652
+ const line = seriesElement.elem("path", {
2653
+ d: path.stringify()
2654
+ }, options.classNames.line, true);
2655
+ this.eventEmitter.emit("draw", {
2656
+ type: "line",
2657
+ values: normalizedData.series[seriesIndex],
2658
+ path: path.clone(),
2659
+ chartRect,
2660
+ // TODO: Remove redundant
2661
+ index: seriesIndex,
2662
+ series,
2663
+ seriesIndex,
2664
+ meta: seriesMeta,
2665
+ axisX,
2666
+ axisY,
2667
+ group: seriesElement,
2668
+ element: line
2669
+ });
2670
+ }
2671
+ // Area currently only works with axes that support a range!
2672
+ if (seriesOptions.showArea && axisY.range) {
2673
+ // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that
2674
+ // the area is not drawn outside the chart area.
2675
+ const areaBase = Math.max(Math.min(seriesOptions.areaBase, axisY.range.max), axisY.range.min);
2676
+ // We project the areaBase value into screen coordinates
2677
+ const areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase);
2678
+ // In order to form the area we'll first split the path by move commands so we can chunk it up into segments
2679
+ path.splitByCommand("M")// We filter only "solid" segments that contain more than one point. Otherwise there's no need for an area
2680
+ .filter((pathSegment)=>pathSegment.pathElements.length > 1
2681
+ ).map((solidPathSegments)=>{
2682
+ // Receiving the filtered solid path segments we can now convert those segments into fill areas
2683
+ const firstElement = solidPathSegments.pathElements[0];
2684
+ const lastElement = solidPathSegments.pathElements[solidPathSegments.pathElements.length - 1];
2685
+ // Cloning the solid path segment with closing option and removing the first move command from the clone
2686
+ // We then insert a new move that should start at the area base and draw a straight line up or down
2687
+ // at the end of the path we add an additional straight line to the projected area base value
2688
+ // As the closing option is set our path will be automatically closed
2689
+ return solidPathSegments.clone(true).position(0).remove(1).move(firstElement.x, areaBaseProjected).line(firstElement.x, firstElement.y).position(solidPathSegments.pathElements.length + 1).line(lastElement.x, areaBaseProjected);
2690
+ }).forEach((areaPath)=>{
2691
+ // For each of our newly created area paths, we'll now create path elements by stringifying our path objects
2692
+ // and adding the created DOM elements to the correct series group
2693
+ const area = seriesElement.elem("path", {
2694
+ d: areaPath.stringify()
2695
+ }, options.classNames.area, true);
2696
+ // Emit an event for each area that was drawn
2697
+ this.eventEmitter.emit("draw", {
2698
+ type: "area",
2699
+ values: normalizedData.series[seriesIndex],
2700
+ path: areaPath.clone(),
2701
+ series,
2702
+ seriesIndex,
2703
+ axisX,
2704
+ axisY,
2705
+ chartRect,
2706
+ // TODO: Remove redundant
2707
+ index: seriesIndex,
2708
+ group: seriesElement,
2709
+ element: area,
2710
+ meta: seriesMeta
2711
+ });
2712
+ });
2713
+ }
2714
+ });
2715
+ this.eventEmitter.emit("created", {
2716
+ chartRect,
2717
+ axisX,
2718
+ axisY,
2719
+ svg,
2720
+ options
2721
+ });
2722
+ }
2723
+ /**
2724
+ * This method creates a new line chart.
2725
+ * @param query A selector query string or directly a DOM element
2726
+ * @param data The data object that needs to consist of a labels and a series array
2727
+ * @param options The options object with options that override the default options. Check the examples for a detailed list.
2728
+ * @param responsiveOptions Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
2729
+ * @return An object which exposes the API for the created chart
2730
+ *
2731
+ * @example
2732
+ * // Create a simple line chart
2733
+ * const data = {
2734
+ * // A labels array that can contain any sort of values
2735
+ * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
2736
+ * // Our series array that contains series objects or in this case series data arrays
2737
+ * series: [
2738
+ * [5, 2, 4, 2, 0]
2739
+ * ]
2740
+ * };
2741
+ *
2742
+ * // As options we currently only set a static size of 300x200 px
2743
+ * const options = {
2744
+ * width: '300px',
2745
+ * height: '200px'
2746
+ * };
2747
+ *
2748
+ * // 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
2749
+ * new LineChart('.ct-chart', data, options);
2750
+ *
2751
+ * @example
2752
+ * // Use specific interpolation function with configuration from the Chartist.Interpolation module
2753
+ *
2754
+ * const chart = new LineChart('.ct-chart', {
2755
+ * labels: [1, 2, 3, 4, 5],
2756
+ * series: [
2757
+ * [1, 1, 8, 1, 7]
2758
+ * ]
2759
+ * }, {
2760
+ * lineSmooth: Chartist.Interpolation.cardinal({
2761
+ * tension: 0.2
2762
+ * })
2763
+ * });
2764
+ *
2765
+ * @example
2766
+ * // Create a line chart with responsive options
2767
+ *
2768
+ * const data = {
2769
+ * // A labels array that can contain any sort of values
2770
+ * labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
2771
+ * // Our series array that contains series objects or in this case series data arrays
2772
+ * series: [
2773
+ * [5, 2, 4, 2, 0]
2774
+ * ]
2775
+ * };
2776
+ *
2777
+ * // In addition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries.
2778
+ * const responsiveOptions = [
2779
+ * ['screen and (min-width: 641px) and (max-width: 1024px)', {
2780
+ * showPoint: false,
2781
+ * axisX: {
2782
+ * labelInterpolationFnc: function(value) {
2783
+ * // Will return Mon, Tue, Wed etc. on medium screens
2784
+ * return value.slice(0, 3);
2785
+ * }
2786
+ * }
2787
+ * }],
2788
+ * ['screen and (max-width: 640px)', {
2789
+ * showLine: false,
2790
+ * axisX: {
2791
+ * labelInterpolationFnc: function(value) {
2792
+ * // Will return M, T, W etc. on small screens
2793
+ * return value[0];
2794
+ * }
2795
+ * }
2796
+ * }]
2797
+ * ];
2798
+ *
2799
+ * new LineChart('.ct-chart', data, null, responsiveOptions);
2800
+ *
2801
+ */ constructor(query, data, options, responsiveOptions){
2802
+ super(query, data, defaultOptions$2, extend({}, defaultOptions$2, options), responsiveOptions);
2803
+ this.data = data;
2804
+ }
2805
+ }
2806
+
2807
+ function getSerialSums(series) {
2808
+ return serialMap(series, function() {
2809
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
2810
+ args[_key] = arguments[_key];
2811
+ }
2812
+ return Array.from(args).reduce((prev, curr)=>{
2813
+ return {
2814
+ x: prev.x + (safeHasProperty(curr, "x") ? curr.x : 0),
2815
+ y: prev.y + (safeHasProperty(curr, "y") ? curr.y : 0)
2816
+ };
2817
+ }, {
2818
+ x: 0,
2819
+ y: 0
2820
+ });
2821
+ });
2822
+ }
2823
+ /**
2824
+ * Default options in bar charts. Expand the code view to see a detailed list of options with comments.
2825
+ */ const defaultOptions$1 = {
2826
+ // Options for X-Axis
2827
+ axisX: {
2828
+ // The offset of the chart drawing area to the border of the container
2829
+ offset: 30,
2830
+ // 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.
2831
+ position: "end",
2832
+ // Allows you to correct label positioning on this axis by positive or negative x and y offset.
2833
+ labelOffset: {
2834
+ x: 0,
2835
+ y: 0
2836
+ },
2837
+ // If labels should be shown or not
2838
+ showLabel: true,
2839
+ // If the axis grid should be drawn or not
2840
+ showGrid: true,
2841
+ // Interpolation function that allows you to intercept the value from the axis label
2842
+ labelInterpolationFnc: noop,
2843
+ // This value specifies the minimum width in pixel of the scale steps
2844
+ scaleMinSpace: 30,
2845
+ // Use only integer values (whole numbers) for the scale steps
2846
+ onlyInteger: false
2847
+ },
2848
+ // Options for Y-Axis
2849
+ axisY: {
2850
+ // The offset of the chart drawing area to the border of the container
2851
+ offset: 40,
2852
+ // 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.
2853
+ position: "start",
2854
+ // Allows you to correct label positioning on this axis by positive or negative x and y offset.
2855
+ labelOffset: {
2856
+ x: 0,
2857
+ y: 0
2858
+ },
2859
+ // If labels should be shown or not
2860
+ showLabel: true,
2861
+ // If the axis grid should be drawn or not
2862
+ showGrid: true,
2863
+ // Interpolation function that allows you to intercept the value from the axis label
2864
+ labelInterpolationFnc: noop,
2865
+ // This value specifies the minimum height in pixel of the scale steps
2866
+ scaleMinSpace: 20,
2867
+ // Use only integer values (whole numbers) for the scale steps
2868
+ onlyInteger: false
2869
+ },
2870
+ // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
2871
+ width: undefined,
2872
+ // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
2873
+ height: undefined,
2874
+ // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
2875
+ high: undefined,
2876
+ // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
2877
+ low: undefined,
2878
+ // Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale.
2879
+ referenceValue: 0,
2880
+ // 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}
2881
+ chartPadding: {
2882
+ top: 15,
2883
+ right: 15,
2884
+ bottom: 5,
2885
+ left: 10
2886
+ },
2887
+ // Specify the distance in pixel of bars in a group
2888
+ seriesBarDistance: 15,
2889
+ // If set to true this property will cause the series bars to be stacked. Check the `stackMode` option for further stacking options.
2890
+ stackBars: false,
2891
+ // If set to 'overlap' this property will force the stacked bars to draw from the zero line.
2892
+ // 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.
2893
+ stackMode: "accumulate",
2894
+ // 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.
2895
+ horizontalBars: false,
2896
+ // 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.
2897
+ distributeSeries: false,
2898
+ // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
2899
+ reverseData: false,
2900
+ // If the bar chart should add a background fill to the .ct-grids group.
2901
+ showGridBackground: false,
2902
+ // Override the class names that get used to generate the SVG structure of the chart
2903
+ classNames: {
2904
+ chart: "ct-chart-bar",
2905
+ horizontalBars: "ct-horizontal-bars",
2906
+ label: "ct-label",
2907
+ labelGroup: "ct-labels",
2908
+ series: "ct-series",
2909
+ bar: "ct-bar",
2910
+ grid: "ct-grid",
2911
+ gridGroup: "ct-grids",
2912
+ gridBackground: "ct-grid-background",
2913
+ vertical: "ct-vertical",
2914
+ horizontal: "ct-horizontal",
2915
+ start: "ct-start",
2916
+ end: "ct-end"
2917
+ }
2918
+ };
2919
+ class BarChart extends BaseChart {
2920
+ /**
2921
+ * Creates a new chart
2922
+ */ createChart(options) {
2923
+ const { data } = this;
2924
+ const normalizedData = normalizeData(data, options.reverseData, options.horizontalBars ? "x" : "y", true);
2925
+ // Create new svg element
2926
+ const svg = createSvg(this.container, options.width, options.height, options.classNames.chart + (options.horizontalBars ? " " + options.classNames.horizontalBars : ""));
2927
+ const highLow = options.stackBars && options.stackMode !== true && normalizedData.series.length ? getHighLow([
2928
+ getSerialSums(normalizedData.series)
2929
+ ], options, options.horizontalBars ? "x" : "y") : getHighLow(normalizedData.series, options, options.horizontalBars ? "x" : "y");
2930
+ this.svg = svg;
2931
+ // Drawing groups in correct order
2932
+ const gridGroup = svg.elem("g").addClass(options.classNames.gridGroup);
2933
+ const seriesGroup = svg.elem("g");
2934
+ const labelGroup = svg.elem("g").addClass(options.classNames.labelGroup);
2935
+ // Overrides of high / low from settings
2936
+ if (typeof options.high === "number") {
2937
+ highLow.high = options.high;
2938
+ }
2939
+ if (typeof options.low === "number") {
2940
+ highLow.low = options.low;
2941
+ }
2942
+ const chartRect = createChartRect(svg, options);
2943
+ let valueAxis;
2944
+ const labelAxisTicks = options.distributeSeries && options.stackBars ? // use only the first label for the step axis
2945
+ normalizedData.labels.slice(0, 1) : // If we are drawing a regular bar chart with two dimensional series data, we just use the labels array
2946
+ // as the bars are normalized
2947
+ normalizedData.labels;
2948
+ let labelAxis;
2949
+ let axisX;
2950
+ let axisY;
2951
+ // Set labelAxis and valueAxis based on the horizontalBars setting. This setting will flip the axes if necessary.
2952
+ if (options.horizontalBars) {
2953
+ if (options.axisX.type === undefined) {
2954
+ valueAxis = axisX = new AutoScaleAxis(axisUnits.x, normalizedData.series, chartRect, {
2955
+ ...options.axisX,
2956
+ highLow: highLow,
2957
+ referenceValue: 0
2958
+ });
2959
+ } else {
2960
+ // eslint-disable-next-line new-cap
2961
+ valueAxis = axisX = new options.axisX.type(axisUnits.x, normalizedData.series, chartRect, {
2962
+ ...options.axisX,
2963
+ highLow: highLow,
2964
+ referenceValue: 0
2965
+ });
2966
+ }
2967
+ if (options.axisY.type === undefined) {
2968
+ labelAxis = axisY = new StepAxis(axisUnits.y, normalizedData.series, chartRect, {
2969
+ ticks: labelAxisTicks
2970
+ });
2971
+ } else {
2972
+ // eslint-disable-next-line new-cap
2973
+ labelAxis = axisY = new options.axisY.type(axisUnits.y, normalizedData.series, chartRect, options.axisY);
2974
+ }
2975
+ } else {
2976
+ if (options.axisX.type === undefined) {
2977
+ labelAxis = axisX = new StepAxis(axisUnits.x, normalizedData.series, chartRect, {
2978
+ ticks: labelAxisTicks
2979
+ });
2980
+ } else {
2981
+ // eslint-disable-next-line new-cap
2982
+ labelAxis = axisX = new options.axisX.type(axisUnits.x, normalizedData.series, chartRect, options.axisX);
2983
+ }
2984
+ if (options.axisY.type === undefined) {
2985
+ valueAxis = axisY = new AutoScaleAxis(axisUnits.y, normalizedData.series, chartRect, {
2986
+ ...options.axisY,
2987
+ highLow: highLow,
2988
+ referenceValue: 0
2989
+ });
2990
+ } else {
2991
+ // eslint-disable-next-line new-cap
2992
+ valueAxis = axisY = new options.axisY.type(axisUnits.y, normalizedData.series, chartRect, {
2993
+ ...options.axisY,
2994
+ highLow: highLow,
2995
+ referenceValue: 0
2996
+ });
2997
+ }
2998
+ }
2999
+ // Projected 0 point
3000
+ const zeroPoint = options.horizontalBars ? chartRect.x1 + valueAxis.projectValue(0) : chartRect.y1 - valueAxis.projectValue(0);
3001
+ // Used to track the screen coordinates of stacked bars
3002
+ const stackedBarValues = [];
3003
+ labelAxis.createGridAndLabels(gridGroup, labelGroup, options, this.eventEmitter);
3004
+ valueAxis.createGridAndLabels(gridGroup, labelGroup, options, this.eventEmitter);
3005
+ if (options.showGridBackground) {
3006
+ createGridBackground(gridGroup, chartRect, options.classNames.gridBackground, this.eventEmitter);
3007
+ }
3008
+ // Draw the series
3009
+ data.series.forEach((series, seriesIndex)=>{
3010
+ // Calculating bi-polar value of index for seriesOffset. For i = 0..4 biPol will be -1.5, -0.5, 0.5, 1.5 etc.
3011
+ const biPol = seriesIndex - (data.series.length - 1) / 2;
3012
+ // Half of the period width between vertical grid lines used to position bars
3013
+ let periodHalfLength;
3014
+ // We need to set periodHalfLength based on some options combinations
3015
+ if (options.distributeSeries && !options.stackBars) {
3016
+ // If distributed series are enabled but stacked bars aren't, we need to use the length of the normaizedData array
3017
+ // which is the series count and divide by 2
3018
+ periodHalfLength = labelAxis.axisLength / normalizedData.series.length / 2;
3019
+ } else if (options.distributeSeries && options.stackBars) {
3020
+ // If distributed series and stacked bars are enabled we'll only get one bar so we should just divide the axis
3021
+ // length by 2
3022
+ periodHalfLength = labelAxis.axisLength / 2;
3023
+ } else {
3024
+ // On regular bar charts we should just use the series length
3025
+ periodHalfLength = labelAxis.axisLength / normalizedData.series[seriesIndex].length / 2;
3026
+ }
3027
+ // Adding the series group to the series element
3028
+ const seriesElement = seriesGroup.elem("g");
3029
+ const seriesName = safeHasProperty(series, "name") && series.name;
3030
+ const seriesClassName = safeHasProperty(series, "className") && series.className;
3031
+ const seriesMeta = safeHasProperty(series, "meta") ? series.meta : undefined;
3032
+ // Write attributes to series group element. If series name or meta is undefined the attributes will not be written
3033
+ if (seriesName) {
3034
+ seriesElement.attr({
3035
+ "ct:series-name": seriesName
3036
+ });
3037
+ }
3038
+ if (seriesMeta) {
3039
+ seriesElement.attr({
3040
+ "ct:meta": serialize(seriesMeta)
3041
+ });
3042
+ }
3043
+ // Use series class from series data or if not set generate one
3044
+ seriesElement.addClass([
3045
+ options.classNames.series,
3046
+ seriesClassName || "".concat(options.classNames.series, "-").concat(alphaNumerate(seriesIndex))
3047
+ ].join(" "));
3048
+ normalizedData.series[seriesIndex].forEach((value, valueIndex)=>{
3049
+ let labelAxisValueIndex;
3050
+ // We need to set labelAxisValueIndex based on some options combinations
3051
+ if (options.distributeSeries && !options.stackBars) {
3052
+ // If distributed series are enabled but stacked bars aren't, we can use the seriesIndex for later projection
3053
+ // on the step axis for label positioning
3054
+ labelAxisValueIndex = seriesIndex;
3055
+ } else if (options.distributeSeries && options.stackBars) {
3056
+ // If distributed series and stacked bars are enabled, we will only get one bar and therefore always use
3057
+ // 0 for projection on the label step axis
3058
+ labelAxisValueIndex = 0;
3059
+ } else {
3060
+ // On regular bar charts we just use the value index to project on the label step axis
3061
+ labelAxisValueIndex = valueIndex;
3062
+ }
3063
+ let projected;
3064
+ // We need to transform coordinates differently based on the chart layout
3065
+ if (options.horizontalBars) {
3066
+ projected = {
3067
+ x: chartRect.x1 + valueAxis.projectValue(safeHasProperty(value, "x") ? value.x : 0, valueIndex, normalizedData.series[seriesIndex]),
3068
+ y: chartRect.y1 - labelAxis.projectValue(safeHasProperty(value, "y") ? value.y : 0, labelAxisValueIndex, normalizedData.series[seriesIndex])
3069
+ };
3070
+ } else {
3071
+ projected = {
3072
+ x: chartRect.x1 + labelAxis.projectValue(safeHasProperty(value, "x") ? value.x : 0, labelAxisValueIndex, normalizedData.series[seriesIndex]),
3073
+ y: chartRect.y1 - valueAxis.projectValue(safeHasProperty(value, "y") ? value.y : 0, valueIndex, normalizedData.series[seriesIndex])
3074
+ };
3075
+ }
3076
+ // If the label axis is a step based axis we will offset the bar into the middle of between two steps using
3077
+ // the periodHalfLength value. Also we do arrange the different series so that they align up to each other using
3078
+ // the seriesBarDistance. If we don't have a step axis, the bar positions can be chosen freely so we should not
3079
+ // add any automated positioning.
3080
+ if (labelAxis instanceof StepAxis) {
3081
+ // Offset to center bar between grid lines, but only if the step axis is not stretched
3082
+ if (!labelAxis.stretch) {
3083
+ projected[labelAxis.units.pos] += periodHalfLength * (options.horizontalBars ? -1 : 1);
3084
+ }
3085
+ // Using bi-polar offset for multiple series if no stacked bars or series distribution is used
3086
+ projected[labelAxis.units.pos] += options.stackBars || options.distributeSeries ? 0 : biPol * options.seriesBarDistance * (options.horizontalBars ? -1 : 1);
3087
+ }
3088
+ // Enter value in stacked bar values used to remember previous screen value for stacking up bars
3089
+ const previousStack = stackedBarValues[valueIndex] || zeroPoint;
3090
+ stackedBarValues[valueIndex] = previousStack - (zeroPoint - projected[labelAxis.counterUnits.pos]);
3091
+ // Skip if value is undefined
3092
+ if (value === undefined) {
3093
+ return;
3094
+ }
3095
+ const positions = {
3096
+ ["".concat(labelAxis.units.pos, "1")]: projected[labelAxis.units.pos],
3097
+ ["".concat(labelAxis.units.pos, "2")]: projected[labelAxis.units.pos]
3098
+ };
3099
+ if (options.stackBars && (options.stackMode === "accumulate" || !options.stackMode)) {
3100
+ // Stack mode: accumulate (default)
3101
+ // If bars are stacked we use the stackedBarValues reference and otherwise base all bars off the zero line
3102
+ // We want backwards compatibility, so the expected fallback without the 'stackMode' option
3103
+ // to be the original behaviour (accumulate)
3104
+ positions["".concat(labelAxis.counterUnits.pos, "1")] = previousStack;
3105
+ positions["".concat(labelAxis.counterUnits.pos, "2")] = stackedBarValues[valueIndex];
3106
+ } else {
3107
+ // Draw from the zero line normally
3108
+ // This is also the same code for Stack mode: overlap
3109
+ positions["".concat(labelAxis.counterUnits.pos, "1")] = zeroPoint;
3110
+ positions["".concat(labelAxis.counterUnits.pos, "2")] = projected[labelAxis.counterUnits.pos];
3111
+ }
3112
+ // Limit x and y so that they are within the chart rect
3113
+ positions.x1 = Math.min(Math.max(positions.x1, chartRect.x1), chartRect.x2);
3114
+ positions.x2 = Math.min(Math.max(positions.x2, chartRect.x1), chartRect.x2);
3115
+ positions.y1 = Math.min(Math.max(positions.y1, chartRect.y2), chartRect.y1);
3116
+ positions.y2 = Math.min(Math.max(positions.y2, chartRect.y2), chartRect.y1);
3117
+ const metaData = getMetaData(series, valueIndex);
3118
+ // Create bar element
3119
+ const bar = seriesElement.elem("line", positions, options.classNames.bar).attr({
3120
+ "ct:value": [
3121
+ safeHasProperty(value, "x") && value.x,
3122
+ safeHasProperty(value, "y") && value.y
3123
+ ].filter(isNumeric).join(","),
3124
+ "ct:meta": serialize(metaData)
3125
+ });
3126
+ this.eventEmitter.emit("draw", {
3127
+ type: "bar",
3128
+ value,
3129
+ index: valueIndex,
3130
+ meta: metaData,
3131
+ series,
3132
+ seriesIndex,
3133
+ axisX,
3134
+ axisY,
3135
+ chartRect,
3136
+ group: seriesElement,
3137
+ element: bar,
3138
+ ...positions
3139
+ });
3140
+ });
3141
+ });
3142
+ this.eventEmitter.emit("created", {
3143
+ chartRect,
3144
+ axisX,
3145
+ axisY,
3146
+ svg,
3147
+ options
3148
+ });
3149
+ }
3150
+ /**
3151
+ * This method creates a new bar chart and returns API object that you can use for later changes.
3152
+ * @param query A selector query string or directly a DOM element
3153
+ * @param data The data object that needs to consist of a labels and a series array
3154
+ * @param options The options object with options that override the default options. Check the examples for a detailed list.
3155
+ * @param responsiveOptions Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
3156
+ * @return An object which exposes the API for the created chart
3157
+ *
3158
+ * @example
3159
+ * // Create a simple bar chart
3160
+ * const data = {
3161
+ * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
3162
+ * series: [
3163
+ * [5, 2, 4, 2, 0]
3164
+ * ]
3165
+ * };
3166
+ *
3167
+ * // 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.
3168
+ * new BarChart('.ct-chart', data);
3169
+ *
3170
+ * @example
3171
+ * // This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10
3172
+ * new BarChart('.ct-chart', {
3173
+ * labels: [1, 2, 3, 4, 5, 6, 7],
3174
+ * series: [
3175
+ * [1, 3, 2, -5, -3, 1, -6],
3176
+ * [-5, -2, -4, -1, 2, -3, 1]
3177
+ * ]
3178
+ * }, {
3179
+ * seriesBarDistance: 12,
3180
+ * low: -10,
3181
+ * high: 10
3182
+ * });
3183
+ *
3184
+ */ constructor(query, data, options, responsiveOptions){
3185
+ super(query, data, defaultOptions$1, extend({}, defaultOptions$1, options), responsiveOptions);
3186
+ this.data = data;
3187
+ }
3188
+ }
3189
+
3190
+ /**
3191
+ * Default options in line charts. Expand the code view to see a detailed list of options with comments.
3192
+ */ const defaultOptions = {
3193
+ // Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
3194
+ width: undefined,
3195
+ // Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
3196
+ height: undefined,
3197
+ // 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}
3198
+ chartPadding: 5,
3199
+ // Override the class names that are used to generate the SVG structure of the chart
3200
+ classNames: {
3201
+ chartPie: "ct-chart-pie",
3202
+ chartDonut: "ct-chart-donut",
3203
+ series: "ct-series",
3204
+ slicePie: "ct-slice-pie",
3205
+ sliceDonut: "ct-slice-donut",
3206
+ label: "ct-label"
3207
+ },
3208
+ // The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise.
3209
+ startAngle: 0,
3210
+ // 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.
3211
+ total: undefined,
3212
+ // If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices.
3213
+ donut: false,
3214
+ // Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future.
3215
+ // This option can be set as number or string to specify a relative width (i.e. 100 or '30%').
3216
+ donutWidth: 60,
3217
+ // If a label should be shown or not
3218
+ showLabel: true,
3219
+ // 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.
3220
+ labelOffset: 0,
3221
+ // 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.
3222
+ labelPosition: "inside",
3223
+ // An interpolation function for the label value
3224
+ labelInterpolationFnc: noop,
3225
+ // 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.
3226
+ labelDirection: "neutral",
3227
+ // If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
3228
+ reverseData: false,
3229
+ // If true empty values will be ignored to avoid drawing unnecessary slices and labels
3230
+ ignoreEmptyValues: false
3231
+ };
3232
+ /**
3233
+ * Determines SVG anchor position based on direction and center parameter
3234
+ */ function determineAnchorPosition(center, label, direction) {
3235
+ const toTheRight = label.x > center.x;
3236
+ if (toTheRight && direction === "explode" || !toTheRight && direction === "implode") {
3237
+ return "start";
3238
+ } else if (toTheRight && direction === "implode" || !toTheRight && direction === "explode") {
3239
+ return "end";
3240
+ } else {
3241
+ return "middle";
3242
+ }
3243
+ }
3244
+ class PieChart extends BaseChart {
3245
+ /**
3246
+ * Creates the pie chart
3247
+ *
3248
+ * @param options
3249
+ */ createChart(options) {
3250
+ const { data } = this;
3251
+ const normalizedData = normalizeData(data);
3252
+ const seriesGroups = [];
3253
+ let labelsGroup;
3254
+ let labelRadius;
3255
+ let startAngle = options.startAngle;
3256
+ // Create SVG.js draw
3257
+ const svg = createSvg(this.container, options.width, options.height, options.donut ? options.classNames.chartDonut : options.classNames.chartPie);
3258
+ this.svg = svg;
3259
+ // Calculate charting rect
3260
+ const chartRect = createChartRect(svg, options);
3261
+ // Get biggest circle radius possible within chartRect
3262
+ let radius = Math.min(chartRect.width() / 2, chartRect.height() / 2);
3263
+ // Calculate total of all series to get reference value or use total reference from optional options
3264
+ const totalDataSum = options.total || normalizedData.series.reduce(sum, 0);
3265
+ const donutWidth = quantity(options.donutWidth);
3266
+ if (donutWidth.unit === "%") {
3267
+ donutWidth.value *= radius / 100;
3268
+ }
3269
+ // If this is a donut chart we need to adjust our radius to enable strokes to be drawn inside
3270
+ // Unfortunately this is not possible with the current SVG Spec
3271
+ // See this proposal for more details: http://lists.w3.org/Archives/Public/www-svg/2003Oct/0000.html
3272
+ radius -= options.donut ? donutWidth.value / 2 : 0;
3273
+ // If labelPosition is set to `outside` or a donut chart is drawn then the label position is at the radius,
3274
+ // if regular pie chart it's half of the radius
3275
+ if (options.labelPosition === "outside" || options.donut) {
3276
+ labelRadius = radius;
3277
+ } else if (options.labelPosition === "center") {
3278
+ // If labelPosition is center we start with 0 and will later wait for the labelOffset
3279
+ labelRadius = 0;
3280
+ } else {
3281
+ // Default option is 'inside' where we use half the radius so the label will be placed in the center of the pie
3282
+ // slice
3283
+ labelRadius = radius / 2;
3284
+ }
3285
+ // Add the offset to the labelRadius where a negative offset means closed to the center of the chart
3286
+ if (options.labelOffset) {
3287
+ labelRadius += options.labelOffset;
3288
+ }
3289
+ // Calculate end angle based on total sum and current data value and offset with padding
3290
+ const center = {
3291
+ x: chartRect.x1 + chartRect.width() / 2,
3292
+ y: chartRect.y2 + chartRect.height() / 2
3293
+ };
3294
+ // Check if there is only one non-zero value in the series array.
3295
+ const hasSingleValInSeries = data.series.filter((val)=>safeHasProperty(val, "value") ? val.value !== 0 : val !== 0
3296
+ ).length === 1;
3297
+ // Creating the series groups
3298
+ data.series.forEach((_, index)=>seriesGroups[index] = svg.elem("g")
3299
+ );
3300
+ // if we need to show labels we create the label group now
3301
+ if (options.showLabel) {
3302
+ labelsGroup = svg.elem("g");
3303
+ }
3304
+ // Draw the series
3305
+ // initialize series groups
3306
+ data.series.forEach((series, index)=>{
3307
+ var ref, ref1;
3308
+ // If current value is zero and we are ignoring empty values then skip to next value
3309
+ if (normalizedData.series[index] === 0 && options.ignoreEmptyValues) {
3310
+ return;
3311
+ }
3312
+ const seriesName = safeHasProperty(series, "name") && series.name;
3313
+ const seriesClassName = safeHasProperty(series, "className") && series.className;
3314
+ const seriesMeta = safeHasProperty(series, "meta") ? series.meta : undefined;
3315
+ // If the series is an object and contains a name or meta data we add a custom attribute
3316
+ if (seriesName) {
3317
+ seriesGroups[index].attr({
3318
+ "ct:series-name": seriesName
3319
+ });
3320
+ }
3321
+ // Use series class from series data or if not set generate one
3322
+ seriesGroups[index].addClass([
3323
+ (ref = options.classNames) === null || ref === void 0 ? void 0 : ref.series,
3324
+ seriesClassName || "".concat((ref1 = options.classNames) === null || ref1 === void 0 ? void 0 : ref1.series, "-").concat(alphaNumerate(index))
3325
+ ].join(" "));
3326
+ // If the whole dataset is 0 endAngle should be zero. Can't divide by 0.
3327
+ let endAngle = totalDataSum > 0 ? startAngle + normalizedData.series[index] / totalDataSum * 360 : 0;
3328
+ // Use slight offset so there are no transparent hairline issues
3329
+ const overlappigStartAngle = Math.max(0, startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2));
3330
+ // If we need to draw the arc for all 360 degrees we need to add a hack where we close the circle
3331
+ // with Z and use 359.99 degrees
3332
+ if (endAngle - overlappigStartAngle >= 359.99) {
3333
+ endAngle = overlappigStartAngle + 359.99;
3334
+ }
3335
+ const start = polarToCartesian(center.x, center.y, radius, overlappigStartAngle);
3336
+ const end = polarToCartesian(center.x, center.y, radius, endAngle);
3337
+ // 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
3338
+ const path = new SvgPath(!options.donut).move(end.x, end.y).arc(radius, radius, 0, Number(endAngle - startAngle > 180), 0, start.x, start.y);
3339
+ // If regular pie chart (no donut) we add a line to the center of the circle for completing the pie
3340
+ if (!options.donut) {
3341
+ path.line(center.x, center.y);
3342
+ }
3343
+ // Create the SVG path
3344
+ // If this is a donut chart we add the donut class, otherwise just a regular slice
3345
+ const pathElement = seriesGroups[index].elem("path", {
3346
+ d: path.stringify()
3347
+ }, options.donut ? options.classNames.sliceDonut : options.classNames.slicePie);
3348
+ // Adding the pie series value to the path
3349
+ pathElement.attr({
3350
+ "ct:value": normalizedData.series[index],
3351
+ "ct:meta": serialize(seriesMeta)
3352
+ });
3353
+ // If this is a donut, we add the stroke-width as style attribute
3354
+ if (options.donut) {
3355
+ pathElement.attr({
3356
+ style: "stroke-width: " + donutWidth.value + "px"
3357
+ });
3358
+ }
3359
+ // Fire off draw event
3360
+ this.eventEmitter.emit("draw", {
3361
+ type: "slice",
3362
+ value: normalizedData.series[index],
3363
+ totalDataSum: totalDataSum,
3364
+ index,
3365
+ meta: seriesMeta,
3366
+ series,
3367
+ group: seriesGroups[index],
3368
+ element: pathElement,
3369
+ path: path.clone(),
3370
+ center,
3371
+ radius,
3372
+ startAngle,
3373
+ endAngle,
3374
+ chartRect
3375
+ });
3376
+ // If we need to show labels we need to add the label for this slice now
3377
+ if (options.showLabel) {
3378
+ let labelPosition;
3379
+ if (data.series.length === 1) {
3380
+ // If we have only 1 series, we can position the label in the center of the pie
3381
+ labelPosition = {
3382
+ x: center.x,
3383
+ y: center.y
3384
+ };
3385
+ } else {
3386
+ // Position at the labelRadius distance from center and between start and end angle
3387
+ labelPosition = polarToCartesian(center.x, center.y, labelRadius, startAngle + (endAngle - startAngle) / 2);
3388
+ }
3389
+ let rawValue;
3390
+ if (normalizedData.labels && !isFalseyButZero(normalizedData.labels[index])) {
3391
+ rawValue = normalizedData.labels[index];
3392
+ } else {
3393
+ rawValue = normalizedData.series[index];
3394
+ }
3395
+ const interpolatedValue = options.labelInterpolationFnc(rawValue, index);
3396
+ if (interpolatedValue || interpolatedValue === 0) {
3397
+ const labelElement = labelsGroup.elem("text", {
3398
+ dx: labelPosition.x,
3399
+ dy: labelPosition.y,
3400
+ "text-anchor": determineAnchorPosition(center, labelPosition, options.labelDirection)
3401
+ }, options.classNames.label).text(String(interpolatedValue));
3402
+ // Fire off draw event
3403
+ this.eventEmitter.emit("draw", {
3404
+ type: "label",
3405
+ index,
3406
+ group: labelsGroup,
3407
+ element: labelElement,
3408
+ text: "" + interpolatedValue,
3409
+ chartRect,
3410
+ series,
3411
+ meta: seriesMeta,
3412
+ ...labelPosition
3413
+ });
3414
+ }
3415
+ }
3416
+ // Set next startAngle to current endAngle.
3417
+ // (except for last slice)
3418
+ startAngle = endAngle;
3419
+ });
3420
+ this.eventEmitter.emit("created", {
3421
+ chartRect,
3422
+ svg: svg,
3423
+ options
3424
+ });
3425
+ }
3426
+ /**
3427
+ * This method creates a new pie chart and returns an object that can be used to redraw the chart.
3428
+ * @param query A selector query string or directly a DOM element
3429
+ * @param 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.
3430
+ * @param options The options object with options that override the default options. Check the examples for a detailed list.
3431
+ * @param responsiveOptions Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]]
3432
+ *
3433
+ * @example
3434
+ * // Simple pie chart example with four series
3435
+ * new PieChart('.ct-chart', {
3436
+ * series: [10, 2, 4, 3]
3437
+ * });
3438
+ *
3439
+ * @example
3440
+ * // Drawing a donut chart
3441
+ * new PieChart('.ct-chart', {
3442
+ * series: [10, 2, 4, 3]
3443
+ * }, {
3444
+ * donut: true
3445
+ * });
3446
+ *
3447
+ * @example
3448
+ * // Using donut, startAngle and total to draw a gauge chart
3449
+ * new PieChart('.ct-chart', {
3450
+ * series: [20, 10, 30, 40]
3451
+ * }, {
3452
+ * donut: true,
3453
+ * donutWidth: 20,
3454
+ * startAngle: 270,
3455
+ * total: 200
3456
+ * });
3457
+ *
3458
+ * @example
3459
+ * // Drawing a pie chart with padding and labels that are outside the pie
3460
+ * new PieChart('.ct-chart', {
3461
+ * series: [20, 10, 30, 40]
3462
+ * }, {
3463
+ * chartPadding: 30,
3464
+ * labelOffset: 50,
3465
+ * labelDirection: 'explode'
3466
+ * });
3467
+ *
3468
+ * @example
3469
+ * // Overriding the class names for individual series as well as a name and meta data.
3470
+ * // The name will be written as ct:series-name attribute and the meta data will be serialized and written
3471
+ * // to a ct:meta attribute.
3472
+ * new PieChart('.ct-chart', {
3473
+ * series: [{
3474
+ * value: 20,
3475
+ * name: 'Series 1',
3476
+ * className: 'my-custom-class-one',
3477
+ * meta: 'Meta One'
3478
+ * }, {
3479
+ * value: 10,
3480
+ * name: 'Series 2',
3481
+ * className: 'my-custom-class-two',
3482
+ * meta: 'Meta Two'
3483
+ * }, {
3484
+ * value: 70,
3485
+ * name: 'Series 3',
3486
+ * className: 'my-custom-class-three',
3487
+ * meta: 'Meta Three'
3488
+ * }]
3489
+ * });
3490
+ */ constructor(query, data, options, responsiveOptions){
3491
+ super(query, data, defaultOptions, extend({}, defaultOptions, options), responsiveOptions);
3492
+ this.data = data;
3493
+ }
3494
+ }
3495
+
3496
+ export { AutoScaleAxis, Axis, BarChart, BaseChart, EPSILON, EventEmitter, FixedScaleAxis, index as Interpolation, LineChart, PieChart, StepAxis, Svg, SvgList, SvgPath, alphaNumerate, axisUnits, createChartRect, createGrid, createGridBackground, createLabel, createSvg, deserialize, determineAnchorPosition, easings, ensureUnit, escapingMap, extend, getBounds, getHighLow, getMetaData, getMultiValue, getNumberOrUndefined, getSeriesOption, isArrayOfArrays, isArrayOfSeries, isDataHoleValue, isFalseyButZero, isMultiValue, isNumeric, namespaces, noop, normalizeData, normalizePadding, optionsProvider, orderOfMagnitude, polarToCartesian, precision, projectLength, quantity, rho, roundWithPrecision, safeHasProperty, serialMap, serialize, splitIntoSegments, sum, times };
3497
+ //# sourceMappingURL=index.js.map