All files / owid-grapher/grapher/stackedCharts MarimekkoChart.tsx

54.46% Statements 720/1322
68.25% Branches 86/126
71.43% Functions 55/77
54.46% Lines 720/1322

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 17431x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                     1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 30x 30x 30x 30x 30x 30x                                               30x 30x 30x 30x 30x 39x 39x 30x 30x 30x 30x                     30x 30x 30x 30x 30x             30x 30x 30x 34x 34x 34x 34x 34x 34x 29x 29x 34x 34x 30x 30x 30x 30x 30x 34x 34x 22x 22x 22x 22x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 22x 22x 22x 22x 34x 34x 34x 34x 22x 22x 29x 22x 75x 75x 75x 75x 75x 22x 22x 34x 34x 12x 12x 12x 12x 12x 36x 36x 36x 36x 36x 36x 12x 12x 12x 12x 12x 12x 12x 12x 34x 34x 56x 56x   56x 56x 34x 34x 46x 46x 34x 34x 16x 16x 16x 16x 34x 34x 8x 8x 8x 8x 8x 8x 8x 34x 8x 8x 8x         8x 8x 34x 8x 8x   8x 8x 34x 34x 8x 8x 8x 8x 8x 34x 34x 26x 26x 34x 34x 22x 22x     22x 22x 34x 34x 38x 38x 34x 34x 8x 8x 34x 34x 34x           34x 34x           34x 8x 8x 34x 34x 64x 64x 34x 34x 8x 8x 34x 34x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 34x 34x 12x 12x 34x 34x 8x 8x 34x 34x 8x 8x 34x 34x 8x 8x 34x 34x 8x 8x 8x 8x 8x 8x 8x 8x 34x 8x 8x 8x 8x 34x 34x 8x 8x 34x 34x 8x 8x 34x 34x 8x 8x 8x 8x 8x 34x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 34x 8x 8x 8x 34x 8x 8x 8x 8x 8x 34x 34x 8x 8x 8x 8x                     8x 8x 8x 8x 8x 8x 8x 8x 34x 34x 8x 8x 8x 8x 8x 8x 34x 34x 8x 8x 34x 34x 8x 8x 8x 8x 8x 34x 34x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 24x 24x 24x               24x 8x 8x 34x 34x 8x 8x 8x 8x 8x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 30x 30x 30x 30x 26x 26x 26x 26x 26x 26x 26x 24x 24x 24x 8x 8x 8x 8x 34x 34x 8x 8x 8x 8x 8x     8x     3x     8x 8x 8x 24x 24x 22x 22x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 34x 34x 4x 4x 4x 4x 12x 12x 12x 12x 12x 12x 4x 4x 34x 34x     34x 34x 34x 34x 8x 8x 34x 34x     34x 34x     34x 34x     34x 34x 8x 8x 34x 34x 8x 8x 34x 34x 12x 12x 34x 34x 8x 8x 8x 8x 10x 10x 10x 10x 10x 10x 10x 8x 34x 34x     34x 34x     34x 34x 8x 8x 34x 34x     34x 34x     34x 34x     34x 34x     34x 34x     34x         34x 34x                                                       34x 34x                                                                                                                                                                                                                                                                                                                             34x 34x 34x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 34x 34x 34x 34x 34x 34x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 24x 104x 104x 104x 104x 24x 24x 24x 8x 8x 8x 8x 34x 34x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 24x 24x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 20x 20x 20x 20x 2x 2x 2x 2x       20x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 24x 24x       24x 8x 24x 24x 8x 8x 8x 8x 34x 34x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import * as React from "react"
import {
    findLastIndex,
    min,
    max,
    maxBy,
    last,
    flatten,
    excludeUndefined,
    sortBy,
    sumBy,
    partition,
    first,
} from "../../clientUtils/Util"
import { action, computed, observable } from "mobx"
import { observer } from "mobx-react"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import {
    BASE_FONT_SIZE,
    EntitySelectionMode,
    SeriesName,
} from "../core/GrapherConstants"
import { DualAxisComponent } from "../axis/AxisViews"
import { NoDataModal } from "../noDataModal/NoDataModal"
import { AxisConfig } from "../axis/AxisConfig"
import { ChartInterface } from "../chart/ChartInterface"
import { OwidTable } from "../../coreTable/OwidTable"
import { autoDetectYColumnSlugs, makeSelectionArray } from "../chart/ChartUtils"
 
import {
    HorizontalAlign,
    Position,
    SortBy,
    SortConfig,
    SortOrder,
} from "../../clientUtils/owidTypes"
import { StackedPoint, StackedSeries } from "./StackedConstants"
import { ColorSchemes } from "../color/ColorSchemes"
import {
    EntityName,
    OwidVariableRow,
    OwidTableSlugs,
} from "../../coreTable/OwidTableConstants"
import {
    HorizontalCategoricalColorLegend,
    HorizontalColorLegendManager,
} from "../horizontalColorLegend/HorizontalColorLegends"
import { CategoricalBin, ColorScaleBin } from "../color/ColorScaleBin"
import { CoreColumn } from "../../coreTable/CoreTableColumns"
import { TippyIfInteractive } from "../chart/Tippy"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons/faInfoCircle"
import { DualAxis, HorizontalAxis, VerticalAxis } from "../axis/Axis"
import { ColorScale, ColorScaleManager } from "../color/ColorScale"
import {
    ColorScaleConfig,
    ColorScaleConfigDefaults,
} from "../color/ColorScaleConfig"
import { ColorSchemeName } from "../color/ColorConstants"
import { color } from "d3-color"
import { SelectionArray } from "../selection/SelectionArray"
import { ColorScheme } from "../color/ColorScheme"
import {
    MarimekkoChartManager,
    EntityColorData,
    SimplePoint,
    SimpleChartSeries,
    BarShape,
    Bar,
    Item,
    PlacedItem,
    TooltipProps,
    EntityWithSize,
    LabelCandidate,
    LabelWithPlacement,
    LabelCandidateWithElement,
    MarimekkoBarProps,
} from "./MarimekkoChartConstants"
 
const MARKER_MARGIN: number = 4
const MARKER_AREA_HEIGHT: number = 25
 
