All files / common si-chart-base.component.ts

37.19% Statements 340/914
34.42% Branches 262/761
33.33% Functions 51/153
37.31% Lines 328/879

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064                                                                                                                          117x                 45x 45x 45x 45x 45x             45x   45x   45x   45x           45x             45x           45x           45x           45x           45x           45x               45x           45x           45x           45x           45x   45x   45x           45x           45x       45x       45x       45x               45x       45x                 45x       45x           45x   45x             45x     45x   45x   45x   45x   45x   45x   45x     45x   45x                           45x 45x 45x 45x 45x 45x 45x 45x 45x     45x   45x 45x   45x     45x 45x   45x 45x 45x 45x 45x 45x   45x               45x 45x                                     45x                       44x     44x 44x 44x 44x                         44x       52x 3x     52x 38x     14x       14x 14x                       14x               14x         14x 14x 14x   14x                 2x               2x 2x 2x       2x     14x   12x 12x     14x                         2x 2x     14x 2x 2x     14x 2x 2x     14x   14x 14x         14x   14x                           14x   14x       14x     14x         14x       44x 44x 44x 44x 44x           44x   44x               44x 44x 44x 44x 44x           44x 44x   44x 44x 44x   44x 44x 44x 44x 44x 44x   44x                             44x   44x 44x 44x                       45x 44x   45x           45x                                                                                                                                                                                                                                                               44x 44x   44x 44x   44x 44x                                                                             46x   46x           46x 46x 46x 46x 46x 46x               22x 12x   10x   10x 10x 10x     10x 10x     10x 10x 10x 10x 10x   10x   10x 10x 10x 10x 10x                                                         10x       10x     10x 10x   10x       10x 7x   10x       7x 7x 7x   7x   7x 7x       7x       7x         7x     7x         17x       191x       191x 191x 191x   191x 367x   191x       191x       59x 59x 59x 59x                                     59x 51x       51x 37x   8x 8x         45x 45x 13x 13x     45x 45x       38x 38x   38x 38x               38x 38x 38x   38x           44x                                                                     38x 38x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         28x                                                                                                                                   58x 58x                                                                                         100x               19x                                                                                                                   37x     37x 37x 37x 37x                                                                         37x 37x 37x 37x         37x       37x 37x 23x     14x 37x 37x       14x 37x   8x     14x     14x 37x           14x               14x 14x 14x                             14x 14x 14x                   14x                 14x                       14x               10x     10x 10x   10x             14x     14x 18x 18x 18x 18x       18x 18x 10x 10x   10x 10x         14x                                                                                                                 17x 17x       17x         17x                                                                                                         17x                                                                                   46x 46x 46x       46x                     1x 1x       1x 1x 1x               1x         1x   1x       1x 1x                     1x       2x 2x                                                                                                                                                                                         8x 8x 8x 8x     8x 8x 8x 1x       8x                                                             81x       81x 81x                                                           81x                                               46x 46x           46x                     46x      
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import {
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  ElementRef,
  inject,
  input,
  model,
  NgZone,
  OnChanges,
  OnDestroy,
  OnInit,
  output,
  signal,
  SimpleChanges,
  viewChild,
  viewChildren
} from '@angular/core';
import {
  CustomLegend,
  CustomLegendItem,
  CustomLegendProps,
  SiCustomLegendComponent
} from '@siemens/charts-ng/custom-legend';
import { SiChartLoadingSpinnerComponent } from '@siemens/charts-ng/loading-spinner';
 
import { echarts } from './echarts.custom';
import {
  DataZoomComponentOption,
  EChartOption,
  EChartSeries,
  GridComponentOption
} from './echarts.model';
import {
  AxisPointerEvent,
  CustomLegendMultiLineInfo,
  DataZoomEvent,
  DataZoomRange,
  FilterMode,
  GridRectCoordinate,
  LegendItem,
  LineColor,
  SelectedLegendItem,
  SeriesSelectionState,
  SeriesUpdate
} from './si-chart.interfaces';
import { themeSupport } from './theme-support';
 
@Component({
  selector: 'si-chart-base',
  imports: [SiCustomLegendComponent, SiChartLoadingSpinnerComponent],
  templateUrl: './si-chart-base.component.html',
  styleUrl: './si-chart-base.component.scss',
  host: {
    '(window:theme-switch)': 'themeSwitch()'
  }
})
export class SiChartBaseComponent implements AfterViewInit, OnChanges, OnInit, OnDestroy {
  /**
   * reference to the wrapper container. Used for setting scroll position, etc.
   *
   * @defaultValue
   * ```
   * viewChild.required<ElementRef>('chartContainerWrapper')
   * ```
   */
  readonly chartContainerWrapper = viewChild.required<ElementRef>('chartContainerWrapper');
  protected readonly chartContainer = viewChild<ElementRef>('chart');
  protected readonly externalZoomSliderContainer = viewChild<ElementRef>('externalZoomSlider');
  protected readonly siCustomLegend = viewChildren('siCustomLegend', {
    read: SiCustomLegendComponent
  });
 
  /**
   * See [ECharts 5.x Documentation]{@link https://echarts.apache.org/en/option.html}
   * for all available options.
   */
  readonly options = input<EChartOption>();
  /** Used to override specific properties set in `options`. */
  readonly additionalOptions = input<EChartOption>();
  /** The title of the chart. */
  readonly title = input<string>();
  /** The subtitle of the chart. */
  readonly subTitle = input<string>();
  /**
   * Show Echarts legend
   *
   * @defaultValue true
   */
  readonly showLegend = model(true);
  /**
   * Enable to show a custom legend.
   * The custom legend offers additional features such as, scroll bar to avoid legend and chart overlapping,
   * Left and right alignment of legends based on y-axis, etc and many more.
   * @defaultValue false
   */
  readonly showCustomLegend = input(false);
  /**
   * the renderer to use: canvas or svg
   *
   * @defaultValue 'canvas'
   */
  readonly renderer = input<'canvas' | 'svg'>('canvas');
  /**
   * Enables the zoom slider below the chart.
   *
   * @defaultValue false
   */
  readonly zoomSlider = input(false);
  /**
   * Shows data shadow in dataZoom slider, use together with `zoomSlider`.
   *
   * @defaultValue true
   */
  readonly zoomSliderShadow = input(true);
  /**
   * realtime update mode for zoom slider
   *
   * @defaultValue true
   */
  readonly zoomSliderRealtime = input(true);
  /**
   * enable brush mode for zoom slider
   *
   * @defaultValue true
   */
  readonly zoomSliderBrush = input(true);
  /**
   * Enables zooming inside the chart with the mouse wheel/touch.
   *
   * Whether zooming inside the chart is possible with mouse.
   *
   * @defaultValue false
   */
  readonly zoomInside = input(false);
  /**
   * Maximum number of series data points shown in the chart.
   *
   * @defaultValue 1000
   */
  readonly maxEntries = input(1000);
  /**
   * No auto dataZoom update) by default. Use together with `autoZoomSeriesIndex`.
   *
   * @defaultValue -1
   */
  readonly visibleEntries = model(-1);
  /**
   * No auto dataZoom update) by default. Use together with `autoZoomSeriesIndex`.
   *
   * @defaultValue -1
   */
  readonly visibleRange = model(-1);
  /**
   * No auto dataZoom update) by default. Use together with `visibleEntries`.
   *
   * @defaultValue -1
   */
  readonly autoZoomSeriesIndex = input(-1);
  /** The desired theme to load. */
  readonly theme = input<any>();
  /** Used to override specific options of loaded `theme`. */
  readonly themeCustomization = input<any>();
  /**
   * The name of the color palette (if any) of the loaded `theme`.
   *
   * @defaultValue undefined
   */
  readonly palette = input<string | undefined>();
  /**
   * Used to display `axisPointer` line either by click or mouse-move.
   *
   * @defaultValue false
   */
  readonly axisPointer = input<(boolean | string) | undefined>(false);
  /**
   * Apply a specific zoom range (see {@link https://echarts.apache.org/en/option.html#dataZoom-inside}).
   */
  readonly dataZoomRange = input<DataZoomRange>();
  /**
   * The lower limit of the data zoom slider (see {@link https://echarts.apache.org/en/option.html#dataZoom-slider.minValueSpan}).
   */
  readonly dataZoomMinValueSpan = input<number>();
  /**
   * The upper limit of the data zoom slider (see {@link https://echarts.apache.org/en/option.html#dataZoom-slider.maxValueSpan}).
   */
  readonly dataZoomMaxValueSpan = input<number>();
  /**
   * The data zoom filter mode. (see {@link https://echarts.apache.org/en/option.html#dataZoom-inside.filterMode})
   *
   * The value 'filter' will cause the lines to be disconnected to the outside of the chart.
   *
   * @defaultValue 'none'
   */
  readonly dataZoomFilterMode = input<FilterMode>('none');
  /**
   * Enable custom legend click actions exposed by the `selectionChanged` event.
   */
  readonly customLegendAction = input<boolean>();
  /**
   * Specify selected legend item.
   *
   * @defaultValue
   * ```
   * { legendItemName: '' }
   * ```
   */
  readonly selectedItem = input<SelectedLegendItem>({ legendItemName: '' });
  /**
   * The height of the ECharts container as decimal.
   */
  readonly eChartContainerHeight = input<string | null>();
  /**
   * Flag to use external zoom slider
   *
   * @defaultValue false
   */
  readonly externalZoomSlider = input(false);
  /** External XAxis Formatter from consumer */
  readonly externalXAxisFormatter = input<(value: any, visibleRange: number) => string>();
  /**
   * If true, add consumer-provided time range bar. Use together with `zoomSlider`.
   * @deprecated The input will be removed in future versions as the time range bar slot is deprecated.
   *
   * @defaultValue false
   */
  readonly showTimeRangeBar = input(false);
 
