All files / owid-grapher/grapher/core Grapher.tsx

81.56% Statements 2141/2625
72.79% Branches 329/452
70.48% Functions 160/227
81.56% Lines 2141/2625

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 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 25661x 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 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 223x 223x 223x 25x 25x 25x 25x 25x 25x 25x 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 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 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 223x 223x 223x 223x 1x 1x               1x 1x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 207x 95x 49x 207x 207x 1x 1x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 1x 1x 265x 265x 265x         265x 265x 265x         265x 265x 265x 265x 265x 265x 265x 265x   265x 265x 265x 265x 265x         265x 265x 265x         265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x     265x   265x     265x 1x 1x 41x 41x 41x 41x 1x 1x 112x 112x 1x 1x 289x 289x 1x 1x 61x 61x 1x 1x 12x 12x 1x 1x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 51x 51x 51x 51x 51x 51x 1x 1x 1x 226x 226x 226x 226x 226x 226x     226x 226x 226x 1x 1x 1x     1x 1x 1x 112x 112x 111x 111x 1x 1x 114x 114x 114x 114x 5x 109x 114x 1x 1x 1x 109x 109x 109x 109x 109x 109x 109x 1x 1x 142x 142x 1x 1x 1x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 36x 36x 36x 36x 36x 36x 36x 34x 34x 39x 39x 4x 4x 4x 4x 9x 9x 4x 4x 4x 1x 1x 39x 39x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x         1x 1x 1x 49x 49x 49x                           49x       49x 1x 1x     1x 1x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x   50x   50x 50x 1x 1x 50x 50x 50x 50x 50x 50x 1x 1x 1x 1x 50x 50x 50x 50x 50x 50x 1x 1x 50x 50x 50x 50x 50x 50x 50x 1x 1x 56x 56x 56x 56x 56x 1x 1x 1x 1x 12x 12x 12x 12x 1x 1x 26x 26x 1x 1x 1x 114x 114x 1x 1x 114x 114x 58x 58x 58x 58x       58x 58x 56x 114x     1x 1x 1x 114x 114x 114x 114x 1x 1x 60x 60x 60x 60x 1x 1x 13x 13x 1x 1x 111x 106x 106x 111x 111x 111x 111x 111x 111x 111x 111x 111x 1x 1x 52x 18x 18x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 54x 54x 1x 1x 1x 1x 1x 49x 49x 1x 1x 49x 49x 1x 1x 59x 59x 55x 55x 55x 59x 59x 1x 1x 13x 13x 13x 13x 13x 13x       1x 1x 49x 49x 1x 1x         1x 1x         1x 1x 1x 1x 13x 13x 13x 13x 1x 1x 1x         1x 1x 1x 1x     1x 1x 13x 13x 1x 1x 1x 1x                                       1x 1x                                           1x 1x 1x 13x 13x 13x 13x 1x 1x 13x 13x 1x 1x 13x 13x 1x 1x 3x 3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 1x 1x 192x 4x 4x 4x 188x 188x 188x 188x 188x 188x 1x 1x 55x     55x 55x 55x 55x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x     2x     1x 1x 49x 49x 1x 1x     1x 1x                           1x 1x 176x 176x 176x 176x 176x 176x 1x 1x 2x 2x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 23x 23x 23x 23x 23x 23x     23x 23x       23x 23x 23x 16x 23x 23x 23x 23x 23x 23x 23x   23x 23x 23x 23x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 27x 27x 27x 28x 4x 28x 28x 28x 28x 28x 28x 28x 22x 28x 21x 28x 15x 15x 28x 28x 28x 28x   28x 28x 1x 1x 15x 15x 15x 1x 1x 78x 78x 156x 78x 78x 78x 1x 1x 8x 8x 8x 8x 8x 8x 8x     1x 1x     1x 1x 109x 3x 109x 1x 1x 25x 25x 25x 25x 1x 1x 33x 30x 30x 33x 1x 1x 110x 72x 110x 110x 110x 110x 1x 1x 27x 24x 24x 27x 1x 1x 36x 36x 1x 1x 19x 19x 1x 1x 85x 85x 85x 85x 1x 1x     1x 1x     1x 1x 23x 23x 23x 23x 21x 21x 23x 16x 16x 16x 16x 23x 23x 23x 1x 1x 13x 13x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 13x 13x 13x 13x 13x 13x 22x 22x 22x 22x 22x 66x 66x   66x 66x 66x 66x 66x 66x 66x 66x 22x 22x 13x 13x 13x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 24x 2x 24x 24x 1x 1x 24x 24x 24x 24x 23x 23x 23x 23x 23x 23x 23x 23x 23x 24x 24x 23x 24x 24x 23x 23x 23x 1x 1x 24x 24x 1x 1x 1x     1x 1x 1x 114x 114x 83x 83x 114x 1x 1x 116x 116x 1x 65x 65x 1x     1x 19x 19x 1x 55x 55x 1x 68x 68x 1x 21x 21x 1x 55x 55x 1x 58x 58x 1x 1x 114x 114x 1x 1x     1x 1x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 12x 12x 1x 1x 1x     1x 1x         1x 1x     1x 1x                 1x 1x 7x 7x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 49x 49x 1x 1x 10x 6x 6x 6x 6x 6x 6x 6x 6x 10x   10x 10x 6x 6x 6x 1x 1x 1x         1x 1x                                                               1x 1x                                         1x 1x     1x 1x 13x 13x 1x 1x 13x 13x 1x 1x 13x 13x 1x 1x 13x 13x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x       1x 1x 1x           1x 1x 1x 1x 13x 13x   13x 13x 13x 1x 13x 13x   13x 13x 13x 1x 1x 13x 13x   13x 13x 1x 1x 1x 1x 1x 1x 13x 13x 1x 1x 1x 1x 1x     1x 1x 2x 2x 1x 1x 1x     1x 1x     1x 1x 3x 3x 1x 1x 13x                               1x 1x 26x 26x 26x   26x 26x 26x   26x 26x 26x 1x 1x 26x 26x 26x 26x 1x 1x 32x 32x 1x 1x     1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 50x 50x 1x 1x 22x 220x 220x 220x 220x 220x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x     22x 22x     22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 22x 22x 22x 1x 1x 1x 1x           1x 1x       1x 1x           1x 1x           1x 1x     1x 1x 10x 10x 10x   10x 10x 1x 1x 9x 9x 9x 9x 9x 9x 1x 1x 9x 9x 9x 9x 9x 9x 9x     9x       9x 9x 1x 1x 23x 23x 1x 1x 33x 33x 33x 33x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 3x 3x 30x 30x 30x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x     10x     10x 10x 10x 10x 7x 7x 10x     10x 10x 10x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x           14x 14x             14x 14x       1x 1x                     1x 1x                 1x 1x                                                                             1x 1x 1x     1x 1x 1x                 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1x 1x 1x 13x 13x 13x 1x 1x 26x 26x 26x 26x 26x 1x 1x 1x 1x                           1x 1x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 4x 4x 80x               80x 4x 4x 1x 1x             1x 1x         1x 1x 13x 13x 13x 1x 1x       1x 1x 1x 1x 13x     13x 1x 1x 13x 13x 1x 1x 13x 13x 13x 13x 13x 13x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 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 1x 1x 1x 1x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 1x 1x 1x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 114x 114x 129x 129x 114x 114x 114x 1x 1x 1x 1x 65x 65x 1x 1x 1x 134x 134x 134x 134x 134x 134x 134x 1x 1x 17x 17x 1x 1x 15x 13x 13x 15x 1x 1x 270x 270x 1x 1x 1x 14x 14x 14x 14x 14x 1x 1x     1x 1x         1x 1x 118x 118x 118x 93x 118x 118x 1x 1x 10x 10x 1x 1x 131x 131x 60x 131x 131x 131x 131x 131x 11x 1x 1x 1x 11x 120x 120x 25x 25x 25x 25x 131x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x       1x 1x 8x 8x 1x 1x               1x 1x 10x 10x 1x 1x 10x 10x 7x 7x 1x 1x 10x 10x 10x 1x 1x 10x 10x 1x 1x 10x                 10x 10x 1x 1x 10x 10x 1x 1x 10x 10x 1x 1x 10x 10x 10x 10x 3x 3x 3x 10x 10x 1x 1x 10x 10x 3x 3x 3x 3x 10x 10x 1x 1x 12x 11x 11x 1x 1x 1x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 1x 1x 12x 12x 1x 1x 1x 12x 12x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x
import * as React from "react"
import * as ReactDOMServer from "react-dom/server"
import {
    observable,
    computed,
    action,
    autorun,
    runInAction,
    reaction,
    IReactionDisposer,
} from "mobx"
import { bind } from "decko"
import {
    uniqWith,
    isEqual,
    uniq,
    slugify,
    identity,
    lowerCaseFirstLetterUnlessAbbreviation,
    isMobile,
    isVisible,
    throttle,
    next,
    sampleFrom,
    range,
    difference,
    exposeInstanceOnWindow,
    findClosestTime,
    excludeUndefined,
    debounce,
    isInIFrame,
    differenceObj,
    fetchWithRetries,
} from "../../clientUtils/Util"
import { QueryParams } from "../../clientUtils/urls/UrlUtils"
import {
    ChartTypeName,
    GrapherTabOption,
    ScaleType,
    StackMode,
    EntitySelectionMode,
    ScatterPointLabelStrategy,
    RelatedQuestionsConfig,
    BASE_FONT_SIZE,
    CookieKey,
    FacetStrategy,
    ThereWasAProblemLoadingThisChart,
    SeriesColorMap,
    FacetAxisDomain,
} from "../core/GrapherConstants"
import { OwidVariablesAndEntityKey } from "../../clientUtils/OwidVariable"
import * as Cookies from "js-cookie"
import {
    ChartDimension,
    LegacyDimensionsManager,
} from "../chart/ChartDimension"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { TooltipProps, TooltipManager } from "../tooltip/TooltipProps"
import {
    minTimeBoundFromJSONOrNegativeInfinity,
    maxTimeBoundFromJSONOrPositiveInfinity,
    TimeBounds,
    getTimeDomainFromQueryString,
    TimeBound,
    minTimeToJSON,
    maxTimeToJSON,
    timeBoundToTimeBoundString,
} from "../../clientUtils/TimeBounds"
import {
    strToQueryParams,
    queryParamsToStr,
    setWindowQueryStr,
} from "../../clientUtils/urls/UrlUtils"
import { populationMap } from "../../coreTable/PopulationMap"
import {
    GrapherInterface,
    grapherKeysToSerialize,
    GrapherQueryParams,
    LegacyGrapherInterface,
} from "../core/GrapherInterface"
import { DimensionSlot } from "../chart/DimensionSlot"
import {
    getSelectedEntityNamesParam,
    setSelectedEntityNamesParam,
} from "./EntityUrlBuilder"
import { MapProjectionName } from "../mapCharts/MapProjections"
import { LogoOption } from "../captionedChart/Logos"
import { AxisConfig, FontSizeManager } from "../axis/AxisConfig"
import { ColorScaleConfig } from "../color/ColorScaleConfig"
import { MapConfig } from "../mapCharts/MapConfig"
import { ComparisonLineConfig } from "../scatterCharts/ComparisonLine"
import {
    objectWithPersistablesToObject,
    deleteRuntimeAndUnchangedProps,
    updatePersistables,
} from "../../clientUtils/persistable/Persistable"
import { ColumnSlugs, Time } from "../../coreTable/CoreTableConstants"
import { isOnTheMap } from "../mapCharts/EntitiesOnTheMap"
import { ChartManager } from "../chart/ChartManager"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faExclamationTriangle } from "@fortawesome/free-solid-svg-icons/faExclamationTriangle"
import {
    AbsRelToggleManager,
    FacetStrategyDropdownManager,
    FooterControls,
    FooterControlsManager,
    SmallCountriesFilterManager,
} from "../controls/Controls"
import { TooltipView } from "../tooltip/Tooltip"
import { EntitySelectorModal } from "../controls/EntitySelectorModal"
import { DownloadTab, DownloadTabManager } from "../downloadTab/DownloadTab"
import * as ReactDOM from "react-dom"
import { observer } from "mobx-react"
import "d3-transition"
import { SourcesTab, SourcesTabManager } from "../sourcesTab/SourcesTab"
import { DataTable, DataTableManager } from "../dataTable/DataTable"
import { MapChartManager } from "../mapCharts/MapChartConstants"
import { MapChart } from "../mapCharts/MapChart"
import { DiscreteBarChartManager } from "../barCharts/DiscreteBarChartConstants"
import { Command, CommandPalette } from "../controls/CommandPalette"
import { ShareMenuManager } from "../controls/ShareMenu"
import {
    CaptionedChart,
    CaptionedChartManager,
    StaticCaptionedChart,
} from "../captionedChart/CaptionedChart"
import {
    TimelineController,
    TimelineManager,
} from "../timeline/TimelineController"
import {
    EntityId,
    EntityName,
    OwidColumnDef,
} from "../../coreTable/OwidTableConstants"
import { BlankOwidTable, OwidTable } from "../../coreTable/OwidTable"
import * as Mousetrap from "mousetrap"
import { SlideShowController } from "../slideshowController/SlideShowController"
import {
    ChartComponentClassMap,
    DefaultChartClass,
} from "../chart/ChartTypeMap"
import { ColorSchemeName } from "../color/ColorConstants"
import { SelectionArray } from "../selection/SelectionArray"
import { legacyToOwidTableAndDimensions } from "./LegacyToOwidTable"
import { ScatterPlotManager } from "../scatterCharts/ScatterPlotChartConstants"
import { autoDetectYColumnSlugs } from "../chart/ChartUtils"
import classNames from "classnames"
import { GrapherAnalytics } from "./GrapherAnalytics"
import {
    ADMIN_BASE_URL,
    BAKED_GRAPHER_URL,
} from "../../settings/clientSettings"
import { legacyToCurrentGrapherQueryParams } from "./GrapherUrlMigrations"
import { Url } from "../../clientUtils/urls/Url"
import {
    Annotation,
    ColumnSlug,
    DimensionProperty,
    SortBy,
    SortConfig,
    SortOrder,
} from "../../clientUtils/owidTypes"
import { ColumnTypeMap, CoreColumn } from "../../coreTable/CoreTableColumns"
import { ChartInterface } from "../chart/ChartInterface"
import { OwidChartDimensionInterface } from "../../clientUtils/OwidVariableDisplayConfigInterface"
import { MarimekkoChartManager } from "../stackedCharts/MarimekkoChartConstants"
import { AxisConfigInterface } from "../axis/AxisConfigInterface"
import Bugsnag from "@bugsnag/js"
import { FacetChartManager } from "../facetChart/FacetChartConstants"
 
