Repository navigation
Expand file tree
/
Copy pathchart.js
More file actions
1176 lines (1005 loc) · 38.4 KB
/
Copy pathchart.js
File metadata and controls
1176 lines (1005 loc) · 38.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @import { ChartData, NormalizedChartData, NormalizedChartDataset } from './data.js'; */
/** @import { ChartMark } from './layers/layer.js'; */
/** @import { LegendItem } from './layers/legend.js'; */
import BarChart from './charts/bar.js';
import LineChart from './charts/line.js';
import PieChart from './charts/pie.js';
import PolarAreaChart from './charts/polar-area.js';
import RadarChart from './charts/radar.js';
import { formatValue, normalizeData } from './data.js';
import { ease } from './easing.js';
import Grid from './layers/grid.js';
import LabelsR from './layers/labels-r.js';
import LabelsX from './layers/labels-x.js';
import LabelsY from './layers/labels-y.js';
import Layer from './layers/layer.js';
import Legend from './layers/legend.js';
import RadialGrid from './layers/radial-grid.js';
import Title from './layers/title.js';
import Tooltip from './layers/tooltip.js';
import { freezeOptions, mergeOptions, normalizeOptions } from './options.js';
import Rect from './rect.js';
import { createScale } from './scale.js';
/**
* @typedef {object} ChartFont
* @property {string} [family='"Helvetica Neue", Helvetica, Arial, sans-serif'] The CSS font family.
* @property {number} [size=12] The font size in CSS pixels.
* @property {string|number} [weight='normal'] The CSS font weight.
* @property {string} [style='normal'] The CSS font style.
* @property {number} [lineHeight=1.2] The line height as a multiple of the font size.
*/
/**
* @typedef {object} ChartTitleOptions
* @property {boolean} [display=true] Whether to show the title.
* @property {string} [text='Title'] The title text.
* @property {'top'|'right'|'bottom'|'left'} [position='top'] The title edge.
* @property {'start'|'center'|'end'|'left'|'right'} [align='center'] Alignment along the edge.
* @property {number} [padding=10] Space between the title and the chart.
* @property {ChartFont} [font] Font overrides; defaults to size 18 and bold weight.
* @property {string} [color='#334155'] The text color.
*/
/**
* @typedef {object} ChartLegendLabelOptions
* @property {number} [boxWidth=20] The swatch width in CSS pixels.
* @property {number} [boxHeight=12] The swatch height in CSS pixels.
* @property {number} [padding=10] Space around legend items.
* @property {ChartFont} [font] Overrides for the inherited chart font.
* @property {string} [color='#334155'] The text color.
* @property {'start'|'center'|'end'|'left'|'right'} [textAlign='start'] The label alignment.
*/
/**
* @typedef {object} ChartLegendOptions
* @property {boolean} [display=true] Whether to show the legend.
* @property {boolean} [interactive=true] Whether legend items toggle data visibility.
* @property {'top'|'right'|'bottom'|'left'} [position='top'] The legend edge.
* @property {'start'|'center'|'end'|'left'|'right'} [align='center'] Alignment along the edge.
* @property {number|null} [maxWidth=null] The maximum width in CSS pixels, or no explicit limit.
* @property {number|null} [maxHeight=null] The maximum height in CSS pixels, or no explicit limit.
* @property {ChartLegendLabelOptions} [labels] Legend swatches and text.
*/
/**
* @callback ChartTickCallback
* @param {string|number} value The category label or scale value.
* @param {number} index The tick index.
* @returns {string|number} The formatted label.
*/
/**
* @typedef {object} ChartGridOptions
* @property {boolean} [display=true] Whether to show grid lines.
* @property {boolean} [drawBorder=true] Whether to draw the axis border.
* @property {string} [borderColor='#cbd5e1'] The axis border color.
* @property {number} [borderWidth=1] The axis border width.
* @property {string} [lineColor='#e2e8f0'] The grid line color.
* @property {number} [lineWidth=1] The grid line width.
* @property {number} [tickLength=8] The tick mark length.
*/
/**
* @typedef {object} ChartTickOptions
* @property {boolean} [display=true] Whether to show tick labels.
* @property {boolean} [drawTicks=true] Whether to draw tick marks.
* @property {string} [tickColor] The tick mark color.
* @property {number} [padding=5] The distance between tick marks and labels.
* @property {ChartFont} [font] Overrides for the inherited chart font.
* @property {string} [color='#334155'] The label color.
* @property {ChartTickCallback|null} [callback=null] The label formatter.
*/
/**
* @typedef {object} ChartAxisOptions
* @property {boolean} [display=true] Whether to show the axis.
* @property {ChartGridOptions} [grid] The grid lines and axis border.
* @property {ChartTickOptions} [ticks] The tick labels and marks.
*/
/**
* @typedef {object} ChartRadialLabelOptions
* @property {boolean} [display=true] Whether to show category labels.
* @property {ChartFont} [font] Overrides for the inherited chart font.
* @property {string} [color='#334155'] The label color.
* @property {number} [padding=8] The distance from the outer grid ring.
*/
/**
* @typedef {object} ChartRadialAxisOptions
* @property {boolean} [display=true] Whether to show the radial axis.
* @property {Pick<ChartGridOptions, 'display'|'lineColor'|'lineWidth'>} [grid] The radial grid lines.
* @property {Pick<ChartTickOptions, 'display'|'font'|'color'|'callback'>} [ticks] The scale labels.
* @property {ChartRadialLabelOptions} [labels] The category labels.
*/
/**
* @typedef {object} ChartScaleOptions
* @property {ChartAxisOptions} [x] The horizontal axis.
* @property {ChartAxisOptions} [y] The vertical axis.
* @property {ChartRadialAxisOptions} [r] The polar area and radar axis.
*/
/**
* @typedef {object} ChartAnimationOptions
* @property {number} [duration=300] The duration in milliseconds; zero disables animation.
* @property {'linear'|'easeOutQuad'|'easeInOutQuad'} [easing='easeOutQuad'] The timing curve.
*/
/**
* @typedef {object} ChartLayoutOptions
* @property {number} [padding=20] The outer padding in CSS pixels.
*/
/**
* @typedef {object} ChartTooltipOptions
* @property {boolean} [display=true] Whether to show tooltips.
* @property {'cursor'|'fixed'} [position='fixed'] Anchor to the data mark or follow the pointer.
* @property {number} [padding=10] The inner padding in CSS pixels.
* @property {number} [borderRadius=6] The corner radius in CSS pixels.
* @property {number} [arrowSize=5] The arrow size; zero hides it.
* @property {string} [backgroundColor='rgba(24, 28, 36, .92)'] The background color.
* @property {string} [color='#fff'] The text color.
* @property {ChartFont} [font] Overrides for the inherited chart font.
*/
/**
* @typedef {object} ChartOptions
* @property {'bar'|'line'|'area'|'pie'|'donut'|'scatter'|'polarArea'|'radar'} [type='bar'] The chart type.
* @property {ChartData} [data] The category labels and datasets.
* @property {'vertical'|'horizontal'} [orientation='vertical'] The bar direction.
* @property {boolean} [stacked=false] Whether bar datasets share a stack.
* @property {ChartFont} [font] The font inherited by chart layers.
* @property {ChartTitleOptions} [title] The title text, position, and appearance.
* @property {ChartLegendOptions} [legend] The legend position, bounds, and labels.
* @property {ChartScaleOptions} [scales] The Cartesian and radial grid and tick settings.
* @property {ChartLayoutOptions} [layout] The outer chart padding.
* @property {ChartAnimationOptions} [animation] The animation duration and easing curve.
* @property {number} [cutout=.6] The donut's inner radius as a fraction of its outer radius.
* @property {ChartTooltipOptions} [tooltip] The tooltip visibility, font, and colors.
* @property {boolean} [responsive=true] Whether to observe container size changes.
* @property {string} [ariaLabel='Chart'] The accessible chart description prefix.
*/
/**
* Composes canvas layers to render Cartesian and circular charts.
*/
export default class Chart {
static Area = LineChart;
static Bar = BarChart;
/** @type {ChartOptions} */
static defaults = {
type: 'bar',
orientation: 'vertical',
stacked: false,
data: {
labels: [],
datasets: [],
},
animation: {
duration: 300,
easing: 'easeOutQuad',
},
cutout: .6,
responsive: true,
ariaLabel: 'Chart',
tooltip: {
display: true,
padding: 10,
borderRadius: 6,
arrowSize: 5,
position: 'fixed',
backgroundColor: 'rgba(24, 28, 36, .92)',
color: '#fff',
font: {},
},
font: {
family: '"Helvetica Neue", Helvetica, Arial, sans-serif',
size: 12,
weight: 'normal',
lineHeight: 1.2,
},
title: {
display: true,
text: 'Title',
padding: 10,
font: {
size: 18,
weight: 'bold',
},
color: '#334155',
position: 'top',
align: 'center',
},
legend: {
display: true,
interactive: true,
position: 'top',
align: 'center',
maxHeight: null,
maxWidth: null,
labels: {
boxWidth: 20,
boxHeight: 12,
font: {},
padding: 10,
color: '#334155',
textAlign: 'start',
},
},
scales: {
r: {
display: true,
grid: {
display: true,
lineColor: '#e2e8f0',
lineWidth: 1,
},
ticks: {
display: true,
font: {},
color: '#334155',
callback: null,
},
labels: {
display: true,
font: {},
color: '#334155',
padding: 8,
},
},
x: {
display: true,
grid: {
display: true,
drawBorder: true,
borderColor: '#cbd5e1',
borderWidth: 1,
lineColor: '#e2e8f0',
lineWidth: 1,
tickLength: 8,
},
ticks: {
display: true,
font: {},
padding: 5,
color: '#334155',
callback: null,
drawTicks: true,
},
},
y: {
display: true,
grid: {
display: true,
drawBorder: true,
borderColor: '#cbd5e1',
borderWidth: 1,
lineColor: '#e2e8f0',
lineWidth: 1,
tickLength: 8,
},
ticks: {
display: true,
font: {},
padding: 5,
color: '#334155',
callback: null,
drawTicks: true,
},
},
},
layout: {
padding: 20,
},
};
static Donut = PieChart;
static Grid = Grid;
static Layer = Layer;
static Legend = Legend;
static Line = LineChart;
static Pie = PieChart;
static PolarArea = PolarAreaChart;
static Radar = RadarChart;
static Rect = Rect;
static Scatter = LineChart;
static Title = Title;
static Tooltip = Tooltip;
static #instances = new WeakMap();
#canvas = null;
#context = null;
#data = null;
#eventsController = null;
#frame = null;
#height = 0;
#hiddenDatasets = new Set();
#hiddenItems = new Set();
#inputOptions = null;
#layers = {};
#legendControls = null;
#node = null;
#observer = null;
#options = null;
#outerRect = null;
#pixelRatio = 1;
#pointer = null;
#progress = 1;
#scale = [0, 1];
#scaleX = [0, 1];
#settings = null;
#width = 0;
#window = null;
/**
* Gets the existing chart for a container or creates one.
* @param {HTMLElement} node The chart container.
* @param {ChartOptions} [options] The options for a new chart.
* @returns {Chart} The existing or newly created chart.
* @throws {TypeError} When the container, chart type, or data format is invalid.
* @throws {RangeError} When data counts, signs, or stack totals are invalid.
* @throws {Error} When a canvas 2D context is unavailable.
*/
static init(node, options) {
return Chart.#instances.get(node) || new this(node, options);
}
/**
* Creates a Chart in an HTML container.
* @param {HTMLElement} node The chart container.
* @param {ChartOptions} [options] The chart options.
* @throws {TypeError} When the container, chart type, or data format is invalid.
* @throws {RangeError} When data counts, signs, or stack totals are invalid.
* @throws {Error} When the container already has a chart or a canvas 2D context is unavailable.
*/
constructor(node, options) {
const view = node?.ownerDocument?.defaultView;
if (!view || !(node instanceof view.HTMLElement) || node.matches('canvas, input, img')) {
throw new TypeError('Chart must be created on an HTML container element.');
}
if (Chart.#instances.has(node)) {
throw new Error('This container already has a chart. Use Chart.init() to reuse it.');
}
this.#node = node;
this.#window = view;
try {
const { data, ...inputOptions } = mergeOptions(this.constructor.defaults, options);
this.#inputOptions = inputOptions;
this.#settings = normalizeOptions(mergeOptions(inputOptions), this.constructor.defaults);
this.#data = normalizeData(data, this.#settings.type, this.#settings.stacked);
this.#updateOptions();
this.#canvas = node.ownerDocument.createElement('canvas');
this.#canvas.setAttribute('role', 'img');
this.#canvas.style.display = 'block';
this.#canvas.style.maxWidth = '100%';
this.#context = this.#canvas.getContext('2d');
if (!this.#context) {
throw new Error('Chart requires a canvas 2D context.');
}
this.node.append(this.#canvas);
this.#build();
this.#events();
this.#resize();
this.update();
Chart.#instances.set(node, this);
} catch (error) {
this.dispose();
throw error;
}
}
/**
* Gets the chart container.
* @returns {HTMLElement|null} The container, or null after disposal.
*/
get node() {
return this.#node;
}
/**
* Gets the options snapshot with copied arrays and plain objects frozen.
* @returns {Readonly<ChartOptions & {data: NormalizedChartData}>|null} The options, or null after disposal.
*/
get options() {
return this.#options;
}
/**
* Gets the bounds shared by the chart's layout layers.
* @returns {Rect} A copy of the outer rectangle.
*/
get outerRect() {
return this.#outerRect.clone();
}
/**
* Gets the backing resolution used by the chart and its layers.
* @returns {number} The device pixel ratio.
*/
get pixelRatio() {
return this.#pixelRatio;
}
/**
* Calculates layer bounds and data geometry using the current dimensions.
*/
calculate() {
if (!this.node) {
return;
}
const padding = Math.min(this.#settings.layout.padding, this.#width / 2, this.#height / 2);
const horizontal = this.#settings.type === 'bar' && this.#settings.orientation === 'horizontal';
const scaleSize = horizontal ? this.#width : this.#height;
const tickSize = this.#settings.font.size * (horizontal ? 5 : 2.5);
const radial = ['radar', 'polarArea'].includes(this.#settings.type);
const maxSteps = radial ? 5 : Math.floor(scaleSize / tickSize);
this.#outerRect = new Rect(
padding,
padding,
Math.max(0, this.#width - padding * 2),
Math.max(0, this.#height - padding * 2),
);
const values = this.#settings.type === 'bar' && this.#settings.stacked ?
this.#getStackTotals() :
this.getValues();
this.#scale = createScale(values, maxSteps);
this.#scaleX = horizontal ? this.#scale : [0, 1];
if (this.#settings.type === 'scatter') {
const maxStepsX = Math.floor(this.#width / (this.#settings.font.size * 5));
this.#scaleX = createScale(this.getValues('x'), maxStepsX);
}
const layers = Object.values(this.#layers);
const chartRect = this.#outerRect.clone();
const next = (rect) => {
const layer = layers.shift();
if (layer) {
layer.calculate(rect, next);
}
};
next(chartRect);
for (const layer of Object.values(this.#layers)) {
layer.calculateCanvas();
layer.update();
}
this.#layers.chart.data();
}
/**
* Releases animation frames, observers, generated markup, and registration.
*/
dispose() {
if (!this.node) {
return;
}
this.#stop();
this.#eventsController?.abort();
this.#observer?.disconnect();
this.#canvas?.remove();
this.#legendControls?.remove();
Chart.#instances.delete(this.#node);
this.#canvas = null;
this.#context = null;
this.#data = null;
this.#eventsController = null;
this.#inputOptions = null;
this.#legendControls = null;
this.#layers = {};
this.#node = null;
this.#observer = null;
this.#options = null;
this.#settings = null;
this.#window = null;
}
/**
* Composites the rendered layers onto the visible canvas.
*/
draw() {
if (!this.node) {
return;
}
this.#context.clearRect(0, 0, this.#canvas.width / this.#pixelRatio, this.#canvas.height / this.#pixelRatio);
for (const layer of Object.values(this.#layers)) {
layer.draw(this.#context);
}
}
/**
* Gets independent copies of the normalized datasets.
* @returns {NormalizedChartDataset[]} The datasets.
*/
getData() {
return this.#data ? this.#data.datasets.map((dataset) => mergeOptions(dataset)) : [];
}
/**
* Gets a copy of the category labels.
* @returns {string[]} The labels.
*/
getLabels() {
return this.#data ? [...this.#data.labels] : [];
}
/**
* Gets a copy of the calculated numeric scale.
* @param {string} [axis='y'] The numeric axis; x is used by scatter charts.
* @returns {number[]} The scale ticks.
*/
getScale(axis = 'y') {
return [...(axis === 'x' ? this.#scaleX : this.#scale)];
}
/**
* Gets the upper scale boundary.
* @param {string} [axis='y'] The numeric axis.
* @returns {number} The maximum tick value.
*/
getScaleMax(axis = 'y') {
return (axis === 'x' ? this.#scaleX : this.#scale).at(-1);
}
/**
* Gets the lower scale boundary.
* @param {string} [axis='y'] The numeric axis.
* @returns {number} The minimum tick value.
*/
getScaleMin(axis = 'y') {
return (axis === 'x' ? this.#scaleX : this.#scale)[0];
}
/**
* Gets the numeric values from visible datasets and data items.
* @param {string} [axis='y'] The coordinate to read for scatter data.
* @returns {number[]} The dataset values.
*/
getValues(axis = 'y') {
if (!this.#data) {
return [];
}
const circular = ['pie', 'donut', 'polarArea'].includes(this.#settings.type);
const scatter = this.#settings.type === 'scatter';
const values = [];
for (const [datasetIndex, dataset] of this.#data.datasets.entries()) {
if (!this.isDatasetVisible(datasetIndex)) {
continue;
}
for (const [index, value] of dataset.data.entries()) {
if (circular && this.#hiddenItems.has(`${datasetIndex}:${index}`)) {
continue;
}
values.push(scatter ? value[axis] : value);
}
}
return values;
}
/**
* Checks whether a dataset is enabled.
* @param {number} index The dataset index.
* @returns {boolean} Whether the dataset is visible.
*/
isDatasetVisible(index) {
return Boolean(this.#data?.datasets[index]) && !this.#hiddenDatasets.has(index);
}
/**
* Checks whether a data item and its dataset are enabled.
* @param {number} datasetIndex The dataset index.
* @param {number} index The item index.
* @returns {boolean} Whether the item is visible.
*/
isDataVisible(datasetIndex, index) {
const circular = ['pie', 'donut', 'polarArea'].includes(this.#settings?.type);
const exists = this.#data?.datasets[datasetIndex]?.data[index] != null;
return exists && this.isDatasetVisible(datasetIndex) && (!circular || !this.#hiddenItems.has(`${datasetIndex}:${index}`));
}
/**
* Renders the layers at their final positions without starting an animation.
*/
render() {
if (!this.node) {
return;
}
this.#render(1);
}
/**
* Measures the container and updates the visible and offscreen canvases.
*/
resize() {
if (!this.node || !this.#resize()) {
return;
}
this.calculate();
this.render();
}
/**
* Animates the chart layer using elapsed time and a single pending frame.
*/
run() {
if (!this.node) {
return;
}
const reducedMotion = this.#window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const duration = reducedMotion ? 0 : this.#settings.animation.duration;
if (!duration || !this.getValues().length) {
this.render();
return;
}
this.#render(0);
const start = this.#window.performance.now();
const tick = (now) => {
this.#frame = null;
if (!this.node) {
return;
}
const elapsed = now - start;
const progress = Math.min(1, Math.max(0, elapsed / duration));
this.#progress = ease(progress, this.#settings.animation.easing);
this.#layers.chart.render(this.#progress);
if (this.#pointer) {
this.#setActive(this.#layers.chart.hitTest(this.#pointer.x, this.#pointer.y));
} else {
this.draw();
}
if (progress < 1) {
this.#frame = this.#window.requestAnimationFrame(tick);
}
};
this.#frame = this.#window.requestAnimationFrame(tick);
}
/**
* Replaces chart data after validating the entire update.
* @param {ChartData} [data] The new data; defaults to the current data.
* @throws {TypeError} When labels, datasets, values, or colors are invalid.
* @throws {RangeError} When label counts differ, circular or radial values are negative, or stack totals overflow.
*/
setData(data = this.#data) {
if (!this.node) {
return;
}
const normalized = normalizeData(data, this.#settings.type, this.#settings.stacked);
this.#data = normalized;
this.#updateOptions();
this.#pruneVisibility();
this.update();
}
/**
* Shows or hides a dataset without removing its values or changing its color.
* @param {number} index The dataset index.
* @param {boolean} visible Whether to show the dataset.
*/
setDatasetVisibility(index, visible) {
if (!this.#data?.datasets[index]) {
return;
}
if (visible) {
this.#hiddenDatasets.delete(index);
} else {
this.#hiddenDatasets.add(index);
}
this.update();
}
/**
* Shows or hides an individual slice in a circular chart.
* @param {number} datasetIndex The dataset index.
* @param {number} index The item index.
* @param {boolean} visible Whether to show the item.
*/
setDataVisibility(datasetIndex, index, visible) {
if (!['pie', 'donut', 'polarArea'].includes(this.#settings?.type) || this.#data?.datasets[datasetIndex]?.data[index] == null) {
return;
}
const key = `${datasetIndex}:${index}`;
if (visible) {
this.#hiddenItems.delete(key);
} else {
this.#hiddenItems.add(key);
}
this.update();
}
/**
* Merges changed settings and rebuilds the affected layers.
* @param {ChartOptions} [settings={}] The changed settings.
* @throws {TypeError} When the chart type or data format is invalid.
* @throws {RangeError} When the data is invalid for the new chart type or stacking mode.
*/
setSettings(settings = {}) {
if (!this.node) {
return;
}
const { data: inputData, ...changedSettings } = settings;
const inputOptions = mergeOptions(this.#inputOptions, changedSettings);
const options = normalizeOptions(mergeOptions(inputOptions), this.constructor.defaults);
const data = normalizeData(inputData ?? this.#data, options.type, options.stacked);
this.#stop();
this.#inputOptions = inputOptions;
this.#settings = options;
this.#data = data;
this.#updateOptions();
this.#pruneVisibility();
this.#build();
if (this.#settings.responsive) {
this.#resize();
}
this.update();
}
/**
* Recalculates data, refreshes the layers, and starts the configured animation.
*/
update() {
if (!this.node) {
return;
}
this.calculate();
this.#updateDescription();
this.run();
}
/**
* Creates the title, legend, axes, chart, and tooltip layers in drawing order.
*/
#build() {
this.#layers = {
title: new Title(this, this.#settings.title),
legend: new Legend(this, this.#settings.legend),
};
if (['radar', 'polarArea'].includes(this.#settings.type)) {
this.#layers.grid = new RadialGrid(this, this.#settings.scales.r);
} else if (!['pie', 'donut'].includes(this.#settings.type)) {
this.#layers.ticksX = new LabelsX(this, this.#settings.scales.x.ticks);
this.#layers.ticksY = new LabelsY(this, this.#settings.scales.y.ticks);
this.#layers.grid = new Grid(this, this.#settings.scales);
}
switch (this.#settings.type) {
case 'bar':
this.#layers.chart = new BarChart(this, this.#settings.scales);
break;
case 'line':
case 'area':
case 'scatter':
this.#layers.chart = new LineChart(this, this.#settings.scales);
break;
case 'radar':
this.#layers.chart = new RadarChart(this, this.#settings.scales.r);
break;
case 'polarArea':
this.#layers.chart = new PolarAreaChart(this, this.#settings.scales.r);
break;
case 'pie':
case 'donut':
this.#layers.chart = new PieChart(this, this.#settings.scales);
break;
}
if (['radar', 'polarArea'].includes(this.#settings.type)) {
this.#layers.ticksR = new LabelsR(this, this.#settings.scales.r.ticks);
}
this.#layers.tooltip = new Tooltip(this, this.#settings.tooltip);
}
/**
* Clears pointer state before a data, layout, or settings update.
*/
#clearActive() {
this.#pointer = null;
this.#layers.chart.setActive(null);
this.#layers.tooltip.setActive(null);
this.#canvas.removeAttribute('aria-description');
}
/**
* Registers pointer events and responsive sizing until disposal.
*/
#events() {
this.#eventsController = new this.#window.AbortController();
const { signal } = this.#eventsController;
this.#canvas.addEventListener('pointermove', (event) => {
const point = this.#pointerPosition(event);
if (!point) {
return;
}
this.#pointer = point;
const legend = this.#settings.legend.interactive && this.#layers.legend.hitTest(point.x, point.y);
const item = legend ? null : this.#layers.chart.hitTest(point.x, point.y);
this.#canvas.style.cursor = legend ? 'pointer' : '';
this.#setActive(item);
}, { signal });
this.#canvas.addEventListener('click', (event) => {
const point = this.#pointerPosition(event);
if (point && this.#settings.legend.interactive) {
const item = this.#layers.legend.hitTest(point.x, point.y);
if (item) {
this.#toggleLegendItem(item);
}
}
}, { signal });
this.#canvas.addEventListener('pointerleave', () => {
this.#pointer = null;
this.#canvas.style.cursor = '';
this.#setActive(null);
}, { signal });
this.#window.addEventListener('resize', () => {
if (this.#settings.responsive) {
this.resize();
}
}, { signal });
if (this.#window.ResizeObserver) {
this.#observer = new this.#window.ResizeObserver(() => {
if (this.#settings.responsive) {
this.resize();
}
});
this.#observer.observe(this.node);
}
}
/**
* Calculates positive and negative stack extents independently.
* @returns {number[]} The visible stack totals.
*/
#getStackTotals() {
return this.#data.labels.flatMap((label, index) => {
let positive = 0;
let negative = 0;
for (const [datasetIndex, dataset] of this.#data.datasets.entries()) {
if (!this.isDataVisible(datasetIndex, index)) {
continue;
}
const value = dataset.data[index];
if (value < 0) {
negative += value;
} else {
positive += value;
}
}
return [negative, positive];
});
}
/**
* Converts a pointer event to chart-local CSS coordinates.
* @param {PointerEvent|MouseEvent} event The pointer event.
* @returns {{x: number, y: number}|null} The coordinates, or null for a hidden canvas.
*/
#pointerPosition(event) {
const rect = this.#canvas.getBoundingClientRect();
if (!rect.width || !rect.height) {
return null;
}
return {
x: (event.clientX - rect.left) * this.#width / rect.width,
y: (event.clientY - rect.top) * this.#height / rect.height,
};
}
/**
* Drops visibility state for datasets and items removed by a data update.
*/
#pruneVisibility() {
for (const index of this.#hiddenDatasets) {
if (!this.#data.datasets[index]) {
this.#hiddenDatasets.delete(index);
}
}
for (const key of this.#hiddenItems) {
const [datasetIndex, index] = key.split(':').map(Number);
if (this.#data.datasets[datasetIndex]?.data[index] == null) {
this.#hiddenItems.delete(key);
}
}
}
/**
* Renders every layer at the starting or final animation position.
* @param {number} progress The animation fraction.
*/
#render(progress) {
this.#stop();
this.#clearActive();
this.#progress = progress;
for (const layer of Object.values(this.#layers)) {
layer.render(progress);
}
this.#syncLegendControls();