  /** Event emitted when data zoom changes. */
  readonly dataZoom = output<DataZoomEvent>();
  /** Event emitted when axis pointer moves. */
  readonly pointer = output<AxisPointerEvent>();
  /** Event emitted when selection changes e.g. clicking on a legend item. */
  readonly selectionChanged = output<any>();
  /** Event emitted when a chart series is clicked. */
  readonly chartSeriesClick = output<LegendItem>();
  /** Event emitted when chart grid is resized. */
  readonly chartGridResized = output<GridRectCoordinate>();
  /** Event emitted when custom legend multi-line info changes. */
  readonly customLegendMultiLineInfoEvent = output<CustomLegendMultiLineInfo[]>();
  /** Emitted when data zoom changes, indicating the time range in milliseconds, 0 for full range */
  readonly timeRangeChange = output<number>();
 
  /** Allow to override options specific for a chart type. */
  protected actualOptions: EChartOption = {};
 
  protected customLegend: CustomLegend[] = [
    {
      customLegends: [
        { list: [], unit: '' },
        { list: [], unit: '' }
      ],
      legendAxis: 'both'
    }
  ];
  /** @internal */
  chart!: echarts.ECharts;
  private extZoomSliderChart!: echarts.ECharts;
  private echartElement!: HTMLElement;
  private eChartExtSliderElement!: HTMLElement;
  protected readonly inProgress = signal(false);
  protected readonly backgroundColor = signal('');
  protected readonly textColor = signal('');
  protected readonly titleColor = signal('');
  protected readonly subTitleColor = signal('');
  private selectedSeriesColors: LineColor = {};
  private unselectedSeriesColors: LineColor = {};
  private seriesSelectionState: SeriesSelectionState = {};
  protected readonly containerHeight = signal<number | null>(null);
 
  protected activeTheme: any;
  protected autoZoomUpdate = true;
 
  private prevAxisPointer: any = {};
  private lastValidDataZoom: any = {};
  private presetDataZoomRange?: DataZoomRange;
  private dataZoomSetupDone = false;
  private requestedDataZoom?: DataZoomRange;
  private measureCanvas?: CanvasRenderingContext2D;
  private readonly cdRef = inject(ChangeDetectorRef);
  private readonly ngZone = inject(NgZone);
 
  protected curWidth = 0;
  protected curHeight = 0;
  protected readonly timeBarBottom = signal(50);
  protected readonly timeBarLeft = signal(32);
  protected readonly timeBarRight = signal(32);
  protected readonly timeBarHeight = signal(32);
 
  private gridCoordinates: GridRectCoordinate = {
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    containerWidth: 0,
    containerHeight: 0
  };
  private customLegendsMultiLineInfo: CustomLegendMultiLineInfo[] = [];
  protected extZoomSliderOptions: EChartOption = {
    animation: false,
    dataZoom: [
      { type: 'slider', showDataShadow: false },
      { type: 'inside', showDataShadow: false }
    ],
    grid: [{ left: 32, right: 32, top: 0, height: 0, containLabel: false }],
    xAxis: [{ type: 'time', axisLine: { onZero: true }, zlevel: 1 }],
    yAxis: [{ type: 'value', boundaryGap: [0, '100%'], splitLine: { show: false }, show: false }],
    series: [{ type: 'line', showSymbol: false, lineStyle: { opacity: 0 }, data: [] }]
  };
 
  private readonly echartMouseDown = (): void => this.handleChartMouseDown();
  private readonly echartMouseUp = (event: MouseEvent): void => this.handleChartMouseUp(event);
 
  private readonly echartExtSliderMouseDown = (): void => this.handleExtChartMouseDown();
  private readonly echartExtSliderMouseUp = (event: MouseEvent): void =>
    this.handleExtChartMouseUp(event);
 
  protected readonly shapePaths: Record<string, string> = {
    circle: 'M6 0A6 6 0 1 1 6 12A6 6 0 1 1 6 0Z',
    rect: 'M0 0H12V12H0Z',
    roundRect: 'M2 0H10A2 2 0 0 1 12 2V10A2 2 0 0 1 10 12H2A2 2 0 0 1 0 10V2A2 2 0 0 1 2 0Z',
    triangle: 'M6 0L12 12H0L6 0Z',
    diamond: 'M6 0L12 6L6 12L0 6L6 0Z',
    pin: 'M6.00049 0C8.48577 0 10.5005 2.01472 10.5005 4.5C10.5005 5.51817 10.0175 6.461 9.46826 7.31836C8.42358 8.94924 7.16317 10.4497 6.00049 12C4.83781 10.4497 3.57642 8.94924 2.53174 7.31836C1.98255 6.461 1.49951 5.51817 1.49951 4.5C1.49951 2.01472 3.51521 0 6.00049 0Z'
  };
  /**
   * Allow consuming applications to re-draw chart on window resizes.
   */
  resize(): void {
    Iif (!this.chart) {
      return;
    }
    const rect = this.chartContainer()?.nativeElement.getBoundingClientRect();
    const width = Math.floor(rect.width);
    const height = Math.floor(rect.height);
    Iif (width && height && (width !== this.curWidth || height !== this.curHeight)) {
      this.curWidth = width;
      this.curHeight = height;
 
      this.ngZone.runOutsideAngular(() => {
        this.chart.resize({ width, height: this.containerHeight() ?? height });
        if (this.externalZoomSlider()) {
          this.extZoomSliderChart.resize();
        }
        setTimeout(() => this.checkGridSizeChange());
      });
      this.afterChartResize();
    }
    this.updateCustomLegendMultiLineInfo();
  }
 
  ngOnChanges(changes: SimpleChanges<unknown>): void {
    if (changes.options?.currentValue) {
      this.actualOptions = this.options()!;
    }
 
    if (!this.chart) {
      return;
    }
 
    Iif (changes.eChartContainerHeight) {
      this.setContainerHeight();
    }
 
    const selectedLegendItem = changes.selectedItem;
    Iif (
      selectedLegendItem &&
      !selectedLegendItem.isFirstChange() &&
      selectedLegendItem.currentValue
    ) {
      const event = {
        name: selectedLegendItem.currentValue.legendItemName,
        type: 'legendToggleSelect'
      };
      this.dispatchEChartAction(event);
    }
 
    Iif (
      this.customLegendAction() &&
      changes.options &&
      !changes.options.isFirstChange() &&
      !changes.options.currentValue.color.length
    ) {
      this.actualOptions.color = changes.options.previousValue.color;
    }
    Iif (changes.theme || changes.renderer) {
      // need to completely redo the chart for the theme change to take effect
      return this.resetChart();
    }
 
    let updates = 0;
    let applyAll = false;
    let skipMerge = false;
 
    if (
      changes.forceAll ||
      changes.yAxis ||
      changes.xAxis ||
      changes.options ||
      changes.series ||
      changes.value
    ) {
      // this is to clean the legend item list
      Iif (this.showCustomLegend() && this.customLegend && this.customLegend.length > 0) {
        this.customLegend.forEach(cl => {
          cl.customLegends = [
            { list: [], unit: '' },
            { list: [], unit: '' }
          ];
        });
      }
      this.applyOptions();
      applyAll = true;
      skipMerge =
        changes.series?.previousValue &&
        changes.series.currentValue &&
        changes.series.currentValue.length < changes.series.previousValue.length;
      updates++;
    }
 
    if (!applyAll && (changes.title || changes.subTitle)) {
      // already called when `applyOptions()` has been called
      this.applyTitles();
      updates++;
    }
 
    if (
      applyAll ||
      changes.forceAll ||
      changes.zoomSlider ||
      changes.zoomSliderShadow ||
      changes.zoomSliderRealtime ||
      changes.zoomSliderBrush ||
      changes.zoomInside ||
      changes.axisPointer ||
      changes.autoZoomSeriesIndex ||
      changes.visibleEntries ||
      changes.visibleRange
    ) {
      this.applyDataZoom();
      updates++;
    }
 
    if (applyAll || changes.forceAll || changes.palette || changes.additionalOptions) {
      this.applyAdditionalOptions();
      updates++;
    }
 
    if (applyAll) {
      this.applyStyles();
      setTimeout(() => this.updateCustomLegendMultiLineInfo());
    }
 
    let skipDz = false;
 
    Eif (updates) {
      Iif (changes.dataZoomRange) {
        this.setDataZoomRange(true);
        skipDz = true;
      }
 
      const dz = this.actualOptions.dataZoom!;
      let currentDataZoom: DataZoomComponentOption | undefined;
      Iif (skipMerge && this.hasDataZoom() && this.hasData() && !skipDz) {
        // forced updated is required when adding/removing series, see:
        //   https://github.com/apache/incubator-echarts/issues/6202
        // in order not to mess up current datazoom, save the current value and add it to options
        this.saveCurrentDataZoom();
        if (this.lastValidDataZoom) {
          currentDataZoom = dz[0];
          const newDataZoom: DataZoomComponentOption = {};
          echarts.util.merge(newDataZoom, dz[0], true);
          echarts.util.merge(newDataZoom, this.lastValidDataZoom, true);
          dz[0] = newDataZoom;
        }
      }
 
      this.updateEChart(skipMerge);
 
      Iif (currentDataZoom) {
        dz[0] = currentDataZoom;
        this.updateEChart(false, { dataZoom: this.actualOptions.dataZoom });
      }
      this.applyColorsToCustomLegends();
    }
 
    Iif (!skipDz && changes.dataZoomRange) {
      // this is done after a possible setOptions call to ensure echarts has all the desired states
      this.setDataZoomRange();
    }
 
    this.cdRef.markForCheck();
  }
 