function MarimekkoBar({
    bar,
    tooltipProps,
    barWidth,
    isHovered,
    isSelected,
    isFaint,
    entityColor,
    y0,
    isInteractive,
    dualAxis,
}: MarimekkoBarProps): JSX.Element {
    const { seriesName } = bar
    const isPlaceholder = bar.kind === BarShape.BarPlaceholder
    const barBaseColor =
        entityColor ?? (bar.kind === BarShape.Bar ? bar.color : "#555")

    const barColor =
        bar.kind === BarShape.BarPlaceholder
            ? "#555"
            : isHovered
            ? color(barBaseColor)?.brighter(0.9).toString() ?? barBaseColor
            : isSelected
            ? color(barBaseColor)?.brighter(0.6).toString() ?? barBaseColor
            : barBaseColor
    const strokeColor = barColor
    const strokeWidth = isHovered || isSelected ? "1px" : "0.5px"
    const strokeOpacity = isPlaceholder ? 0.8 : isFaint ? 0.2 : 1.0
    const fillOpacity = isHovered
        ? 0.7
        : isFaint
        ? 0.2
        : isSelected
        ? isPlaceholder
            ? 0.3
            : 0.7
        : 0.7
    const overalOpacity = isPlaceholder ? 0.2 : 1.0

    let barY: number = 0
    let barHeight: number = 0
    if (bar.kind === BarShape.Bar) {
        barY = dualAxis.verticalAxis.place(y0 + bar.yPoint.valueOffset)
        barHeight =
            dualAxis.verticalAxis.place(y0) -
            dualAxis.verticalAxis.place(bar.yPoint.value)
    } else {
        barY = dualAxis.verticalAxis.place(y0)
        barHeight = bar.height
    }
    const barX = 0

    const renderedBar = (
        <g key={seriesName}>
            <rect
                x={0}
                y={0}
                transform={`translate(${barX}, ${barY - barHeight})`}
                width={barWidth}
                height={barHeight}
                fill={barColor}
                fillOpacity={fillOpacity}
                stroke={strokeColor}
                strokeWidth={strokeWidth}
                strokeOpacity={strokeOpacity}
                opacity={overalOpacity}
                style={{
                    transition: "translate 200ms ease",
                }}
            />
        </g>
    )
    if (tooltipProps) {
        return (
            <TippyIfInteractive
                lazy
                isInteractive={isInteractive}
                key={seriesName}
                animation={false}
                visible={isHovered}
                content={<MarimekkoChart.Tooltip {...tooltipProps} />}
            >
                {renderedBar}
            </TippyIfInteractive>
        )
    } else return renderedBar
}
 
interface MarimekkoBarsProps {
    entityName: string
    bars: Bar[]
    entityColor: EntityColorData | undefined
    isFaint: boolean
    isHovered: boolean
    isSelected: boolean
    barWidth: number
    tooltipProps: TooltipProps
    currentX: number
    onEntityMouseOver: (entityName: string) => void
    onEntityMouseLeave: () => void
    onEntityClick: (entityName: string) => void
    labelYOffset: number
    y0: number
    noDataHeight: number
    dualAxis: DualAxis
    isExportingToSvgOrPng: boolean | undefined
}
 
function MarimekkoBarsForOneEntity(props: MarimekkoBarsProps): JSX.Element {
    7
    const {
        entityName,
        bars,
        entityColor,
        isFaint,
        isHovered,
        isSelected,
        barWidth,
        tooltipProps,
        currentX,
        onEntityClick,
        onEntityMouseLeave,
        onEntityMouseOver,
        labelYOffset,
        y0,
        noDataHeight,
        dualAxis,
        isExportingToSvgOrPng,
    } = props

    let content = undefined
    if (bars.length) {
        let lastNonZeroBarIndex = findLastIndex(
            bars,
            (bar) => bar.yPoint.value > 0
        )
        lastNonZeroBarIndex = lastNonZeroBarIndex >= 0 ? lastNonZeroBarIndex : 0 // if we don't find an item with a nonzero value it doesn't really matter which one we pick
        const predecessors = bars.slice(0, lastNonZeroBarIndex)
        const lastNonZero = bars[lastNonZeroBarIndex]
        const successors = bars.slice(lastNonZeroBarIndex + 1, bars.length)

        // This is annoying - I tried to use the tippy element around all bars instead of inside
        // one single bar but then it renders at the document origin instead of at the right attach point
        // since we will switch to another tooltip solution anyhow I would leave it at this for now -
        // later on this splitting into allbutlast and last can be removed and tooltips just done elsewhere
        const predecessorBars = predecessors.map((bar) => (
            <MarimekkoBar
                key={`${entityName}-${bar.seriesName}`}
                bar={bar}
                tooltipProps={undefined}
                barWidth={barWidth}
                isHovered={isHovered}
                isSelected={isSelected}
                isFaint={isFaint}
                entityColor={entityColor?.color}
                y0={y0}
                isInteractive={!isExportingToSvgOrPng}
                dualAxis={dualAxis}
            />
        ))
        const lastNonZeroBar = (
            <MarimekkoBar
                key={`${entityName}-${lastNonZero.seriesName}`}
                bar={lastNonZero}
                tooltipProps={{
                    ...tooltipProps,
                    highlightedSeriesName: lastNonZero.seriesName,
                }}
                barWidth={barWidth}
                isHovered={isHovered}
                isSelected={isSelected}
                isFaint={isFaint}
                entityColor={entityColor?.color}
                y0={y0}
                isInteractive={!isExportingToSvgOrPng}
                dualAxis={dualAxis}
            />
        )
        const successorBars = successors.map((bar) => (
            <MarimekkoBar
                key={`${entityName}-${bar.seriesName}`}
                bar={bar}
                tooltipProps={undefined}
                barWidth={barWidth}
                isHovered={isHovered}
                isSelected={isSelected}
                isFaint={isFaint}
                entityColor={entityColor?.color}
                y0={y0}
                isInteractive={!isExportingToSvgOrPng}
                dualAxis={dualAxis}
            />
        ))

        content = [...predecessorBars, lastNonZeroBar, ...successorBars]
    } else {
        content = (
            <MarimekkoBar
                key={`${entityName}-placeholder`}
                tooltipProps={tooltipProps}
                bar={{
                    kind: BarShape.BarPlaceholder,
                    seriesName: entityName,
                    height: noDataHeight,
                }}
                barWidth={barWidth}
                isHovered={isHovered}
                isSelected={isSelected}
                isFaint={isFaint}
                entityColor={entityColor?.color}
                y0={y0}
                isInteractive={!isExportingToSvgOrPng}
                dualAxis={dualAxis}
            />
        )
    }

    return (
        <g
            key={entityName}
            className="bar"
            transform={`translate(${currentX}, ${labelYOffset})`}
            onMouseOver={(): void => onEntityMouseOver(entityName)}
            onMouseLeave={(): void => onEntityMouseLeave()}
            onClick={(): void => onEntityClick(entityName)}
        >
            {content}
        </g>
    )
}
 