declare const window: any
 
const legacyConfigToConfig = (
    config: LegacyGrapherInterface | GrapherInterface
): GrapherInterface => {
    const legacyConfig = config as LegacyGrapherInterface
    if (!legacyConfig.selectedData) return legacyConfig
 
    const newConfig = { ...legacyConfig } as GrapherInterface
    newConfig.selectedEntityIds = uniq(
        legacyConfig.selectedData.map((row) => row.entityId)
    ) // We need to do uniq because an EntityName may appear multiple times in the old graphers, once for each dimension
    return newConfig
}
 
const DEFAULT_MS_PER_TICK = 100
 
// Exactly the same as GrapherInterface, but contains options that developers want but authors won't be touching.
export interface GrapherProgrammaticInterface extends GrapherInterface {
    owidDataset?: OwidVariablesAndEntityKey // This is temporarily used for testing. Will be removed
    manuallyProvideData?: boolean // This will be removed.
    hideEntityControls?: boolean
    queryStr?: string
    isMediaCard?: boolean
    bounds?: Bounds
    table?: OwidTable
    bakedGrapherURL?: string
    adminBaseUrl?: string
    env?: string
 
    getGrapherInstance?: (instance: Grapher) => void
 
    enableKeyboardShortcuts?: boolean
    bindUrlToWindow?: boolean
    isEmbeddedInAnOwidPage?: boolean
 
    manager?: GrapherManager
}
 
export interface GrapherManager {
    canonicalUrl?: string
    embedDialogUrl?: string
    embedDialogAdditionalElements?: React.ReactElement
    selection?: SelectionArray
    editUrl?: string
}
 