  ngOnInit(): void {
    const canvas = document.createElement('canvas') as HTMLCanvasElement;
    this.measureCanvas = canvas.getContext('2d') as CanvasRenderingContext2D;
    this.measureCanvas.font = '12px "SiemensSans Pro"';
    const externalXAxisFormatter = this.externalXAxisFormatter();
    Iif (this.externalZoomSlider() && externalXAxisFormatter) {
      const consumerFormatter = externalXAxisFormatter;
      this.extZoomSliderOptions.xAxis[0].axisLabel = {
        formatter: (value: any) => consumerFormatter(value, this.visibleRange())
      };
    }
    this.applyTheme();
    // this is to clean the legend item list
    Iif (this.showCustomLegend() && this.customLegend && this.customLegend.length > 0) {
      this.customLegend.forEach(cl => {
        cl.customLegends = [
          { list: [], unit: '' },
          { list: [], unit: '' }
        ];
      });
    }
    this.applyOptions();
    this.applyAdditionalOptions();
    this.applyDataZoom();
    this.applyStyles();
    Iif (this.customLegendAction()) {
      this.fetchSeriesColors();
    }
  }
 
  ngAfterViewInit(skipZoom?: boolean): void {
    this.ngZone.runOutsideAngular(() => {
      const chartContainerEl = this.chartContainer()!.nativeElement;
      // set current dimension to avoid initial resize() call on chart
      const rect = chartContainerEl.getBoundingClientRect();
      this.curWidth = Math.floor(rect.width);
      this.curHeight = Math.floor(rect.height);
 
      const opts = { renderer: this.renderer() };
      this.chart = echarts.init(chartContainerEl, this.activeTheme, opts);
      this.echartElement = chartContainerEl as HTMLElement;
      this.getEChartInner()?.addEventListener('mousedown', this.echartMouseDown);
      this.chart.setOption(this.actualOptions);
      setTimeout(() => this.checkGridSizeChange());
 
      Iif (this.externalZoomSlider()) {
        this.extZoomSliderChart = echarts.init(
          this.externalZoomSliderContainer()!.nativeElement,
          this.activeTheme,
          opts
        );
        this.eChartExtSliderElement = this.externalZoomSliderContainer()!
          .nativeElement as HTMLElement;
        this.getEChartExternalSliderInner()?.addEventListener(
          'mousedown',
          this.echartExtSliderMouseDown
        );
        this.extZoomSliderChart.setOption(this.extZoomSliderOptions);
        this.extZoomSliderChart.on('datazoom', (event: any) => this.handleExtDataZoom(event));
      }
      this.afterChartInit(skipZoom);
    });
    setTimeout(() => {
      this.resize();
      this.applyColorsToCustomLegends();
    });
  }
 
  private calculateTextWidth(text: string): number {
    if (!this.measureCanvas) {
      return 150;
    }
    return Math.ceil(this.measureCanvas.measureText(text).width);
  }
 
  private disposeChart(): void {
    if (this.chart && !this.chart.isDisposed()) {
      this.chart.dispose();
    }
    Iif (this.extZoomSliderChart && !this.extZoomSliderChart.isDisposed()) {
      this.extZoomSliderChart.dispose();
    }
  }
 
  ngOnDestroy(): void {
    this.disposeChart();
  }
 
  /**
   * Switch theme using echarts api, which does not need reloading the whole chart.
   */
  themeSwitch(): void {
    if (!this.chart) {
      return;
    }
 
    this.applyTheme();
    this.chart.setTheme(this.activeTheme);
 
    // Since color palette is set thorugh options, it needs to be set again.
    this.themeChanged();
    this.applyPalette();
    this.applyStyles();
    this.applyTitles();
 
    setTimeout(() => {
      this.applyColorsToCustomLegends();
    });
    this.chart.setOption(this.actualOptions);
 
    if (this.externalZoomSlider()) {
      this.extZoomSliderChart.setTheme(this.activeTheme);
      this.extZoomSliderChart.setOption(this.extZoomSliderOptions);
    }
    this.cdRef.markForCheck();
  }
 
  /**
   * Re-render the whole chart.
   * @deprecated The method is deprecated and should not be used directly by the consumer.
   */
  resetChart(): void {
    this.applyTheme();
 
    if (!this.actualOptions) {
      // this can happen if the SiThemeService fires the theme switch when the chart is not
      // yet completely initialized
      return;
    }
 
    this.disposeChart();
    this.applyPalette();
    const addOpts = this.additionalOptions();
    if (addOpts?.palette) {
      echarts.util.merge(this.actualOptions.palette, addOpts.palette, true);
    }
    this.themeChanged();
    this.applyStyles();
    this.applyTitles();
    this.ngAfterViewInit(true); // eslint-disable-line @angular-eslint/no-lifecycle-call
    this.cdRef.markForCheck();
  }
 
  protected handleLegendClick(legend: CustomLegendItem): void {
    this.doToggleSeriesVisibility(legend.name, legend.selected, legend);
    this.cdRef.markForCheck();
  }
 
  protected handleLegendHover(legend: CustomLegendItem, start: boolean): void {
    this.dispatchEChartAction({
      type: start ? 'highlight' : 'downplay',
      [legend.alternativeNaming ? 'name' : 'seriesName']: legend.name
    });
  }
 
  /**
   * Toggle visibility of a series.
   */
  toggleSeriesVisibility(name: string, visible: boolean): void {
    const legendItem = this.findCustomLegendItem(name);
    this.doToggleSeriesVisibility(name, visible, legendItem);
    this.cdRef.markForCheck();
  }
 
  private doToggleSeriesVisibility(
    name: string,
    visible: boolean,
    legendItem?: CustomLegendItem
  ): void {
    if (legendItem) {
      legendItem.selected = visible;
    }
    this.dispatchEChartAction({ type: visible ? 'legendSelect' : 'legendUnSelect', name });
 
    if (this.externalZoomSlider()) {
      this.ngZone.runOutsideAngular(() => {
        this.extZoomSliderChart.dispatchAction({
          type: visible ? 'legendSelect' : 'legendUnSelect',
          name
        });
      });
    }
    const opt = this.getOptionNoClone();
    if (Array.isArray(opt.legend)) {
      const selection: any = {};
      opt.legend.forEach((l: any) => Object.assign(selection, l.selected));
      this.handleSelectionChanged({ selected: selection });
    }
  }
 
  private findCustomLegendItem(name: string): CustomLegendItem | undefined {
    if (this.showCustomLegend()) {
      for (const cl of this.customLegend) {
        for (const l of cl.customLegends) {
          for (const item of l.list) {
            if (item.name === name) {
              return item;
            }
          }
        }
      }
    }
    return undefined;
  }
 
  protected getValidXAxis(): Set<number> | undefined {
    return undefined;
  }
 
  protected setZoomMode(): void {}
 
  private applyTheme(): void {
    // Set default theme if no theme provided
    const theme = this.theme();
    Iif (theme?.style) {
      this.activeTheme = theme.style();
    E} else if (themeSupport._defaultTheme?.style) {
      this.activeTheme = themeSupport._defaultTheme.style();
    }
    const themeCustomization = this.themeCustomization();
    Iif (themeCustomization) {
      const custom = echarts.util.merge({}, themeCustomization);
      this.activeTheme = echarts.util.merge(custom, this.activeTheme);
    }
  }
 
  protected themeChanged(): void {}
 
  protected applyOptions(): void {}
 
  protected applyCustomLegendPosition(): void {
    if (this.showLegend() && this.showCustomLegend()) {
      this.customLegend.forEach(cl => {
        if (cl.customLegends?.[0].list && cl.customLegends?.[1].list) {
          const leftLegend = cl.customLegends[0];
          const rightLegend = cl.customLegends[1];
 
          // if we have left and right axis
          if (leftLegend.list.length > 0 && rightLegend.list.length > 0) {
            cl.legendAxis = 'both';
          } else if (leftLegend.list.length > 0 && rightLegend.list.length === 0) {
            // if we have only left axis data
            cl.legendAxis = 'left';
          } else if (leftLegend.list.length === 0 && rightLegend.list.length > 0) {
            // if we have only right axis data
            cl.legendAxis = 'right';
          } else {
            cl.legendAxis = 'both';
          }
        } else {
          cl.legendAxis = 'both';
        }
      });
      this.cdRef.markForCheck();
    }
  }
 