@observer
export class MarimekkoChart
    extends React.Component<{
        bounds?: Bounds
        manager: MarimekkoChartManager
    }>
    implements ChartInterface, HorizontalColorLegendManager, ColorScaleManager
{
    base: React.RefObject<SVGGElement> = React.createRef()
 
    defaultBaseColorScheme = ColorSchemeName.continents
    defaultNoDataColor = "#959595"
    labelAngleInDegrees = -45 // 0 is horizontal, -90 is vertical from bottom to top, ...
 
    transformTable(table: OwidTable): OwidTable {
        if (!this.yColumnSlugs.length) return table
        if (!this.xColumnSlug) return table
        const { excludedEntities, includedEntities } = this.manager
        const { yColumnSlugs, manager, colorColumnSlug, xColumnSlug } = this
 
        if (excludedEntities || includedEntities) {
            const excludedEntityIdsSet = new Set(excludedEntities)
            const includedEntityIdsSet = new Set(includedEntities)
            const excludeEntitiesFilter = (entityId: any): boolean =>
                !excludedEntityIdsSet.has(entityId as number)
            const includedEntitiesFilter = (entityId: any): boolean =>
                includedEntityIdsSet.size > 0
                    ? includedEntityIdsSet.has(entityId as number)
                    : true
            const filterFn = (entityId: any): boolean =>
                excludeEntitiesFilter(entityId) &&
                includedEntitiesFilter(entityId)
            const excludedList = excludedEntities
                ? excludedEntities.join(", ")
                : ""
            const includedList = includedEntities
                ? includedEntities.join(", ")
                : ""
            table = table.columnFilter(
                OwidTableSlugs.entityId,
                filterFn,
                `Excluded entity ids specified by author: ${excludedList} - Included entity ids specified by author: ${includedList}`
            )
        }
 
        // TODO: remove this filter once we don't have mixed type columns in datasets
        table = table.replaceNonNumericCellsWithErrorValues(yColumnSlugs)
 
        yColumnSlugs.forEach((slug) => {
            table = table.interpolateColumnWithTolerance(slug)
        })
 
        table = table.interpolateColumnWithTolerance(xColumnSlug)
 
        if (colorColumnSlug) {
            const tolerance =
                table.get(colorColumnSlug)?.display?.tolerance ?? Infinity
            table = table.interpolateColumnWithTolerance(
                colorColumnSlug,
                tolerance
            )
            if (manager.matchingEntitiesOnly) {
                table = table.dropRowsWithErrorValuesForColumn(colorColumnSlug)
            }
        }
        if (!manager.showNoDataArea)
            table = table.dropRowsWithErrorValuesForAllColumns(yColumnSlugs)
 
        table = table.dropRowsWithErrorValuesForColumn(xColumnSlug)
        if (manager.isRelativeMode) {
            // TODO: this should not be necessary but we sometimes get NoMatchingValuesAfterJoin if both relative and showNoDataArea are set
            table = table.dropRowsWithErrorValuesForColumn(
                table.timeColumn.slug
            )
            table = table.toPercentageFromEachEntityForEachTime(xColumnSlug)
        }
 
        return table
    }
 
    @observable private hoveredEntityName?: string
 
    @observable focusColorBin?: ColorScaleBin
 
    @computed get inputTable(): OwidTable {
        return this.manager.table
    }
 
    @computed get transformedTable(): OwidTable {
        return (
            this.manager.transformedTable ??
            this.transformTable(this.inputTable)
        )
    }
 
    @computed private get unstackedSeries(): StackedSeries<EntityName>[] {
        const { colorScheme, yColumns } = this
        return (
            yColumns
                .map((col, i) => {
                    return {
                        seriesName: col.displayName,
                        columnSlug: col.slug,
                        color:
                            col.def.color ??
                            colorScheme.getColors(yColumns.length)[i],
                        points: col.owidRows.map((row) => ({
                            time: row.time,
                            position: row.entityName,
                            value: row.value,
                            valueOffset: 0,
                        })),
                    }
                })
                // Do not plot columns without data
                .filter((series) => series.points.length > 0)
        )
    }
 
    //@computed private get rows(): readonly
 
    @computed get series(): readonly StackedSeries<EntityName>[] {
        const valueOffsets = new Map<string, number>()
        return this.unstackedSeries.map((series) => ({
            ...series,
            points: series.points.map((point) => {
                const offset = valueOffsets.get(point.position) ?? 0
                const newPoint = { ...point, valueOffset: offset }
                valueOffsets.set(point.position, offset + point.value)
                return newPoint
            }),
        }))
    }
 
    @computed get xSeries(): SimpleChartSeries {
        const createStackedXPoints = (
            rows: OwidVariableRow<any>[]
        ): SimplePoint[] => {
            const points: SimplePoint[] = []
            for (const row of rows) {
                points.push({
                    time: row.time,
                    value: row.value,
                    entity: row.entityName,
                })
            }
            return points
        }
        const column = this.xColumn
        return {
            seriesName: column.displayName,
            points: createStackedXPoints(column.owidRows),
        }
    }
 
    @computed protected get yColumnSlugs(): string[] {
        return (
            this.manager.yColumnSlugsInSelectionOrder ??
            autoDetectYColumnSlugs(this.manager)
        )
    }
 
    @computed protected get xColumnSlug(): string | undefined {
        return this.manager.xColumnSlug
    }
 
    @computed protected get xColumn(): CoreColumn {
        const columnSlugs = this.xColumnSlug ? [this.xColumnSlug] : []
        if (!columnSlugs.length) console.warn("No x column slug!")
        return this.transformedTable.getColumns(columnSlugs)[0]
    }
 
    @computed private get latestTime(): number | undefined {
        const times =
            this.manager.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter?.getTimesUniqSortedAscForColumns(
                this.yColumnSlugs
            )
 
        return times ? last(times) : undefined
    }
    @computed private get tableAtLatestTimelineTimepoint():
        | OwidTable
        | undefined {
        if (this.latestTime)
            return this.manager.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter?.filterByTargetTimes(
                [this.latestTime],
                0
            )
        else return undefined
    }
    @computed protected get xColumnAtLastTimePoint(): CoreColumn | undefined {
        const columnSlug = this.xColumnSlug ? [this.xColumnSlug] : []
        if (this.tableAtLatestTimelineTimepoint)
            return this.tableAtLatestTimelineTimepoint.getColumns(columnSlug)[0]
        else return undefined
    }
 
    @computed protected get yColumnsAtLastTimePoint(): CoreColumn[] {
        const columnSlugs = this.yColumnSlugs
        return (
            this.tableAtLatestTimelineTimepoint?.getColumns(columnSlugs) ?? []
        )
    }
 
    @computed protected get yColumns(): CoreColumn[] {
        return this.transformedTable.getColumns(this.yColumnSlugs)
    }
 
    @computed private get colorScheme(): ColorScheme {
        return (
            (this.manager.baseColorScheme
                ? ColorSchemes[this.manager.baseColorScheme]
                : undefined) ?? ColorSchemes["owid-distinct"]
        )
    }
 
    @computed private get colorColumnSlug(): string | undefined {
        return this.manager.colorColumnSlug
    }
 
    @computed private get colorColumn(): CoreColumn {
        return this.transformedTable.get(this.colorColumnSlug)
    }
 
    colorScale = new ColorScale(this)
    @computed get colorScaleConfig(): ColorScaleConfigDefaults | undefined {
        return (
            ColorScaleConfig.fromDSL(this.colorColumn.def) ??
            this.manager.colorScale
        )
    }
 
    @computed get colorScaleColumn(): CoreColumn {
        // We need to use inputTable in order to get consistent coloring for a variable across
        // charts, e.g. each continent being assigned to the same color.
        // inputTable is unfiltered, so it contains every value that exists in the variable.
        return this.inputTable.get(this.colorColumnSlug)
    }
    @computed private get sortConfig(): SortConfig {
        return this.manager.sortConfig ?? {}
    }
 
    @computed private get manager(): MarimekkoChartManager {
        return this.props.manager
    }
 
    @computed private get bounds(): Bounds {
        return (this.props.bounds ?? DEFAULT_BOUNDS).padRight(10)
    }
 
    @computed private get innerBounds(): Bounds {
        // This is a workaround to get the actual width of the vertical axis - dualAxis does this
        // internally but we can't access this.dualAxis here due to a dependency cycle
        const axis = this.verticalAxisPart.clone()
        axis.range = [0, this.bounds.height]
        const verticalAxisTrueWidth = axis.width
 
        const whiteSpaceOnLeft = this.bounds.left + verticalAxisTrueWidth
        const labelLinesHeight = MARKER_AREA_HEIGHT
        // only pad left by the amount the longest label would exceed whatever space the
        // vertical axis needs anyhow for label and tickmarks
        const marginToEnsureWidestEntityLabelFitsEvenIfAtX0 =
            Math.max(whiteSpaceOnLeft, this.longestLabelWidth) -
            whiteSpaceOnLeft
        return this.bounds
            .padBottom(this.longestLabelHeight)
            .padBottom(labelLinesHeight)
            .padTop(this.legend.height + this.legendPaddingTop)
            .padLeft(marginToEnsureWidestEntityLabelFitsEvenIfAtX0)
    }
 
    @computed private get baseFontSize(): number {
        return this.manager.baseFontSize ?? BASE_FONT_SIZE
    }
 
    @computed private get x0(): number {
        return 0
    }
 
    @computed private get y0(): number {
        return 0
    }
 
    @computed private get allPoints(): StackedPoint<EntityName>[] {
        return flatten(this.series.map((series) => series.points))
    }
 
    @computed private get yDomainDefault(): [number, number] {
        const maxValues = this.allPoints.map(
            (point) => point.value + point.valueOffset
        )
        return [
            Math.min(this.y0, min(maxValues) as number),
            Math.max(this.y0, max(maxValues) as number),
        ]
    }
    @computed private get xDomainDefault(): [number, number] {
        const sum = sumBy(this.xSeries.points, (point) => point.value)
 
        return [this.x0, sum]
    }
 
    @computed private get xRange(): [number, number] {
        return [this.bounds.left, this.bounds.right]
    }
 
    @computed private get yAxisConfig(): AxisConfig {
        return new AxisConfig(this.manager.yAxisConfig, this)
    }
 
    @computed private get xAxisConfig(): AxisConfig {
        return new AxisConfig(
            { ...this.manager.xAxisConfig, orient: Position.top },
            this
        )
    }
    @computed private get verticalAxisPart(): VerticalAxis {
        const config = this.yAxisConfig
        const axis = config.toVerticalAxis()
        axis.updateDomainPreservingUserSettings(this.yDomainDefault)
 
        axis.formatColumn = this.yColumns[0]
        const fallbackLabel =
            this.yColumns.length > 0 ? this.yColumns[0].displayName : ""
        axis.label = this.isNarrow ? "" : config.label || fallbackLabel
 
        return axis
    }
    @computed private get isNarrow(): boolean {
        // TODO: this should probably come from grapher?
        return this.bounds.width < 650 // innerBounds would lead to dependency cycle
    }
    @computed private get xAxisLabelBase(): string {
        const xDimName = this.xColumn?.displayName
        if (this.manager.xOverrideTime !== undefined)
            return `${xDimName} in ${this.manager.xOverrideTime}`
        return xDimName
    }
 
    @computed private get horizontalAxisPart(): HorizontalAxis {
        const { manager, xAxisLabelBase, xDomainDefault, xColumn } = this
        const config = this.xAxisConfig
        let axis = config.toHorizontalAxis()
        if (manager.isRelativeMode) {
            // MobX and classes  interact in an annoying way here so we have to construct a new object via
            // an object copy of the AxisConfig class instance to be able to set a property without
            // making MobX unhappy about a mutation originating from a computed property
            axis = new HorizontalAxis(
                new AxisConfig(
                    { ...config.toObject(), maxTicks: 10 },
                    config.fontSizeManager
                )
            )
            axis.domain = [0, 100]
        } else axis.updateDomainPreservingUserSettings(xDomainDefault)
 
        axis.formatColumn = xColumn
 
        const label = config.label || xAxisLabelBase
        axis.label = label
        return axis
    }
 
    @computed private get dualAxis(): DualAxis {
        return new DualAxis({
            bounds: this.innerBounds,
            verticalAxis: this.verticalAxisPart,
            horizontalAxis: this.horizontalAxisPart,
        })
    }
 
    @computed private get selectionArray(): SelectionArray {
        return makeSelectionArray(this.manager)
    }
 
    @computed private get selectedItems(): Item[] {
        const selectedSet = this.selectionArray.selectedSet
        const { sortedItems } = this
        if (selectedSet.size === 0) return []
        return sortedItems.filter((item) => selectedSet.has(item.entityName))
    }
 
    @computed private get domainColorForEntityMap(): Map<
        string,
        EntityColorData
    > {
        const { colorColumn, colorScale } = this
        const entityNames = this.xColumn.uniqEntityNames
        const hasColorColumn = !colorColumn.isMissing
        const colorRowsByEntity = hasColorColumn
            ? colorColumn.owidRowsByEntityName
            : undefined
        const domainColorMap = new Map<string, EntityColorData>()
        for (const name of entityNames) {
            const colorDomainValue = colorRowsByEntity?.get(name)?.[0]
 
            if (colorDomainValue) {
                const color = colorScale.getColor(colorDomainValue.value)
                if (color)
                    domainColorMap.set(name, {
                        color,
                        colorDomainValue: colorDomainValue.value,
                    })
            }
        }
        return domainColorMap
    }
 
    @computed private get items(): Item[] {
        const entityNames = this.xColumn.uniqEntityNames
        const { xSeries, series, domainColorForEntityMap } = this
 
        const items: Item[] = entityNames
            .map((entityName) => {
                const xPoint = xSeries.points.find(
                    (point) => point.entity === entityName
                )
                if (!xPoint) return undefined
 
                const color = domainColorForEntityMap.get(entityName)
 
                return {
                    entityName,
                    xPoint: xPoint,
                    entityColor: color,
                    bars: excludeUndefined(
                        series.map((series): Bar | undefined => {
                            const point = series.points.find(
                                (point) => point.position === entityName
                            )
                            if (!point) return undefined
                            return {
                                kind: BarShape.Bar,
                                yPoint: point,
                                color: series.color,
                                seriesName: series.seriesName,
                            }
                        })
                    ),
                }
            })
            .filter((item) => item) as Item[]
 
        return items
    }
 
    @computed private get sortedItems(): Item[] {
        const { items, sortConfig } = this
 
        let sortByFunc: (item: Item) => number | string
        switch (sortConfig.sortBy) {
            case SortBy.entityName:
                sortByFunc = (item: Item): string => item.entityName
                break
            case SortBy.column:
                const sortColumnSlug = sortConfig.sortColumnSlug
                sortByFunc = (item: Item): number =>
                    item.bars.find((b) => b.seriesName === sortColumnSlug)
                        ?.yPoint.value ?? 0
                break
            default:
            case SortBy.total:
                sortByFunc = (item: Item): number => {
                    const lastPoint = last(item.bars)?.yPoint
                    if (!lastPoint) return 0
                    return lastPoint.valueOffset + lastPoint.value
                }
        }
        const sortedItems = sortBy(items, sortByFunc)
        const sortOrder = sortConfig.sortOrder ?? SortOrder.desc
        if (sortOrder === SortOrder.desc) sortedItems.reverse()
 
        const [itemsWithValues, itemsWithoutValues] = partition(
            sortedItems,
            (item) => item.bars.length !== 0
        )
 
        return [...itemsWithValues, ...itemsWithoutValues]
    }
 
    @computed get placedItems(): PlacedItem[] {
        const { sortedItems, dualAxis, x0 } = this
        const placedItems: PlacedItem[] = []
        let currentX = 0
        for (const item of sortedItems) {
            placedItems.push({ ...item, xPosition: currentX })
            const preciseX =
                dualAxis.horizontalAxis.place(item.xPoint.value) -
                dualAxis.horizontalAxis.place(x0)
            currentX += preciseX
        }
        return placedItems
    }
 
    @computed get placedItemsMap(): Map<string, PlacedItem> {
        return new Map(this.placedItems.map((item) => [item.entityName, item]))
    }
 
    // legend props
 
    @computed get legendPaddingTop(): number {
        return this.baseFontSize
    }
 
    @computed get legendX(): number {
        return this.bounds.x
    }
 
    @computed get categoryLegendY(): number {
        return this.bounds.top
    }
 
    @computed get legendOpacity(): number {
        return 0.7
    }
 
    @computed get legendWidth(): number {
        return this.bounds.width
    }
 
    @computed get legendAlign(): HorizontalAlign {
        return HorizontalAlign.left
    }
 
    @computed get fontSize(): number {
        return this.baseFontSize
    }
 
    @computed get categoricalLegendData(): CategoricalBin[] {
        const { colorColumnSlug, colorScale, series } = this
        if (colorColumnSlug) return colorScale.categoricalLegendBins
        else
            return series.map((series, index) => {
                return new CategoricalBin({
                    index,
                    value: series.seriesName,
                    label: series.seriesName,
                    color: series.color,
                })
            })
    }
 
    @action.bound onLegendMouseOver(bin: ColorScaleBin): void {
        this.focusColorBin = bin
    }
 
    @action.bound onLegendMouseLeave(): void {
        this.focusColorBin = undefined
    }
 
    @computed private get legend(): HorizontalCategoricalColorLegend {
        return new HorizontalCategoricalColorLegend({ manager: this })
    }
 
    @computed private get formatColumn(): CoreColumn {
        return this.yColumns[0]
    }
 
    @action.bound private onEntityMouseOver(entityName: string): void {
        this.hoveredEntityName = entityName
    }
 
    @action.bound private onEntityMouseLeave(): void {
        this.hoveredEntityName = undefined
    }
 
    @action.bound private onEntityClick(entityName: string): void {
        this.onSelectEntity(entityName)
    }
 
    @action.bound private onSelectEntity(entityName: string): void {
        if (this.canAddCountry) this.selectionArray.toggleSelection(entityName)
    }
    @computed private get canAddCountry(): boolean {
        const { addCountryMode } = this.manager
        return (addCountryMode &&
            addCountryMode !== EntitySelectionMode.Disabled) as boolean
    }
 
    render(): JSX.Element {
        if (this.failMessage)
            return (
                <NoDataModal
                    manager={this.manager}
                    bounds={this.bounds}
                    message={this.failMessage}
                />
            )

        const { bounds, dualAxis } = this

        return (
            <g ref={this.base} className="MarimekkoChart">
                <rect
                    x={bounds.left}
                    y={bounds.top}
                    width={bounds.width}
                    height={bounds.height}
                    opacity={0}
                    fill="rgba(255,255,255,0)"
                />
                <DualAxisComponent dualAxis={dualAxis} showTickMarks={true} />
                <HorizontalCategoricalColorLegend manager={this} />
                {this.renderBars()}
            </g>
        )
    }
 
    private renderBars(): JSX.Element[] {
        const normalElements: JSX.Element[] = []
        const highlightedElements: JSX.Element[] = [] // highlighted elements have a thicker stroke and should be drawn last to overlap others
        const {
            dualAxis,
            x0,
            y0,
            focusColorBin,
            placedLabels,
            labelLines,
            placedItems,
            hoveredEntityName,
        } = this
        const selectionSet = this.selectionArray.selectedSet
        const targetTime = this.manager.endTime
        const timeColumn = this.inputTable.timeColumn
        const yAxisColumn = this.formatColumn
        const xAxisColumn = this.xColumn
        const labelYOffset = 0
        const hasSelection = selectionSet.size > 0
        let noDataAreaElement = undefined
        let noDataLabel = undefined
        let patterns: JSX.Element[] = []
        const noDataHeight = Bounds.forText("no data").height + 10 //  dualAxis.verticalAxis.rangeSize

        const firstNanValue = placedItems.findIndex((item) => !item.bars.length)
        const anyNonNanAfterFirstNan =
            firstNanValue >= 0
                ? placedItems
                      .slice(firstNanValue)
                      .some((item) => item.bars.length !== 0)
                : false

        if (anyNonNanAfterFirstNan)
            console.error("Found Non-NAN values after NAN value!")

        if (firstNanValue !== -1) {
            const firstNanValueItem = placedItems[firstNanValue]
            const lastItem = last(placedItems)!
            const noDataRangeStartX =
                firstNanValueItem.xPosition + dualAxis.horizontalAxis.place(x0)
            const noDataRangeEndX =
                lastItem?.xPosition +
                dualAxis.horizontalAxis.place(lastItem.xPoint.value)
            const yStart = dualAxis.verticalAxis.place(y0)

            const noDataLabelX =
                noDataRangeStartX + (noDataRangeEndX - noDataRangeStartX) / 2
            const boundsForNoData = Bounds.forText("no data")
            const noDataLabelY = yStart - boundsForNoData.width
            noDataLabel = (
                <text
                    key={`noDataArea-label`}
                    x={0}
                    transform={`rotate(-90, ${noDataLabelX}, ${noDataLabelY})
                    translate(${noDataLabelX}, ${noDataLabelY})`}
                    y={0}
                    width={noDataRangeEndX - noDataRangeStartX}
                    height={noDataHeight}
                    fontWeight={700}
                    fill="#666"
                    opacity={1}
                    fontSize="0.8em"
                    textAnchor="middle"
                    dominantBaseline="middle"
                    style={{ pointerEvents: "none" }}
                >
                    no data
                </text>
            )

            noDataAreaElement = (
                <rect
                    key="noDataArea"
                    x={noDataRangeStartX}
                    y={yStart - noDataHeight}
                    //transform={`translate(${barX}, ${barY - barHeight})`}
                    width={noDataRangeEndX - noDataRangeStartX}
                    height={noDataHeight}
                    fill={"url(#diagonalHatch)"}
                    // stroke={strokeColor}
                    // strokeWidth={strokeWidth}
                    opacity={0.5}
                ></rect>
            )

            patterns = [
                <pattern
                    id="diagonalHatch"
                    key="diagonalHatch"
                    patternUnits="userSpaceOnUse"
                    width="4"
                    height="4"
                    patternTransform="rotate(-45 2 2)"
                >
                    <path d="M -1,2 l 6,0" stroke="#ccc" strokeWidth="1" />
                </pattern>,
            ]
        }

        for (const item of placedItems) {
            const { entityName, bars, xPoint, entityColor } = item
            const currentX = dualAxis.horizontalAxis.place(x0) + item.xPosition
            const tooltipProps = {
                item,
                targetTime,
                timeColumn,
                yAxisColumn,
                xAxisColumn,
            }

            const barWidth =
                dualAxis.horizontalAxis.place(xPoint.value) -
                dualAxis.horizontalAxis.place(x0)

            const isSelected = selectionSet.has(entityName)
            const isHovered = entityName === hoveredEntityName
            const isFaint =
                (focusColorBin !== undefined &&
                    !focusColorBin.contains(entityColor?.colorDomainValue)) ||
                (hasSelection && !isSelected)

            const barsProps = {
                entityName,
                bars,
                xPoint,
                entityColor,
                isFaint,
                isHovered,
                isSelected,
                barWidth,
                tooltipProps,
                currentX,
                onEntityClick: this.onEntityClick,
                onEntityMouseLeave: this.onEntityMouseLeave,
                onEntityMouseOver: this.onEntityMouseOver,
                labelYOffset,
                y0,
                noDataHeight,
                dualAxis,
                isExportingToSvgOrPng: this.manager.isExportingtoSvgOrPng,
            }
            const result = (
                <MarimekkoBarsForOneEntity key={entityName} {...barsProps} />
            )
            if (isSelected || isHovered) highlightedElements.push(result)
            else normalElements.push(result)
        }

        return ([] as JSX.Element[]).concat(
            patterns,
            noDataAreaElement ? [noDataAreaElement] : [],
            normalElements,
            placedLabels,
            labelLines,
            highlightedElements,
            noDataLabel ? [noDataLabel] : []
        )
    }
    private paddingInPixels = 5
 
    private static labelCandidateFromItem(
        item: EntityWithSize,
        baseFontSize: number,
        isSelected: boolean
    ): LabelCandidate {
        return {
            item: item,
            bounds: Bounds.forText(item.entityName, {
                fontSize: 0.7 * baseFontSize,
            }),
            isPicked: isSelected,
            isSelected,
        }
    }
 
    /** This function splits label candidates into N groups so that each group has approximately
    the same sum of x value metric. This is useful for picking labels because we want to have e.g.
    20 labels relatively evenly spaced (in x domain space) and this function gives us 20 groups that
    are roughly of equal size and then we can pick the largest of each group */
    private static splitIntoEqualDomainSizeChunks(
        candidates: LabelCandidate[],
        numChunks: number
    ): LabelCandidate[][] {
        const chunks: LabelCandidate[][] = []
        let currentChunk: LabelCandidate[] = []
        let domainSizeOfChunk = 0
        const domainSizeThreshold = Math.ceil(
            sumBy(candidates, (candidate) => candidate.item.xValue) / numChunks
        )
        for (const candidate of candidates) {
            while (domainSizeOfChunk > domainSizeThreshold) {
                chunks.push(currentChunk)
                currentChunk = []
                domainSizeOfChunk -= domainSizeThreshold
            }
            domainSizeOfChunk += candidate.item.xValue
            currentChunk.push(candidate)
        }
        chunks.push(currentChunk)
 
        return chunks.filter((chunk) => chunk.length > 0)
    }
 
    @computed private get pickedLabelCandidates(): LabelCandidate[] {
        const {
            xColumnAtLastTimePoint,
            yColumnsAtLastTimePoint,
            selectedItems,
            xRange,
            baseFontSize,
            paddingInPixels,
        } = this
 
        if (!xColumnAtLastTimePoint || yColumnsAtLastTimePoint.length === 0)
            return []
 
        // Measure the labels (before any rotation, just normal horizontal labels)
        const selectedItemsSet = new Set(
            selectedItems.map((item) => item.entityName)
        )
 
        // This is similar to what we would get with .sortedItems but
        // we want this for the last year to pick all labels there - sortedItems
        // changes with the time point the user selects
        const ySizeMap: Map<string, number> = new Map(
            yColumnsAtLastTimePoint[0].owidRows.map((row) => [
                row.entityName,
                row.value,
            ])
        )
 
        const labelCandidates: LabelCandidate[] =
            xColumnAtLastTimePoint.owidRows.map((row) =>
                MarimekkoChart.labelCandidateFromItem(
                    {
                        entityName: row.entityName,
                        xValue: row.value,
                        ySortValue: ySizeMap.get(row.entityName),
                    },
                    baseFontSize,
                    selectedItemsSet.has(row.entityName)
                )
            )
 
        labelCandidates.sort((a, b) => {
            const yRowsForA = a.item.ySortValue
            const yRowsForB = b.item.ySortValue
 
            if (yRowsForA !== undefined && yRowsForB !== undefined)
                return yRowsForB - yRowsForA
            else if (yRowsForA === undefined && yRowsForB !== undefined)
                return -1
            else if (yRowsForA !== undefined && yRowsForB === undefined)
                return 1
            // (yRowsForA === undefined && yRowsForB === undefined)
            else return 0
        })
 
        const averageCharacterCount =
            sumBy(labelCandidates, (item) => item.item.entityName.length) /
            labelCandidates.length
 
        const firstDefined = labelCandidates.find(
            (item) => item.item.ySortValue !== undefined
        )
        const labelCharacterCountThreshold = 1.4 * averageCharacterCount
        // Always pick the first and last element and the first one that is not undefined for y
        // but only if it is less than 1.4 times as long in character count as the average label (avoid
        // picking "Democratic Republic of Congo" for this reason and thus needing lots of space)
        if (
            firstDefined &&
            firstDefined.item.entityName.length < labelCharacterCountThreshold
        )
            firstDefined.isPicked = true
        const labelHeight = labelCandidates[0].bounds.height
        if (
            labelCandidates[labelCandidates.length - 1].item.entityName.length <
            labelCharacterCountThreshold
        )
            labelCandidates[labelCandidates.length - 1].isPicked = true
        const availablePixels = xRange[1] - xRange[0]
 
        const numLabelsToAdd = Math.floor(
            Math.min(availablePixels / (labelHeight + paddingInPixels) / 4, 20) // factor 4 is arbitrary to taste
        )
        const chunks = MarimekkoChart.splitIntoEqualDomainSizeChunks(
            labelCandidates,
            numLabelsToAdd
        )
        const picks = chunks.flatMap((chunk) => {
            const picked = chunk.filter((candidate) => candidate.isPicked)
            if (picked.length > 0) return picked
            else {
                return maxBy(chunk, (candidate) => candidate.item.xValue)
            }
        })
        for (const max of picks) {
            if (max) max.isPicked = true
        }
        const picked = labelCandidates.filter((candidate) => candidate.isPicked)
 
        return picked
    }
 
    @computed private get labelsWithPlacementInfo(): LabelWithPlacement[] {
        const {
            dualAxis,
            x0,
            placedItemsMap,
            labels,
            unrotatedLongestLabelWidth,
            unrotatedHighestLabelHeight,
            labelAngleInDegrees,
        } = this
        const labelsYPosition = dualAxis.verticalAxis.place(0)

        const labelsWithPlacements: LabelWithPlacement[] = labels
            .map(({ candidate, labelElement }) => {
                const item = placedItemsMap.get(candidate.item.entityName)
                const xPoint = item?.xPoint.value ?? 0
                const barWidth =
                    dualAxis.horizontalAxis.place(xPoint) -
                    dualAxis.horizontalAxis.place(x0)

                const labelId = candidate.item.entityName
                if (!item) {
                    console.error(
                        "Could not find item",
                        candidate.item.entityName
                    )
                    return null
                } else {
                    const currentX =
                        dualAxis.horizontalAxis.place(x0) + item.xPosition
                    const labelWithPlacement = {
                        label: (
                            <g
                                transform={`translate(${0}, ${labelsYPosition})`}
                            >
                                {labelElement}
                            </g>
                        ),
                        preferredPlacement: currentX + barWidth / 2,
                        correctedPlacement: currentX + barWidth / 2,
                        labelKey: labelId,
                    }
                    return labelWithPlacement
                }
            })
            .filter(
                (item: LabelWithPlacement | null): item is LabelWithPlacement =>
                    item !== null
            )

        // This collision detection code is optimized for the particular
        // case of distributing items in 1D, knowing that we picked a low
        // enough number of labels that we will be able to fit all labels.
        // The algorithm iterates the list twice, i.e. works in linear time
        // with the number of labels to show
        // The logic in pseudo code:
        // for current, next in iterate-left-to-right-pairs:
        //   if next.x < current.x + label-width:
        //      next.x = current.x + label-width
        // last.x = Math.min(last.x, max-x)
        // for current, prev in iterate-right-to-left-pairs:
        //   if prev.x > current.x - label-width:
        //      prev.x = current.x - label-width

        // The label width is uniform for now and starts with
        // the height of a label when printed in normal horizontal layout
        // Since labels are rotated we need to make a bit more space so that they
        // stack correctly. Consider:
        //     ╱---╱ ╱---╱
        //    ╱   ╱ ╱   ╱
        //   ╱   ╱ ╱   ╱
        //  ╱---╱ ╱---╱
        // If we would just use exactly the label width then the flatter the angle
        // the more they would actually overlap so we need a correction factor. It turns
        // out than tan(angle) is the correction factor we want, although for horizontal
        // labels we don't want to use +infinity :) so we Math.min it with the longest label width
        if (labelsWithPlacements.length === 0) return []

        labelsWithPlacements.sort(
            (a, b) => a.preferredPlacement - b.preferredPlacement
        )

        const labelWidth = unrotatedHighestLabelHeight
        const correctionFactor =
            1 +
            Math.min(
                unrotatedLongestLabelWidth / labelWidth,
                Math.abs(Math.tan(labelAngleInDegrees))
            )
        const correctedLabelWidth = labelWidth * correctionFactor

        for (let i = 0; i < labelsWithPlacements.length - 1; i++) {
            const current = labelsWithPlacements[i]
            const next = labelsWithPlacements[i + 1]
            const minNextX = current.correctedPlacement + correctedLabelWidth
            if (next.correctedPlacement < minNextX)
                next.correctedPlacement = minNextX
        }
        labelsWithPlacements[
            labelsWithPlacements.length - 1
        ].correctedPlacement = Math.min(
            labelsWithPlacements[labelsWithPlacements.length - 1]
                .correctedPlacement,
            dualAxis.horizontalAxis.rangeSize
        )
        for (let i = labelsWithPlacements.length - 1; i > 0; i--) {
            const current = labelsWithPlacements[i]
            const previous = labelsWithPlacements[i - 1]
            const maxPreviousX =
                current.correctedPlacement - correctedLabelWidth
            if (previous.correctedPlacement > maxPreviousX)
                previous.correctedPlacement = maxPreviousX
        }
 
        return labelsWithPlacements
    }
 
    @computed private get labelLines(): JSX.Element[] {
        const { labelsWithPlacementInfo, dualAxis, selectedItems } = this
        const shiftedGroups: LabelWithPlacement[][] = []
        const unshiftedElements: LabelWithPlacement[] = []
        const selectedItemsKeys = new Set(
            selectedItems.map((item) => item.entityName)
        )
        let startNewGroup = true
 
        const barEndpointY = dualAxis.verticalAxis.place(0)
 
        for (const labelWithPlacement of labelsWithPlacementInfo) {
            if (
                labelWithPlacement.preferredPlacement ===
                labelWithPlacement.correctedPlacement
            ) {
                unshiftedElements.push(labelWithPlacement)
                startNewGroup = true
            } else {
                if (startNewGroup) {
                    shiftedGroups.push([labelWithPlacement])
                    startNewGroup = false
                } else {
                    shiftedGroups[shiftedGroups.length - 1].push(
                        labelWithPlacement
                    )
                }
            }
        }
        // If we wanted to hide the label lines if all lines are straight
        // then we could do this but this makes it jumpy over time
        // if (shiftedGroups.length === 0) return []
        // else {
        const labelLines: JSX.Element[] = []
        for (const group of shiftedGroups) {
            let indexInGroup = 0
            for (const item of group) {
                const lineColor = selectedItemsKeys.has(item.labelKey)
                    ? "#999"
                    : "#bbb"
                const markerBarEndpointX = item.preferredPlacement
                const markerTextEndpointX = item.correctedPlacement
                const markerBarEndpointY = barEndpointY + MARKER_MARGIN
                const markerTextEndpointY =
                    barEndpointY + MARKER_AREA_HEIGHT - MARKER_MARGIN
                const markerNetHeight = MARKER_AREA_HEIGHT - 2 * MARKER_MARGIN
                const markerStepSize = markerNetHeight / (group.length + 1)
                const directionUnawareMakerYMid =
                    (indexInGroup + 1) * markerStepSize
                const markerYMid =
                    markerBarEndpointX > markerTextEndpointX
                        ? directionUnawareMakerYMid
                        : markerNetHeight - directionUnawareMakerYMid
                labelLines.push(
                    <g className="indicator" key={`labelline-${item.labelKey}`}>
                        <path
                            d={`M${markerBarEndpointX},${markerBarEndpointY} v${markerYMid} H${markerTextEndpointX} V${markerTextEndpointY}`}
                            stroke={lineColor}
                            strokeWidth={1}
                            fill="none"
                        />
                    </g>
                )
                indexInGroup++
            }
        }
        for (const item of unshiftedElements) {
            const lineColor = selectedItemsKeys.has(item.labelKey)
                ? "#555"
                : "#bbb"
            const markerBarEndpointX = item.preferredPlacement
            const markerBarEndpointY = barEndpointY + MARKER_MARGIN
            const markerTextEndpointY =
                barEndpointY + MARKER_AREA_HEIGHT - MARKER_MARGIN
 
            labelLines.push(
                <g className="indicator" key={`labelline-${item.labelKey}`}>
                    <path
                        d={`M${markerBarEndpointX},${markerBarEndpointY} V${markerTextEndpointY}`}
                        stroke={lineColor}
                        strokeWidth={1}
                        fill="none"
                    />
                </g>
            )
        }
        return labelLines
        //}
    }
 
    @computed private get placedLabels(): JSX.Element[] {
        const labelOffset = MARKER_AREA_HEIGHT
        // old logic tried to hide labellines but that is too jumpy
        // labelLines.length
        //     ? MARKER_AREA_HEIGHT
        //     : this.baseFontSize / 2
        const placedLabels = this.labelsWithPlacementInfo.map((item) => (
            <g
                key={`label-${item.labelKey}`}
                className="bar-label"
                transform={`translate(${item.correctedPlacement}, ${labelOffset})`}
            >
                {item.label}
            </g>
        ))
 
        return placedLabels
    }
 
    @computed private get unrotatedLongestLabelWidth(): number {
        const widths = this.pickedLabelCandidates.map(
            (candidate) => candidate.bounds.width
        )
        const maxWidth = Math.max(...widths)
        return maxWidth
    }
 
    @computed private get unrotatedHighestLabelHeight(): number {
        const heights = this.pickedLabelCandidates.map(
            (candidate) => candidate.bounds.height
        )
        return Math.max(...heights)
    }
 
    @computed private get longestLabelHeight(): number {
        // This takes the angle of rotation of the entity labels into account
        // This is somewhat simplified as we treat this as a one-dimensional
        // entity whereas in reality the textbox if of course 2D. To account
        // for that we do max(fontSize, rotatedLabelHeight) in the end
        // as a rough proxy
        const rotatedLabelHeight =
            this.unrotatedLongestLabelWidth *
            Math.abs(Math.sin((this.labelAngleInDegrees * Math.PI) / 180))
        return Math.max(this.fontSize, rotatedLabelHeight)
    }
 
    @computed private get longestLabelWidth(): number {
        // This takes the angle of rotation of the entity labels into account
        // This is somewhat simplified as we treat this as a one-dimensional
        // entity whereas in reality the textbox if of course 2D. To account
        // for that we do max(fontSize, rotatedLabelHeight) in the end
        // as a rough proxy
        const rotatedLabelWidth =
            this.unrotatedLongestLabelWidth *
            Math.abs(Math.cos((this.labelAngleInDegrees * Math.PI) / 180))
        return Math.max(this.fontSize, rotatedLabelWidth)
    }
 
    @computed private get labels(): LabelCandidateWithElement[] {
        const { labelAngleInDegrees, series, domainColorForEntityMap } = this
        return this.pickedLabelCandidates.map((candidate) => {
            const labelX = candidate.bounds.width
            const domainColor = domainColorForEntityMap.get(
                candidate.item.entityName
            )
            const seriesColor = series[0].color
            const color = domainColor?.color ?? seriesColor ?? "#000"
            return {
                candidate,
                labelElement: (
                    <text
                        key={`${candidate.item.entityName}-label`}
                        x={-labelX}
                        y={0}
                        width={candidate.bounds.width}
                        height={candidate.bounds.height}
                        fontWeight={candidate.isSelected ? 700 : 400}
                        fill={color}
                        transform={`rotate(${labelAngleInDegrees}, 0, 0)`}
                        opacity={1}
                        fontSize="0.7em"
                        textAnchor="right"
                        dominantBaseline="middle"
                        onMouseOver={(): void =>
                            this.onEntityMouseOver(candidate.item.entityName)
                        }
                        onMouseLeave={(): void => this.onEntityMouseLeave()}
                        onClick={(): void =>
                            this.onEntityClick(candidate.item.entityName)
                        }
                    >
                        {candidate.item.entityName}
                    </text>
                ),
            }
        })
    }
 
    static Tooltip(props: TooltipProps): JSX.Element {
        const isSingleVariable = props.item.bars.length === 1
        // shouldShowXTimeNoitice is a bit of a lie since at the moment we don't include
        // entities that don't have x values for the current year. This might change though
        // and then the mechanism is already in place
        const shouldShowXTimeNotice =
            props.item.xPoint.time !== props.targetTime
        let hasTimeNotice = shouldShowXTimeNotice
        const header = isSingleVariable ? (
            <tr>
                <td>
                    <div
                        style={{
                            width: "10px",
                            height: "10px",
                            backgroundColor: props.item.entityColor?.color,
                            display: "inline-block",
                        }}
                    />
                </td>
                <td colSpan={3} style={{ color: "#111" }}>
                    <strong>{props.item.entityName}</strong>
                </td>
            </tr>
        ) : (
            <tr>
                <td colSpan={4} style={{ color: "#111" }}>
                    <strong>{props.item.entityName}</strong>
                </td>
            </tr>
        )
 
        return (
            <table
                style={{
                    lineHeight: "1em",
                    whiteSpace: "normal",
                    borderSpacing: "0.5em",
                }}
            >
                <tbody>
                    {header}
                    {props.item.bars.map((bar) => {
                        const { highlightedSeriesName } = props
                        const squareColor = bar.color
                        const isHighlighted =
                            bar.seriesName === highlightedSeriesName
                        const isFaint =
                            highlightedSeriesName !== undefined &&
                            !isHighlighted
                        const shouldShowYTimeNotice =
                            bar.yPoint.value !== undefined &&
                            bar.yPoint.time !== props.targetTime
 
                        hasTimeNotice ||= shouldShowYTimeNotice
                        const colorSquare = isSingleVariable ? null : (
                            <div
                                style={{
                                    width: "10px",
                                    height: "10px",
                                    backgroundColor: squareColor,
                                    display: "inline-block",
                                }}
                            />
                        )
 
                        return (
                            <tr
                                key={`${bar.seriesName}`}
                                style={{
                                    color: isHighlighted
                                        ? "#000"
                                        : isFaint
                                        ? "#707070"
                                        : "#444",
                                }}
                            >
                                <td>{colorSquare}</td>
                                <td
                                    style={{
                                        paddingRight: "0.8em",
                                        fontSize: "0.9em",
                                    }}
                                >
                                    {bar.seriesName}
                                </td>
                                <td
                                    style={{
                                        textAlign: "right",
                                        whiteSpace: "nowrap",
                                    }}
                                >
                                    {bar.yPoint.value === undefined
                                        ? "No data"
                                        : props.yAxisColumn.formatValueShort(
                                              bar.yPoint.value,
                                              {
                                                  noTrailingZeroes: false,
                                              }
                                          )}
                                </td>
                                {shouldShowYTimeNotice && (
                                    <td
                                        style={{
                                            fontWeight: "normal",
                                            color: "#707070",
                                            fontSize: "0.8em",
                                            whiteSpace: "nowrap",
                                            paddingLeft: "8px",
                                        }}
                                    >
                                        <span className="icon">
                                            <FontAwesomeIcon
                                                icon={faInfoCircle}
                                                style={{
                                                    marginRight: "0.25em",
                                                }}
                                            />{" "}
                                        </span>
                                        {props.timeColumn.formatValue(
                                            bar.yPoint.time
                                        )}
                                    </td>
                                )}
                            </tr>
                        )
                    })}
                    <tr>
                        <td></td>
                        <td>{props.xAxisColumn.displayName}</td>
                        <td
                            style={{
                                textAlign: "right",
                                whiteSpace: "nowrap",
                            }}
                        >
                            {props.xAxisColumn.formatValueShort(
                                props.item.xPoint.value
                            )}
                            {shouldShowXTimeNotice && (
                                <td
                                    style={{
                                        fontWeight: "normal",
                                        color: "#707070",
                                        fontSize: "0.8em",
                                        whiteSpace: "nowrap",
                                        paddingLeft: "8px",
                                    }}
                                >
                                    <span className="icon">
                                        <FontAwesomeIcon
                                            icon={faInfoCircle}
                                            style={{
                                                marginRight: "0.25em",
                                            }}
                                        />{" "}
                                    </span>
                                    {props.timeColumn.formatValue(
                                        props.item.xPoint.time
                                    )}
                                </td>
                            )}
                        </td>
                        <td></td>
                    </tr>
                    {hasTimeNotice && (
                        <tr>
                            <td
                                colSpan={4}
                                style={{
                                    color: "#707070",
                                    fontSize: "0.8em",
                                    paddingTop: "10px",
                                }}
                            >
                                <div style={{ display: "flex" }}>
                                    <span
                                        className="icon"
                                        style={{ marginRight: "0.5em" }}
                                    >
                                        <FontAwesomeIcon icon={faInfoCircle} />{" "}
                                    </span>
                                    <span>
                                        No data available for{" "}
                                        {props.timeColumn.formatValue(
                                            props.targetTime
                                        )}
                                        . Showing closest available data point
                                        instead.
                                    </span>
                                </div>
                            </td>
                        </tr>
                    )}
                </tbody>
            </table>
        )
    }
 
    @computed get failMessage(): string {
        const column = this.yColumns[0]
        const { yColumns, yColumnSlugs, xColumn } = this
 
        if (!column) return "No Y column to chart"
        if (!xColumn) return "No X column to chart"
 
        return yColumns.every((col) => col.isEmpty)
            ? `No matching data in columns ${yColumnSlugs.join(", ")}`
            : ""
    }
}