@observer
export class Grapher
    extends React.Component<GrapherProgrammaticInterface>
    implements
        TimelineManager,
        ChartManager,
        FontSizeManager,
        CaptionedChartManager,
        SourcesTabManager,
        DownloadTabManager,
        DiscreteBarChartManager,
        LegacyDimensionsManager,
        ShareMenuManager,
        SmallCountriesFilterManager,
        AbsRelToggleManager,
        TooltipManager,
        FooterControlsManager,
        DataTableManager,
        ScatterPlotManager,
        MarimekkoChartManager,
        FacetStrategyDropdownManager,
        FacetChartManager,
        MapChartManager
{
    @observable.ref type = ChartTypeName.LineChart
    @observable.ref id?: number = undefined
    @observable.ref version = 1
    @observable.ref slug?: string = undefined
    @observable.ref title?: string = undefined
    @observable.ref subtitle = ""
    @observable.ref sourceDesc?: string = undefined
    @observable.ref note = ""
    @observable.ref hideTitleAnnotation?: boolean = undefined
    @observable.ref minTime?: TimeBound = undefined
    @observable.ref maxTime?: TimeBound = undefined
    @observable.ref timelineMinTime?: Time = undefined
    @observable.ref timelineMaxTime?: Time = undefined
    @observable.ref addCountryMode = EntitySelectionMode.MultipleEntities
    @observable.ref stackMode = StackMode.absolute
    @observable.ref showNoDataArea: boolean = true
    @observable.ref hideLegend?: boolean = false
    @observable.ref logo?: LogoOption = undefined
    @observable.ref hideLogo?: boolean = undefined
    @observable.ref hideRelativeToggle? = true
    @observable.ref entityType = "country"
    @observable.ref entityTypePlural = "countries"
    @observable.ref hideTimeline?: boolean = undefined
    @observable.ref zoomToSelection?: boolean = undefined
    @observable.ref minPopulationFilter?: number = undefined
    @observable.ref showYearLabels?: boolean = undefined // Always show year in labels for bar charts
    @observable.ref hasChartTab: boolean = true
    @observable.ref hasMapTab: boolean = false
    @observable.ref tab = GrapherTabOption.chart
    @observable.ref overlay?: GrapherTabOption = undefined
    @observable.ref internalNotes = ""
    @observable.ref variantName?: string = undefined
    @observable.ref originUrl = ""
    @observable.ref isPublished?: boolean = undefined
    @observable.ref baseColorScheme?: ColorSchemeName = undefined
    @observable.ref invertColorScheme?: boolean = undefined
    @observable.ref hideLinesOutsideTolerance?: boolean = undefined
    @observable hideConnectedScatterLines?: boolean = undefined // Hides lines between points when timeline spans multiple years. Requested by core-econ for certain charts
    @observable
    scatterPointLabelStrategy?: ScatterPointLabelStrategy = undefined
    @observable.ref compareEndPointsOnly?: boolean = undefined
    @observable.ref matchingEntitiesOnly?: boolean = undefined
    /** Hides the total value label that is normally displayed for stacked bar charts */
    @observable.ref hideTotalValueLabel?: boolean = undefined
 
    @observable.ref xAxis = new AxisConfig(undefined, this)
    @observable.ref yAxis = new AxisConfig(undefined, this)
    @observable colorScale = new ColorScaleConfig()
    @observable map = new MapConfig()
    @observable.ref dimensions: ChartDimension[] = []
 
    @observable ySlugs?: ColumnSlugs = undefined
    @observable xSlug?: ColumnSlug = undefined
    @observable colorSlug?: ColumnSlug = undefined
    @observable sizeSlug?: ColumnSlug = undefined
    @observable tableSlugs?: ColumnSlugs = undefined
    @observable backgroundSeriesLimit?: number = undefined
 
    @observable selectedEntityNames: EntityName[] = []
    @observable selectedEntityColors: { [entityName: string]: string } = {}
    @observable selectedEntityIds: EntityId[] = []
    @observable excludedEntities?: number[] = undefined
    /** IncludedEntities are ususally empty which means use all available entites. When
        includedEntities is set it means "only use these entities". excludedEntities
        are evaluated afterwards and can still remove entities even if they were included before.
     */
    @observable includedEntities?: number[] = undefined
    @observable comparisonLines: ComparisonLineConfig[] = [] // todo: Persistables?
    @observable relatedQuestions: RelatedQuestionsConfig[] = [] // todo: Persistables?
    @observable.ref annotation?: Annotation = undefined
 
    @observable hideFacetControl?: boolean = true
 
    // the desired faceting strategy, which might not be possible if we change the data
    @observable selectedFacetStrategy?: FacetStrategy = undefined
 
    @observable sortBy?: SortBy
    @observable sortOrder?: SortOrder
    @observable sortColumnSlug?: string
 
    owidDataset?: OwidVariablesAndEntityKey = undefined // This is temporarily used for testing. Will be removed
    manuallyProvideData? = false // This will be removed.
 
    // TODO: Pass these 5 in as options, don't get them as globals.
    isDev = this.props.env === "development"
    analytics = new GrapherAnalytics(this.props.env ?? "")
    isEditor =
        typeof window !== "undefined" && (window as any).isEditor === true
    @observable bakedGrapherURL = BAKED_GRAPHER_URL
    adminBaseUrl = ADMIN_BASE_URL
 
    @observable.ref inputTable: OwidTable
 
    @observable.ref legacyConfigAsAuthored: Partial<LegacyGrapherInterface> = {}
 
    @computed get dataTableSlugs(): ColumnSlug[] {
        return this.tableSlugs ? this.tableSlugs.split(" ") : this.newSlugs
    }
 
    /**
     * todo: factor this out and make more RAII.
     *
     * Explorers create 1 Grapher instance, but as the user clicks around the Explorer loads other author created Graphers.
     * But currently some Grapher features depend on knowing how the current state is different than the "authored state".
     * So when an Explorer updates the grapher, it also needs to update this "original state".
     */
    @action.bound setAuthoredVersion(
        config: Partial<LegacyGrapherInterface>
    ): void {
        this.legacyConfigAsAuthored = config
    }
 
    @action.bound updateAuthoredVersion(
        config: Partial<LegacyGrapherInterface>
    ): void {
        this.legacyConfigAsAuthored = {
            ...this.legacyConfigAsAuthored,
            ...config,
        }
    }
 
    constructor(
        propsWithGrapherInstanceGetter: GrapherProgrammaticInterface = {}
    ) {
        super(propsWithGrapherInstanceGetter)
 
        const { getGrapherInstance, ...props } = propsWithGrapherInstanceGetter
 
        this.inputTable = props.table ?? BlankOwidTable(`initialGrapherTable`)
        const modernConfig = props ? legacyConfigToConfig(props) : props
 
        if (props) this.setAuthoredVersion(props)
 
        this.updateFromObject(modernConfig)
 
        if (!props.table) this.downloadData()
 
        this.populateFromQueryParams(
            legacyToCurrentGrapherQueryParams(props.queryStr ?? "")
        )
 
        if (this.isEditor) this.ensureValidConfigWhenEditing()
 
        if (getGrapherInstance) getGrapherInstance(this) // todo: possibly replace with more idiomatic ref
 
        this.checkVisibility = throttle(this.checkVisibility, 400)
    }
 
    toObject(): GrapherInterface {
        const obj: GrapherInterface = objectWithPersistablesToObject(
            this,
            grapherKeysToSerialize
        )
 
        if (this.selection.hasSelection)
            obj.selectedEntityNames = this.selection.selectedEntityNames
 
        deleteRuntimeAndUnchangedProps(obj, defaultObject)
 
        // todo: nulls got into the DB for this one. we can remove after moving Graphers from DB.
        if (obj.stackMode === null) delete obj.stackMode
 
        // JSON doesn't support Infinity, so we use strings instead.
        if (obj.minTime) obj.minTime = minTimeToJSON(this.minTime) as any
        if (obj.maxTime) obj.maxTime = maxTimeToJSON(this.maxTime) as any
 
        // todo: remove dimensions concept
        // if (this.legacyConfigAsAuthored?.dimensions)
        //     obj.dimensions = this.legacyConfigAsAuthored.dimensions
 
        return obj
    }
 
    @action.bound downloadData(): void {
        if (this.manuallyProvideData) {
        } else if (this.owidDataset)
            this._receiveOwidDataAndApplySelection(this.owidDataset)
        else this.downloadLegacyDataFromOwidVariableIds()
    }
 
    @action.bound updateFromObject(obj?: GrapherProgrammaticInterface): void {
        if (!obj) return
 
        // we can remove when we purge current graphers which have this set.
        if (obj.stackMode === null) delete obj.stackMode
 
        updatePersistables(this, obj)
 
        // Regression fix: some legacies have this set to Null. Todo: clean DB.
        if (obj.originUrl === null) this.originUrl = ""
 
        // JSON doesn't support Infinity, so we use strings instead.
        this.minTime = minTimeBoundFromJSONOrNegativeInfinity(obj.minTime)
        this.maxTime = maxTimeBoundFromJSONOrPositiveInfinity(obj.maxTime)
 
        // Todo: remove once we are more RAII.
        if (obj?.dimensions?.length)
            this.setDimensionsFromConfigs(obj.dimensions)
    }
 
    @action.bound populateFromQueryParams(params: GrapherQueryParams): void {
        // Set tab if specified
        const tab = params.tab
        if (tab) {
            if (!this.availableTabs.includes(tab as GrapherTabOption))
                console.error("Unexpected tab: " + tab)
            else this.tab = tab as GrapherTabOption
        }
 
        const overlay = params.overlay
        if (overlay) {
            if (!this.availableTabs.includes(overlay as GrapherTabOption))
                console.error("Unexpected overlay: " + overlay)
            else this.overlay = overlay as GrapherTabOption
        }
 
        // Stack mode for bar and stacked area charts
        this.stackMode = (params.stackMode ?? this.stackMode) as StackMode
 
        this.zoomToSelection =
            params.zoomToSelection === "true" ? true : this.zoomToSelection
 
        this.minPopulationFilter = params.minPopulationFilter
            ? parseInt(params.minPopulationFilter)
            : this.minPopulationFilter
 
        // Axis scale mode
        const xScaleType = params.xScale
        if (xScaleType) {
            if (xScaleType === ScaleType.linear || xScaleType === ScaleType.log)
                this.xAxis.scaleType = xScaleType
            else console.error("Unexpected xScale: " + xScaleType)
        }
 
        const yScaleType = params.yScale
        if (yScaleType) {
            if (yScaleType === ScaleType.linear || yScaleType === ScaleType.log)
                this.yAxis.scaleType = yScaleType
            else console.error("Unexpected xScale: " + yScaleType)
        }
 
        const time = params.time
        if (time !== undefined && time !== "")
            this.setTimeFromTimeQueryParam(time)
 
        const endpointsOnly = params.endpointsOnly
        if (endpointsOnly !== undefined)
            this.compareEndPointsOnly = endpointsOnly === "1" ? true : undefined
 
        const region = params.region
        if (region !== undefined)
            this.map.projection = region as MapProjectionName
 
        const selection = getSelectedEntityNamesParam(
            Url.fromQueryParams(params)
        )
 
        if (this.addCountryMode !== EntitySelectionMode.Disabled && selection)
            this.selection.setSelectedEntities(selection)
 
        // faceting
        if (params.facet && params.facet in FacetStrategy) {
            this.selectedFacetStrategy = params.facet as FacetStrategy
        }
        if (params.uniformYAxis === "0") {
            this.yAxis.facetDomain = FacetAxisDomain.independent
        } else if (params.uniformYAxis === "1") {
            this.yAxis.facetDomain = FacetAxisDomain.shared
        }
    }
 
    @action.bound private setTimeFromTimeQueryParam(time: string): void {
        this.timelineHandleTimeBounds = getTimeDomainFromQueryString(time).map(
            (time) => findClosestTime(this.times, time) ?? time
        ) as TimeBounds
    }
 
    @computed private get isChartOrMapTab(): boolean {
        return this.tab === GrapherTabOption.chart || this.isOnMapTab
    }
 
    @computed private get isOnMapTab(): boolean {
        return this.tab === GrapherTabOption.map
    }
 
    @computed get yAxisConfig(): Readonly<AxisConfigInterface> {
        return this.yAxis.toObject()
    }
 
    @computed get xAxisConfig(): Readonly<AxisConfigInterface> {
        return this.xAxis.toObject()
    }
 
    @computed get tableForSelection(): OwidTable {
        // This table specifies which entities can be selected in the charts EntitySelectorModal.
        // It should contain all entities that can be selected, and none more.
        // Depending on the chart type, the criteria for being able to select an entity are
        // different; e.g. for scatterplots, the entity needs to (1) not be excluded and
        // (2) needs to have data for the x and y dimension.
 
        if (this.isScatter || this.isSlopeChart)
            // for scatter and slope charts, the `transformTable()` call takes care of removing
            // all entities that cannot be selected
            return this.tableAfterAuthorTimelineAndActiveChartTransform
 
        // for other chart types, the `transformTable()` call would sometimes remove too many
        // entities, and we want to use the inputTable instead (which should have exactly the
        // entities where data is available)
        return this.inputTable
    }
 
    // If an author sets a timeline filter run it early in the pipeline so to the charts it's as if the filtered times do not exist
    @computed get tableAfterAuthorTimelineFilter(): OwidTable {
        const table = this.inputTable
        if (
            this.timelineMinTime === undefined &&
            this.timelineMaxTime === undefined
        )
            return table
        return table.filterByTimeRange(
            this.timelineMinTime ?? -Infinity,
            this.timelineMaxTime ?? Infinity
        )
    }
 
    // Convenience method for debugging
    windowQueryParams(str = location.search): QueryParams {
        return strToQueryParams(str)
    }
 
    @computed
    private get tableAfterAuthorTimelineAndActiveChartTransform(): OwidTable {
        const table = this.tableAfterAuthorTimelineFilter
        if (!this.isReady || !this.isChartOrMapTab) return table
        return this.chartInstance.transformTable(table)
    }
 
    @computed get chartInstance(): ChartInterface {
        // Note: when timeline handles on a LineChart are collapsed into a single handle, the
        // LineChart turns into a DiscreteBar.
 
        return this.isOnMapTab
            ? new MapChart({ manager: this })
            : this.chartInstanceExceptMap
    }
 
    // When Map becomes a first-class chart instance, we should drop this
    @computed get chartInstanceExceptMap(): ChartInterface {
        const chartTypeName =
            this.typeExceptWhenLineChartAndSingleTimeThenWillBeBarChart
 
        const ChartClass =
            ChartComponentClassMap.get(chartTypeName) ?? DefaultChartClass
        return new ChartClass({ manager: this })
    }
 
    @computed get table(): OwidTable {
        return this.tableAfterAuthorTimelineFilter
    }
 
    @computed
    get tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter(): OwidTable {
        const table = this.tableAfterAuthorTimelineAndActiveChartTransform
        // todo: could make these separate memoized computeds to speed up
        // todo: add cross filtering. 1 dimension at a time.
        return this.minPopulationFilter
            ? table.filterByPopulationExcept(
                  this.minPopulationFilter,
                  this.selection.selectedEntityNames
              )
            : table
    }
 
    @computed
    private get tableAfterAllTransformsAndFilters(): OwidTable {
        const { startTime, endTime } = this
        const table =
            this
                .tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter
 
        if (startTime === undefined || endTime === undefined) return table
 
        if (this.isOnMapTab)
            return table.filterByTargetTimes(
                [endTime],
                this.map.timeTolerance ??
                    table.get(this.mapColumnSlug).tolerance
            )
 
        if (
            this.isDiscreteBar ||
            this.isLineChartThatTurnedIntoDiscreteBar ||
            this.isMarimekko
        )
            return table.filterByTargetTimes(
                [endTime],
                table.get(this.yColumnSlugs[0]).tolerance
            )
 
        if (this.isSlopeChart)
            return table.filterByTargetTimes([startTime, endTime])
 
        return table.filterByTimeRange(startTime, endTime)
    }
 
    @computed get transformedTable(): OwidTable {
        return this.tableAfterAllTransformsAndFilters
    }
 
    @observable.ref isMediaCard = false
    @observable.ref isExportingtoSvgOrPng = false
    @observable.ref tooltip?: TooltipProps
    @observable isPlaying = false
    @observable.ref isSelectingData = false
 
    private get isStaging(): boolean {
        if (typeof location === undefined) return false
        return location.host.includes("staging")
    }
 
    @computed get editUrl(): string | undefined {
        if (!this.showAdminControls && !this.isDev && !this.isStaging)
            return undefined
        return `${this.adminBaseUrl}/admin/${
            this.manager?.editUrl ?? `charts/${this.id}/edit`
        }`
    }
 
    private populationFilterToggleOption = 1e6
    // Make the default filter toggle option reflect what is initially loaded.
    @computed get populationFilterOption(): number {
        if (this.minPopulationFilter)
            this.populationFilterToggleOption = this.minPopulationFilter
        return this.populationFilterToggleOption
    }
 
    // Checks if the data 1) is about countries and 2) has countries with less than the filter option. Used to partly determine whether to show the filter control.
    @computed private get hasCountriesSmallerThanFilterOption(): boolean {
        return this.inputTable.availableEntityNames.some(
            (entityName) =>
                populationMap[entityName] &&
                populationMap[entityName] < this.populationFilterOption
        )
    }
 
    // at startDrag, we want to show the full axis
    @observable.ref useTimelineDomains = false
 
    /**
     * Whether the chart is rendered in an Admin context (e.g. on owid.cloud).
     */
    @computed get useAdminAPI(): boolean {
        if (typeof window === "undefined") return false
        return window.admin !== undefined
    }
 
    /**
     * Whether the user viewing the chart is an admin and we should show admin controls,
     * like the "Edit" option in the share menu.
     */
    @computed get showAdminControls(): boolean {
        // This cookie is set by visiting ourworldindata.org/identifyadmin on the static site.
        // There is an iframe on owid.cloud to trigger a visit to that page.
        return !!Cookies.get(CookieKey.isAdmin)
    }
 
    @action.bound
    private async downloadLegacyDataFromOwidVariableIds(): Promise<void> {
        if (this.variableIds.length === 0)
            // No data to download
            return

        try {
            if (this.useAdminAPI) {
                const json = await window.admin.getJSON(
                    `/api/data/variables/${this.dataFileName}`
                )
                this._receiveOwidDataAndApplySelection(json)
            } else {
                const response = await fetchWithRetries(this.dataUrl)
                if (!response.ok) throw new Error(response.statusText)
                const json = await response.json()
                this._receiveOwidDataAndApplySelection(json)
            }
        } catch (err) {
            console.log(`Error fetching '${this.dataUrl}'`)
            console.error(err)
        }
    }
 
    @action.bound receiveOwidData(json: OwidVariablesAndEntityKey): void {
        this._receiveOwidDataAndApplySelection(json)
    }
 
    @action.bound private _setInputTable(
        json: OwidVariablesAndEntityKey,
        legacyConfig: Partial<LegacyGrapherInterface>
    ): void {
        const { dimensions, table } = legacyToOwidTableAndDimensions(
            json,
            legacyConfig
        )
 
        this.inputTable = table
        // We need to reset the dimensions because some of them may have changed slugs in the legacy
        // transformation (can happen when columns use targetTime)
        this.setDimensionsFromConfigs(dimensions)
 
        this.appendNewEntitySelectionOptions()
 
        if (this.manager?.selection?.hasSelection) {
            // Selection is managed externally, do nothing.
        } else if (this.selection.hasSelection) {
            // User has changed the selection, use theris
        } else this.applyOriginalSelectionAsAuthored()
    }
 
    @action rebuildInputOwidTable(): void {
        if (!this.legacyVariableDataJson) return
        this._setInputTable(
            this.legacyVariableDataJson,
            this.legacyConfigAsAuthored
        )
    }
 
    @observable private legacyVariableDataJson?: OwidVariablesAndEntityKey
 
    @action.bound private _receiveOwidDataAndApplySelection(
        json: OwidVariablesAndEntityKey
    ): void {
        this.legacyVariableDataJson = json
 
        this.rebuildInputOwidTable()
    }
 
    @action.bound appendNewEntitySelectionOptions(): void {
        const { selection } = this
        const currentEntities = selection.availableEntityNameSet
        const missingEntities = this.availableEntities.filter(
            (entity) => !currentEntities.has(entity.entityName)
        )
        selection.addAvailableEntityNames(missingEntities)
    }
 
    @action.bound private applyOriginalSelectionAsAuthored(): void {
        if (this.selectedEntityNames.length)
            this.selection.setSelectedEntities(this.selectedEntityNames)
        else if (this.selectedEntityIds.length)
            this.selection.setSelectedEntitiesByEntityId(this.selectedEntityIds)
    }
 
    @observable private _baseFontSize = BASE_FONT_SIZE
 
    @computed get baseFontSize(): number {
        if (this.isMediaCard) return 24
        else if (this.isExportingtoSvgOrPng) return 18
        return this._baseFontSize
    }
 
    set baseFontSize(val: number) {
        this._baseFontSize = val
    }
 
    // Ready to go iff we have retrieved data for every variable associated with the chart
    @computed get isReady(): boolean {
        return this.whatAreWeWaitingFor === ""
    }
 
    @computed get whatAreWeWaitingFor(): string {
        const { newSlugs, inputTable, dimensions } = this
        if (newSlugs.length || dimensions.length === 0) {
            const missingColumns = newSlugs.filter(
                (slug) => !inputTable.has(slug)
            )
            return missingColumns.length
                ? `Waiting for columns ${missingColumns.join(",")} in table '${
                      inputTable.tableSlug
                  }'. ${inputTable.tableDescription}`
                : ""
        }
        if (dimensions.length > 0 && this.loadingDimensions.length === 0)
            return ""
        return `Waiting for dimensions ${this.loadingDimensions.join(",")}.`
    }
 
    // If we are using new slugs and not dimensions, Grapher is ready.
    @computed get newSlugs(): string[] {
        const { xSlug, colorSlug, sizeSlug } = this
        const ySlugs = this.ySlugs ? this.ySlugs.split(" ") : []
        return excludeUndefined([...ySlugs, xSlug, colorSlug, sizeSlug])
    }
 
    @computed private get loadingDimensions(): ChartDimension[] {
        return this.dimensions.filter(
            (dim) => !this.inputTable.has(dim.columnSlug)
        )
    }
 
    @computed get isInIFrame(): boolean {
        return isInIFrame()
    }
 
    @computed get times(): Time[] {
        const columnSlugs = this.isOnMapTab
            ? [this.mapColumnSlug]
            : this.yColumnSlugs
 
        // Generate the times only after the chart transform has been applied, so that we don't show
        // times on the timeline for which data may not exist, e.g. when the selected entity
        // doesn't contain data for all years in the table.
        // -@danielgavrilov, 2020-10-22
        return this.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter.getTimesUniqSortedAscForColumns(
            columnSlugs
        )
    }
 
    @computed get startHandleTimeBound(): TimeBound {
        if (this.onlySingleTimeSelectionPossible) return this.endHandleTimeBound
        return this.timelineHandleTimeBounds[0]
    }
 
    set startHandleTimeBound(newValue: TimeBound) {
        if (this.onlySingleTimeSelectionPossible)
            this.timelineHandleTimeBounds = [newValue, newValue]
        else
            this.timelineHandleTimeBounds = [
                newValue,
                this.timelineHandleTimeBounds[1],
            ]
    }
 
    set endHandleTimeBound(newValue: TimeBound) {
        if (this.onlySingleTimeSelectionPossible)
            this.timelineHandleTimeBounds = [newValue, newValue]
        else
            this.timelineHandleTimeBounds = [
                this.timelineHandleTimeBounds[0],
                newValue,
            ]
    }
 
    @computed get endHandleTimeBound(): TimeBound {
        return this.timelineHandleTimeBounds[1]
    }
 
    // Keeps a running cache of series colors at the Grapher level.
    seriesColorMap: SeriesColorMap = new Map()
 
    @computed get startTime(): Time | undefined {
        return findClosestTime(this.times, this.startHandleTimeBound)
    }
 
    @computed get endTime(): Time | undefined {
        return findClosestTime(this.times, this.endHandleTimeBound)
    }
 
    @computed private get onlySingleTimeSelectionPossible(): boolean {
        return (
            this.isDiscreteBar ||
            this.isStackedDiscreteBar ||
            this.isOnMapTab ||
            this.isMarimekko
        )
    }
 
    @computed get shouldLinkToOwid(): boolean {
        if (
            this.props.isEmbeddedInAnOwidPage ||
            this.isExportingtoSvgOrPng ||
            !this.isInIFrame
        )
            return false

        return true
    }
 
    @computed.struct private get variableIds(): number[] {
        return uniq(this.dimensions.map((d) => d.variableId))
    }
 
    @computed private get dataFileName(): string {
        return `${this.variableIds.join("+")}.json?v=${
            this.isEditor ? undefined : this.cacheTag
        }`
    }
 
    @computed get dataUrl(): string {
        return `${this.bakedGrapherURL ?? ""}/data/variables/${
            this.dataFileName
        }`
    }
 
    externalCsvLink = ""
 
    @computed get hasOWIDLogo(): boolean {
        return (
            !this.hideLogo && (this.logo === undefined || this.logo === "owid")
        )
    }
 
    // todo: did this name get botched in a merge?
    @computed get hasFatalErrors(): boolean {
        return this.relatedQuestions.some(
            (question) => !!getErrorMessageRelatedQuestionUrl(question)
        )
    }
 
    disposers: IReactionDisposer[] = []
 
    @bind dispose(): void {
        this.disposers.forEach((dispose) => dispose())
    }
 
    @computed get fontSize(): number {
        return this.baseFontSize
    }
 
    // todo: can we remove this?
    // I believe these states can only occur during editing.
    @action.bound private ensureValidConfigWhenEditing(): void {
        this.disposers.push(
            reaction(
                () => this.variableIds,
                this.downloadLegacyDataFromOwidVariableIds
            )
        )
        const disposers = [
            autorun(() => {
                if (!this.availableTabs.includes(this.tab))
                    runInAction(() => (this.tab = this.availableTabs[0]))
            }),
            autorun(() => {
                const validDimensions = this.validDimensions
                if (!isEqual(this.dimensions, validDimensions))
                    this.dimensions = validDimensions
            }),
        ]
        this.disposers.push(...disposers)
    }
 
    @computed private get validDimensions(): ChartDimension[] {
        const { dimensions } = this
        const validProperties = this.dimensionSlots.map((d) => d.property)
        let validDimensions = dimensions.filter((dim) =>
            validProperties.includes(dim.property)
        )

        this.dimensionSlots.forEach((slot) => {
            if (!slot.allowMultiple)
                validDimensions = uniqWith(
                    validDimensions,
                    (
                        a: OwidChartDimensionInterface,
                        b: OwidChartDimensionInterface
                    ) =>
                        a.property === slot.property &&
                        a.property === b.property
                )
        })

        return validDimensions
    }
 
    // todo: do we need this?
    @computed get originUrlWithProtocol(): string {
        let url = this.originUrl
        if (!url.startsWith("http")) url = `https://${url}`
        return url
    }
 
    @computed get overlayTab(): GrapherTabOption | undefined {
        return this.overlay
    }
 
    @computed get currentTab(): GrapherTabOption {
        return this.overlay ? this.overlay : this.tab
    }
 
    set currentTab(desiredTab: GrapherTabOption) {
        if (
            desiredTab === GrapherTabOption.chart ||
            desiredTab === GrapherTabOption.map ||
            desiredTab === GrapherTabOption.table
        ) {
            this.tab = desiredTab
            this.overlay = undefined
            return
        }
 
        // table tab cannot be downloaded, so revert to default tab
        if (desiredTab === GrapherTabOption.download && this.isOnTableTab)
            this.tab = this.authorsVersion.tab ?? GrapherTabOption.chart
        this.overlay = desiredTab
    }
 
    @computed get timelineHandleTimeBounds(): TimeBounds {
        if (this.isOnMapTab) {
            const time = maxTimeBoundFromJSONOrPositiveInfinity(this.map.time)
            return [time, time]
        }
        return [
            // Handle `undefined` values in minTime/maxTime
            minTimeBoundFromJSONOrNegativeInfinity(this.minTime),
            maxTimeBoundFromJSONOrPositiveInfinity(this.maxTime),
        ]
    }
 
    set timelineHandleTimeBounds(value: TimeBounds) {
        if (this.isOnMapTab) {
            this.map.time = value[1]
        } else {
            this.minTime = value[0]
            this.maxTime = value[1]
        }
    }
 
    // Get the dimension slots appropriate for this type of chart
    @computed get dimensionSlots(): DimensionSlot[] {
        const xAxis = new DimensionSlot(this, DimensionProperty.x)
        const yAxis = new DimensionSlot(this, DimensionProperty.y)
        const color = new DimensionSlot(this, DimensionProperty.color)
        const size = new DimensionSlot(this, DimensionProperty.size)
 
        if (this.isLineChart || this.isDiscreteBar) return [yAxis, color]
        else if (this.isScatter) return [yAxis, xAxis, size, color]
        else if (this.isMarimekko) return [yAxis, xAxis, color]
        else if (this.isTimeScatter) return [yAxis, xAxis]
        else if (this.isSlopeChart) return [yAxis, size, color]
        return [yAxis]
    }
 
    @computed.struct get filledDimensions(): ChartDimension[] {
        return this.isReady ? this.dimensions : []
    }
 
    @action.bound addDimension(config: OwidChartDimensionInterface): void {
        this.dimensions.push(new ChartDimension(config, this))
    }
 
    @action.bound setDimensionsForProperty(
        property: DimensionProperty,
        newConfigs: OwidChartDimensionInterface[]
    ): void {
        let newDimensions: ChartDimension[] = []
        this.dimensionSlots.forEach((slot) => {
            if (slot.property === property)
                newDimensions = newDimensions.concat(
                    newConfigs.map((config) => new ChartDimension(config, this))
                )
            else newDimensions = newDimensions.concat(slot.dimensions)
        })
        this.dimensions = newDimensions
    }
 
    @action.bound setDimensionsFromConfigs(
        configs: OwidChartDimensionInterface[]
    ): void {
        this.dimensions = configs.map(
            (config) => new ChartDimension(config, this)
        )
    }
 
    @computed get displaySlug(): string {
        return this.slug ?? slugify(this.displayTitle)
    }
 
    @computed get availableTabs(): GrapherTabOption[] {
        return [
            this.hasChartTab && GrapherTabOption.chart,
            this.hasMapTab && GrapherTabOption.map,
            GrapherTabOption.table,
            GrapherTabOption.sources,
            GrapherTabOption.download,
        ].filter(identity) as GrapherTabOption[]
    }
 
    @computed get currentTitle(): string {
        let text = this.displayTitle
        const selectedEntityNames = this.selection.selectedEntityNames
        const showTitleAnnotation = !this.hideTitleAnnotation
 
        if (
            this.tab === GrapherTabOption.chart &&
            this.addCountryMode !== EntitySelectionMode.MultipleEntities &&
            selectedEntityNames.length === 1 &&
            (showTitleAnnotation || this.canChangeEntity)
        ) {
            const entityStr = selectedEntityNames[0]
            if (entityStr?.length) text = `${text}, ${entityStr}`
        }
 
        if (
            this.isLineChart &&
            this.isRelativeMode &&
            (showTitleAnnotation || this.canToggleRelativeMode)
        )
            text = "Change in " + lowerCaseFirstLetterUnlessAbbreviation(text)
 
        if (
            this.isReady &&
            (showTitleAnnotation ||
                (this.hasTimeline &&
                    (this.isLineChartThatTurnedIntoDiscreteBar ||
                        this.isOnMapTab)))
        )
            text += this.timeTitleSuffix
 
        return text.trim()
    }
 
    /**
     * Uses some explicit and implicit information to decide whether a timeline is shown.
     * Note the difference between `hasTimeline` and `showTimeline`:
     * - `hasTimeline` indicates whether the current _normal_ (non-overlay) tab has a timeline.
     * - `showTimeline` takes into account whether we are on an overlay tab, and thus indicates
     *    whether we should currently show the timeline.
     */
    @computed get hasTimeline(): boolean {
        // we don't have more than one distinct time point in our data, so it doesn't make sense to show a timeline
        if (this.times.length <= 1) return false
 
        switch (this.tab) {
            // the map tab has its own `hideTimeline` option
            case GrapherTabOption.map:
                return !this.map.hideTimeline
 
            // use the chart-level `hideTimeline` option for the table, too
            case GrapherTabOption.table:
                return !this.hideTimeline
 
            // StackedBar, StackedArea, and DiscreteBar charts never display a timeline
            case GrapherTabOption.chart:
                return (
                    !this.hideTimeline &&
                    !(
                        this.isStackedBar ||
                        this.isStackedArea ||
                        this.isDiscreteBar
                    )
                )
 
            default:
                return false
        }
    }
 
    @computed get showTimeline(): boolean {
        // don't show the timeline when on an overlay tab
        return this.hasTimeline && this.overlay === undefined
    }
 
    @computed private get areHandlesOnSameTime(): boolean {
        const times = this.tableAfterAuthorTimelineFilter.timeColumn.uniqValues
        const [start, end] = this.timelineHandleTimeBounds.map((time) =>
            findClosestTime(times, time)
        )
        return start === end
    }
 
    @computed get mapColumnSlug(): string {
        const mapColumnSlug = this.map.columnSlug
        // If there's no mapColumnSlug or there is one but it's not in the dimensions array, use the first ycolumn
        if (
            !mapColumnSlug ||
            !this.dimensions.some((dim) => dim.columnSlug === mapColumnSlug)
        )
            return this.yColumnSlug!
        return mapColumnSlug
    }
 
    getColumnForProperty(property: DimensionProperty): CoreColumn | undefined {
        return this.dimensions.find((dim) => dim.property === property)?.column
    }
 
    getSlugForProperty(property: DimensionProperty): string | undefined {
        return this.dimensions.find((dim) => dim.property === property)
            ?.columnSlug
    }
 
    @computed get yColumnsFromDimensions(): CoreColumn[] {
        return this.filledDimensions
            .filter((dim) => dim.property === DimensionProperty.y)
            .map((dim) => dim.column)
    }
 
    @computed get yColumnSlugsInSelectionOrder(): string[] {
        return this.selectedColumnSlugs?.length
            ? this.selectedColumnSlugs
            : this.yColumnSlugs
    }
 
    @computed get yColumnSlugs(): string[] {
        return this.ySlugs
            ? this.ySlugs.split(" ")
            : this.dimensions
                  .filter((dim) => dim.property === DimensionProperty.y)
                  .map((dim) => dim.columnSlug)
    }
 
    @computed get yColumnSlug(): string | undefined {
        return this.ySlugs
            ? this.ySlugs.split(" ")[0]
            : this.getSlugForProperty(DimensionProperty.y)
    }
 
    @computed get xColumnSlug(): string | undefined {
        return this.xSlug ?? this.getSlugForProperty(DimensionProperty.x)
    }
 
    @computed get sizeColumnSlug(): string | undefined {
        return this.sizeSlug ?? this.getSlugForProperty(DimensionProperty.size)
    }
 
    @computed get colorColumnSlug(): string | undefined {
        return (
            this.colorSlug ?? this.getSlugForProperty(DimensionProperty.color)
        )
    }
 
    @computed get yScaleType(): ScaleType | undefined {
        return this.yAxis.scaleType
    }
 
    @computed get xScaleType(): ScaleType | undefined {
        return this.xAxis.scaleType
    }
 
    @computed private get timeTitleSuffix(): string {
        const timeColumn = this.table.timeColumn
        if (timeColumn.isMissing) return "" // Do not show year until data is loaded
        const { startTime, endTime } = this
        if (startTime === undefined || endTime === undefined) return ""
 
        const time =
            startTime === endTime
                ? timeColumn.formatValue(startTime)
                : timeColumn.formatValue(startTime) +
                  " to " +
                  timeColumn.formatValue(endTime)
 
        return ", " + time
    }
 
    @computed get sourcesLine(): string {
        return this.sourceDesc ?? this.defaultSourcesLine
    }
 
    // Columns that are used as a dimension in the currently active view
    @computed get activeColumnSlugs(): string[] {
        const { yColumnSlugs, xColumnSlug, sizeColumnSlug, colorColumnSlug } =
            this
 
        return excludeUndefined([
            ...yColumnSlugs,
            xColumnSlug,
            sizeColumnSlug,
            colorColumnSlug,
        ])
    }
 
    @computed get columnsWithSources(): CoreColumn[] {
        const { yColumnSlugs, xColumnSlug, sizeColumnSlug, colorColumnSlug } =
            this
 
        const columnSlugs = [...yColumnSlugs]
 
        if (xColumnSlug !== undefined) columnSlugs.push(xColumnSlug)
 
        // exclude "Total population (Gapminder, HYDE & UN)" if its used as the size dimension in a scatter plot
        if (sizeColumnSlug !== undefined && sizeColumnSlug != "72")
            columnSlugs.push(sizeColumnSlug)
 
        // exclude "Countries Continent" if its used as the color dimension in a scatter plot, slope chart etc.
        if (colorColumnSlug !== undefined && colorColumnSlug != "123")
            columnSlugs.push(colorColumnSlug)
 
        return this.inputTable
            .getColumns(uniq(columnSlugs))
            .filter((column) => !!column.source.name)
    }
 
    @computed private get defaultSourcesLine(): string {
        let sourceNames = this.columnsWithSources.map(
            (column) => column.source.name ?? ""
        )
 
        // Shorten automatic source names for certain major sources: todo: this sort of thing we could do in a smarter editor, and not at runtime
        sourceNames = sourceNames.map((sourceName) => {
            for (const majorSource of [
                "World Bank – WDI",
                "World Bank",
                "ILOSTAT",
            ]) {
                if (
                    sourceName.startsWith(majorSource) &&
                    !sourceName.match(
                        new RegExp(
                            "^" + majorSource + "\\s+(based on|and)",
                            "gi"
                        )
                    )
                )
                    return majorSource
            }
            return sourceName
        })
 
        return uniq(sourceNames).join(", ")
    }
 
    @computed private get axisDimensions(): ChartDimension[] {
        return this.filledDimensions.filter(
            (dim) =>
                dim.property === DimensionProperty.y ||
                dim.property === DimensionProperty.x
        )
    }
 
    // todo: remove when we remove dimensions
    @computed private get yColumnsFromDimensionsOrSlugsOrAuto(): CoreColumn[] {
        return this.yColumnsFromDimensions.length
            ? this.yColumnsFromDimensions
            : this.table.getColumns(autoDetectYColumnSlugs(this))
    }
 
    @computed private get defaultTitle(): string {
        const yColumns = this.yColumnsFromDimensionsOrSlugsOrAuto
 
        if (this.isScatter)
            return this.axisDimensions
                .map((dimension) => dimension.column.displayName)
                .join(" vs. ")
 
        const uniqueDatasetNames = uniq(
            excludeUndefined(
                yColumns.map((col) => (col.def as OwidColumnDef).datasetName)
            )
        )
 
        if (this.hasMultipleYColumns && uniqueDatasetNames.length === 1)
            return uniqueDatasetNames[0]
 
        if (yColumns.length === 2)
            return yColumns.map((col) => col.displayName).join(" and ")
 
        return yColumns.map((col) => col.displayName).join(", ")
    }
 
    @computed get displayTitle(): string {
        return this.title ?? this.defaultTitle
    }
 
    // Returns an object ready to be serialized to JSON
    @computed get object(): GrapherInterface {
        return this.toObject()
    }
 
    @computed
    get typeExceptWhenLineChartAndSingleTimeThenWillBeBarChart(): ChartTypeName {
        // Switch to bar chart if a single year is selected. Todo: do we want to do this?
        return this.isLineChartThatTurnedIntoDiscreteBar
            ? ChartTypeName.DiscreteBar
            : this.type
    }
 
    @computed get isLineChart(): boolean {
        return this.type === ChartTypeName.LineChart
    }
    @computed get isScatter(): boolean {
        return this.type === ChartTypeName.ScatterPlot
    }
    @computed get isTimeScatter(): boolean {
        return this.type === ChartTypeName.TimeScatter
    }
    @computed get isStackedArea(): boolean {
        return this.type === ChartTypeName.StackedArea
    }
    @computed get isSlopeChart(): boolean {
        return this.type === ChartTypeName.SlopeChart
    }
    @computed get isDiscreteBar(): boolean {
        return this.type === ChartTypeName.DiscreteBar
    }
    @computed get isStackedBar(): boolean {
        return this.type === ChartTypeName.StackedBar
    }
    @computed get isMarimekko(): boolean {
        return this.type === ChartTypeName.Marimekko
    }
    @computed get isStackedDiscreteBar(): boolean {
        return this.type === ChartTypeName.StackedDiscreteBar
    }
 
    @computed get isLineChartThatTurnedIntoDiscreteBar(): boolean {
        return this.isLineChart && this.areHandlesOnSameTime
    }
 
    @computed get supportsMultipleYColumns(): boolean {
        return !(this.isScatter || this.isTimeScatter || this.isSlopeChart)
    }
 
    @computed private get xDimension(): ChartDimension | undefined {
        return this.filledDimensions.find(
            (d) => d.property === DimensionProperty.x
        )
    }
 
    // todo: this is only relevant for scatter plots and Marimekko. move to scatter plot class?
    // todo: remove this. Should be done as a simple column transform at the data level.
    // Possible to override the x axis dimension to target a special year
    // In case you want to graph say, education in the past and democracy today https://ourworldindata.org/grapher/correlation-between-education-and-democracy
    @computed get xOverrideTime(): number | undefined {
        return this.xDimension?.targetYear
    }
 
    // todo: this is only relevant for scatter plots and Marimekko. move to scatter plot class?
    set xOverrideTime(value: number | undefined) {
        this.xDimension!.targetYear = value
    }
 
    @computed get idealBounds(): Bounds {
        return this.isMediaCard
            ? new Bounds(0, 0, 1200, 630)
            : new Bounds(0, 0, 850, 600)
    }
 
    @computed get hasYDimension(): boolean {
        return this.dimensions.some((d) => d.property === DimensionProperty.y)
    }
 
    get staticSVG(): string {
        const _isExportingtoSvgOrPng = this.isExportingtoSvgOrPng
        this.isExportingtoSvgOrPng = true
        const staticSvg = ReactDOMServer.renderToStaticMarkup(
            <StaticCaptionedChart manager={this} bounds={this.idealBounds} />
        )
        this.isExportingtoSvgOrPng = _isExportingtoSvgOrPng
        return staticSvg
    }
 
    @computed get mapConfig(): MapConfig {
        return this.map
    }
 
    @computed get cacheTag(): string {
        return this.version.toString()
    }
 
    @computed get mapIsClickable(): boolean {
        return (
            this.hasChartTab &&
            (this.isLineChart || this.isScatter) &&
            !isMobile()
        )
    }
 
    @computed get relativeToggleLabel(): string {
        if (this.isScatter || this.isTimeScatter) return "Average annual change"
        else if (this.isLineChart) return "Relative change"
        return "Relative"
    }
 
    // NB: The timeline scatterplot in relative mode calculates changes relative
    // to the lower bound year rather than creating an arrow chart
    @computed get isRelativeMode(): boolean {
        return this.stackMode === StackMode.relative
    }
 
    @computed get canToggleRelativeMode(): boolean {
        if (this.isLineChart)
            return (
                !this.hideRelativeToggle &&
                !this.areHandlesOnSameTime &&
                this.yScaleType !== ScaleType.log
            )
 
        // actually trying to exclude relative mode with just one metric
        if (
            this.isStackedDiscreteBar &&
            this.facetStrategy !== FacetStrategy.none
        )
            return false
 
        return !this.hideRelativeToggle
    }
 
    // Filter data to what can be display on the map (across all times)
    @computed get mappableData() {
        return this.inputTable
            .get(this.mapColumnSlug)
            .owidRows.filter((row) => isOnTheMap(row.entityName))
    }
 
    static renderGrapherIntoContainer(
        config: GrapherProgrammaticInterface,
        containerNode: Element
    ): Grapher | null {
        const grapherInstanceRef = React.createRef<Grapher>()

        let ErrorBoundary = React.Fragment // use React.Fragment as a sort of default error boundary if Bugsnag is not available
        if (Bugsnag && (Bugsnag as any)._client) {
            ErrorBoundary =
                Bugsnag.getPlugin("react").createErrorBoundary(React)
        }

        const setBoundsFromContainerAndRender = (): void => {
            const props: GrapherProgrammaticInterface = {
                ...config,
                bounds: Bounds.fromRect(containerNode.getBoundingClientRect()),
            }
            ReactDOM.render(
                <ErrorBoundary>
                    <Grapher ref={grapherInstanceRef} {...props} />
                </ErrorBoundary>,
                containerNode
            )
        }

        setBoundsFromContainerAndRender()
        window.addEventListener(
            "resize",
            throttle(setBoundsFromContainerAndRender, 400)
        )
        return grapherInstanceRef.current
    }
 
    static renderSingleGrapherOnGrapherPage(
        jsonConfig: GrapherInterface
    ): void {
        const container = document.getElementsByTagName("figure")[0]

        try {
            Grapher.renderGrapherIntoContainer(
                {
                    ...jsonConfig,
                    bindUrlToWindow: true,
                    enableKeyboardShortcuts: true,
                    queryStr: window.location.search,
                },
                container
            )
        } catch (err) {
            container.innerHTML = `<img src="/grapher/exports/${jsonConfig.slug}.svg"/><p>Unable to load interactive visualization</p>`
            container.setAttribute("id", "fallback")
            throw err
        }
    }
 
    @computed get isMobile(): boolean {
        return isMobile()
    }
 
    @computed private get bounds(): Bounds {
        return this.props.bounds ?? DEFAULT_BOUNDS
    }
 
    @computed private get isPortrait(): boolean {
        return this.bounds.width < this.bounds.height && this.bounds.width < 850
    }
 
    @computed private get widthForDeviceOrientation(): number {
        return this.isPortrait ? 400 : 680
    }
 
    @computed private get heightForDeviceOrientation(): number {
        return this.isPortrait ? 640 : 480
    }
 
    @computed private get useIdealBounds(): boolean {
        const {
            isEditor,
            isExportingtoSvgOrPng,
            bounds,
            widthForDeviceOrientation,
            heightForDeviceOrientation,
            isInIFrame,
        } = this
 
        // For these, defer to the bounds that is set externally
        if (
            this.props.isEmbeddedInAnOwidPage ||
            this.props.manager ||
            isInIFrame
        )
            return false
 
        // If the user is using interactive version and then goes to export chart, use current bounds to maintain WSYIWYG
        if (isExportingtoSvgOrPng) return false
 
        // todo: can remove this if we drop old adminSite editor
        if (isEditor) return true
 
        // If the available space is very small, we use all of the space given to us
        if (
            bounds.height < heightForDeviceOrientation ||
            bounds.width < widthForDeviceOrientation
        )
            return false

        return true
    }
 
    // If we have a big screen to be in, we can define our own aspect ratio and sit in the center
    @computed private get scaleToFitIdeal(): number {
        return Math.min(
            (this.bounds.width * 0.95) / this.widthForDeviceOrientation,
            (this.bounds.height * 0.95) / this.heightForDeviceOrientation
        )
    }
 
    // These are the final render dimensions
    // Todo: add explanation around why isExporting removes 5 px
    @computed private get renderWidth(): number {
        return Math.floor(
            this.useIdealBounds
                ? this.widthForDeviceOrientation * this.scaleToFitIdeal
                : this.bounds.width - (this.isExportingtoSvgOrPng ? 0 : 5)
        )
    }
    @computed private get renderHeight(): number {
        return Math.floor(
            this.useIdealBounds
                ? this.heightForDeviceOrientation * this.scaleToFitIdeal
                : this.bounds.height - (this.isExportingtoSvgOrPng ? 0 : 5)
        )
    }
 
    @computed get tabBounds(): Bounds {
        const bounds = new Bounds(0, 0, this.renderWidth, this.renderHeight)
        return this.isExportingtoSvgOrPng
            ? bounds
            : bounds.padBottom(this.footerControlsHeight)
    }
 
    @observable.ref private popups: JSX.Element[] = []
 
    base: React.RefObject<HTMLDivElement> = React.createRef()
 
    @computed get containerElement(): HTMLDivElement | undefined {
        return this.base.current || undefined
    }
 
    @observable private hasBeenVisible = false
    @observable private uncaughtError?: Error
 
    @action.bound setError(err: Error): void {
        this.uncaughtError = err
    }
 
    @action.bound clearErrors(): void {
        this.uncaughtError = undefined
    }
 
    // todo: clean up this popup stuff
    addPopup(vnode: JSX.Element): void {
        this.popups = this.popups.concat([vnode])
    }
 
    removePopup(vnodeType: JSX.Element): void {
        this.popups = this.popups.filter((d) => !(d.type === vnodeType))
    }
 
    @computed private get isOnTableTab(): boolean {
        return this.tab === GrapherTabOption.table
    }
 
    private renderPrimaryTab(): JSX.Element | undefined {
        if (this.isChartOrMapTab) return <CaptionedChart manager={this} />

        const { tabBounds } = this
        if (this.isOnTableTab)
            // todo: should this "Div" and styling just be in DataTable class?
            return (
                <div
                    className="tableTab"
                    style={{ ...tabBounds.toCSS(), position: "absolute" }}
                >
                    <DataTable bounds={tabBounds} manager={this} />
                </div>
            )

        return undefined
    }
 
    private renderOverlayTab(): JSX.Element | undefined {
        const bounds = this.tabBounds
        if (this.overlayTab === GrapherTabOption.sources)
            return (
                <SourcesTab key="sourcesTab" bounds={bounds} manager={this} />
            )
        if (this.overlayTab === GrapherTabOption.download)
            return (
                <DownloadTab key="downloadTab" bounds={bounds} manager={this} />
            )
        return undefined
    }
 
    private get commandPalette(): JSX.Element | null {
        return this.props.enableKeyboardShortcuts ? (
            <CommandPalette commands={this.keyboardShortcuts} display="none" />
        ) : null
    }
 
    formatTimeFn(time: Time): string {
        return this.inputTable.timeColumnFormatFunction(time)
    }
 
    @action.bound private toggleTabCommand(): void {
        this.currentTab = next(this.availableTabs, this.currentTab)
    }
 
    @action.bound private togglePlayingCommand(): void {
        this.timelineController.togglePlay()
    }
 
    selection =
        this.manager?.selection ??
        new SelectionArray(
            this.props.selectedEntityNames ?? [],
            this.props.table?.availableEntities ?? []
        )
 
    @computed get availableEntities() {
        return this.tableForSelection.availableEntities
    }
 
    private get keyboardShortcuts(): Command[] {
        const temporaryFacetTestCommands = range(0, 10).map((num) => {
            return {
                combo: `${num}`,
                fn: (): void => this.randomSelection(num),
            }
        })
        const shortcuts = [
            ...temporaryFacetTestCommands,
            {
                combo: "t",
                fn: (): void => this.toggleTabCommand(),
                title: "Toggle tab",
                category: "Navigation",
            },
            {
                combo: "?",
                fn: (): void => CommandPalette.togglePalette(),
                title: `Toggle Help`,
                category: "Navigation",
            },
            {
                combo: "a",
                fn: (): void | SelectionArray =>
                    this.selection.hasSelection
                        ? this.selection.clearSelection()
                        : this.selection.selectAll(),
                title: this.selection.hasSelection
                    ? `Select None`
                    : `Select All`,
                category: "Selection",
            },
            {
                combo: "f",
                fn: (): void => this.toggleFilterAllCommand(),
                title: "Hide unselected",
                category: "Selection",
            },
            {
                combo: "p",
                fn: (): void => this.togglePlayingCommand(),
                title: this.isPlaying ? `Pause` : `Play`,
                category: "Timeline",
            },
            {
                combo: "f",
                fn: (): void => this.toggleFacetControlVisibility(),
                title: `Toggle Faceting`,
                category: "Chart",
            },
            {
                combo: "l",
                fn: (): void => this.toggleYScaleTypeCommand(),
                title: "Toggle Y log/linear",
                category: "Chart",
            },
            {
                combo: "esc",
                fn: (): void => this.clearErrors(),
            },
            {
                combo: "z",
                fn: (): void => this.toggleTimelineCommand(),
                title: "Latest/Earliest/All period",
                category: "Timeline",
            },
            {
                combo: "shift+o",
                fn: (): void => this.clearQueryParams(),
                title: "Reset to original",
                category: "Navigation",
            },
        ]
 
        if (this.slideShow) {
            const slideShow = this.slideShow
            shortcuts.push({
                combo: "right",
                fn: () => slideShow.playNext(),
                title: "Next chart",
                category: "Browse",
            })
            shortcuts.push({
                combo: "left",
                fn: () => slideShow.playPrevious(),
                title: "Previous chart",
                category: "Browse",
            })
        }
 
        return shortcuts
    }
 
    @observable slideShow?: SlideShowController<any>
 
    @action.bound private toggleTimelineCommand(): void {
        // Todo: add tests for this
        this.setTimeFromTimeQueryParam(
            next(["latest", "earliest", ".."], this.timeParam!)
        )
    }
 
    @action.bound private toggleFilterAllCommand(): void {
        this.minPopulationFilter =
            this.minPopulationFilter === 2e9 ? undefined : 2e9
    }
 
    @action.bound private toggleYScaleTypeCommand(): void {
        this.yAxis.scaleType = next(
            [ScaleType.linear, ScaleType.log],
            this.yAxis.scaleType
        )
    }
 
    @action.bound private toggleFacetStrategy(): void {
        this.facetStrategy = next(
            this.availableFacetStrategies,
            this.facetStrategy
        )
    }
 
    @action.bound private toggleFacetControlVisibility(): void {
        this.hideFacetControl = !this.hideFacetControl
    }
 
    @computed get showFacetYDomainToggle(): boolean {
        // don't offer to make the y range relative if the range is discrete
        return (
            this.facetStrategy !== FacetStrategy.none &&
            !this.isStackedDiscreteBar
        )
    }
 
    @computed get _sortConfig(): Readonly<SortConfig> {
        return {
            sortBy: this.sortBy ?? SortBy.total,
            sortOrder: this.sortOrder ?? SortOrder.desc,
            sortColumnSlug: this.sortColumnSlug,
        }
    }
 
    @computed get sortConfig(): SortConfig {
        const sortConfig = { ...this._sortConfig }
        // In relative mode, where the values for every entity sum up to 100%, sorting by total
        // doesn't make sense. It's also jumpy because of some rounding errors. For this reason,
        // we sort by entity name instead.
        // Marimekko charts are special and there we don't do this forcing of sort order
        if (
            !this.isMarimekko &&
            this.isRelativeMode &&
            sortConfig.sortBy === SortBy.total
        ) {
            sortConfig.sortBy = SortBy.entityName
            sortConfig.sortOrder = SortOrder.asc
        }
        return sortConfig
    }
 
    @computed private get hasMultipleYColumns(): boolean {
        return this.yColumnSlugs.length > 1
    }
 
    @computed get selectedColumnSlugs(): ColumnSlug[] {
        const { selectedData } = this.legacyConfigAsAuthored
        const dimensions = this.filledDimensions
 
        if (selectedData) {
            const columnSlugs = selectedData.map((item) => {
                const columnSlug = dimensions[item.index]?.columnSlug
 
                if (!columnSlug)
                    console.warn(
                        `Couldn't find specified dimension in chart config`,
                        item
                    )
                return columnSlug
            })
            return uniq(excludeUndefined(columnSlugs))
        }
 
        return []
    }
 
    @computed get availableFacetStrategies(): FacetStrategy[] {
        const strategies: FacetStrategy[] = [FacetStrategy.none]
 
        const numNonProjectedColumns =
            this.yColumnsFromDimensionsOrSlugsOrAuto.filter(
                (c) => !c.display?.isProjection
            ).length
        if (
            // multiple metrics (excluding projections)
            numNonProjectedColumns > 1 &&
            // more than one data point per metric
            this.transformedTable.numRows > 1
        ) {
            strategies.push(FacetStrategy.metric)
        }
 
        if (
            // multiple entities
            this.selection.numSelectedEntities > 1 &&
            // more than one data point per entity
            this.transformedTable.numRows > this.selection.numSelectedEntities
        ) {
            strategies.push(FacetStrategy.entity)
        }
 
        return strategies
    }
 
    private disableAutoFaceting = true // turned off for now
 
    // the actual facet setting used by a chart, potentially overriding selectedFacetStrategy
    @computed get facetStrategy(): FacetStrategy {
        if (
            this.selectedFacetStrategy &&
            this.availableFacetStrategies.includes(this.selectedFacetStrategy)
        )
            return this.selectedFacetStrategy
 
        if (this.disableAutoFaceting) return FacetStrategy.none

        // Auto facet on SingleEntity charts with multiple selected entities
        if (
            this.addCountryMode === EntitySelectionMode.SingleEntity &&
            this.selection.numSelectedEntities > 1
        )
            return FacetStrategy.entity

        // Auto facet when multiple slugs and multiple entities selected. todo: not sure if this is correct.
        if (
            this.addCountryMode === EntitySelectionMode.MultipleEntities &&
            this.hasMultipleYColumns &&
            this.selection.numSelectedEntities > 1
        )
            return FacetStrategy.metric

        return FacetStrategy.none
    }
 
    set facetStrategy(facet: FacetStrategy) {
        this.selectedFacetStrategy = facet

        if (
            this.isStackedDiscreteBar &&
            this.selectedFacetStrategy !== FacetStrategy.none
        ) {
            // actually trying to exclude relative mode with just one metric
            this.stackMode = StackMode.absolute
        }
    }
 
    @action.bound randomSelection(num: number): void {
        // Continent, Population, GDP PC, GDP, PopDens, UN, Language, etc.
        this.clearErrors()
        const currentSelection = this.selection.selectedEntityNames.length
        const newNum = num ? num : currentSelection ? currentSelection * 2 : 10
        this.selection.setSelectedEntities(
            sampleFrom(this.selection.availableEntityNames, newNum, Date.now())
        )
    }
 
    private renderError(): JSX.Element {
        return (
            <div
                title={this.uncaughtError?.message}
                style={{
                    width: "100%",
                    height: "100%",
                    position: "relative",
                    display: "flex",
                    flexDirection: "column",
                    justifyContent: "center",
                    textAlign: "center",
                    lineHeight: 1.5,
                    padding: "3rem",
                }}
            >
                <p style={{ color: "#cc0000", fontWeight: 700 }}>
                    <FontAwesomeIcon icon={faExclamationTriangle} />
                    {ThereWasAProblemLoadingThisChart}
                </p>
                <p>
                    We have been notified of this error, please check back later
                    whether it's been fixed. If the error persists, get in touch
                    with us at{" "}
                    <a
                        href={`mailto:info@ourworldindata.org?subject=Broken chart on page ${window.location.href}`}
                    >
                        info@ourworldindata.org
                    </a>
                    .
                </p>
                {this.uncaughtError && this.uncaughtError.message && (
                    <pre style={{ fontSize: "11px" }}>
                        Error: {this.uncaughtError.message}
                    </pre>
                )}
            </div>
        )
    }
 
    @action.bound
    resetAnnotation(): void {
        this.renderAnnotation(undefined)
    }
 
    @action.bound
    renderAnnotation(annotation: Annotation | undefined): void {
        this.setAuthoredVersion(this.props)
        this.reset()
        this.updateFromObject({ ...this.props })
        this.populateFromQueryParams(
            legacyToCurrentGrapherQueryParams(this.props.queryStr ?? "")
        )
        this.annotation = annotation
    }
 
    render(): JSX.Element | undefined {
        const { isExportingtoSvgOrPng, isPortrait } = this
        // TODO how to handle errors in exports?
        // TODO tidy this up
        if (isExportingtoSvgOrPng) return this.renderPrimaryTab() // todo: remove this? should have a simple toStaticSVG for importing.
 
        const { renderWidth, renderHeight } = this
 
        const style = {
            width: renderWidth,
            height: renderHeight,
            fontSize: this.baseFontSize,
        }
 
        const classes = classNames(
            "GrapherComponent",
            isExportingtoSvgOrPng && "isExportingToSvgOrPng",
            isPortrait && "GrapherPortraitClass"
        )
 
        return (
            <div ref={this.base} className={classes} style={style}>
                {this.commandPalette}
                {this.uncaughtError ? this.renderError() : this.renderReady()}
            </div>
        )
    }
 
    private renderReady(): JSX.Element {
        return (
            <>
                {this.hasBeenVisible && this.renderPrimaryTab()}
                <FooterControls manager={this} />
                {this.renderOverlayTab()}
                {this.popups}
                <TooltipView
                    width={this.renderWidth}
                    height={this.renderHeight}
                    tooltipProvider={this}
                />
                {this.isSelectingData && (
                    <EntitySelectorModal
                        canChangeEntity={this.canChangeEntity}
                        selectionArray={this.selection}
                        key="entitySelector"
                        isMobile={this.isMobile}
                        onDismiss={action(() => (this.isSelectingData = false))}
                    />
                )}
            </>
        )
    }
 
    // Chart should only render SVG when it's on the screen
    @action.bound private checkVisibility(): void {
        if (!this.hasBeenVisible && isVisible(this.base.current))
            this.hasBeenVisible = true
    }
 
    @action.bound private setBaseFontSize(): void {
        const { renderWidth } = this
        if (renderWidth <= 400) this.baseFontSize = 14
        else if (renderWidth < 1080) this.baseFontSize = 16
        else if (renderWidth >= 1080) this.baseFontSize = 18
    }
 
    // Binds chart properties to global window title and URL. This should only
    // ever be invoked from top-level JavaScript.
    private bindToWindow(): void {
        // There is a surprisingly considerable performance overhead to updating the url
        // while animating, so we debounce to allow e.g. smoother timelines
        const pushParams = (): void =>
            setWindowQueryStr(queryParamsToStr(this.changedParams))
        const debouncedPushParams = debounce(pushParams, 100)

        reaction(
            () => this.changedParams,
            () => (this.debounceMode ? debouncedPushParams() : pushParams())
        )

        autorun(() => (document.title = this.currentTitle))
    }
 
    componentDidMount(): void {
        window.addEventListener("scroll", this.checkVisibility)
        this.setBaseFontSize()
        this.checkVisibility()
        exposeInstanceOnWindow(this, "grapher")
        if (this.props.bindUrlToWindow) this.bindToWindow()
        if (this.props.enableKeyboardShortcuts) this.bindKeyboardShortcuts()
    }
 
    private _shortcutsBound = false
    private bindKeyboardShortcuts(): void {
        if (this._shortcutsBound) return
        this.keyboardShortcuts.forEach((shortcut) => {
            Mousetrap.bind(shortcut.combo, () => {
                shortcut.fn()
                this.analytics.logKeyboardShortcut(
                    shortcut.title || "",
                    shortcut.combo
                )
                return false
            })
        })
        this._shortcutsBound = true
    }
 
    private unbindKeyboardShortcuts(): void {
        if (!this._shortcutsBound) return
        this.keyboardShortcuts.forEach((shortcut) => {
            Mousetrap.unbind(shortcut.combo)
        })
        this._shortcutsBound = false
    }
 
    componentWillUnmount(): void {
        this.unbindKeyboardShortcuts()
        window.removeEventListener("scroll", this.checkVisibility)
        this.dispose()
    }
 
    componentDidUpdate(): void {
        this.setBaseFontSize()
        this.checkVisibility()
    }
 
    componentDidCatch(error: Error, info: any): void {
        this.setError(error)
        this.analytics.logGrapherViewError(error, info)
    }
 
    @observable isShareMenuActive = false
 
    @computed get hasRelatedQuestion(): boolean {
        if (!this.relatedQuestions.length) return false
        const question = this.relatedQuestions[0]
        return !!question && !!question.text && !!question.url
    }
 
    @computed private get footerControlsLines(): number {
        return this.hasTimeline ? 2 : 1
    }
 
    @computed get footerControlsHeight(): number {
        const footerRowHeight = 32 // todo: cleanup. needs to keep in sync with grapher.scss' $footerRowHeight
        return (
            this.footerControlsLines * footerRowHeight +
            (this.hasRelatedQuestion ? 20 : 0)
        )
    }
 
    @action.bound clearQueryParams(): void {
        const { authorsVersion } = this
        this.tab = authorsVersion.tab
        this.xAxis.scaleType = authorsVersion.xAxis.scaleType
        this.yAxis.scaleType = authorsVersion.yAxis.scaleType
        this.stackMode = authorsVersion.stackMode
        this.zoomToSelection = authorsVersion.zoomToSelection
        this.minPopulationFilter = authorsVersion.minPopulationFilter
        this.compareEndPointsOnly = authorsVersion.compareEndPointsOnly
        this.minTime = authorsVersion.minTime
        this.maxTime = authorsVersion.maxTime
        this.map.time = authorsVersion.map.time
        this.map.projection = authorsVersion.map.projection
        this.selection.clearSelection()
        this.applyOriginalSelectionAsAuthored()
    }
 
    // Todo: come up with a more general pattern?
    // The idea here is to reset the Grapher to a blank slate, so that if you updateFromObject and the object contains some blanks, those blanks
    // won't overwrite defaults (like type == LineChart). RAII would probably be better, but this works for now.
    @action.bound reset(): void {
        const grapher = new Grapher()
        this.title = grapher.title
        this.subtitle = grapher.subtitle
        this.note = grapher.note
        this.type = grapher.type
        this.ySlugs = grapher.ySlugs
        this.xSlug = grapher.xSlug
        this.colorSlug = grapher.colorSlug
        this.sizeSlug = grapher.sizeSlug
        this.hasMapTab = grapher.hasMapTab
        this.selectedFacetStrategy = FacetStrategy.none
        this.hasChartTab = grapher.hasChartTab
        this.map = grapher.map
        this.yAxis.scaleType = grapher.yAxis.scaleType
        this.yAxis.min = grapher.yAxis.min
        this.sortBy = grapher.sortBy
        this.sortOrder = grapher.sortOrder
        this.sortColumnSlug = grapher.sortColumnSlug
        this.hideRelativeToggle = grapher.hideRelativeToggle
        this.stackMode = grapher.stackMode
        this.hideTotalValueLabel = grapher.hideTotalValueLabel
        this.hideTitleAnnotation = grapher.hideTitleAnnotation
        this.timelineMinTime = grapher.timelineMinTime
        this.timelineMaxTime = grapher.timelineMaxTime
        this.relatedQuestions = grapher.relatedQuestions
    }
 
    debounceMode = false
 
    @computed.struct get allParams(): GrapherQueryParams {
        const params: GrapherQueryParams = {}
        params.tab = this.tab
        params.xScale = this.xAxis.scaleType
        params.yScale = this.yAxis.scaleType
        params.stackMode = this.stackMode
        params.zoomToSelection = this.zoomToSelection ? "true" : undefined
        params.minPopulationFilter = this.minPopulationFilter?.toString()
        params.endpointsOnly = this.compareEndPointsOnly ? "1" : "0"
        params.time = this.timeParam
        params.region = this.map.projection
        params.facet = this.selectedFacetStrategy
        params.uniformYAxis =
            this.yAxis.facetDomain === FacetAxisDomain.independent ? "0" : "1"
        return setSelectedEntityNamesParam(
            Url.fromQueryParams(params),
            this.selectedEntitiesIfDifferentThanAuthors
        ).queryParams
    }
 
    // Todo: move all Graphers to git. Upgrade the selection property; delete the entityId stuff, and remove this.
    @computed private get selectedEntitiesIfDifferentThanAuthors():
        | EntityName[]
        | undefined {
        const authoredConfig = this.legacyConfigAsAuthored
 
        const originalSelectedEntityIds =
            authoredConfig.selectedData?.map((row) => row.entityId) || []
        const currentSelectedEntityIds = this.selection.allSelectedEntityIds
 
        const entityIdsThatTheUserDeselected = difference(
            currentSelectedEntityIds,
            originalSelectedEntityIds
        )
 
        if (
            currentSelectedEntityIds.length !==
                originalSelectedEntityIds.length ||
            entityIdsThatTheUserDeselected.length
        )
            return this.selection.selectedEntityNames
 
        return undefined
    }
 
    // Autocomputed url params to reflect difference between current grapher state
    // and original config state
    @computed.struct get changedParams(): Partial<GrapherQueryParams> {
        return differenceObj(this.allParams, this.authorsVersion.allParams)
    }
 
    // If you want to compare current state against the published grapher.
    @computed private get authorsVersion(): Grapher {
        return new Grapher({
            ...this.legacyConfigAsAuthored,
            manager: undefined,
            manuallyProvideData: true,
            queryStr: "",
        })
    }
 
    @computed get queryStr(): string {
        return queryParamsToStr(this.changedParams)
    }
 
    @computed get baseUrl(): string | undefined {
        return this.isPublished
            ? `${this.bakedGrapherURL ?? "/grapher"}/${this.displaySlug}`
            : undefined
    }
 
    @computed private get manager(): GrapherManager | undefined {
        return this.props.manager
    }
 
    // Get the full url representing the canonical location of this grapher state
    @computed get canonicalUrl(): string | undefined {
        return (
            this.manager?.canonicalUrl ??
            (this.baseUrl ? this.baseUrl + this.queryStr : undefined)
        )
    }
 
    @computed get embedUrl(): string | undefined {
        return this.manager?.embedDialogUrl ?? this.canonicalUrl
    }
 
    @computed get embedDialogAdditionalElements():
        | React.ReactElement
        | undefined {
        return this.manager?.embedDialogAdditionalElements
    }
 
    @computed private get hasUserChangedTimeHandles(): boolean {
        const authorsVersion = this.authorsVersion
        return (
            this.minTime !== authorsVersion.minTime ||
            this.maxTime !== authorsVersion.maxTime
        )
    }
 
    @computed private get hasUserChangedMapTimeHandle(): boolean {
        return this.map.time !== this.authorsVersion.map.time
    }
 
    @computed get timeParam(): string | undefined {
        const { timeColumn } = this.table
        const formatTime = (t: Time) =>
            timeBoundToTimeBoundString(
                t,
                timeColumn instanceof ColumnTypeMap.Day
            )
 
        if (this.isOnMapTab) {
            return this.map.time !== undefined &&
                this.hasUserChangedMapTimeHandle
                ? formatTime(this.map.time)
                : undefined
        }
 
        if (!this.hasUserChangedTimeHandles) return undefined
 
        const [startTime, endTime] =
            this.timelineHandleTimeBounds.map(formatTime)
        return startTime === endTime ? startTime : `${startTime}..${endTime}`
    }
 
    msPerTick = DEFAULT_MS_PER_TICK
 
    timelineController = new TimelineController(this)
 
    onPlay(): void {
        this.analytics.logGrapherTimelinePlay(this.slug)
    }
 
    // todo: restore this behavior??
    onStartPlayOrDrag(): void {
        this.debounceMode = true
        this.useTimelineDomains = true
    }
 
    onStopPlayOrDrag(): void {
        this.debounceMode = false
        this.useTimelineDomains = false
    }
 
    @computed get disablePlay(): boolean {
        return this.isSlopeChart
    }
 
    formatTime(value: Time): string {
        const timeColumn = this.table.timeColumn
        if (timeColumn.isMissing)
            return this.table.timeColumnFormatFunction(value)
        return isMobile()
            ? timeColumn.formatValueForMobile(value)
            : timeColumn.formatValue(value)
    }
 
    @computed get showSmallCountriesFilterToggle(): boolean {
        return this.isScatter && this.hasCountriesSmallerThanFilterOption
    }
 
    @computed get showYScaleToggle(): boolean | undefined {
        if (this.isRelativeMode) return false
        if (this.isStackedArea || this.isStackedBar) return false // We currently do not have these charts with log scale
        return this.yAxis.canChangeScaleType
    }
 
    @computed get showXScaleToggle(): boolean | undefined {
        if (this.isRelativeMode) return false
        return this.xAxis.canChangeScaleType
    }
 
    @computed get showZoomToggle(): boolean {
        return this.isScatter && this.selection.hasSelection
    }
 
    @computed get showAbsRelToggle(): boolean {
        if (!this.canToggleRelativeMode) return false
        if (this.isScatter)
            return this.xOverrideTime === undefined && this.hasTimeline
        return (
            this.isStackedArea ||
            this.isStackedDiscreteBar ||
            this.isScatter ||
            this.isLineChart ||
            this.isMarimekko
        )
    }
 
    @computed get showNoDataAreaToggle(): boolean {
        return this.isMarimekko
    }
 
    @computed get showChangeEntityButton(): boolean {
        return !this.hideEntityControls && this.canChangeEntity
    }
 
    @computed get showAddEntityButton(): boolean {
        return (
            !this.hideEntityControls &&
            this.canSelectMultipleEntities &&
            (this.isLineChart ||
                this.isStackedArea ||
                this.isDiscreteBar ||
                this.isStackedDiscreteBar)
        )
    }
 
    @computed get showSelectEntitiesButton(): boolean {
        return (
            !this.hideEntityControls &&
            this.addCountryMode !== EntitySelectionMode.Disabled &&
            this.numSelectableEntityNames > 1 &&
            !this.showAddEntityButton &&
            !this.showChangeEntityButton
        )
    }
 
    @computed get canSelectMultipleEntities(): boolean {
        if (this.numSelectableEntityNames < 2) return false
        if (this.addCountryMode === EntitySelectionMode.MultipleEntities)
            return true
        if (
            this.addCountryMode === EntitySelectionMode.SingleEntity &&
            this.facetStrategy !== FacetStrategy.none
        )
            return true
 
        return false
    }
 
    // This is just a helper method to return the correct table for providing entity choices. We want to
    // provide the root table, not the transformed table.
    // A user may have added time or other filters that would filter out all rows from certain entities, but
    // we may still want to show those entities as available in a picker. We also do not want to do things like
    // hide the Add Entity button as the user drags the timeline.
    @computed private get numSelectableEntityNames(): number {
        return this.selection.numAvailableEntityNames
    }
 
    @computed get canChangeEntity(): boolean {
        return (
            !this.isScatter &&
            !this.canSelectMultipleEntities &&
            this.addCountryMode === EntitySelectionMode.SingleEntity &&
            this.numSelectableEntityNames > 1
        )
    }
 
    @computed get startSelectingWhenLineClicked(): boolean {
        return this.showAddEntityButton
    }
 
    // For now I am only exposing this programmatically for the dashboard builder. Setting this to true
    // allows you to still use add country "modes" without showing the buttons in order to prioritize
    // another entity selector over the built in ones.
    @observable hideEntityControls = false
}
 
const defaultObject = objectWithPersistablesToObject(
    new Grapher(),
    grapherKeysToSerialize
)
 
export const getErrorMessageRelatedQuestionUrl = (
    question: RelatedQuestionsConfig
): string | undefined => {
    return question.text
        ? (!question.url && "Missing URL") ||
              (!question.url.match(/^https?:\/\//) &&
                  "URL should start with http(s)://") ||
              undefined
        : undefined
}