  private applyAdditionalOptions(): void {
    // need to merge palette before the additionalOptions so that overrides work as expected
    this.applyPalette();
 
    Iif (this.additionalOptions()) {
      echarts.util.merge(this.actualOptions, this.additionalOptions(), true);
    }
  }
 
  private applyPalette(): void {
    const paletteValue = this.palette() ?? 'default';
    Eif (paletteValue) {
      const palette = this.getThemeCustomValue(['colorPalettes', paletteValue], null);
      Eif (palette) {
        this.actualOptions.color = palette;
        Iif (this.customLegendAction()) {
          this.fetchSeriesColors(palette);
        }
      }
    }
  }
 
  protected applyDataZoom(): void {
    if (!this.actualOptions.grid) {
      return;
    }
    this.actualOptions.dataZoom ??= [];
 
    const sliderOptions: any = {};
    const dataZoomMinValueSpan = this.dataZoomMinValueSpan();
    Iif (dataZoomMinValueSpan) {
      sliderOptions.minValueSpan = dataZoomMinValueSpan;
    }
    const dataZoomMaxValueSpan = this.dataZoomMaxValueSpan();
    Iif (dataZoomMaxValueSpan) {
      sliderOptions.maxValueSpan = dataZoomMaxValueSpan;
    }
    sliderOptions.realtime = this.zoomSliderRealtime();
    sliderOptions.brushSelect = this.zoomSliderBrush();
    sliderOptions.showDataShadow = this.zoomSliderShadow();
    sliderOptions.filterMode = this.dataZoomFilterMode();
    sliderOptions.showDetail = false;
    // keep external zoom slider in sync, always at index 0
    Object.assign(this.extZoomSliderOptions.dataZoom![0], sliderOptions);
 
    const dz = this.actualOptions.dataZoom!;
    const sliderIdx = dz.findIndex(z => z.type === 'slider');
    const insideIdx = dz.findIndex(z => z.type === 'inside');
    const zoomSlider = this.zoomSlider();
    Iif (zoomSlider && sliderIdx === -1) {
      // for the non-external, merge with other options
      const customOptions = this.getThemeCustomValue(['dataZoom', 'options'], {});
      const dzSliderOptions: any = Object.assign({ type: 'slider' }, customOptions, sliderOptions);
      Object.assign(this.extZoomSliderOptions.dataZoom![0], customOptions);
 
      const externalZoomSlider = this.externalZoomSlider();
      if (externalZoomSlider) {
        dzSliderOptions.show = false;
      }
      dz.push(dzSliderOptions);
 
      const gridOptions = externalZoomSlider
        ? this.getThemeCustomValue(['externalZoomSlider', 'grid'], {})
        : this.getThemeCustomValue(['dataZoom', 'grid'], {});
 
      if (this.showTimeRangeBar()) {
        const timeBarOptions = this.getThemeCustomValue(['timeRangeBar'], {});
        if (customOptions.height && customOptions.bottom) {
          this.timeBarBottom.set(customOptions.height + customOptions.bottom);
        }
        this.timeBarHeight.set(timeBarOptions?.height ?? 32);
 
        if (!externalZoomSlider) {
          gridOptions.bottom = (gridOptions?.bottom ?? 0) + this.timeBarHeight();
        }
      }
 
      echarts.util.merge(this.actualOptions.grid, gridOptions, true);
    I} else if (zoomSlider && sliderIdx >= 0) {
      // update existing
      const dzSliderOptions = dz[sliderIdx];
      Object.assign(dzSliderOptions, sliderOptions);
    I} else if (!zoomSlider && sliderIdx >= 0) {
      dz.splice(sliderIdx, 1);
    }
    const zoomInside = this.zoomInside();
    Iif (zoomInside && insideIdx === -1) {
      dz.push({ type: 'inside', filterMode: this.dataZoomFilterMode() });
    I} else if (!zoomInside && insideIdx >= 0) {
      dz.splice(insideIdx, 1);
    }
 
    if (this.actualOptions.xAxis) {
      this.handleAxisPointer(this.actualOptions);
    }
    this.cdRef.markForCheck();
  }
 
  private handleAxisPointer(options: EChartOption): void {
    const axisPointer = this.axisPointer();
    Eif (axisPointer !== undefined) {
      options.axisPointer ??= {};
    }
    Iif (axisPointer === true) {
      options.axisPointer.triggerOn = 'click';
    } else if (axisPointer === false) {
      options.axisPointer.triggerOn = 'mousemove|click';
    E} else if (typeof axisPointer === 'string') {
      options.axisPointer.triggerOn = axisPointer;
    }
    Iif (Array.isArray(options.xAxis)) {
      const xAxisArray: any[] = options.xAxis;
      xAxisArray.forEach(axis => this.handleAxisPointerSingleAxis(axis));
    } else {
      this.handleAxisPointerSingleAxis(options.xAxis);
    }
  }
 
  private handleAxisPointerSingleAxis(xAxis: any): void {
    Iif (this.axisPointer()) {
      echarts.util.merge(xAxis, { axisPointer: { handle: { show: true } } }, true);
    } else {
      echarts.util.merge(xAxis, { axisPointer: { handle: { show: false } } }, true);
    }
  }
 
  protected hasDataZoom(): boolean {
    return !!this.actualOptions.dataZoom?.length;
  }
 
  protected getThemeValue(props: string[], defaultValue: any, ns?: string): any {
    Iif (!this.activeTheme) {
      return defaultValue;
    }
 
    let currentValue = this.activeTheme;
    Eif (ns) {
      currentValue = currentValue[ns];
    }
    for (let i = 0; currentValue && i < props.length; i++) {
      currentValue = currentValue[props[i]];
    }
    return currentValue ?? defaultValue;
  }
 
  protected getThemeCustomValue(props: string[], defaultValue: any): any {
    return this.getThemeValue(props, defaultValue, 'simpl');
  }
 
  protected applyTitles(): void {
    const title = this.title();
    const subTitle = this.subTitle();
    const options = this.actualOptions;
    Iif (this.showLegend() && this.showCustomLegend()) {
      if (options.title) {
        options.title.show = false;
      }
      options.legend?.forEach(legend => {
        legend.show = false;
        legend.height = 0;
      });
      if (options.grid) {
        const gridOptions = this.getThemeCustomValue(['customLegend', 'grid'], {});
        echarts.util.merge(options.grid, gridOptions, true);
      }
 
      this.titleColor.set(this.getThemeValue(['title', 'textStyle', 'color'], null));
      this.subTitleColor.set(
        this.getThemeValue(['title', 'subtextStyle', 'color'], this.titleColor)
      );
      this.textColor.set(this.getThemeValue(['legend', 'textStyle', 'color'], null));
      this.backgroundColor.set(this.getThemeValue(['backgroundColor'], null));
    } else if (title || subTitle) {
      options.title = {
        text: title,
        subtext: subTitle
      };
      if (subTitle) {
        this.modifyTopAlignment('subTitle');
      }
    E} else if (!title && !subTitle && !options.title) {
      this.modifyTopAlignment('noTitle');
    }
  }
 
  private modifyTopAlignment(key: string): void {
    const options = this.actualOptions;
    if (options.grid) {
      const gridOptions = this.getThemeCustomValue([key, 'grid'], {});
      echarts.util.merge(options.grid, gridOptions, true);
    }
 
    const legendOptions = this.getThemeCustomValue([key, 'legend'], {});
    options.legend?.forEach(legend => echarts.util.merge(legend, legendOptions, true));
  }
 
  protected afterChartInit(skipZoom?: boolean): void {
    this.chart.on('datazoom', (event: any) => this.handleDataZoom(event, 'echart'));
    if (!this.customLegendAction()) {
      // default generic si-chart behavior
      this.chart.on('legendselectchanged', (event: any) => this.handleSelectionChanged(event));
      this.chart.on('click', (event: any) => this.handleClickOnChart(event, false));
    } else E{
      // custom chart behaviour
      this.chart.on('legendselectchanged', (event: any) =>
        this.handleSelectionChangedCustom(event)
      );
      this.chart.on('click', (event: any) => this.handleClickOnChart(event, true));
    }
    this.chart.on('updateaxispointer', (event: any) => this.handleUpdateAxisPointer(event));
    Eif (!skipZoom) {
      this.setDataZoomRange();
    }
    this.cdRef.markForCheck();
  }
 
  protected afterChartResize(): void {}
 
  private getEChartInner(): Element | null {
    return this.echartElement.querySelector(':scope > div:first-child');
  }
 
  private getEChartExternalSliderInner(): Element | null {
    return this.eChartExtSliderElement.querySelector(':scope > div:first-child');
  }
 
  private handleExtChartMouseDown(): void {
    window.addEventListener('mouseup', this.echartExtSliderMouseUp);
  }
 
  private handleExtChartMouseUp(event: MouseEvent): void {
    window.removeEventListener('mouseup', this.echartExtSliderMouseUp);
    const newEvent = new MouseEvent('mouseup', event);
    setTimeout(() => {
      this.getEChartExternalSliderInner()?.dispatchEvent(newEvent);
      this.cdRef.markForCheck();
    }, 1);
  }
 
  private handleChartMouseDown(): void {
    window.addEventListener('mouseup', this.echartMouseUp);
  }
 
  private handleChartMouseUp(event: MouseEvent): void {
    window.removeEventListener('mouseup', this.echartMouseUp);
    const newEvent = new MouseEvent('mouseup', event);
    setTimeout(() => {
      this.getEChartInner()?.dispatchEvent(newEvent);
      this.cdRef.markForCheck();
    }, 1);
  }
 
  private setDataZoomRange(skipUpdate?: boolean): void {
    // Checking if we received a valid dataZoomRange Object
    const dataZoomRange = this.dataZoomRange();
    Iif (dataZoomRange && Object.keys(dataZoomRange).length > 0) {
      // If series has data, then directly dispatch action for the dataZoom event
      // Else, Store the dataZoomRange values in presetDataZoomRange variable for applying zoom
      // after data is received in chart
      // No need to reassign presetDataZoomRange if earlier value is not consumed
      if (this.hasData()) {
        const dz = this.getPresetDataZoom(dataZoomRange);
        if (dz) {
          const requested = { ...dataZoomRange };
          this.presetDataZoomRange = undefined;
 
          this.updateDataZoom(dz);
          if (!skipUpdate) {
            this.updateEChart(false, { dataZoom: [dz] });
          }
 
          // update user with proper data
          setTimeout(() => {
            this.ngZone.runOutsideAngular(() => {
              this.requestedDataZoom = requested;
              this.handleDataZoom(dz, 'setDataZoomRange');
            });
          });
 
          return;
        }
      }
      this.presetDataZoomRange = dataZoomRange;
    }
  }
 
  private handleDataZoom(event: any, source?: string): void {
    // events can be batched
    if (event.batch?.length) {
      event = event.batch[0];
    }
    if (Number.isNaN(event.start) || Number.isNaN(event.end)) {
      // need to fix to the last valid dataZoom setting, see below
      this.chart.dispatchAction({ type: 'dataZoom', ...this.lastValidDataZoom });
      return;
    }
 
    const effectiveOpts = this.getOptionNoClone();
    // in case of pane by chart area, event.start and event.end are always undefined.
    // and in case of slider move, they has values in percentage(0-100)
    // so, to handle in case of pane, we need to get start and end values from datazoom property
    // following condition will be executed only if autozoom is false; and start and end are undefined(undefined means call is from pane)
    const dz = effectiveOpts.dataZoom[0];
    this.autoZoomUpdate = !!dz && dz.end === 100;
    // Due to chart updates outside Angular, we need to emit events back
    // inside Angular to activate Angular's change detection.
    const range = this.getVisibleRange();
    if (range) {
      range.source = source ?? event.source;
      this.calculateVisibleRange(range);
      if (this.requestedDataZoom) {
        range.requested = this.requestedDataZoom;
        this.requestedDataZoom = undefined;
      }
 
      this.ngZone.run(() => {
        this.dataZoom.emit(range);
        this.timeRangeChange.emit(
          dz.start === 0 && dz.end === 100 ? 0 : range.rangeEnd - range.rangeStart
        );
      });
 
      setTimeout(() => this.checkGridSizeChange());
      this.presetDataZoomRange = undefined;
      this.dataZoomSetupDone = true;
 
      // sync/store values
      this.updateDataZoom({ startValue: range.rangeStart, endValue: range.rangeEnd });
 
      if (event.source !== 'extSlider') {
        this.extZoomSliderChart?.dispatchAction({
          type: 'dataZoom',
          source: 'mainChart',
          startValue: range.rangeStart,
          endValue: range.rangeEnd
        });
      }
    }
    this.cdRef.markForCheck();
  }
 
  private handleExtDataZoom(event: any): void {
    if (event.batch?.length) {
      event = event.batch[0];
    }
 
    if (event.source === 'mainChart') {
      return;
    }
 
    const zoomModel = (this.extZoomSliderChart as any)._model;
    const range = this.doGetVisibleRange(zoomModel);
    if (range) {
      this.calculateVisibleRange(range);
      this.chart?.dispatchAction({
        type: 'dataZoom',
        source: 'extSlider',
        startValue: range.rangeStart,
        endValue: range.rangeEnd
      });
    }
  }
 
  protected handleSelectionChanged(event: any): void {
    this.selectionChanged.emit(event);
 
    for (const a in event.selected) {
      if (event.selected[a] !== false) {
        return;
      }
    }
 
    this.saveCurrentDataZoom();
  }
 
  /**
   * Creates two objects that stores the colors for selected and unselected series. Used only for custom legend actions.
   */
  protected fetchSeriesColors(colorsToBeUSed?: any): void {
    const options = this.actualOptions;
    if (!options.color?.length && this.activeTheme) {
      options.color = [...this.activeTheme.color];
    }
    if (!colorsToBeUSed && !this.activeTheme) {
      return;
    }
    options.series?.forEach((element, index) => {
      this.unselectedSeriesColors[element.name!] = {
        color: this.getThemeValue(['legend', 'unselected', 'color'], '#ccc'),
        index
      };
      const colors = colorsToBeUSed ?? this.activeTheme.color;
      this.selectedSeriesColors[element.name!] = { color: colors[index], index };
    });
  }
 
  /**
   * Handles legend select event in non echart native way.
   * @param event -  legend select
   */
  protected handleSelectionChangedCustom(event: any): void {
    const optionsToChange = this.styleSelectedSeries(event.name, false, event.dataIndex);
    this.ngZone.runOutsideAngular(() => {
      this.chart.setOption(optionsToChange);
      this.chart.dispatchAction({ type: 'legendSelect', name: event.name });
    });
  }
 
  /**
   * Handles click on series in non echart native way.
   * @param event -  click
   */
  protected handleClickOnChart(event: any, toggleVisibility: boolean): void {
    if (event.componentType !== 'series') {
      return;
    }
    if (toggleVisibility) {
      const optionsToChange = this.styleSelectedSeries(event.seriesName, true, event.dataIndex);
      this.chart.setOption(optionsToChange);
    } else {
      this.ngZone.run(() =>
        this.chartSeriesClick.emit({
          itemName: event.seriesName,
          dataIndex: event.dataIndex
        })
      );
    }
  }
 
  /**
   * Selects or unselects the series based on series state object
   * @param seriesName -  series to be selected/unselected
   * @param emit -  if true event is emitted otherwise no event is emitted
   */
  protected styleSelectedSeries(seriesName: string, emit: boolean, seriesDataIndex: number): any {
    if (this.seriesSelectionState?.[seriesName]) {
      const elementToStyle = this.actualOptions.series?.find(
        element => element.name === seriesName
      );
      this.seriesSelectionState[seriesName] = false;
      return this.selectSeries(elementToStyle, emit, seriesDataIndex);
    } else {
      const elementToStyle = this.actualOptions.series?.find(
        element => element.name === seriesName
      );
      this.seriesSelectionState[seriesName] = true;
      return this.unselectSeries(elementToStyle, emit, seriesDataIndex);
    }
  }
 
  /**
   * Selects the series
   * @param element -  to be styled as selected
   * @param emit -  if true event is emitted otherwise no event is emitted
   */
  protected selectSeries(element: any, emit: boolean, seriesDataIndex: number): any {
    const options = this.actualOptions;
    const optionsToChange = { color: options.color, series: [options.series] };
    const optionsColorIndex = this.selectedSeriesColors[element.name].index;
    optionsToChange.color[optionsColorIndex] = this.selectedSeriesColors[element.name].color;
    if (element.areaStyle) {
      element.areaStyle.opacity = 0.4;
      optionsToChange.series[this.selectedSeriesColors[element.name].index] = element;
    }
    if (emit) {
      this.chartSeriesClick.emit({
        itemName: element.name,
        dataIndex: seriesDataIndex,
        selected: false,
        color: this.selectedSeriesColors[element.name].color
      });
    }
    return optionsToChange;
  }
 
  /**
   * Unselects the series
   * @param element - to be styled as unselected
   * @param emit - if true event is emitted otherwise no event is emitted
   */
  protected unselectSeries(
    element: any,
    emit: boolean,
    seriesDataIndex: number
  ): {
    color: any;
    series: (EChartSeries | undefined)[];
  } {
    const options = this.actualOptions;
    const optionsToChange = { color: options.color, series: [options.series] };
    const optionsColorIndex = this.selectedSeriesColors[element.name].index;
    optionsToChange.color[optionsColorIndex] = this.unselectedSeriesColors[element.name].color;
    if (element.areaStyle) {
      element.areaStyle.opacity = 0;
      optionsToChange.series[this.unselectedSeriesColors[element.name].index] = element;
    }
    if (emit) {
      this.chartSeriesClick.emit({
        itemName: element.name,
        dataIndex: seriesDataIndex,
        selected: true,
        color: this.selectedSeriesColors[element.name].color
      });
    }
    return optionsToChange;
  }
 
  private isValidDataZoomValue(val: any): boolean {
    return val !== null && val !== undefined && !Number.isNaN(val);
  }
 
  private saveCurrentDataZoom(): void {
    const options = this.actualOptions;
    if (!options.grid || !options.dataZoom) {
      return;
    }
 
    // When the last item on the legend is disabled, remember the current valid
    // dataZoom setting. Due to a bug in ECharts it happens
    // that the zoom slider disappears not to ever reappear again. To work around
    // the problem, we simply inject the last valid dataZoom settings saved here
    // once the invalid values (NaN) are detected
    const currentOpts = this.getOptionNoClone();
    if (!currentOpts?.dataZoom?.[0]) {
      return;
    }
 
    const dz = currentOpts.dataZoom[0];
    if (dz) {
      this.lastValidDataZoom = {};
      if (this.isValidDataZoomValue(dz.startValue)) {
        this.lastValidDataZoom.startValue = dz.startValue;
      } else if (this.isValidDataZoomValue(dz.start)) {
        this.lastValidDataZoom.start = dz.start;
      }
      if (this.isValidDataZoomValue(dz.endValue)) {
        this.lastValidDataZoom.endValue = dz.endValue;
      } else if (this.isValidDataZoomValue(dz.end)) {
        this.lastValidDataZoom.end = dz.end;
      }
    }
  }
 
  /**
   * Get color by series name.
   */
  getSeriesColorBySeriesName(seriesName: string): string | undefined {
    return this.doGetSeriesColorBySeriesName(seriesName).color;
  }
 
  private doGetSeriesColorBySeriesName(seriesName: string): {
    color: string | undefined;
    altName: boolean;
  } {
    const ecModel = this.internalGetModel();
    const ecSeries = ecModel.getSeriesByName(seriesName);
    if (ecSeries && ecSeries.length > 0) {
      return { color: ecSeries[0].getData().getVisual('style')?.fill as string, altName: false };
    }
 
    let ret = { color: undefined as string | undefined, altName: false };
    ecModel.eachRawSeries((seriesModel: any) => {
      const idx = seriesModel.legendVisualProvider?.indexOfName(seriesName) ?? -1;
      if (idx >= 0) {
        ret = {
          color: seriesModel.legendVisualProvider.getItemVisual(idx, 'style')?.fill as string,
          altName: true
        };
      }
    });
    return ret;
  }
 
  private applyColorsToCustomLegends(): void {
    Eif (!this.showLegend() || !this.showCustomLegend()) {
      return;
    }
    this.customLegend.forEach(cl => {
      cl.customLegends.forEach(legendAxis => {
        legendAxis?.list.forEach(legend => {
          const color = this.doGetSeriesColorBySeriesName(legend.name);
          legend.color = color.color;
          legend.alternativeNaming = color.altName;
        });
      });
    });
    this.cdRef.markForCheck();
  }
 
  private handleUpdateAxisPointer(event: any): void {
    if (
      event.seriesIndex !== this.prevAxisPointer.seriesIndex ||
      event.dataIndex !== this.prevAxisPointer.dataIndex
    ) {
      this.prevAxisPointer.seriesIndex = event.seriesIndex;
      this.prevAxisPointer.dataIndex = event.dataIndex;
 
      if (this.axisPointer() && event.seriesIndex === undefined) {
        return;
      }
 
      // Due to chart updates outside Angular, we need to emit events back
      // inside Angular to activate Angular's change detection.
      this.ngZone.run(() => {
        this.pointer.emit({
          seriesIndex: event.seriesIndex,
          dataIndex: event.dataIndex
        });
      });
    }
  }
 
  /**
   * Get current data zoom range.
   */
  getVisibleRange(): DataZoomEvent | undefined {
    return this.doGetVisibleRange(this.internalGetModel());
  }
 
  protected internalGetModel(): any {
    return (this.chart as any)._model;
  }
 
  /**
   * returns the current EChart options, w/o cloning anything. Be very careful
   * not to change anything in the data structure in it.
   */
  getOptionNoClone(): any {
    return this.internalGetModel().option;
  }
 
  protected parsePercent(percent: string | number, all: number): number {
    if (typeof percent === 'string') {
      if (percent.match(/\d+%/)) {
        return (parseFloat(percent) / 100) * all;
      }
      return parseFloat(percent);
    }
    return percent;
  }
 
  private doGetVisibleRange(zoomModel: any): DataZoomEvent | undefined {
    const effectiveOpts: any = zoomModel.option;
    const xAxis = effectiveOpts.xAxis?.[0];
    const dz = effectiveOpts.dataZoom[0];
 
    const rangeStartArray: number[] = [];
    const rangeEndArray: number[] = [];
    for (let i = 0; i < effectiveOpts.xAxis?.length; i++) {
      const axis = zoomModel.getComponent('xAxis', i);
      const extent = axis?.axis?.scale?.getExtent();
      if (extent?.length) {
        if (this.isValidDataZoomValue(extent[0])) {
          rangeStartArray.push(extent[0]);
        }
        if (this.isValidDataZoomValue(extent[1])) {
          rangeEndArray.push(extent[1]);
        }
      }
    }
 
    const rangeStart = rangeStartArray.length ? Math.min(...rangeStartArray) : dz?.startValue;
    const rangeEnd = rangeEndArray.length ? Math.max(...rangeEndArray) : dz?.endValue;
 
    if (!this.isValidDataZoomValue(rangeEnd)) {
      return;
    }
 
    let gridWidth: number | undefined;
    if (effectiveOpts.grid && effectiveOpts.grid.length > 0) {
      const width = this.chart.getWidth();
      const grid = effectiveOpts.grid[0];
      gridWidth =
        width - this.parsePercent(grid.left, width) - this.parsePercent(grid.right, width);
    }
 
    return {
      rangeType: xAxis.type,
      rangeStart,
      rangeEnd,
      width: gridWidth,
      autoZoomUpdate: this.autoZoomUpdate
    };
  }
 
  protected updateEChart(force = false, options?: EChartOption): void {
    Iif (!this.chart) {
      return;
    }
    let axisDZUpdated = this.updateAxisAndDataZoom(options);
    options ??= this.actualOptions;
    const isFilledArray = (v: any): boolean => Array.isArray(v) && v.length > 0;
    Iif (
      isFilledArray(options.grid) &&
      isFilledArray(options.xAxis) &&
      isFilledArray(options.dataZoom)
    ) {
      // adjust grid for axis labels
      let max = 0;
      options.yAxis.forEach((axis: any) => {
        if (axis.position !== 'right' && isFilledArray(axis.data)) {
          axis.data.forEach((label: string) => {
            const width = this.calculateTextWidth(label);
            max = Math.max(max, width);
          });
        }
      });
      max += 16; // long text getting truncated, so add some padding
      const grids = options.grid as GridComponentOption[];
      grids.forEach(g => (g.left = Math.max(g.left as number, max)));
 
      // update dataZoom if not already set
      const zoom = options.dataZoom![0];
      if (
        !this.isValidDataZoomValue(zoom?.startValue) &&
        !this.isValidDataZoomValue(zoom?.endValue) &&
        !this.isValidDataZoomValue(zoom?.end)
      ) {
        const range = this.getVisibleRange();
        if (range) {
          this.updateDataZoom({ startValue: range.rangeStart, endValue: range.rangeEnd });
        }
      }
 
      // change in grid/axis requires a full update
      force = true;
      axisDZUpdated = true;
    }
 
    this.ngZone.runOutsideAngular(() => {
      this.chart.setOption(options!, force);
      this.setZoomMode();
      Iif (axisDZUpdated && this.externalZoomSlider()) {
        this.extZoomSliderChart.setOption(this.extZoomSliderOptions, false);
      }
    });
 
    setTimeout(() => this.checkGridSizeChange());
  }
 
  protected updateAxisAndDataZoom(inOptions?: EChartOption): boolean {
    const options = this.actualOptions;
    if (!options.xAxis) {
      return false;
    }
 
    const isFull = !inOptions || inOptions === options;
    inOptions = inOptions ?? {};
    Iif (!isFull && !inOptions.series && !options.dataZoom) {
      return false;
    }
 
    const xAxis = Array.isArray(options.xAxis) ? options.xAxis : [options.xAxis];
    if (!isFull && !inOptions.xAxis) {
      // for delta update, make sure we have same-sized axis array
      inOptions.xAxis = xAxis.map(() => ({}));
    }
 
    const minMax = this.getSeriesMinMax();
 
    // extend range if DZ is bigger than actual data
    const dz = inOptions?.dataZoom?.[0];
    Iif (
      dz?.startValue != null &&
      (minMax.min === undefined || (dz.startValue as number) < minMax.min)
    ) {
      minMax.min = dz.startValue as number;
    }
    Iif (
      dz?.endValue != null &&
      (minMax.max === undefined || (dz.endValue as number) > minMax.max)
    ) {
      minMax.max = dz.endValue as number;
    }
 
    // Update all sub chart index to be controlled by the dataZoom
    let xAxisIndexes: number[] = [];
    xAxis.forEach((axis, index) => {
      Iif (axis.gridIndex >= 0) {
        // set min/max the same on all axis so that datazoom can work
        axis.min = minMax.min;
        axis.max = minMax.max;
 
        if (!isFull) {
          inOptions.xAxis[index].min = minMax.min;
          inOptions.xAxis[index].max = minMax.max;
        }
 
        xAxisIndexes.push(index);
      }
    });
 
    // update dataZoom
    const effectiveOpts = this.getOptionNoClone();
    const effectiveXAxis = effectiveOpts.xAxis;
    Iif (effectiveXAxis.length > 1) {
      // 1. find out all visible series
      // 2. find out valid x index
      // 3. remove invalid x axis from the xAxisIndex array
      const validXAxis = this.getValidXAxis();
      if (validXAxis) {
        xAxisIndexes = xAxisIndexes.filter(index => validXAxis.has(index));
      }
    }
 
    Iif (xAxisIndexes.length) {
      const allDataZoom = options.dataZoom!;
      allDataZoom.forEach(zoom => (zoom.xAxisIndex = xAxisIndexes));
      if (!isFull && inOptions.dataZoom) {
        inOptions.dataZoom.forEach(zoom => (zoom.xAxisIndex = xAxisIndexes));
      }
    }
 
    // update external slider if required
    Iif (this.externalZoomSlider()) {
      const extSliderAxis = this.extZoomSliderOptions.xAxis[0];
      if (extSliderAxis.min !== minMax.min || extSliderAxis.max !== minMax.max) {
        extSliderAxis.min = minMax.min;
        extSliderAxis.max = minMax.max;
        this.extZoomSliderOptions.series![0].data = [
          [minMax.min, null],
          [minMax.max, null]
        ];
      }
    }
 
    return true;
  }
 
  /**
   * Send action to echart.
   * @see https://echarts.apache.org/en/api.html#action
   */
  dispatchEChartAction(action: echarts.Payload): void {
    Iif (!this.chart) {
      return;
    }
    this.ngZone.runOutsideAngular(() => {
      this.chart.dispatchAction(action);
    });
    this.cdRef.markForCheck();
  }
 
  private getSeriesMinMax(visibleOnly = false): {
    min: number | undefined;
    max: number | undefined;
  } {
    const legend = visibleOnly ? this.internalGetModel().getComponent('legend') : undefined;
    let min: number | undefined;
    let max: number | undefined;
    this.actualOptions.series?.forEach(s => {
      const seriesData = s.data as any[];
      Eif (seriesData?.length > 1 && (!legend || legend.isSelected(s.name))) {
        const start = seriesData[0][0]?.valueOf();
        const last = seriesData[seriesData.length - 1];
        // end value is can be undefined sometimes, if we don't have milliseconds as a value, instead
        // we have value[] array of Date, so to handle that scenario we are taking value[0].valueOf() to
        // calculate the millisecond value i.e from Date(value[0])
        const end = last[0]?.valueOf() ?? last.value?.[0]?.valueOf();
        if (this.isValidDataZoomValue(start) && this.isValidDataZoomValue(end)) {
          Eif (min === undefined || start < min) {
            min = start;
          }
          Eif (max === undefined || end > max) {
            max = end;
          }
        }
      }
    });
    return { min, max };
  }
 
  private calculateVisibleRange(range: DataZoomEvent | undefined): void {
    const options = this.actualOptions;
    if (!options.xAxis || !this.hasDataZoom() || !range) {
      return;
    }
    if (!Array.isArray(options.xAxis) && options.xAxis.type === 'category') {
      this.visibleRange.set(Math.ceil(range.rangeEnd) - Math.floor(range.rangeStart));
    } else {
      this.visibleRange.set(Math.round(range.rangeEnd - range.rangeStart));
    }
 
    // once in range mode, disable the entries mode to prevent overriding the user
    this.visibleEntries.set(-1);
  }
 
  private getValueFromSeriesPoint(point: any): any[] {
    return Array.isArray(point) ? point : point.value;
  }
 
  private calculateZoomStartValue(): any {
    const options = this.actualOptions;
    if (!options.series) {
      return null;
    }
 
    const seriesData = options.series[this.autoZoomSeriesIndex()]?.data as any[];
    if (!seriesData) {
      return null;
    }
 
    if (this.visibleEntries() > -1) {
      const offset = Math.min(seriesData.length, this.visibleEntries());
      const data = seriesData[seriesData.length - offset];
      return data ? this.getValueFromSeriesPoint(data)[0] : null;
    } else if (this.visibleRange() > -1) {
      const minMax = this.getSeriesMinMax(true);
      if (minMax.min && minMax.max) {
        // make sure startValue is >= the min data value
        return Math.max(minMax.min, minMax.max - this.visibleRange());
      }
      const data = seriesData[seriesData.length - 1];
      return data ? this.getValueFromSeriesPoint(data)[0] - this.visibleRange() : null;
    }
    return null;
  }
 
  protected hasData(): boolean {
    return this.actualOptions.series?.some(s => (s.data as any[])?.length > 0) ?? false;
  }
 
  /**
   * Re-render the chart series data. This method should be called on series data changes.
   */
  refreshSeries(isLive: boolean = true, dzToSet?: DataZoomRange): void {
    dzToSet ??= this.presetDataZoomRange;
    const optionsToUpdate: any = {
      series: this.actualOptions.series
    };
 
    Iif (!isLive) {
      this.updateEChart(false, optionsToUpdate);
      return;
    }
 
    Iif (this.hasDataZoom() && this.hasData()) {
      if (dzToSet) {
        this.dataZoomSetupDone = true;
 
        const dz = this.getPresetDataZoom(dzToSet);
        if (dz) {
          const requested = { ...dzToSet };
          this.presetDataZoomRange = undefined;
          this.updateDataZoom(dz, optionsToUpdate);
 
          // dispatch the same async. reasoning: the sync here is needed to prevent
          // flickering, the async dispatch to ensure a DataZoomEvent is fired so
          // that any consumer of this event work as expected
          setTimeout(() => {
            this.ngZone.runOutsideAngular(() => {
              this.requestedDataZoom = requested;
              this.handleDataZoom(dz, 'refreshSeries');
            });
          });
        }
      } else if (!this.dataZoomSetupDone) {
        // need to do this async to have the data in ECharts
        setTimeout(() => {
          if (!this.dataZoomSetupDone && !this.dataZoomRange() && this.chart) {
            this.calculateVisibleRange(this.getVisibleRange());
          }
          this.dataZoomSetupDone = true;
        });
      } else if (this.zoomSlider() && this.autoZoomUpdate && this.autoZoomSeriesIndex() !== -1) {
        // this ensures the slider is at the end and the window size remains stable, showing new data
        const startValue = this.calculateZoomStartValue();
        if (this.isValidDataZoomValue(startValue)) {
          this.updateDataZoom({ startValue, end: 100 }, optionsToUpdate);
        }
        if (isLive) {
          this.dispatchEChartAction({ type: 'hideTip' });
        }
      } else {
        // this ensures the current displayed window stays stable as new data arrives
        const dz = this.getOptionNoClone().dataZoom[0];
        if (
          this.isValidDataZoomValue(dz.startValue) &&
          this.isValidDataZoomValue(dz.endValue) &&
          dz.end !== 100
        ) {
          this.updateDataZoom(
            { startValue: dz.startValue, endValue: dz.endValue },
            optionsToUpdate
          );
        }
      }
    }
 
    this.updateEChart(false, optionsToUpdate);
  }
 
  // this ensures DZ is in sync everywhere
  private updateDataZoom(dz: DataZoomRange, optionsToUpdate?: EChartOption): void {
    const options = this.actualOptions;
    if (options.dataZoom?.[0]) {
      this.doUpdateDZ(dz, options.dataZoom[0]);
    }
    if (optionsToUpdate && optionsToUpdate !== options) {
      if (Array.isArray(optionsToUpdate.dataZoom)) {
        this.doUpdateDZ(dz, optionsToUpdate.dataZoom[0]);
      } else if (optionsToUpdate.dataZoom) {
        this.doUpdateDZ(dz, optionsToUpdate.dataZoom);
      } else {
        optionsToUpdate.dataZoom = [{ ...dz }];
      }
    }
    if (this.externalZoomSlider()) {
      this.doUpdateDZ(dz, this.extZoomSliderOptions.dataZoom![0]);
    }
  }
 
  private doUpdateDZ(dz: DataZoomRange, dzOptions: DataZoomComponentOption): void {
    // make sure only to have value or percent
    if (this.isValidDataZoomValue(dz.startValue)) {
      dzOptions.startValue = dz.startValue;
      dzOptions.start = undefined;
    } else if (this.isValidDataZoomValue(dz.start)) {
      dzOptions.start = dz.start;
      dzOptions.startValue = undefined;
    }
    if (this.isValidDataZoomValue(dz.endValue)) {
      dzOptions.endValue = dz.endValue;
      dzOptions.end = undefined;
    } else if (this.isValidDataZoomValue(dz.end)) {
      dzOptions.end = dz.end;
      dzOptions.endValue = undefined;
    }
  }
 
  protected applyStyles(): void {
    const bodyStyle: CSSStyleDeclaration = window.getComputedStyle(document.body);
    const options = this.actualOptions;
    options.textStyle = {
      fontFamily: navigator.webdriver ? 'sans-serif' : bodyStyle.fontFamily,
      fontSize: bodyStyle.fontSize
    };
    this.extZoomSliderOptions.textStyle = options.textStyle;
  }
 
  protected addLegendItem(
    name: string,
    visible?: boolean | null,
    index: number = 0,
    gridIndex: number = 0,
    customLegendProp?: CustomLegendProps,
    seriesSymbol?: string
  ): void {
    const options = this.actualOptions;
    Iif (!options.legend?.length) {
      return;
    }
 
    const legend = options.legend[options.legend.length > index ? index : 0];
    const unitText = customLegendProp ? customLegendProp.unit : undefined;
    const customLegendItem: CustomLegendItem = {
      name: '',
      displayName: '',
      color: '',
      selected: false,
      tooltip: customLegendProp ? customLegendProp.tooltip : '',
      symbol: this.getPath(seriesSymbol, false)
    };
    legend.data?.push({
      name,
      icon: this.getPath(seriesSymbol, true)
    });
 
    legend.selected ??= {};
 
    Iif (visible !== null && visible !== undefined) {
      legend.selected[name] = visible;
      customLegendItem.selected = visible;
    }
    const showCustomLegend = this.showCustomLegend();
    Iif (this.showLegend() && showCustomLegend) {
      if (visible !== false) {
        customLegendItem.selected = true;
      }
      customLegendItem.name = name;
      customLegendItem.displayName = customLegendProp?.displayName ?? name;
 
      if (showCustomLegend) {
        this.addCustomLegend(customLegendItem, unitText, index, gridIndex);
      }
    }
    this.cdRef.markForCheck();
  }
 
  private getPath(seriesSymbol: string | undefined, prefix: boolean): string {
    const path = seriesSymbol ? this.shapePaths[seriesSymbol] : this.shapePaths.circle;
    return prefix ? 'path://' + path : path;
  }
 
  private addCustomLegend(
    customLegendItem: CustomLegendItem,
    unitText: string | undefined,
    index: number,
    gridIndex: number = 0
  ): void {
    if (this.actualOptions.legend) {
      if (!this.customLegend[gridIndex].customLegends) {
        this.customLegend[gridIndex].customLegends = [
          { list: [], unit: '' },
          { list: [], unit: '' }
        ];
      }
      // index = 0 means left legend
      if (index === 0) {
        if (!this.customLegend[gridIndex]?.customLegends[0]?.list) {
          this.customLegend[gridIndex].customLegends[0] = { list: [customLegendItem] };
        } else {
          // legend with same id and name not found
          this.customLegend[gridIndex].customLegends[0].list.push(customLegendItem);
        }
        this.customLegend[gridIndex].customLegends[0].unit = unitText;
      } else {
        // index = 1 means right legend
        if (!this.customLegend[gridIndex]?.customLegends[1]?.list) {
          this.customLegend[gridIndex].customLegends[1] = { list: [customLegendItem] };
        } else {
          this.customLegend[gridIndex].customLegends[1].list.push(customLegendItem);
        }
        this.customLegend[gridIndex].customLegends[1].unit = unitText;
      }
      this.applyCustomLegendPosition();
    }
  }
 
  /**
   * Show loading indicator.
   */
  public startProgressIndication(): void {
    this.inProgress.set(true);
  }
 
  /**
   * Hide loading indicator.
   */
  public stopProgressIndication(): void {
    this.inProgress.set(false);
  }
 
  /**
   * Set the data zoom range for the chart in milliseconds.
   * As an example one hour is the value 3600000.
   */
  setTimeRange(range: number): void {
    const currentDZ = this.getVisibleRange();
    const minMax = this.getSeriesMinMax(true);
    if (!currentDZ || minMax.min == null || minMax.max == null) {
      return;
    }
 
    const mid = (currentDZ.rangeStart + currentDZ.rangeEnd) / 2;
    const halfRange = range / 2;
 
    let start: number;
    let end: number;
 
    if (range === 0 || range > minMax.max - minMax.min) {
      start = minMax.min;
      end = minMax.max;
    } else {
      start = mid - halfRange;
      end = mid + halfRange;
 
      // at start
      if (start < minMax.min) {
        start = minMax.min;
        end = start + range;
      }
 
      // at end. Special case: if already at end, keep end
      if (end > minMax.max || currentDZ.rangeEnd === minMax.max) {
        start = minMax.max - range;
        end = minMax.max;
      }
    }
 
    this.dispatchEChartAction({ type: 'dataZoom', startValue: start, endValue: end });
  }
 
  protected addDataInternal(series: SeriesUpdate<any>[]): void {
    const options = this.actualOptions;
    series.forEach(update => {
      const currentSeries = options.series![update.index];
      Iif (!currentSeries) {
        return;
      }
      const seriesData = currentSeries.data as any[];
      seriesData.push(update.data);
      if (this.maxEntries() > 0 && seriesData.length > this.maxEntries()) {
        seriesData.splice(0, seriesData.length - this.maxEntries());
      }
    });
 
    this.refreshSeries();
  }
 
  private getPresetDataZoom(range: DataZoomRange): any {
    let ret: any;
    if (range.visibleWidth && this.autoZoomSeriesIndex() !== -1) {
      this.visibleRange.set(range.visibleWidth);
 
      const startValue = this.calculateZoomStartValue();
      if (this.isValidDataZoomValue(startValue)) {
        this.autoZoomUpdate = true;
        ret = { startValue, end: 100 };
      }
    } else if (
      this.isValidDataZoomValue(range.startValue) &&
      this.isValidDataZoomValue(range.endValue)
    ) {
      // handling the case when startValue and endValue is given as a fixed time interval
      ret = {
        startValue: range.startValue,
        endValue: range.endValue
      };
      this.autoZoomUpdate = false;
    } else {
      ret = { ...range };
    }
 
    return ret;
  }
 
  private checkGridSizeChange(): void {
    Iif (!this.chart) {
      return;
    }
    const gridRectNew: GridRectCoordinate =
      this.internalGetModel()?.getComponent('grid')?.coordinateSystem?._rect;
    Iif (gridRectNew) {
      const nativeWrapper = this.chartContainerWrapper().nativeElement as HTMLElement;
      gridRectNew.containerWidth = nativeWrapper.offsetWidth;
      gridRectNew.containerHeight = nativeWrapper.offsetHeight;
 
      let isGridResized = false;
 
      for (const objKey of Object.keys(this.gridCoordinates) as (keyof GridRectCoordinate)[]) {
        if (this.gridSizeItemChanged(gridRectNew[objKey], this.gridCoordinates[objKey])) {
          isGridResized = true;
          break;
        }
      }
 
      if (isGridResized) {
        // update new coordinates and emit event
        this.gridCoordinates = gridRectNew;
        this.timeBarLeft.set(this.gridCoordinates.x);
        this.timeBarRight.set(
          this.gridCoordinates.containerWidth - this.gridCoordinates.x - this.gridCoordinates.width
        );
 
        if (this.externalZoomSlider() && Array.isArray(this.extZoomSliderOptions?.grid)) {
          this.extZoomSliderOptions.grid[0].left = this.timeBarLeft();
          this.extZoomSliderOptions.grid[0].right = this.timeBarRight();
          this.extZoomSliderChart.setOption({ grid: this.extZoomSliderOptions.grid }, false);
        }
        this.ngZone.run(() => this.chartGridResized.emit(this.gridCoordinates));
      }
    }
    this.cdRef.markForCheck();
  }
 
  private gridSizeItemChanged(a: any, b: any): boolean {
    return Array.isArray(a)
      ? a.length !== b.length || (a as any[]).some((item, index) => item !== b[index])
      : a !== b;
  }
 
  private setContainerHeight(): void {
    const newHeight = parseInt(this.eChartContainerHeight()!, 10) || null;
    if (newHeight !== this.containerHeight()) {
      this.containerHeight.set(newHeight);
 
      this.ngZone.runOutsideAngular(() => {
        this.chart?.resize({ width: this.curWidth, height: newHeight ?? this.curHeight });
        if (this.externalZoomSlider()) {
          this.extZoomSliderChart.resize();
        }
      });
    }
  }
 
  private updateCustomLegendMultiLineInfo(): void {
    const event: CustomLegendMultiLineInfo[] = [];
    this.siCustomLegend().forEach((legend, index) => {
      event.push({
        customLegendId: index,
        isCustomLegendMultilined: legend.customLegendContainer().nativeElement.offsetHeight > 20
      });
    });
    Iif (
      event.length !== this.customLegendsMultiLineInfo.length ||
      event.some(
        (e, index) =>
          e.isCustomLegendMultilined !==
          this.customLegendsMultiLineInfo[index].isCustomLegendMultilined
      )
    ) {
      this.customLegendsMultiLineInfo = event;
      this.customLegendMultiLineInfoEvent.emit(event);
    }
    this.cdRef.markForCheck();
  }
}