File size: 331,802 Bytes
9d2d895 | 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 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 | /**
* DeckGLMap - WebGL-accelerated map visualization for desktop
* Uses deck.gl for high-performance rendering of large datasets
* Mobile devices gracefully degrade to the D3/SVG-based Map component
*/
import { MapboxOverlay } from '@deck.gl/mapbox';
import type { Layer, LayersList, PickingInfo } from '@deck.gl/core';
import { GeoJsonLayer, ScatterplotLayer, PathLayer, IconLayer, TextLayer, PolygonLayer } from '@deck.gl/layers';
import maplibregl from 'maplibre-gl';
import type { StyleSpecification } from 'maplibre-gl';
import { FALLBACK_DARK_STYLE, FALLBACK_LIGHT_STYLE, getMapProvider, getMapTheme, isLightMapTheme } from '@/config/basemap';
import { getStyleForProvider } from '@/config/basemap-styles';
import Supercluster from 'supercluster';
import type {
MapLayers,
Hotspot,
NewsItem,
InternetOutage,
RelatedAsset,
AssetType,
AisDisruptionEvent,
AisDensityZone,
CableAdvisory,
RepairShip,
SocialUnrestEvent,
AIDataCenter,
MilitaryFlight,
MilitaryVessel,
MilitaryFlightCluster,
MilitaryVesselCluster,
NaturalEvent,
UcdpGeoEvent,
MapProtestCluster,
MapTechHQCluster,
MapTechEventCluster,
MapDatacenterCluster,
CyberThreat,
CableHealthRecord,
MilitaryBaseEnriched,
} from '@/types';
import { fetchMilitaryBases, type MilitaryBaseCluster as ServerBaseCluster } from '@/services/military-bases';
import type { AirportDelayAlert, PositionSample } from '@/services/aviation';
import { fetchAircraftPositions } from '@/services/aviation';
import { type IranEvent, getIranEventColor, getIranEventRadius } from '@/services/conflict';
import { getMilitaryBaseColor } from '@/config/military-base-colors';
import { getMineralColor } from '@/config/mineral-colors';
import { getWindColor } from '@/config/wind-colors';
import { CII_LEVEL_COLORS, type CiiLevel } from '@/config/cii-colors';
import type { GpsJamHex } from '@/services/gps-interference';
import { fetchImageryScenes } from '@/services/imagery';
import type { ImageryScene } from '@/generated/server/worldmonitor/imagery/v1/service_server';
import type { TrafficAnomaly as ProtoTrafficAnomaly, DdosLocationHit } from '@/generated/client/worldmonitor/infrastructure/v1/service_client';
import type { DisplacementFlow } from '@/services/displacement';
import type { Earthquake } from '@/services/earthquakes';
import type { ClimateAnomaly } from '@/services/climate';
import type { RadiationObservation } from '@/services/radiation';
import { ArcLayer } from '@deck.gl/layers';
import type { WeatherAlert } from '@/services/weather';
import { escapeHtml } from '@/utils/sanitize';
import {
derivePipelinePublicBadge,
type PipelineEvidenceInput,
type PipelinePublicBadge,
} from '@/shared/pipeline-evidence';
import { getCachedPipelineRegistries } from '@/shared/pipeline-registry-store';
import {
deriveStoragePublicBadge,
type StorageEvidenceInput,
type StoragePublicBadge,
} from '@/shared/storage-evidence';
import { getCachedStorageFacilityRegistry } from '@/shared/storage-facility-registry-store';
import { getCachedFuelShortageRegistry } from '@/shared/fuel-shortage-registry-store';
// getCountryCentroid is imported lower in the file alongside other
// country-geometry helpers; don't re-import it here.
import { tokenizeForMatch, matchKeyword, matchesAnyKeyword, findMatchingKeywords } from '@/utils/keyword-match';
import { t } from '@/services/i18n';
import { debounce, rafSchedule, getCurrentTheme } from '@/utils/index';
import { isInputPending, scheduleYield } from '@/utils/after-paint';
import { showLayerWarning } from '@/utils/layer-warning';
import { localizeMapLabels } from '@/utils/map-locale';
import {
createCountryHoverQueryController,
resolveCountryForPointerInteraction,
shouldRenderTradeAnimationFrame,
shouldRunInputSensitiveMapWork,
type CountryHoverQueryController,
} from './map/input-delay-interactions';
import { getCachedMilitaryBases, preloadMilitaryBases } from '@/services/military-base-config';
import {
INTEL_HOTSPOTS,
CONFLICT_ZONES,
GAMMA_IRRADIATORS,
PIPELINES,
PIPELINE_COLORS,
STRATEGIC_WATERWAYS,
SITE_VARIANT,
PORTS,
STOCK_EXCHANGES,
FINANCIAL_CENTERS,
CENTRAL_BANKS,
COMMODITY_HUBS,
GULF_INVESTMENTS,
MINING_SITES,
PROCESSING_PLANTS,
COMMODITY_PORTS as COMMODITY_GEO_PORTS,
} from '@/config';
// Tech-geo + ai-datacenters + geo-map tables imported directly so their chunks stay
// off the eager @/config barrel and load only with this lazy renderer (#4404).
import { STARTUP_HUBS, ACCELERATORS, TECH_HQS, CLOUD_REGIONS } from '@/config/tech-geo';
import { AI_DATA_CENTERS } from '@/config/ai-datacenters';
import { UNDERSEA_CABLES, NUCLEAR_FACILITIES, ECONOMIC_CENTERS, SPACEPORTS, CRITICAL_MINERALS, SANCTIONED_COUNTRIES_ALPHA2 } from '@/config/geo-map';
import type { GulfInvestment } from '@/types';
import { resolveTradeRouteSegments, TRADE_ROUTES as TRADE_ROUTES_LIST, type TradeRouteSegment, type TradeRouteStatus } from '@/config/trade-routes';
import type { ScenarioVisualState } from '@/config/scenario-templates';
import {
getLayersForVariant,
resolveLayerLabel,
bindLayerSearch,
getLayerExplanation,
hasCuratedLayerExplanation,
type MapVariant,
} from '@/config/map-layer-definitions';
import { renderLayerExplanationCard } from '@/utils/layer-explanation-card';
import { getAuthState, subscribeAuthState } from '@/services/auth-state';
import { onEntitlementChange } from '@/services/entitlements';
import { hasPremiumAccess } from '@/services/panel-gating';
import { trackGateHit } from '@/services/analytics';
import { MapPopup, type PopupType } from './MapPopup';
import { renderMilitaryVesselTooltipHtml } from './deckgl-tooltip-renderers';
import type { GetChokepointStatusResponse } from '@/services/supply-chain';
import type { ChinaCorridorControlTower } from '../../shared/china-corridor-control-towers';
import {
projectChinaCorridorOverlay,
type ChinaCorridorOverlayProjection,
} from './map/china-corridor-overlay';
import {
updateHotspotEscalation,
getHotspotEscalation,
setMilitaryData,
setCIIGetter,
setGeoAlertGetter,
} from '@/services/hotspot-escalation';
import { getCachedCountryScoreValue } from '@/services/cached-risk-scores';
import { getAlertsNearLocation } from '@/services/geo-convergence';
import type { PositiveGeoEvent } from '@/services/positive-events-geo';
import type { KindnessPoint } from '@/services/kindness-data';
import type { HappinessData } from '@/services/happiness-data';
import type { RenewableInstallation } from '@/services/renewable-installations';
import type { SpeciesRecovery } from '@/services/conservation-data';
import { getCountriesGeoJson, getCountryAtCoordinates, getCountryBbox, getCountryCentroid } from '@/services/country-geometry';
import type { DiseaseOutbreakItem } from '@/services/disease-outbreaks';
import type { FeatureCollection, Geometry } from 'geojson';
import type { ResilienceRankingItem } from '@/services/resilience';
import {
RESILIENCE_CHOROPLETH_COLORS,
buildResilienceChoroplethMap,
formatResilienceChoroplethLevel,
normalizeExclusiveChoropleths,
} from './resilience-choropleth-utils';
import { formatResilienceServerLevel } from './resilience-widget-utils';
import { isAllowedPreviewUrl } from '@/utils/imagery-preview';
import { pinWebcam, isPinned } from '@/services/webcams/pinned-store';
import type { WebcamEntry, WebcamCluster } from '@/generated/client/worldmonitor/webcam/v1/service_client';
import { fetchWebcamImage } from '@/services/webcams';
import { setTrustedHtml, trustedHtml } from '@/utils/dom-utils';
import { summarizeRenderTiming, formatRenderTiming } from '@/components/map/render-timing';
import { DeferredHeavyCommit } from '@/components/map/deferred-layer-commit';
import {
type BBox,
type BoundedFeature,
culledIndices,
geometryBounds,
simplifyGeometry,
zoomToSimplifyTolerance,
} from '@/components/map/conflict-zone-cull';
import {
createCountryClickGestureTracker,
finishCountryClickGesture,
markCountryClickDrag,
refreshCountryClickDragSuppression,
shouldSuppressCountryClick,
startCountryClickGesture,
updateCountryClickGestureDrag,
type CountryClickGestureTracker,
} from './map-interaction-guard';
export type TimeRange = '1h' | '6h' | '24h' | '48h' | '7d' | 'all';
export type DeckMapView = 'global' | 'america' | 'mena' | 'eu' | 'asia' | 'latam' | 'africa' | 'oceania';
type MapInteractionMode = 'flat' | '3d';
export interface CountryClickPayload {
lat: number;
lon: number;
code?: string;
name?: string;
}
interface DeckMapState {
zoom: number;
pan: { x: number; y: number };
view: DeckMapView;
layers: MapLayers;
timeRange: TimeRange;
}
interface DeckGLMapOptions {
chrome?: boolean;
}
interface HotspotWithBreaking extends Hotspot {
hasBreaking?: boolean;
}
interface TechEventMarker {
id: string;
title: string;
location: string;
lat: number;
lng: number;
country: string;
startDate: string;
endDate: string;
url: string | null;
daysUntil: number;
}
// View presets with longitude, latitude, zoom
const VIEW_PRESETS: Record<DeckMapView, { longitude: number; latitude: number; zoom: number }> = {
global: { longitude: 0, latitude: 20, zoom: 1.5 },
america: { longitude: -95, latitude: 38, zoom: 3 },
mena: { longitude: 45, latitude: 28, zoom: 3.5 },
eu: { longitude: 15, latitude: 50, zoom: 3.5 },
asia: { longitude: 105, latitude: 35, zoom: 3 },
latam: { longitude: -60, latitude: -15, zoom: 3 },
africa: { longitude: 20, latitude: 5, zoom: 3 },
oceania: { longitude: 135, latitude: -25, zoom: 3.5 },
};
const MAP_INTERACTION_MODE: MapInteractionMode =
import.meta.env.VITE_MAP_INTERACTION_MODE === 'flat' ? 'flat' : '3d';
const HAPPY_DARK_STYLE = '/map-styles/happy-dark.json';
const HAPPY_LIGHT_STYLE = '/map-styles/happy-light.json';
const isHappyVariant = SITE_VARIANT === 'happy';
// Zoom thresholds for layer visibility and labels (matches old Map.ts)
// Zoom-dependent layer visibility and labels
const LAYER_ZOOM_THRESHOLDS: Partial<Record<keyof MapLayers, { minZoom: number; showLabels?: number }>> = {
bases: { minZoom: 3, showLabels: 5 },
nuclear: { minZoom: 3 },
conflicts: { minZoom: 1, showLabels: 3 },
economic: { minZoom: 3 },
natural: { minZoom: 1, showLabels: 2 },
datacenters: { minZoom: 5 },
irradiators: { minZoom: 4 },
spaceports: { minZoom: 3 },
gulfInvestments: { minZoom: 2, showLabels: 5 },
};
// Export for external use
export { LAYER_ZOOM_THRESHOLDS };
// Theme-aware overlay color function — refreshed each buildLayers() call
function getOverlayColors() {
const isLight = getCurrentTheme() === 'light';
return {
// Threat dots: IDENTICAL in both modes (user locked decision)
hotspotHigh: [255, 68, 68, 200] as [number, number, number, number],
hotspotElevated: [255, 165, 0, 200] as [number, number, number, number],
hotspotLow: [255, 255, 0, 180] as [number, number, number, number],
// Conflict zone fills: more transparent in light mode
conflict: isLight
? [255, 0, 0, 60] as [number, number, number, number]
: [255, 0, 0, 100] as [number, number, number, number],
// Infrastructure/category markers: darker variants in light mode for map readability
base: [0, 150, 255, 200] as [number, number, number, number],
nuclear: isLight
? [180, 120, 0, 220] as [number, number, number, number]
: [255, 215, 0, 200] as [number, number, number, number],
datacenter: isLight
? [13, 148, 136, 200] as [number, number, number, number]
: [0, 255, 200, 180] as [number, number, number, number],
cable: [0, 200, 255, 150] as [number, number, number, number],
cableHighlight: [255, 100, 100, 200] as [number, number, number, number],
cableFault: [255, 50, 50, 220] as [number, number, number, number],
cableDegraded: [255, 165, 0, 200] as [number, number, number, number],
earthquake: [255, 100, 50, 200] as [number, number, number, number],
vesselMilitary: [255, 100, 100, 220] as [number, number, number, number],
protest: [255, 150, 0, 200] as [number, number, number, number],
outage: [255, 50, 50, 180] as [number, number, number, number],
trafficAnomaly: [255, 160, 0, 200] as [number, number, number, number],
ddosHit: [180, 0, 255, 200] as [number, number, number, number],
weather: [100, 150, 255, 180] as [number, number, number, number],
startupHub: isLight
? [22, 163, 74, 220] as [number, number, number, number]
: [0, 255, 150, 200] as [number, number, number, number],
techHQ: [100, 200, 255, 200] as [number, number, number, number],
accelerator: isLight
? [180, 120, 0, 220] as [number, number, number, number]
: [255, 200, 0, 200] as [number, number, number, number],
cloudRegion: [150, 100, 255, 180] as [number, number, number, number],
stockExchange: isLight
? [20, 120, 200, 220] as [number, number, number, number]
: [80, 200, 255, 210] as [number, number, number, number],
financialCenter: isLight
? [0, 150, 110, 215] as [number, number, number, number]
: [0, 220, 150, 200] as [number, number, number, number],
centralBank: isLight
? [180, 120, 0, 220] as [number, number, number, number]
: [255, 210, 80, 210] as [number, number, number, number],
commodityHub: isLight
? [190, 95, 40, 220] as [number, number, number, number]
: [255, 150, 80, 200] as [number, number, number, number],
gulfInvestmentSA: [0, 168, 107, 220] as [number, number, number, number],
gulfInvestmentUAE: [255, 0, 100, 220] as [number, number, number, number],
ucdpStateBased: [255, 50, 50, 200] as [number, number, number, number],
ucdpNonState: [255, 165, 0, 200] as [number, number, number, number],
ucdpOneSided: [255, 255, 0, 200] as [number, number, number, number],
};
}
// Initialize and refresh on every buildLayers() call
let COLORS = getOverlayColors();
// SVG icons as data URLs for different marker shapes
const MARKER_ICONS = {
// Square - for datacenters
square: 'data:image/svg+xml;base64,' + btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect x="2" y="2" width="28" height="28" rx="3" fill="white"/></svg>`),
// Diamond - for hotspots
diamond: 'data:image/svg+xml;base64,' + btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><polygon points="16,2 30,16 16,30 2,16" fill="white"/></svg>`),
// Triangle up - for military bases
triangleUp: 'data:image/svg+xml;base64,' + btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><polygon points="16,2 30,28 2,28" fill="white"/></svg>`),
// Hexagon - for nuclear
hexagon: 'data:image/svg+xml;base64,' + btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><polygon points="16,2 28,9 28,23 16,30 4,23 4,9" fill="white"/></svg>`),
// Circle - fallback
circle: 'data:image/svg+xml;base64,' + btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><circle cx="16" cy="16" r="14" fill="white"/></svg>`),
// Star - for special markers
star: 'data:image/svg+xml;base64,' + btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><polygon points="16,2 20,12 30,12 22,19 25,30 16,23 7,30 10,19 2,12 12,12" fill="white"/></svg>`),
// Airplane silhouette - top-down with wings and tail (pointing north, rotated by trackDeg)
plane: 'data:image/svg+xml;base64,' + btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><path d="M16 2 L17.5 10 L17 12 L27 17 L27 19 L17 16 L17 24 L20 26.5 L20 28 L16 27 L12 28 L12 26.5 L15 24 L15 16 L5 19 L5 17 L15 12 L14.5 10 Z" fill="white"/></svg>`),
};
const BASES_ICON_MAPPING = { triangleUp: { x: 0, y: 0, width: 32, height: 32, mask: true } };
const NUCLEAR_ICON_MAPPING = { hexagon: { x: 0, y: 0, width: 32, height: 32, mask: true } };
const DATACENTER_ICON_MAPPING = { square: { x: 0, y: 0, width: 32, height: 32, mask: true } };
const AIRCRAFT_ICON_MAPPING = { plane: { x: 0, y: 0, width: 32, height: 32, mask: true } };
const CONFLICT_COUNTRY_ISO: Record<string, string[]> = {
iran: ['IR'],
ukraine: ['UA'],
sudan: ['SD'],
myanmar: ['MM'],
};
// Altitude-based color gradient matching Wingbits' color scheme.
// Transitions cyan (sea level) → yellow-green → orange → red (cruise altitude).
const ALTITUDE_COLOR_STOPS: Array<{ alt: number; r: number; g: number; b: number }> = [
{ alt: 0, r: 0, g: 217, b: 255 },
{ alt: 5000, r: 50, g: 250, b: 160 },
{ alt: 10000, r: 200, g: 230, b: 60 },
{ alt: 20000, r: 255, g: 165, b: 30 },
{ alt: 30000, r: 255, g: 100, b: 35 },
{ alt: 40000, r: 235, g: 50, b: 55 },
{ alt: 45000, r: 210, g: 40, b: 70 },
];
function altitudeToColor(altFt: number): [number, number, number] {
const stops = ALTITUDE_COLOR_STOPS;
const alt = Number.isFinite(altFt) ? altFt : 0;
if (alt <= stops[0]!.alt) return [stops[0]!.r, stops[0]!.g, stops[0]!.b];
const last = stops[stops.length - 1]!;
if (alt >= last.alt) return [last.r, last.g, last.b];
for (let i = 1; i < stops.length; i++) {
const hi = stops[i]!;
const lo = stops[i - 1]!;
if (alt <= hi.alt) {
const t = (alt - lo.alt) / (hi.alt - lo.alt);
return [
Math.round(lo.r + (hi.r - lo.r) * t),
Math.round(lo.g + (hi.g - lo.g) * t),
Math.round(lo.b + (hi.b - lo.b) * t),
];
}
}
return [last.r, last.g, last.b]; // unreachable: exhaustive bracket search above satisfies TS
}
function ensureClosedRing(ring: [number, number][]): [number, number][] {
if (ring.length < 2) return ring;
const first = ring[0]!;
const last = ring[ring.length - 1]!;
if (first[0] === last[0] && first[1] === last[1]) return ring;
return [...ring, first];
}
/** Module-level Map from routeId → waypoint IDs. Built once, reused across all layer renders. */
const ROUTE_WAYPOINTS_MAP = new Map<string, string[]>(
TRADE_ROUTES_LIST.map(r => [r.id, r.waypoints]),
);
interface TripData {
path: [number, number][];
phase: number;
color: [number, number, number, number];
width: number;
}
type HighlightedMarker = { id: string; lon: number; lat: number; name: string; score: number };
/** GpsJamHex with its H3 cell boundary precomputed once at ingestion (see setGpsJamming). */
type GpsJamHexWithPolygon = GpsJamHex & { polygon: [number, number][] };
interface BypassArcDatum {
source: [number, number];
target: [number, number];
}
function interpolateGreatCircle(
start: [number, number],
end: [number, number],
numPoints: number,
): [number, number][] {
const toRad = (d: number) => d * Math.PI / 180;
const toDeg = (r: number) => r * 180 / Math.PI;
const [lon1, lat1] = [toRad(start[0]), toRad(start[1])];
const [lon2, lat2] = [toRad(end[0]), toRad(end[1])];
const d = 2 * Math.asin(Math.sqrt(
Math.sin((lat2 - lat1) / 2) ** 2 +
Math.cos(lat1) * Math.cos(lat2) * Math.sin((lon2 - lon1) / 2) ** 2,
));
if (d < 1e-10) return [start, end];
const points: [number, number][] = [];
for (let i = 0; i <= numPoints; i++) {
const f = i / numPoints;
const A = Math.sin((1 - f) * d) / Math.sin(d);
const B = Math.sin(f * d) / Math.sin(d);
const x = A * Math.cos(lat1) * Math.cos(lon1) + B * Math.cos(lat2) * Math.cos(lon2);
const y = A * Math.cos(lat1) * Math.sin(lon1) + B * Math.cos(lat2) * Math.sin(lon2);
const z = A * Math.sin(lat1) + B * Math.sin(lat2);
points.push([toDeg(Math.atan2(y, x)), toDeg(Math.atan2(z, Math.sqrt(x * x + y * y)))]);
}
return points;
}
function positionAlongPath(path: [number, number][], progress: number): [number, number] {
if (path.length === 0) return [0, 0];
if (path.length === 1) return path[0]!;
const clamped = Math.max(0, Math.min(1, progress));
const scaled = clamped * (path.length - 1);
const index = Math.min(path.length - 2, Math.floor(scaled));
const fraction = scaled - index;
const [lonA, latA] = path[index]!;
const [lonB, latB] = path[index + 1]!;
// Unwrap longitude across the antimeridian so the lerp takes the short way:
// great-circle samples can straddle ±180 (e.g. 176 → -176), and a raw lerp
// would sweep the dot across the whole map to ~0°E for that segment (#4396).
let deltaLon = lonB - lonA;
if (deltaLon > 180) deltaLon -= 360;
else if (deltaLon < -180) deltaLon += 360;
let lon = lonA + deltaLon * fraction;
if (lon > 180) lon -= 360;
else if (lon < -180) lon += 360;
return [lon, latA + (latB - latA) * fraction];
}
const PREFERS_REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
const TRADE_ANIMATION_CYCLE = 1000;
const TRADE_ANIMATION_SPEED = 0.3;
const TRADE_ANIMATION_MAX_DELTA_MS = 100;
const TRADE_GC_INTERPOLATION_POINTS = 20;
const CHOKEPOINT_PULSE_FREQ = 0.01;
const CHOKEPOINT_PULSE_AMP = 0.3;
function stableTradeRoutePhase(routeId: string): number {
let hash = 2166136261;
for (let i = 0; i < routeId.length; i++) {
const codeUnit = routeId.charCodeAt(i);
hash ^= codeUnit & 0xff;
hash = Math.imul(hash, 16777619);
hash ^= (codeUnit >> 8) & 0xff;
hash = Math.imul(hash, 16777619);
}
return ((hash >>> 0) / 0x100000000) * TRADE_ANIMATION_CYCLE;
}
// Process-wide guard so the window error listener for the deck.gl/maplibre
// interleaved-mode render race is installed exactly once even if a hot-reload
// or recreateWithFallback rebuilds the map.
let __deckInterleavedRaceFilterInstalled = false;
const DECK_INTERLEAVED_RACE_MESSAGE_RE = /Cannot read properties of null \(reading 'id'\)|null is not an object \(evaluating '[\w.]+\.id'\)/;
const DECK_INTERLEAVED_RACE_SOURCE_RE = /(?:^|[/(])deck-stack-[A-Za-z0-9_-]+\.js/;
/**
* Swallow the well-known deck.gl 9.x + maplibre-gl 5.x interleaved-mode race:
*
* Uncaught TypeError: Cannot read properties of null (reading 'id')
* at DeckRenderer._drawLayers (deck-stack-*.js)
* at LayerManager.renderLayers
* at MapLibre painter.renderLayer (maplibre-*.js)
*
* Trigger: setProps({layers}) → deck _resolveLayers calls maplibre.removeLayer
* for a layer that's being swapped → maplibre schedules a triggerRepaint that
* fires the next frame → that repaint runs deck's `render()` via maplibre's
* custom-layer hook → deck iterates the layer list and hits a layer that was
* finalized between resolveLayers and renderLayers.
*
* MapboxOverlay's own onError is bypassed because maplibre — not deck — owns
* the render-loop callstack here (deck doesn't see the throw, so onError is
* never invoked). The next frame renders cleanly with no user-visible
* artifact, so swallowing here is safe.
*
* Sentry's beforeSend in main.ts already filters this exact pattern for
* telemetry, but the browser still logs "Uncaught TypeError" to the console
* — this listener suppresses that.
*
* Narrow on BOTH the message shape AND deck-stack chunk evidence so an
* unrelated null-id crash in first-party code still surfaces. Some browsers
* surface the exception through Sentry's rAF wrapper, so ev.filename can point
* at sentry-*.js while ev.error.stack still contains deck-stack-*.js.
*/
function installDeckInterleavedRaceFilter(): void {
if (__deckInterleavedRaceFilterInstalled) return;
__deckInterleavedRaceFilterInstalled = true;
window.addEventListener('error', (ev) => {
const msg = ev.error?.message ?? ev.message ?? '';
const file = ev.filename ?? '';
const stack = typeof ev.error?.stack === 'string' ? ev.error.stack : '';
const source = `${file}\n${stack}`;
if (
DECK_INTERLEAVED_RACE_MESSAGE_RE.test(msg)
&& DECK_INTERLEAVED_RACE_SOURCE_RE.test(source)
) {
ev.preventDefault();
ev.stopImmediatePropagation();
if (import.meta.env.DEV) {
console.warn('[DeckGLMap] swallowed interleaved-mode render race (deck.gl/maplibre)');
}
}
}, { capture: true });
}
export class DeckGLMap {
private static readonly MAX_CLUSTER_LEAVES = 200;
private container: HTMLElement;
private deckOverlay: MapboxOverlay | null = null;
private maplibreMap: maplibregl.Map | null = null;
private state: DeckMapState;
private popup: MapPopup;
private isResizing = false;
private savedTopLat: number | null = null;
private correctingCenter = false;
// Data stores
private hotspots: HotspotWithBreaking[];
private earthquakes: Earthquake[] = [];
private weatherAlerts: WeatherAlert[] = [];
private outages: InternetOutage[] = [];
private trafficAnomalies: ProtoTrafficAnomaly[] = [];
private ddosLocations: DdosLocationHit[] = [];
private cyberThreats: CyberThreat[] = [];
private aptGroups: import('@/types').APTGroup[] = [];
private aptGroupsLoaded = false;
private _unsubscribeAuthState: (() => void) | null = null;
private _unsubscribeEntitlement: (() => void) | null = null;
private aptGroupsLayerFailed = false;
private satelliteImageryLayerFailed = false;
private iranEvents: IranEvent[] = [];
private aisDisruptions: AisDisruptionEvent[] = [];
private aisDensity: AisDensityZone[] = [];
private liveTankers: Array<{ mmsi: string; lat: number; lon: number; speed: number; shipType: number; name: string }> = [];
private liveTankersAbort: AbortController | null = null;
private liveTankersTimer: ReturnType<typeof setInterval> | null = null;
private cableAdvisories: CableAdvisory[] = [];
private repairShips: RepairShip[] = [];
private healthByCableId: Record<string, CableHealthRecord> = {};
private protests: SocialUnrestEvent[] = [];
private militaryFlights: MilitaryFlight[] = [];
private militaryFlightClusters: MilitaryFlightCluster[] = [];
private activeFlightTrails = new Set<string>();
private clearTrailsBtn: HTMLButtonElement | null = null;
private militaryVessels: MilitaryVessel[] = [];
private militaryVesselClusters: MilitaryVesselCluster[] = [];
private serverBases: MilitaryBaseEnriched[] = [];
private serverBaseClusters: ServerBaseCluster[] = [];
private serverBasesLoaded = false;
private baseConfigLoadPending = false;
private naturalEvents: NaturalEvent[] = [];
private firmsFireData: Array<{ lat: number; lon: number; brightness: number; frp: number; confidence: number; region: string; acq_date: string; daynight: string }> = [];
private techEvents: TechEventMarker[] = [];
private flightDelays: AirportDelayAlert[] = [];
private aircraftPositions: PositionSample[] = [];
private aircraftFetchTimer: ReturnType<typeof setInterval> | null = null;
private news: NewsItem[] = [];
private newsLocations: Array<{ lat: number; lon: number; title: string; threatLevel: string; timestamp?: Date }> = [];
private newsLocationFirstSeen = new Map<string, number>();
private ucdpEvents: UcdpGeoEvent[] = [];
private displacementFlows: DisplacementFlow[] = [];
private gpsJammingHexes: GpsJamHexWithPolygon[] = [];
private gpsJammingLoadSeq = 0;
private climateAnomalies: ClimateAnomaly[] = [];
private radiationObservations: RadiationObservation[] = [];
private diseaseOutbreaks: DiseaseOutbreakItem[] = [];
private tradeRouteSegments: TradeRouteSegment[] = resolveTradeRouteSegments();
private tradeTrips: TripData[] = [];
private tradeAnimationTime = 0;
private tradeAnimationFrame: number | null = null;
private tradeAnimationFrameCount = 0;
private tradeReducedMotionMedia: MediaQueryList | null = null;
private storedChokepointData: GetChokepointStatusResponse | null = null;
private highlightedRouteIds: Set<string> = new Set();
private highlightedMarkers: HighlightedMarker[] = [];
private bypassArcData: BypassArcDatum[] = [];
private scenarioState: ScenarioVisualState | null = null;
private selectedChinaCorridorOverlay: ChinaCorridorOverlayProjection | null = null;
private affectedIso2Set: Set<string> = new Set();
private positiveEvents: PositiveGeoEvent[] = [];
private kindnessPoints: KindnessPoint[] = [];
private imageryScenes: ImageryScene[] = [];
private imagerySearchTimer: ReturnType<typeof setTimeout> | null = null;
private imagerySearchVersion = 0;
// Phase 8 overlay data
private happinessScores: Map<string, number> = new Map();
private happinessYear = 0;
private happinessSource = '';
private speciesRecoveryZones: Array<SpeciesRecovery & { recoveryZone: { name: string; lat: number; lon: number } }> = [];
private renewableInstallations: RenewableInstallation[] = [];
private webcamData: Array<WebcamEntry | WebcamCluster> = [];
private countriesGeoJsonData: FeatureCollection<Geometry> | null = null;
private conflictZoneGeoJson: GeoJSON.FeatureCollection | null = null;
// #4561: all zone features + their precomputed bounds, built once (cheap — no
// tessellation); the viewport cull filters this into conflictZoneGeoJson.
private conflictZoneBounded: BoundedFeature[] | null = null;
// Keyed on the culled feature-index set + simplify tolerance (the FC's actual
// content), NOT the viewport — so a pan that leaves the visible set unchanged
// returns the same FeatureCollection ref and Object.is short-circuits the
// deck.gl re-tessellation (#4561 review P2).
private conflictZoneContentKey: string | null = null;
// #4601: countries features + precomputed bounds, built once (cheap — no
// tessellation); the viewport cull filters this for the choropleth layers,
// mirroring conflictZoneBounded. Invalidated with countriesGeoJsonData.
private countriesBounded: BoundedFeature[] | null = null;
private culledCountriesGeoJson: GeoJSON.FeatureCollection | null = null;
private culledCountriesContentKey = '';
// CII choropleth data
private ciiScoresMap: Map<string, { score: number; level: string }> = new Map();
private ciiScoresVersion = 0;
private resilienceScoresMap: ReturnType<typeof buildResilienceChoroplethMap> = new Map();
private resilienceScoresVersion = 0;
// Country highlight state
private countryGeoJsonLoaded = false;
private countryHoverSetup = false;
private highlightedCountryCode: string | null = null;
private hoveredCountryIso2: string | null = null;
private hoveredCountryName: string | null = null;
// Callbacks
private onHotspotClick?: (hotspot: Hotspot) => void;
private onTradeArcClick?: (segment: TradeRouteSegment, waypoints: string[], x: number, y: number) => void;
private onTimeRangeChange?: (range: TimeRange) => void;
private onCountryClick?: (country: CountryClickPayload) => void;
private onMapContextMenu?: (payload: { lat: number; lon: number; screenX: number; screenY: number; countryCode?: string; countryName?: string }) => void;
private readonly countryClickGesture: CountryClickGestureTracker = createCountryClickGestureTracker();
private readonly handleCountryClickPointerDown = (e: PointerEvent): void => {
if (e.pointerType === 'mouse' && e.button !== 0) return;
if (e.isPrimary === false) return;
startCountryClickGesture(this.countryClickGesture, { x: e.clientX, y: e.clientY });
};
private readonly handleCountryClickPointerMove = (e: PointerEvent): void => {
if (e.isPrimary === false) return;
updateCountryClickGestureDrag(this.countryClickGesture, { x: e.clientX, y: e.clientY });
};
private readonly handleCountryClickPointerEnd = (): void => {
finishCountryClickGesture(this.countryClickGesture);
};
private readonly markCountryDragGesture = (): void => {
markCountryClickDrag(this.countryClickGesture);
};
private readonly refreshCountryDragSuppression = (): void => {
refreshCountryClickDragSuppression(this.countryClickGesture);
};
private attachMapLibreInteractionHandlers(): void {
if (!this.maplibreMap) return;
const canvas = this.maplibreMap.getCanvas();
canvas.addEventListener('contextmenu', this.handleContextMenu);
canvas.addEventListener('pointerdown', this.handleCountryClickPointerDown);
canvas.addEventListener('pointermove', this.handleCountryClickPointerMove);
canvas.addEventListener('pointerup', this.handleCountryClickPointerEnd);
canvas.addEventListener('pointercancel', this.handleCountryClickPointerEnd);
this.maplibreMap.on('dragstart', this.markCountryDragGesture);
this.maplibreMap.on('dragend', this.refreshCountryDragSuppression);
}
private detachMapLibreInteractionHandlers(): void {
if (!this.maplibreMap) return;
const canvas = this.maplibreMap.getCanvas();
this.maplibreMap.off('dragstart', this.markCountryDragGesture);
this.maplibreMap.off('dragend', this.refreshCountryDragSuppression);
canvas.removeEventListener('contextmenu', this.handleContextMenu);
canvas.removeEventListener('pointerdown', this.handleCountryClickPointerDown);
canvas.removeEventListener('pointermove', this.handleCountryClickPointerMove);
canvas.removeEventListener('pointerup', this.handleCountryClickPointerEnd);
canvas.removeEventListener('pointercancel', this.handleCountryClickPointerEnd);
}
private readonly handleContextMenu = (e: MouseEvent): void => {
e.preventDefault();
if (!this.onMapContextMenu || !this.maplibreMap) return;
const rect = this.container.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const lngLat = this.maplibreMap.unproject([x, y]);
if (!Number.isFinite(lngLat.lng)) return;
const country = resolveCountryForPointerInteraction(
{ code: this.hoveredCountryIso2, name: this.hoveredCountryName },
this.hoverQueryThrottle?.isPending() ?? false,
() => this.resolveCountryFromCoordinate(lngLat.lng, lngLat.lat),
);
this.onMapContextMenu({
lat: lngLat.lat,
lon: lngLat.lng,
screenX: e.clientX,
screenY: e.clientY,
countryCode: country?.code,
countryName: country?.name,
});
};
private onLayerChange?: (layer: keyof MapLayers, enabled: boolean, source: 'user' | 'programmatic') => void;
private onStateChange?: (state: DeckMapState) => void;
private onAircraftPositionsUpdate?: (positions: PositionSample[]) => void;
// Highlighted assets
private highlightedAssets: Record<AssetType, Set<string>> = {
pipeline: new Set(),
cable: new Set(),
datacenter: new Set(),
base: new Set(),
nuclear: new Set(),
};
private renderRafId: number | null = null;
private renderPaused = false;
private renderPending = false;
private webglLost = false;
/** Stable empty GeoJSON for the immediate (pre-defer) frame of a heavy layer (#4558). */
private readonly emptyHeavyData: GeoJSON.FeatureCollection = { type: 'FeatureCollection', features: [] };
/**
* Two-phase heavy-layer commit (#4558). On the interaction-attributed frame
* heavy layers render their previously-committed (or empty) data; the real
* data is committed on a deferred (yielded) frame so the deck.gl tessellation
* lands off the measured frame. The gate skips the defer when data is unchanged.
*/
private readonly heavyGate = new DeferredHeavyCommit<unknown>({
// Yield the deferred heavy-layer flush off the interaction frame via
// scheduler.yield (ahead of clamped timers, behind queued input) — #5042 U4.
schedule: (fn) => scheduleYield(fn),
isAlive: () => !this.renderPaused && !this.webglLost && !!this.maplibreMap,
onCommit: () => this.updateLayers(true),
});
private destroyed = false;
private usedFallbackStyle = false;
private readonly chrome: boolean;
private initPromise: Promise<void> = Promise.resolve();
private styleLoadTimeoutId: ReturnType<typeof setTimeout> | null = null;
private tileMonitorGeneration = 0;
private layerCache: Map<string, Layer> = new Map();
private lastZoomThreshold = 0;
private protestSC: Supercluster | null = null;
private techHQSC: Supercluster | null = null;
private techEventSC: Supercluster | null = null;
private datacenterSC: Supercluster | null = null;
private datacenterSCSource: AIDataCenter[] = [];
private protestClusters: MapProtestCluster[] = [];
private techHQClusters: MapTechHQCluster[] = [];
private techEventClusters: MapTechEventCluster[] = [];
private datacenterClusters: MapDatacenterCluster[] = [];
private lastSCZoom = -1;
private lastSCBoundsKey = '';
private lastSCMask = '';
private protestSuperclusterSource: SocialUnrestEvent[] = [];
private newsPulseIntervalId: ReturnType<typeof setInterval> | null = null;
private dayNightIntervalId: ReturnType<typeof setInterval> | null = null;
private cachedNightPolygon: [number, number][] | null = null;
private radarRefreshIntervalId: ReturnType<typeof setInterval> | null = null;
private radarActive = false;
private radarTileUrl = '';
// Drop duplicate `once('idle', applyRadarLayer)` registrations when
// the source isn't loaded yet. Without this, both the style.load
// callback and the 5-minute refresh can register listeners in the
// same load window — they'd all fire on the next idle and call
// setTiles back-to-back. Idempotent today but wasteful.
private radarIdlePending = false;
private readonly startupTime = Date.now();
private basemapSwitchSeq = 0;
private lastCableHighlightSignature = '';
private lastCableHealthSignature = '';
private lastPipelineHighlightSignature = '';
private debouncedRebuildLayers: (() => void) & { cancel(): void };
private debouncedFetchBases: (() => void) & { cancel(): void };
private debouncedFetchAircraft: (() => void) & { cancel(): void };
private rafUpdateLayers: (() => void) & { cancel(): void };
private handleThemeChange: () => void;
private handleMapThemeChange: () => void;
private readonly handleTradeMotionPreferenceChange = (): void => {
if (this.prefersReducedTradeMotion()) {
this.stopTradeAnimation();
} else if (this.state.layers.tradeRoutes && !this.renderPaused) {
this.startTradeAnimation();
}
this.render();
};
private moveTimeoutId: ReturnType<typeof setTimeout> | null = null;
/** Target center set eagerly by setView() so getCenter() returns the correct
* destination before moveend fires, preventing stale intermediate coords
* from being written to the URL during flyTo. Cleared on moveend. */
private pendingCenter: { lat: number; lon: number } | null = null;
private lastAircraftFetchCenter: [number, number] | null = null;
private lastAircraftFetchZoom = -1;
private aircraftFetchSeq = 0;
constructor(container: HTMLElement, initialState: DeckMapState, options: DeckGLMapOptions = {}) {
this.container = container;
this.chrome = options.chrome ?? true;
this.state = {
...initialState,
pan: { ...initialState.pan },
layers: normalizeExclusiveChoropleths(initialState.layers, null),
};
this.hotspots = [...INTEL_HOTSPOTS];
this.debouncedRebuildLayers = debounce(() => {
if (this.renderPaused || this.webglLost || !this.maplibreMap) return;
this.maplibreMap.resize();
this.updateLayers();
}, 150);
this.debouncedFetchBases = debounce(() => this.fetchServerBases(), 300);
this.debouncedFetchAircraft = debounce(() => this.fetchViewportAircraft(), 500);
this.rafUpdateLayers = rafSchedule(() => {
if (this.renderPaused || this.webglLost || !this.maplibreMap) return;
this.updateLayers();
});
this.setupDOM();
this.popup = new MapPopup(container);
this.handleThemeChange = () => {
if (isHappyVariant) {
void this.switchBasemap();
return;
}
const provider = getMapProvider();
const mapTheme = getMapTheme(provider);
const paintTheme = isLightMapTheme(mapTheme) ? 'light' as const : 'dark' as const;
this.updateCountryLayerPaint(paintTheme);
this.render();
};
window.addEventListener('theme-changed', this.handleThemeChange);
this.handleMapThemeChange = () => {
void this.switchBasemap();
};
window.addEventListener('map-theme-changed', this.handleMapThemeChange);
this.tradeReducedMotionMedia = window.matchMedia(PREFERS_REDUCED_MOTION_QUERY);
this.tradeReducedMotionMedia.addEventListener('change', this.handleTradeMotionPreferenceChange);
this.initPromise = this.initMapLibre();
if (this.chrome) {
this.createControls();
this.createTimeSlider();
this.createLayerToggles();
this.createLegend();
}
// Start day/night timer only if layer is initially enabled
if (this.state.layers.dayNight) {
this.startDayNightTimer();
}
if (this.state.layers.weather) {
this.startWeatherRadar();
}
// Kick off lazy APT load if cyberThreats is already on at init (e.g. from URL/localStorage)
if (this.state.layers.cyberThreats && SITE_VARIANT !== 'tech' && SITE_VARIANT !== 'happy') {
this.loadAptGroups();
}
}
private startDayNightTimer(): void {
if (this.dayNightIntervalId) return;
this.cachedNightPolygon = this.computeNightPolygon();
this.dayNightIntervalId = setInterval(() => {
this.cachedNightPolygon = this.computeNightPolygon();
this.render();
}, 5 * 60 * 1000);
}
private stopDayNightTimer(): void {
if (this.dayNightIntervalId) {
clearInterval(this.dayNightIntervalId);
this.dayNightIntervalId = null;
}
this.cachedNightPolygon = null;
}
private startWeatherRadar(): void {
this.radarActive = true;
this.fetchAndApplyRadar();
if (!this.radarRefreshIntervalId) {
this.radarRefreshIntervalId = setInterval(() => this.fetchAndApplyRadar(), 5 * 60 * 1000);
}
}
private stopWeatherRadar(): void {
this.radarActive = false;
if (this.radarRefreshIntervalId) {
clearInterval(this.radarRefreshIntervalId);
this.radarRefreshIntervalId = null;
}
this.removeRadarLayer();
}
private fetchAndApplyRadar(): void {
fetch('https://api.rainviewer.com/public/weather-maps.json')
.then(r => r.json())
.then((data: { host: string; radar: { past: Array<{ path: string }> } }) => {
const past = data.radar?.past;
const latest = past?.[past.length - 1];
if (!latest) return;
this.radarTileUrl = `${data.host}${latest.path}/256/{z}/{x}/{y}/6/1_1.png`;
this.applyRadarLayer();
})
.catch((err) => console.warn('[DeckGLMap] weather radar fetch failed:', err?.message || err));
}
private applyRadarLayer(): void {
if (!this.maplibreMap || !this.radarActive || !this.radarTileUrl) return;
if (!this.maplibreMap.isStyleLoaded()) {
this.maplibreMap.once('style.load', () => this.applyRadarLayer());
return;
}
try {
const existing = this.maplibreMap.getSource('weather-radar') as (maplibregl.RasterTileSource & { setTiles: (tiles: string[]) => void }) | undefined;
if (existing) {
// Guard against the source existing in the style registry while
// its underlying texture is mid-load or being torn down. Calling
// setTiles in that window triggers a render-frame crash inside
// MapLibre at fa() / texture.bind() (Sentry WORLDMONITOR-P6:
// Firefox 149, hit on the 5-minute radar refresh interval).
// isSourceLoaded(id) is MapLibre's official "tiles fetched +
// applied to GL state" check; defer to the next idle if false.
if (!this.maplibreMap.isSourceLoaded('weather-radar')) {
if (!this.radarIdlePending) {
this.radarIdlePending = true;
this.maplibreMap.once('idle', () => {
this.radarIdlePending = false;
this.applyRadarLayer();
});
}
return;
}
existing.setTiles([this.radarTileUrl]);
return;
}
this.maplibreMap.addSource('weather-radar', {
type: 'raster',
tiles: [this.radarTileUrl],
tileSize: 256,
attribution: '© RainViewer',
});
const beforeId = this.maplibreMap.getLayer('country-interactive') ? 'country-interactive' : undefined;
this.maplibreMap.addLayer({
id: 'weather-radar-layer',
type: 'raster',
source: 'weather-radar',
paint: { 'raster-opacity': 0.65 },
}, beforeId);
} catch (err) { console.warn('[DeckGLMap] radar layer apply failed:', (err as Error)?.message); }
}
private removeRadarLayer(): void {
if (!this.maplibreMap) return;
try {
if (this.maplibreMap.getLayer('weather-radar-layer')) this.maplibreMap.removeLayer('weather-radar-layer');
if (this.maplibreMap.getSource('weather-radar')) this.maplibreMap.removeSource('weather-radar');
} catch { /* ignore */ }
}
private setupDOM(): void {
const wrapper = document.createElement('div');
wrapper.className = 'deckgl-map-wrapper';
wrapper.id = 'deckglMapWrapper';
wrapper.style.cssText = 'position: relative; width: 100%; height: 100%; overflow: hidden;';
// MapLibre container - deck.gl renders directly into MapLibre via MapboxOverlay
const mapContainer = document.createElement('div');
mapContainer.id = 'deckgl-basemap';
mapContainer.style.cssText = 'position: absolute; top: 0; left: 0; width: 100%; height: 100%;';
wrapper.appendChild(mapContainer);
const attribution = document.createElement('div');
attribution.className = 'map-attribution';
setTrustedHtml(attribution, trustedHtml(isHappyVariant
? '© <a href="https://carto.com/attributions" target="_blank" rel="noopener">CARTO</a> © <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a>'
: '© <a href="https://protomaps.com" target="_blank" rel="noopener">Protomaps</a> © <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a>', "legacy direct innerHTML migration"));
wrapper.appendChild(attribution);
this.container.appendChild(wrapper);
}
/**
* Resolves once the initial MapLibre construction has settled (success, or a
* guarded teardown that bailed before constructing the map). Rejects if map
* construction throws (e.g. a WebGL init failure), letting
* MapContainer.createDeckGLMap fall back to the SVG renderer — the failure
* path that the fire-and-forget `void this.initMapLibre()` would otherwise
* swallow into an unhandled rejection + blank map.
*/
public whenReady(): Promise<void> {
return this.initPromise;
}
private async initMapLibre(): Promise<void> {
if (maplibregl.getRTLTextPluginStatus() === 'unavailable') {
maplibregl.setRTLTextPlugin(
'/mapbox-gl-rtl-text.min.js',
true,
);
}
const { mapTheme: initialMapTheme, style: primaryStyle } = await this.resolveInitialBasemapStyle();
// The component can be torn down (renderer switch) while the style import
// above is in flight; bail before constructing a MapLibre map that destroy()
// can no longer reach — it would orphan a live WebGL context, its listeners
// and the 10s styleLoadTimeoutId.
if (this.destroyed) return;
const preset = VIEW_PRESETS[this.state.view];
if (!isHappyVariant && typeof primaryStyle === 'string' && !primaryStyle.includes('pmtiles')) {
this.usedFallbackStyle = true;
const attr = this.container.querySelector('.map-attribution');
if (attr) setTrustedHtml(attr, trustedHtml('© <a href="https://openfreemap.org" target="_blank" rel="noopener">OpenFreeMap</a> © <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a>', "legacy direct innerHTML migration"));
}
const basemapEl = document.getElementById('deckgl-basemap');
if (!basemapEl) return;
this.maplibreMap = new maplibregl.Map({
container: basemapEl,
style: primaryStyle,
center: [preset.longitude, preset.latitude],
// Fresh-load default = view preset zoom. Any zoom set during the deferred
// renderer window is re-applied by MapContainer.rehydrateActiveMap() after
// mount, so seeding from this.state.zoom here only undershoots the preset
// on the default desktop view.
zoom: preset.zoom,
renderWorldCopies: false,
attributionControl: false,
interactive: true,
canvasContextAttributes: { powerPreference: 'high-performance' },
...(MAP_INTERACTION_MODE === 'flat'
? {
maxPitch: 0,
pitchWithRotate: false,
dragRotate: false,
touchPitch: false,
}
: {}),
});
const recreateWithFallback = () => {
if (this.usedFallbackStyle) return;
this.usedFallbackStyle = true;
const fallback = isLightMapTheme(initialMapTheme) ? FALLBACK_LIGHT_STYLE : FALLBACK_DARK_STYLE;
console.warn(`[DeckGLMap] Primary basemap failed, recreating with fallback: ${fallback}`);
const attr = this.container.querySelector('.map-attribution');
if (attr) setTrustedHtml(attr, trustedHtml('© <a href="https://openfreemap.org" target="_blank" rel="noopener">OpenFreeMap</a> © <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a>', "legacy direct innerHTML migration"));
this.detachMapLibreInteractionHandlers();
this.maplibreMap?.remove();
const fallbackEl = document.getElementById('deckgl-basemap');
if (!fallbackEl) return;
this.maplibreMap = new maplibregl.Map({
container: fallbackEl,
style: fallback,
center: [preset.longitude, preset.latitude],
zoom: preset.zoom,
renderWorldCopies: false,
attributionControl: false,
interactive: true,
canvasContextAttributes: { powerPreference: 'high-performance' },
...(MAP_INTERACTION_MODE === 'flat'
? {
maxPitch: 0,
pitchWithRotate: false,
dragRotate: false,
touchPitch: false,
}
: {}),
});
this.maplibreMap.on('load', () => {
this.attachMapLibreInteractionHandlers();
localizeMapLabels(this.maplibreMap);
this.initDeck();
this.loadCountryBoundaries();
this.fetchServerBases();
this.render();
});
};
this.maplibreMap.on('load', () => {
localizeMapLabels(this.maplibreMap);
this.initDeck();
this.loadCountryBoundaries();
this.fetchServerBases();
this.render();
});
let tileLoadOk = false;
let tileErrorCount = 0;
this.maplibreMap.on('error', (e: { error?: Error; message?: string }) => {
const msg = e.error?.message ?? e.message ?? '';
console.warn('[DeckGLMap] map error:', msg);
if (msg.includes('Failed to fetch') || msg.includes('AJAXError') || msg.includes('CORS') || msg.includes('NetworkError') || msg.includes('403') || msg.includes('Forbidden')) {
tileErrorCount++;
if (!tileLoadOk && tileErrorCount >= 2) {
recreateWithFallback();
}
}
});
this.maplibreMap.on('data', (e: { dataType?: string }) => {
if (e.dataType === 'source') {
tileLoadOk = true;
if (this.styleLoadTimeoutId) {
clearTimeout(this.styleLoadTimeoutId);
this.styleLoadTimeoutId = null;
}
}
});
this.styleLoadTimeoutId = setTimeout(() => {
this.styleLoadTimeoutId = null;
if (!tileLoadOk) recreateWithFallback();
}, 10000);
const canvas = this.maplibreMap.getCanvas();
canvas.addEventListener('webglcontextlost', (e) => {
e.preventDefault();
this.webglLost = true;
console.warn('[DeckGLMap] WebGL context lost — will restore when browser recovers');
});
canvas.addEventListener('webglcontextrestored', () => {
this.webglLost = false;
console.info('[DeckGLMap] WebGL context restored');
this.maplibreMap?.triggerRepaint();
});
// Pin top edge during drag-resize: correct center shift synchronously
// inside MapLibre's own resize() call (before it renders the frame).
this.maplibreMap.on('move', () => {
if (this.correctingCenter || !this.isResizing || !this.maplibreMap) return;
if (this.savedTopLat === null) return;
const w = this.maplibreMap.getCanvas().clientWidth;
if (w <= 0) return;
const currentTop = this.maplibreMap.unproject([w / 2, 0]).lat;
const delta = this.savedTopLat - currentTop;
if (Math.abs(delta) > 1e-6) {
this.correctingCenter = true;
const c = this.maplibreMap.getCenter();
const clampedLat = Math.max(-90, Math.min(90, c.lat + delta));
this.maplibreMap.jumpTo({ center: [c.lng, clampedLat] });
this.correctingCenter = false;
// Do NOT update savedTopLat — keep the original mousedown position
// so every frame targets the exact same geographic anchor.
}
});
this.attachMapLibreInteractionHandlers();
}
private initDeck(): void {
if (!this.maplibreMap) return;
installDeckInterleavedRaceFilter();
this.deckOverlay = new MapboxOverlay({
interleaved: true,
layers: this.buildLayers(true),
getTooltip: (info: PickingInfo) => this.getTooltip(info),
onClick: (info: PickingInfo) => this.handleClick(info),
pickingRadius: 10,
useDevicePixels: window.devicePixelRatio > 2 ? 2 : true,
onError: (error: Error) => {
console.warn('[DeckGLMap] Render error (non-fatal):', error.message);
if (error.message.includes('apt-groups-layer')) {
this.aptGroupsLayerFailed = true;
}
if (error.message.includes('satellite-imagery-layer')) {
this.satelliteImageryLayerFailed = true;
console.warn('[DeckGLMap] Satellite imagery layer failed (likely Intel GPU driver incompatibility) — rebuilding layer stack without it');
this.updateLayers();
}
},
});
this.maplibreMap.addControl(this.deckOverlay as unknown as maplibregl.IControl);
this.maplibreMap.on('movestart', () => {
if (this.moveTimeoutId) {
clearTimeout(this.moveTimeoutId);
this.moveTimeoutId = null;
}
});
this.maplibreMap.on('moveend', () => {
this.pendingCenter = null;
this.lastSCZoom = -1;
this.rafUpdateLayers();
this.debouncedFetchBases();
this.debouncedFetchAircraft();
this.state.zoom = this.maplibreMap?.getZoom() ?? this.state.zoom;
this.onStateChange?.(this.getState());
if (this.state.layers.satellites) {
if (this.imagerySearchTimer) clearTimeout(this.imagerySearchTimer);
this.imagerySearchTimer = setTimeout(() => this.fetchImageryForViewport(), 500);
}
});
this.maplibreMap.on('move', () => {
if (this.moveTimeoutId) clearTimeout(this.moveTimeoutId);
this.moveTimeoutId = setTimeout(() => {
this.lastSCZoom = -1;
this.rafUpdateLayers();
}, 100);
});
this.maplibreMap.on('zoom', () => {
if (this.moveTimeoutId) clearTimeout(this.moveTimeoutId);
this.moveTimeoutId = setTimeout(() => {
this.lastSCZoom = -1;
this.rafUpdateLayers();
}, 100);
});
this.maplibreMap.on('zoomend', () => {
const currentZoom = Math.floor(this.maplibreMap?.getZoom() || 2);
const thresholdCrossed = Math.abs(currentZoom - this.lastZoomThreshold) >= 1;
if (thresholdCrossed) {
this.lastZoomThreshold = currentZoom;
this.debouncedRebuildLayers();
}
this.state.zoom = this.maplibreMap?.getZoom() ?? this.state.zoom;
this.onStateChange?.(this.getState());
});
}
public setIsResizing(value: boolean): void {
this.isResizing = value;
if (value && this.maplibreMap) {
const w = this.maplibreMap.getCanvas().clientWidth;
if (w > 0) {
this.savedTopLat = this.maplibreMap.unproject([w / 2, 0]).lat;
}
} else {
this.savedTopLat = null;
}
}
private async resolveInitialBasemapStyle(): Promise<{ mapTheme: string; style: StyleSpecification | string }> {
if (isHappyVariant) {
const mapTheme = getCurrentTheme();
return {
mapTheme,
style: mapTheme === 'light' ? HAPPY_LIGHT_STYLE : HAPPY_DARK_STYLE,
};
}
for (let attempt = 0; attempt < 10; attempt++) {
const provider = getMapProvider();
const mapTheme = getMapTheme(provider);
const style = await getStyleForProvider(provider, mapTheme);
const currentProvider = getMapProvider();
const currentMapTheme = getMapTheme(currentProvider);
if (provider === currentProvider && mapTheme === currentMapTheme) {
return { mapTheme, style };
}
}
const provider = getMapProvider();
const mapTheme = getMapTheme(provider);
console.warn('[DeckGLMap] Map provider changed repeatedly during startup; using latest provider state');
return {
mapTheme,
style: provider === 'carto'
? await getStyleForProvider(provider, mapTheme)
: (isLightMapTheme(mapTheme) ? FALLBACK_LIGHT_STYLE : FALLBACK_DARK_STYLE),
};
}
public resize(): void {
this.maplibreMap?.resize();
}
private getSetSignature(set: Set<string>): string {
return [...set].sort().join('|');
}
private hasRecentNews(now = Date.now()): boolean {
for (const ts of this.newsLocationFirstSeen.values()) {
if (now - ts < 30_000) return true;
}
return false;
}
private getTimeRangeMs(range: TimeRange = this.state.timeRange): number {
const ranges: Record<TimeRange, number> = {
'1h': 60 * 60 * 1000,
'6h': 6 * 60 * 60 * 1000,
'24h': 24 * 60 * 60 * 1000,
'48h': 48 * 60 * 60 * 1000,
'7d': 7 * 24 * 60 * 60 * 1000,
'all': Infinity,
};
return ranges[range];
}
private parseTime(value: Date | string | number | undefined | null): number | null {
if (value == null) return null;
const ts = value instanceof Date ? value.getTime() : new Date(value).getTime();
return Number.isFinite(ts) ? ts : null;
}
private filterByTime<T>(
items: T[],
getTime: (item: T) => Date | string | number | undefined | null
): T[] {
if (this.state.timeRange === 'all') return items;
const cutoff = Date.now() - this.getTimeRangeMs();
return items.filter((item) => {
const ts = this.parseTime(getTime(item));
return ts == null ? true : ts >= cutoff;
});
}
private _timeFilterCache = new WeakMap<object, { min: number; range: TimeRange; result: unknown[] }>();
private filterByTimeCached<T>(
items: T[],
getTime: (item: T) => Date | string | number | undefined | null
): T[] {
const min = Math.floor(Date.now() / 60000);
const range = this.state.timeRange;
const cached = this._timeFilterCache.get(items as object);
if (cached && cached.min === min && cached.range === range) return cached.result as T[];
const result = this.filterByTime(items, getTime);
this._timeFilterCache.set(items as object, { min, range, result });
return result;
}
private filterMilitaryFlightClustersByTimeCached(clusters: MilitaryFlightCluster[]): MilitaryFlightCluster[] {
const min = Math.floor(Date.now() / 60000);
const range = this.state.timeRange;
const cached = this._timeFilterCache.get(clusters as object);
if (cached && cached.min === min && cached.range === range) return cached.result as MilitaryFlightCluster[];
const result = this.filterMilitaryFlightClustersByTime(clusters);
this._timeFilterCache.set(clusters as object, { min, range, result });
return result;
}
private filterMilitaryVesselClustersByTimeCached(clusters: MilitaryVesselCluster[]): MilitaryVesselCluster[] {
const min = Math.floor(Date.now() / 60000);
const range = this.state.timeRange;
const cached = this._timeFilterCache.get(clusters as object);
if (cached && cached.min === min && cached.range === range) return cached.result as MilitaryVesselCluster[];
const result = this.filterMilitaryVesselClustersByTime(clusters);
this._timeFilterCache.set(clusters as object, { min, range, result });
return result;
}
private getFilteredProtests(): SocialUnrestEvent[] {
return this.filterByTime(this.protests, (event) => event.time);
}
private filterMilitaryFlightClustersByTime(clusters: MilitaryFlightCluster[]): MilitaryFlightCluster[] {
return clusters
.map((cluster) => {
const flights = this.filterByTime(cluster.flights ?? [], (flight) => flight.lastSeen);
if (flights.length === 0) return null;
return {
...cluster,
flights,
flightCount: flights.length,
};
})
.filter((cluster): cluster is MilitaryFlightCluster => cluster !== null);
}
private filterMilitaryVesselClustersByTime(clusters: MilitaryVesselCluster[]): MilitaryVesselCluster[] {
return clusters
.map((cluster) => {
const vessels = this.filterByTime(cluster.vessels ?? [], (vessel) => vessel.lastAisUpdate);
if (vessels.length === 0) return null;
return {
...cluster,
vessels,
vesselCount: vessels.length,
};
})
.filter((cluster): cluster is MilitaryVesselCluster => cluster !== null);
}
private rebuildProtestSupercluster(source: SocialUnrestEvent[] = this.getFilteredProtests()): void {
this.protestSuperclusterSource = source;
const points = source.map((p, i) => ({
type: 'Feature' as const,
geometry: { type: 'Point' as const, coordinates: [p.lon, p.lat] as [number, number] },
properties: {
index: i,
country: p.country,
severity: p.severity,
eventType: p.eventType,
sourceType: p.sourceType,
validated: Boolean(p.validated),
fatalities: Number.isFinite(p.fatalities) ? Number(p.fatalities) : 0,
timeMs: p.time.getTime(),
},
}));
this.protestSC = new Supercluster({
radius: 60,
maxZoom: 14,
map: (props: Record<string, unknown>) => ({
index: Number(props.index ?? 0),
country: String(props.country ?? ''),
maxSeverityRank: props.severity === 'high' ? 2 : props.severity === 'medium' ? 1 : 0,
riotCount: props.eventType === 'riot' ? 1 : 0,
highSeverityCount: props.severity === 'high' ? 1 : 0,
verifiedCount: props.validated ? 1 : 0,
totalFatalities: Number(props.fatalities ?? 0) || 0,
riotTimeMs: props.eventType === 'riot' && props.sourceType !== 'gdelt' && Number.isFinite(Number(props.timeMs)) ? Number(props.timeMs) : 0,
}),
reduce: (acc: Record<string, unknown>, props: Record<string, unknown>) => {
acc.maxSeverityRank = Math.max(Number(acc.maxSeverityRank ?? 0), Number(props.maxSeverityRank ?? 0));
acc.riotCount = Number(acc.riotCount ?? 0) + Number(props.riotCount ?? 0);
acc.highSeverityCount = Number(acc.highSeverityCount ?? 0) + Number(props.highSeverityCount ?? 0);
acc.verifiedCount = Number(acc.verifiedCount ?? 0) + Number(props.verifiedCount ?? 0);
acc.totalFatalities = Number(acc.totalFatalities ?? 0) + Number(props.totalFatalities ?? 0);
const accRiot = Number(acc.riotTimeMs ?? 0);
const propRiot = Number(props.riotTimeMs ?? 0);
acc.riotTimeMs = Number.isFinite(propRiot) ? Math.max(accRiot, propRiot) : accRiot;
if (!acc.country && props.country) acc.country = props.country;
},
});
this.protestSC.load(points);
this.lastSCZoom = -1;
}
private rebuildTechHQSupercluster(): void {
const points = TECH_HQS.map((h, i) => ({
type: 'Feature' as const,
geometry: { type: 'Point' as const, coordinates: [h.lon, h.lat] as [number, number] },
properties: {
index: i,
city: h.city,
country: h.country,
type: h.type,
},
}));
this.techHQSC = new Supercluster({
radius: 50,
maxZoom: 14,
map: (props: Record<string, unknown>) => ({
index: Number(props.index ?? 0),
city: String(props.city ?? ''),
country: String(props.country ?? ''),
faangCount: props.type === 'faang' ? 1 : 0,
unicornCount: props.type === 'unicorn' ? 1 : 0,
publicCount: props.type === 'public' ? 1 : 0,
}),
reduce: (acc: Record<string, unknown>, props: Record<string, unknown>) => {
acc.faangCount = Number(acc.faangCount ?? 0) + Number(props.faangCount ?? 0);
acc.unicornCount = Number(acc.unicornCount ?? 0) + Number(props.unicornCount ?? 0);
acc.publicCount = Number(acc.publicCount ?? 0) + Number(props.publicCount ?? 0);
if (!acc.city && props.city) acc.city = props.city;
if (!acc.country && props.country) acc.country = props.country;
},
});
this.techHQSC.load(points);
this.lastSCZoom = -1;
}
private rebuildTechEventSupercluster(): void {
const points = this.techEvents.map((e, i) => ({
type: 'Feature' as const,
geometry: { type: 'Point' as const, coordinates: [e.lng, e.lat] as [number, number] },
properties: {
index: i,
location: e.location,
country: e.country,
daysUntil: e.daysUntil,
},
}));
this.techEventSC = new Supercluster({
radius: 50,
maxZoom: 14,
map: (props: Record<string, unknown>) => {
const daysUntil = Number(props.daysUntil ?? Number.MAX_SAFE_INTEGER);
return {
index: Number(props.index ?? 0),
location: String(props.location ?? ''),
country: String(props.country ?? ''),
soonestDaysUntil: Number.isFinite(daysUntil) ? daysUntil : Number.MAX_SAFE_INTEGER,
soonCount: Number.isFinite(daysUntil) && daysUntil <= 14 ? 1 : 0,
};
},
reduce: (acc: Record<string, unknown>, props: Record<string, unknown>) => {
acc.soonestDaysUntil = Math.min(
Number(acc.soonestDaysUntil ?? Number.MAX_SAFE_INTEGER),
Number(props.soonestDaysUntil ?? Number.MAX_SAFE_INTEGER),
);
acc.soonCount = Number(acc.soonCount ?? 0) + Number(props.soonCount ?? 0);
if (!acc.location && props.location) acc.location = props.location;
if (!acc.country && props.country) acc.country = props.country;
},
});
this.techEventSC.load(points);
this.lastSCZoom = -1;
}
private rebuildDatacenterSupercluster(): void {
const activeDCs = AI_DATA_CENTERS.filter(dc => dc.status !== 'decommissioned');
this.datacenterSCSource = activeDCs;
const points = activeDCs.map((dc, i) => ({
type: 'Feature' as const,
geometry: { type: 'Point' as const, coordinates: [dc.lon, dc.lat] as [number, number] },
properties: {
index: i,
country: dc.country,
chipCount: dc.chipCount,
powerMW: dc.powerMW ?? 0,
status: dc.status,
},
}));
this.datacenterSC = new Supercluster({
radius: 70,
maxZoom: 14,
map: (props: Record<string, unknown>) => ({
index: Number(props.index ?? 0),
country: String(props.country ?? ''),
totalChips: Number(props.chipCount ?? 0) || 0,
totalPowerMW: Number(props.powerMW ?? 0) || 0,
existingCount: props.status === 'existing' ? 1 : 0,
plannedCount: props.status === 'planned' ? 1 : 0,
}),
reduce: (acc: Record<string, unknown>, props: Record<string, unknown>) => {
acc.totalChips = Number(acc.totalChips ?? 0) + Number(props.totalChips ?? 0);
acc.totalPowerMW = Number(acc.totalPowerMW ?? 0) + Number(props.totalPowerMW ?? 0);
acc.existingCount = Number(acc.existingCount ?? 0) + Number(props.existingCount ?? 0);
acc.plannedCount = Number(acc.plannedCount ?? 0) + Number(props.plannedCount ?? 0);
if (!acc.country && props.country) acc.country = props.country;
},
});
this.datacenterSC.load(points);
this.lastSCZoom = -1;
}
private updateClusterData(): void {
const zoom = Math.floor(this.maplibreMap?.getZoom() ?? 2);
const bounds = this.maplibreMap?.getBounds();
if (!bounds) return;
const bbox: [number, number, number, number] = [
bounds.getWest(), bounds.getSouth(), bounds.getEast(), bounds.getNorth(),
];
const boundsKey = `${bbox[0].toFixed(4)}:${bbox[1].toFixed(4)}:${bbox[2].toFixed(4)}:${bbox[3].toFixed(4)}`;
const layers = this.state.layers;
const useProtests = layers.protests && this.protestSuperclusterSource.length > 0;
const useTechHQ = SITE_VARIANT === 'tech' && layers.techHQs;
const useTechEvents = SITE_VARIANT === 'tech' && layers.techEvents && this.techEvents.length > 0;
const useDatacenterClusters = layers.datacenters && zoom < 5;
const layerMask = `${Number(useProtests)}${Number(useTechHQ)}${Number(useTechEvents)}${Number(useDatacenterClusters)}`;
if (zoom === this.lastSCZoom && boundsKey === this.lastSCBoundsKey && layerMask === this.lastSCMask) return;
this.lastSCZoom = zoom;
this.lastSCBoundsKey = boundsKey;
this.lastSCMask = layerMask;
if (useTechHQ && !this.techHQSC) this.rebuildTechHQSupercluster();
if (useDatacenterClusters && !this.datacenterSC) this.rebuildDatacenterSupercluster();
if (useProtests && this.protestSC) {
this.protestClusters = this.protestSC.getClusters(bbox, zoom).map(f => {
const coords = f.geometry.coordinates as [number, number];
if (f.properties.cluster) {
const props = f.properties as Record<string, unknown>;
const maxSeverityRank = Number(props.maxSeverityRank ?? 0);
const maxSev = maxSeverityRank >= 2 ? 'high' : maxSeverityRank === 1 ? 'medium' : 'low';
const riotCount = Number(props.riotCount ?? 0);
const highSeverityCount = Number(props.highSeverityCount ?? 0);
const verifiedCount = Number(props.verifiedCount ?? 0);
const totalFatalities = Number(props.totalFatalities ?? 0);
const clusterCount = Number(f.properties.point_count ?? 0);
const riotTimeMs = Number(props.riotTimeMs ?? 0);
return {
id: `pc-${f.properties.cluster_id}`,
_clusterId: f.properties.cluster_id!,
lat: coords[1], lon: coords[0],
count: clusterCount,
items: [] as SocialUnrestEvent[],
country: String(props.country ?? ''),
maxSeverity: maxSev as 'low' | 'medium' | 'high',
hasRiot: riotCount > 0,
latestRiotEventTimeMs: riotTimeMs || undefined,
totalFatalities,
riotCount,
highSeverityCount,
verifiedCount,
sampled: clusterCount > DeckGLMap.MAX_CLUSTER_LEAVES,
};
}
const item = this.protestSuperclusterSource[f.properties.index]!;
return {
id: `pp-${f.properties.index}`, lat: item.lat, lon: item.lon,
count: 1, items: [item], country: item.country,
maxSeverity: item.severity, hasRiot: item.eventType === 'riot',
latestRiotEventTimeMs:
item.eventType === 'riot' && item.sourceType !== 'gdelt' && Number.isFinite(item.time.getTime())
? item.time.getTime()
: undefined,
totalFatalities: item.fatalities ?? 0,
riotCount: item.eventType === 'riot' ? 1 : 0,
highSeverityCount: item.severity === 'high' ? 1 : 0,
verifiedCount: item.validated ? 1 : 0,
sampled: false,
};
});
} else {
this.protestClusters = [];
}
if (useTechHQ && this.techHQSC) {
this.techHQClusters = this.techHQSC.getClusters(bbox, zoom).map(f => {
const coords = f.geometry.coordinates as [number, number];
if (f.properties.cluster) {
const props = f.properties as Record<string, unknown>;
const faangCount = Number(props.faangCount ?? 0);
const unicornCount = Number(props.unicornCount ?? 0);
const publicCount = Number(props.publicCount ?? 0);
const clusterCount = Number(f.properties.point_count ?? 0);
const primaryType = faangCount >= unicornCount && faangCount >= publicCount
? 'faang'
: unicornCount >= publicCount
? 'unicorn'
: 'public';
return {
id: `hc-${f.properties.cluster_id}`,
_clusterId: f.properties.cluster_id!,
lat: coords[1], lon: coords[0],
count: clusterCount,
items: [] as import('@/config/tech-geo').TechHQ[],
city: String(props.city ?? ''),
country: String(props.country ?? ''),
primaryType,
faangCount,
unicornCount,
publicCount,
sampled: clusterCount > DeckGLMap.MAX_CLUSTER_LEAVES,
};
}
const item = TECH_HQS[f.properties.index]!;
return {
id: `hp-${f.properties.index}`, lat: item.lat, lon: item.lon,
count: 1, items: [item], city: item.city, country: item.country,
primaryType: item.type,
faangCount: item.type === 'faang' ? 1 : 0,
unicornCount: item.type === 'unicorn' ? 1 : 0,
publicCount: item.type === 'public' ? 1 : 0,
sampled: false,
};
});
} else {
this.techHQClusters = [];
}
if (useTechEvents && this.techEventSC) {
this.techEventClusters = this.techEventSC.getClusters(bbox, zoom).map(f => {
const coords = f.geometry.coordinates as [number, number];
if (f.properties.cluster) {
const props = f.properties as Record<string, unknown>;
const clusterCount = Number(f.properties.point_count ?? 0);
const soonestDaysUntil = Number(props.soonestDaysUntil ?? Number.MAX_SAFE_INTEGER);
const soonCount = Number(props.soonCount ?? 0);
return {
id: `ec-${f.properties.cluster_id}`,
_clusterId: f.properties.cluster_id!,
lat: coords[1], lon: coords[0],
count: clusterCount,
items: [] as TechEventMarker[],
location: String(props.location ?? ''),
country: String(props.country ?? ''),
soonestDaysUntil: Number.isFinite(soonestDaysUntil) ? soonestDaysUntil : Number.MAX_SAFE_INTEGER,
soonCount,
sampled: clusterCount > DeckGLMap.MAX_CLUSTER_LEAVES,
};
}
const item = this.techEvents[f.properties.index]!;
return {
id: `ep-${f.properties.index}`, lat: item.lat, lon: item.lng,
count: 1, items: [item], location: item.location, country: item.country,
soonestDaysUntil: item.daysUntil,
soonCount: item.daysUntil <= 14 ? 1 : 0,
sampled: false,
};
});
} else {
this.techEventClusters = [];
}
if (useDatacenterClusters && this.datacenterSC) {
const activeDCs = this.datacenterSCSource;
this.datacenterClusters = this.datacenterSC.getClusters(bbox, zoom).map(f => {
const coords = f.geometry.coordinates as [number, number];
if (f.properties.cluster) {
const props = f.properties as Record<string, unknown>;
const clusterCount = Number(f.properties.point_count ?? 0);
const existingCount = Number(props.existingCount ?? 0);
const plannedCount = Number(props.plannedCount ?? 0);
const totalChips = Number(props.totalChips ?? 0);
const totalPowerMW = Number(props.totalPowerMW ?? 0);
return {
id: `dc-${f.properties.cluster_id}`,
_clusterId: f.properties.cluster_id!,
lat: coords[1], lon: coords[0],
count: clusterCount,
items: [] as AIDataCenter[],
region: String(props.country ?? ''),
country: String(props.country ?? ''),
totalChips,
totalPowerMW,
majorityExisting: existingCount >= Math.max(1, clusterCount / 2),
existingCount,
plannedCount,
sampled: clusterCount > DeckGLMap.MAX_CLUSTER_LEAVES,
};
}
const item = activeDCs[f.properties.index]!;
return {
id: `dp-${f.properties.index}`, lat: item.lat, lon: item.lon,
count: 1, items: [item], region: item.country, country: item.country,
totalChips: item.chipCount, totalPowerMW: item.powerMW ?? 0,
majorityExisting: item.status === 'existing',
existingCount: item.status === 'existing' ? 1 : 0,
plannedCount: item.status === 'planned' ? 1 : 0,
sampled: false,
};
});
} else {
this.datacenterClusters = [];
}
}
private isLayerVisible(layerKey: keyof MapLayers): boolean {
const threshold = LAYER_ZOOM_THRESHOLDS[layerKey];
if (!threshold) return true;
const zoom = this.maplibreMap?.getZoom() || 2;
return zoom >= threshold.minZoom;
}
private buildLayers(deferHeavy = false): LayersList {
const startTime = performance.now();
// Refresh theme-aware overlay colors on each rebuild
COLORS = getOverlayColors();
const layers: (Layer | null | false)[] = [];
const { layers: mapLayers } = this.state;
const filteredEarthquakes = mapLayers.natural ? this.filterByTimeCached(this.earthquakes, (eq) => eq.occurredAt) : [];
const filteredNaturalEvents = mapLayers.natural ? this.filterByTimeCached(this.naturalEvents, (event) => event.date) : [];
// Disease outbreaks are sparse-by-nature — WHO Disease Outbreak News
// publishes 1-2 alerts/week, CDC HAN alerts are infrequent, and the
// upstream ThinkGlobalHealth tracker carries 90 days of ProMED items.
// Applying the global time-range filter (max '7d' in the dropdown)
// wholesale-zeroes the layer when the most recent WHO/CDC update is
// 8+ days old, which is normal for these sources. Show all items in
// the cache; the seeder's TTL + per-source lookback already bound
// freshness at write time. PR #3593: production saw 50 valid records
// cached but 0 rendered because the newest CDC item was 11d old.
const filteredDiseaseOutbreaks = mapLayers.diseaseOutbreaks ? this.diseaseOutbreaks : [];
const filteredRadiationObservations = mapLayers.radiationWatch ? this.filterByTimeCached(this.radiationObservations, (obs) => obs.observedAt) : [];
const filteredPositiveEvents = mapLayers.positiveEvents ? this.filterByTimeCached(this.positiveEvents, (e) => e.timestamp) : [];
const filteredIranEvents = mapLayers.iranAttacks ? this.filterByTimeCached(this.iranEvents, (e) => e.timestamp) : [];
const filteredFirmsFireData = mapLayers.fires ? this.filterByTimeCached(this.firmsFireData, (d) => d.acq_date) : [];
const filteredTrafficAnomalies = mapLayers.outages ? this.filterByTimeCached(this.trafficAnomalies, (a) => a.startDate) : [];
const filteredKindnessPoints = mapLayers.kindness ? this.filterByTimeCached(this.kindnessPoints, (p) => p.timestamp) : [];
const filteredImageryScenes = mapLayers.satellites ? this.filterByTimeCached(this.imageryScenes, (s) => s.datetime) : [];
const filteredWeatherAlerts = mapLayers.weather ? this.filterByTimeCached(this.weatherAlerts, (alert) => alert.onset) : [];
const filteredOutages = mapLayers.outages ? this.filterByTimeCached(this.outages, (outage) => outage.pubDate) : [];
const filteredCableAdvisories = mapLayers.cables ? this.filterByTimeCached(this.cableAdvisories, (advisory) => advisory.reported) : [];
const filteredFlightDelays = mapLayers.flights ? this.filterByTimeCached(this.flightDelays, (delay) => delay.updatedAt) : [];
const filteredMilitaryFlights = mapLayers.military ? this.filterByTimeCached(this.militaryFlights, (flight) => flight.lastSeen) : [];
const filteredMilitaryVessels = mapLayers.military ? this.filterByTimeCached(this.militaryVessels, (vessel) => vessel.lastAisUpdate) : [];
const filteredMilitaryFlightClusters = mapLayers.military ? this.filterMilitaryFlightClustersByTimeCached(this.militaryFlightClusters) : [];
const filteredMilitaryVesselClusters = mapLayers.military ? this.filterMilitaryVesselClustersByTimeCached(this.militaryVesselClusters) : [];
// UCDP is a historical dataset (events aged months); time-range filter always zeroes it out
const filteredUcdpEvents = mapLayers.ucdpEvents ? this.ucdpEvents : [];
// Day/night overlay (rendered first as background)
if (mapLayers.dayNight) {
if (!this.dayNightIntervalId) this.startDayNightTimer();
layers.push(this.createDayNightLayer());
} else {
if (this.dayNightIntervalId) this.stopDayNightTimer();
this.layerCache.delete('day-night-layer');
}
if (this.selectedChinaCorridorOverlay) {
layers.push(...this.createChinaCorridorSelectionLayers(this.selectedChinaCorridorOverlay));
}
// Undersea cables layer
if (mapLayers.cables) {
layers.push(this.createCablesLayer());
} else {
this.layerCache.delete('cables-layer');
}
// Pipelines layer — Redis-backed evidence registry (seed-pipelines-{gas,oil}.mjs),
// colored by derived publicBadge. Available on every variant that toggles
// `pipelines: true`. createEnergyPipelinesLayer falls back to the legacy
// static `PIPELINES` layer (createPipelinesLayer below) when the bootstrap
// hasn't hydrated yet, so the static layer is a real fallback — not dead
// code despite an earlier comment claiming it was retired in the gap #3B
// rollout. Removing createPipelinesLayer would leave the map blank on
// cold loads / variant switches before the first hydrate.
if (mapLayers.pipelines) {
layers.push(this.createEnergyPipelinesLayer());
} else {
this.layerCache.delete('pipelines-layer');
}
// Storage facilities layer. Registry is seeded weekly by
// scripts/seed-storage-facilities.mjs; colors by derived publicBadge
// identical to the panel's evidence deriver so first-paint map dots match
// panel status exactly. Available on any variant with
// `mapLayers.storageFacilities: true` (plan §R/#3 decision B).
if (mapLayers.storageFacilities) {
const storageLayer = this.createEnergyStorageLayer();
if (storageLayer) layers.push(storageLayer);
} else {
this.layerCache.delete('storage-facilities-layer');
}
// Fuel shortage pins. One pin per active shortage placed at the country
// centroid. Color by severity; click opens the FuelShortagePanel drawer
// via event. Available on any variant with `mapLayers.fuelShortages: true`
// (plan §R/#3 decision B).
if (mapLayers.fuelShortages) {
const shortageLayer = this.createEnergyShortagePinsLayer();
if (shortageLayer) layers.push(shortageLayer);
} else {
this.layerCache.delete('fuel-shortages-layer');
}
// Live tanker positions inside chokepoint bounding boxes. AIS ship type
// 80-89 (tanker class). Refreshed every 60s; one Map<chokepointId, ...>
// fetch per layer-tick. deckGLOnly per src/config/map-layer-definitions.ts.
// Powered by the relay's tankerReports field (added in PR 3 U7 alongside
// the existing military-only candidateReports). Energy Atlas parity-push.
if (mapLayers.liveTankers) {
// Start (or keep) the refresh loop while the layer is on. The
// ensure helper handles the "first time on" kick + the 60s
// setInterval; idempotent so calling it on every layers update is
// safe. Render immediately if we already have data; the interval
// re-renders when fresh data arrives.
this.ensureLiveTankersLoop();
if (this.liveTankers.length > 0) {
layers.push(this.createLiveTankersLayer());
}
} else {
// Layer toggled off → tear down the timer so we stop hitting the
// relay even when the map is still on screen.
this.stopLiveTankersLoop();
this.layerCache.delete('live-tankers-layer');
}
// Conflict zones layer — heavy GeoJson tessellation routed through the
// two-phase commit so it lands off the interaction frame (#4558).
if (mapLayers.conflicts) {
layers.push(this.createConflictZonesLayer(
this.resolveHeavyData('conflict', () => this.buildConflictZoneGeoJson(), deferHeavy, this.emptyHeavyData),
));
}
// Military bases layer — hidden at low zoom (E: progressive disclosure) + clusters
if (mapLayers.bases && this.isLayerVisible('bases')) {
layers.push(this.createBasesLayer());
layers.push(...this.createBasesClusterLayer());
}
layers.push(this.createEmptyGhost('bases-layer'));
// Nuclear facilities layer — hidden at low zoom
if (mapLayers.nuclear && this.isLayerVisible('nuclear')) {
layers.push(this.createNuclearLayer());
}
layers.push(this.createEmptyGhost('nuclear-layer'));
// Gamma irradiators layer — hidden at low zoom
if (mapLayers.irradiators && this.isLayerVisible('irradiators')) {
layers.push(this.createIrradiatorsLayer());
}
// Spaceports layer — hidden at low zoom
if (mapLayers.spaceports && this.isLayerVisible('spaceports')) {
layers.push(this.createSpaceportsLayer());
}
// Hotspots layer (all hotspots including high/breaking, with pulse + ghost)
if (mapLayers.hotspots) {
layers.push(...this.createHotspotsLayers());
}
// Datacenters layer - SQUARE icons at zoom >= 5, cluster dots at zoom < 5
const currentZoom = this.maplibreMap?.getZoom() || 2;
if (mapLayers.datacenters) {
if (currentZoom >= 5) {
layers.push(this.createDatacentersLayer());
} else {
layers.push(...this.createDatacenterClusterLayers());
}
}
// Earthquakes layer
if (mapLayers.natural && filteredEarthquakes.length > 0) {
layers.push(this.createEarthquakesLayer(filteredEarthquakes));
}
layers.push(this.createEmptyGhost('earthquakes-layer'));
// Natural events layers (non-TC scatter + TC tracks/cones/centers)
if (mapLayers.natural && filteredNaturalEvents.length > 0) {
layers.push(...this.createNaturalEventsLayers(filteredNaturalEvents));
}
if (mapLayers.radiationWatch && filteredRadiationObservations.length > 0) {
layers.push(this.createRadiationLayer(filteredRadiationObservations));
}
layers.push(this.createEmptyGhost('radiation-watch-layer'));
// Disease outbreaks layer
if (mapLayers.diseaseOutbreaks && filteredDiseaseOutbreaks.length > 0) {
layers.push(this.createDiseaseOutbreaksLayer(filteredDiseaseOutbreaks));
}
layers.push(this.createEmptyGhost('disease-outbreaks-layer'));
// Satellite fires layer (NASA FIRMS)
if (mapLayers.fires && filteredFirmsFireData.length > 0) {
layers.push(this.createFiresLayer(filteredFirmsFireData));
}
// Iran events layer
if (mapLayers.iranAttacks && filteredIranEvents.length > 0) {
layers.push(this.createIranEventsLayer(filteredIranEvents));
layers.push(this.createGhostLayer('iran-events-layer', filteredIranEvents, d => [d.longitude, d.latitude], { radiusMinPixels: 12 }));
}
// Weather alerts layer
if (mapLayers.weather && filteredWeatherAlerts.length > 0) {
layers.push(this.createWeatherLayer(filteredWeatherAlerts));
}
// Internet outages layer
if (mapLayers.outages && filteredOutages.length > 0) {
layers.push(this.createOutagesLayer(filteredOutages));
}
layers.push(this.createEmptyGhost('outages-layer'));
if (mapLayers.outages && filteredTrafficAnomalies.length > 0) {
layers.push(this.createTrafficAnomaliesLayer(filteredTrafficAnomalies));
}
layers.push(this.createEmptyGhost('traffic-anomalies-layer'));
if (mapLayers.outages && this.ddosLocations.length > 0) {
layers.push(this.createDdosLocationsLayer(this.ddosLocations));
}
layers.push(this.createEmptyGhost('ddos-locations-layer'));
// Cyber threat IOC layer
if (mapLayers.cyberThreats && this.cyberThreats.length > 0) {
layers.push(this.createCyberThreatsLayer());
}
layers.push(this.createEmptyGhost('cyber-threats-layer'));
// AIS density layer
if (mapLayers.ais && this.aisDensity.length > 0) {
layers.push(this.createAisDensityLayer());
}
// AIS disruptions layer (spoofing/jamming)
if (mapLayers.ais && this.aisDisruptions.length > 0) {
layers.push(this.createAisDisruptionsLayer());
}
// GPS/GNSS jamming layer
if (mapLayers.gpsJamming && this.gpsJammingHexes.length > 0) {
layers.push(this.createGpsJammingLayer());
}
// Strategic ports layer (shown with AIS)
if (mapLayers.ais) {
layers.push(this.createPortsLayer());
}
// Cable advisories layer (shown with cables)
if (mapLayers.cables && filteredCableAdvisories.length > 0) {
layers.push(this.createCableAdvisoriesLayer(filteredCableAdvisories));
}
// Repair ships layer (shown with cables)
if (mapLayers.cables && this.repairShips.length > 0) {
layers.push(this.createRepairShipsLayer());
}
// Aviation layer (flight delays + NOTAM closures + aircraft positions)
if (mapLayers.flights && filteredFlightDelays.length > 0) {
layers.push(this.createFlightDelaysLayer(filteredFlightDelays));
const closures = filteredFlightDelays.filter(d => d.delayType === 'closure');
if (closures.length > 0) {
layers.push(this.createNotamOverlayLayer(closures));
}
}
// Aircraft positions layer (live tracking, under flights toggle)
if (mapLayers.flights && this.aircraftPositions.length > 0) {
layers.push(this.createAircraftPositionsLayer());
}
// Protests layer (Supercluster-based deck.gl layers)
if (mapLayers.protests && this.protests.length > 0) {
layers.push(...this.createProtestClusterLayers());
}
// Military vessels layer
if (mapLayers.military && filteredMilitaryVessels.length > 0) {
layers.push(this.createMilitaryVesselsLayer(filteredMilitaryVessels));
}
// Military vessel clusters layer
if (mapLayers.military && filteredMilitaryVesselClusters.length > 0) {
layers.push(this.createMilitaryVesselClustersLayer(filteredMilitaryVesselClusters));
}
// Military flight trails (rendered beneath dots)
if (mapLayers.military && this.activeFlightTrails.size > 0 && filteredMilitaryFlights.length > 0) {
layers.push(this.createMilitaryFlightTrailsLayer(filteredMilitaryFlights));
}
// Military flights layer
if (mapLayers.military && filteredMilitaryFlights.length > 0) {
layers.push(this.createMilitaryFlightsLayer(filteredMilitaryFlights));
}
// Military flight clusters layer
if (mapLayers.military && filteredMilitaryFlightClusters.length > 0) {
layers.push(this.createMilitaryFlightClustersLayer(filteredMilitaryFlightClusters));
}
// Strategic waterways layer
if (mapLayers.waterways) {
layers.push(this.createWaterwaysLayer());
}
// Economic centers layer — hidden at low zoom
if (mapLayers.economic && this.isLayerVisible('economic')) {
layers.push(this.createEconomicCentersLayer());
}
// Finance variant layers
if (mapLayers.stockExchanges) {
layers.push(this.createStockExchangesLayer());
}
if (mapLayers.financialCenters) {
layers.push(this.createFinancialCentersLayer());
}
if (mapLayers.centralBanks) {
layers.push(this.createCentralBanksLayer());
}
if (mapLayers.commodityHubs) {
layers.push(this.createCommodityHubsLayer());
}
// Critical minerals layer
if (mapLayers.minerals) {
layers.push(this.createMineralsLayer());
}
// Commodity variant layers — mine sites, processing plants, export ports
if (mapLayers.miningSites) {
layers.push(this.createMiningSitesLayer());
}
if (mapLayers.processingPlants) {
layers.push(this.createProcessingPlantsLayer());
}
if (mapLayers.commodityPorts) {
layers.push(this.createCommodityPortsLayer());
}
// APT Groups layer — loaded lazily when cyberThreats layer is enabled
if (mapLayers.cyberThreats && SITE_VARIANT !== 'tech' && SITE_VARIANT !== 'happy' && this.aptGroups.length > 0 && !this.aptGroupsLayerFailed) {
layers.push(this.createAPTGroupsLayer());
}
// UCDP georeferenced events layer
if (mapLayers.ucdpEvents && filteredUcdpEvents.length > 0) {
layers.push(this.createUcdpEventsLayer(filteredUcdpEvents));
}
// Displacement flows arc layer
if (mapLayers.displacement && this.displacementFlows.length > 0) {
layers.push(this.createDisplacementArcsLayer());
}
// Climate anomalies heatmap layer
if (mapLayers.climate && this.climateAnomalies.length > 0) {
layers.push(this.createClimateHeatmapLayer());
}
// Trade routes layer
if (mapLayers.tradeRoutes) {
layers.push(this.createTradeRoutesLayer());
layers.push(this.createTradeRouteTripsLayer());
layers.push(this.createTradeChokepointsLayer());
const hlMarkers = this.createHighlightedChokepointMarkers();
if (hlMarkers) layers.push(hlMarkers);
const bypassArcs = this.createBypassArcsLayer();
if (bypassArcs) layers.push(bypassArcs);
this.startTradeAnimation();
} else {
this.stopTradeAnimation();
this.layerCache.delete('trade-routes-layer');
this.layerCache.delete('trade-route-trips-layer');
this.layerCache.delete('trade-chokepoints-layer');
this.layerCache.delete('highlighted-chokepoint-markers');
this.layerCache.delete('bypass-arcs-layer');
}
// Tech variant layers (Supercluster-based deck.gl layers for HQs and events)
if (SITE_VARIANT === 'tech') {
if (mapLayers.startupHubs) {
layers.push(this.createStartupHubsLayer());
}
if (mapLayers.techHQs) {
layers.push(...this.createTechHQClusterLayers());
}
if (mapLayers.accelerators) {
layers.push(this.createAcceleratorsLayer());
}
if (mapLayers.cloudRegions) {
layers.push(this.createCloudRegionsLayer());
}
if (mapLayers.techEvents && this.techEvents.length > 0) {
layers.push(...this.createTechEventClusterLayers());
}
}
// Gulf FDI investments layer
if (mapLayers.gulfInvestments) {
layers.push(this.createGulfInvestmentsLayer());
}
// Positive events layer (happy variant)
if (mapLayers.positiveEvents && filteredPositiveEvents.length > 0) {
layers.push(...this.createPositiveEventsLayers(filteredPositiveEvents));
}
// Kindness layer (happy variant -- green baseline pulses + real kindness events)
if (mapLayers.kindness && filteredKindnessPoints.length > 0) {
layers.push(...this.createKindnessLayers(filteredKindnessPoints));
}
// Phase 8: Happiness choropleth (rendered below point markers)
if (mapLayers.happiness) {
const choropleth = this.createHappinessChoroplethLayer();
if (choropleth) layers.push(choropleth);
}
// CII choropleth (country instability heat-map)
if (mapLayers.ciiChoropleth) {
const ciiLayer = this.createCIIChoroplethLayer();
if (ciiLayer) layers.push(ciiLayer);
}
if (mapLayers.resilienceScore) {
const resilienceLayer = this.createResilienceChoroplethLayer();
if (resilienceLayer) layers.push(resilienceLayer);
}
// Sanctions choropleth
if (mapLayers.sanctions) {
const sanctionsLayer = this.createSanctionsChoroplethLayer();
if (sanctionsLayer) layers.push(sanctionsLayer);
}
// Scenario heat layer (affected countries tint)
const scenarioHeat = this.scenarioState ? this.createScenarioHeatLayer() : null;
if (scenarioHeat) layers.push(scenarioHeat);
// Phase 8: Species recovery zones
if (mapLayers.speciesRecovery && this.speciesRecoveryZones.length > 0) {
layers.push(this.createSpeciesRecoveryLayer());
}
// Phase 8: Renewable energy installations
if (mapLayers.renewableInstallations && this.renewableInstallations.length > 0) {
layers.push(this.createRenewableInstallationsLayer());
}
if (mapLayers.satellites && filteredImageryScenes.length > 0 && !this.satelliteImageryLayerFailed) {
layers.push(this.createImageryFootprintLayer(filteredImageryScenes));
}
// Webcam layer (server-side clustered markers)
if (mapLayers.webcams && this.webcamData.length > 0) {
layers.push(new ScatterplotLayer<WebcamEntry | WebcamCluster>({
id: 'webcam-layer',
data: this.webcamData,
getPosition: (d) => [d.lng, d.lat],
getRadius: (d) => ('count' in d ? Math.min(8 + d.count * 0.5, 24) : 6),
getFillColor: (d) => ('count' in d ? [0, 212, 255, 180] : [255, 215, 0, 200]) as [number, number, number, number],
radiusUnits: 'pixels',
pickable: true,
}));
}
// News geo-locations (always shown if data exists)
if (this.newsLocations.length > 0) {
layers.push(...this.createNewsLocationsLayer());
}
const result = layers.filter(Boolean) as LayersList;
const elapsed = performance.now() - startTime;
if (import.meta.env.DEV && elapsed > 16) {
console.warn(`[DeckGLMap] buildLayers took ${elapsed.toFixed(2)}ms (>16ms budget), ${result.length} layers`);
}
return result;
}
// Layer creation methods
private createCablesLayer(): PathLayer {
const highlightedCables = this.highlightedAssets.cable;
const cacheKey = 'cables-layer';
const cached = this.layerCache.get(cacheKey) as PathLayer | undefined;
const highlightSignature = this.getSetSignature(highlightedCables);
const healthSignature = Object.keys(this.healthByCableId).sort().join(',');
if (cached && highlightSignature === this.lastCableHighlightSignature && healthSignature === this.lastCableHealthSignature) return cached;
const health = this.healthByCableId;
const layer = new PathLayer({
id: cacheKey,
data: UNDERSEA_CABLES,
getPath: (d) => d.points,
getColor: (d) => {
if (highlightedCables.has(d.id)) return COLORS.cableHighlight;
const h = health[d.id];
if (h?.status === 'fault') return COLORS.cableFault;
if (h?.status === 'degraded') return COLORS.cableDegraded;
return COLORS.cable;
},
getWidth: (d) => {
if (highlightedCables.has(d.id)) return 3;
const h = health[d.id];
if (h?.status === 'fault') return 2.5;
if (h?.status === 'degraded') return 2;
return 1;
},
widthMinPixels: 1,
widthMaxPixels: 5,
pickable: true,
updateTriggers: { highlighted: highlightSignature, health: healthSignature },
});
this.lastCableHighlightSignature = highlightSignature;
this.lastCableHealthSignature = healthSignature;
this.layerCache.set(cacheKey, layer);
return layer;
}
private createPipelinesLayer(): PathLayer {
const highlightedPipelines = this.highlightedAssets.pipeline;
const cacheKey = 'pipelines-layer';
const cached = this.layerCache.get(cacheKey) as PathLayer | undefined;
const highlightSignature = this.getSetSignature(highlightedPipelines);
if (cached && highlightSignature === this.lastPipelineHighlightSignature) return cached;
const layer = new PathLayer({
id: cacheKey,
data: PIPELINES,
getPath: (d) => d.points,
getColor: (d) => {
if (highlightedPipelines.has(d.id)) {
return [255, 100, 100, 200] as [number, number, number, number];
}
const colorKey = d.type as keyof typeof PIPELINE_COLORS;
const hex = PIPELINE_COLORS[colorKey] || '#666666';
return this.hexToRgba(hex, 150);
},
getWidth: (d) => highlightedPipelines.has(d.id) ? 3 : 1.5,
widthMinPixels: 1,
widthMaxPixels: 4,
pickable: true,
updateTriggers: { highlighted: highlightSignature },
});
this.lastPipelineHighlightSignature = highlightSignature;
this.layerCache.set(cacheKey, layer);
return layer;
}
// Energy-variant override for the pipelines map layer. Instead of the
// static PIPELINES config (colored by oil/gas type), this reads the
// evidence-backed pipeline registries seeded by scripts/seed-pipelines-
// {gas,oil}.mjs and colors each path by its derived publicBadge —
// flowing/reduced/offline/disputed. Click dispatches an
// `open-pipeline-detail` window event that PipelineStatusPanel listens
// for to open its drawer. Falls back to the static layer if bootstrap
// hasn't hydrated yet (e.g. variant switch before the fetch completes).
private createEnergyPipelinesLayer(): PathLayer {
const cacheKey = 'pipelines-layer';
const highlightedPipelines = this.highlightedAssets.pipeline;
const highlightSignature = this.getSetSignature(highlightedPipelines);
interface RawEntry {
id?: string; name?: string; commodityType?: string;
startPoint?: { lat?: number; lon?: number };
endPoint?: { lat?: number; lon?: number };
waypoints?: Array<{ lat?: number; lon?: number }>;
operator?: string;
evidence?: PipelineEvidenceInput;
}
interface EnergyPipeline {
id: string;
name: string;
operator: string;
commodityType: string;
points: Array<[number, number]>;
badge: PipelinePublicBadge;
}
// Read through the shared store instead of getHydratedData directly —
// getHydratedData is single-use (deletes on first read), and this same
// data is also consumed by PipelineStatusPanel. The store memoizes so
// both consumers see identical data regardless of mount order.
const { gas, oil } = getCachedPipelineRegistries() as {
gas: { pipelines?: Record<string, RawEntry> } | undefined;
oil: { pipelines?: Record<string, RawEntry> } | undefined;
};
const rawEntries: RawEntry[] = [
...Object.values(gas?.pipelines ?? {}),
...Object.values(oil?.pipelines ?? {}),
];
// Bootstrap not hydrated yet → fall back to the static layer so the
// map always has some representation of the pipelines toggle.
if (rawEntries.length === 0) return this.createPipelinesLayer();
const data: EnergyPipeline[] = rawEntries
.map(raw => {
const id = typeof raw.id === 'string' ? raw.id : '';
if (!id) return null;
const start = raw.startPoint;
const end = raw.endPoint;
if (!start || !end || typeof start.lat !== 'number' || typeof start.lon !== 'number' ||
typeof end.lat !== 'number' || typeof end.lon !== 'number') return null;
const points: Array<[number, number]> = [[start.lon, start.lat]];
if (Array.isArray(raw.waypoints)) {
for (const wp of raw.waypoints) {
if (wp && typeof wp.lat === 'number' && typeof wp.lon === 'number') {
points.push([wp.lon, wp.lat]);
}
}
}
points.push([end.lon, end.lat]);
return {
id,
name: raw.name || id,
operator: raw.operator || '',
commodityType: raw.commodityType || 'gas',
points,
badge: derivePipelinePublicBadge(raw.evidence),
} as EnergyPipeline;
})
.filter((p): p is EnergyPipeline => p != null);
const HIGHLIGHT_COLOR: [number, number, number, number] = [255, 100, 100, 240];
const badgeColor = (b: PipelinePublicBadge): [number, number, number, number] => {
switch (b) {
case 'flowing': return [46, 204, 113, 200]; // green
case 'reduced': return [243, 156, 18, 220]; // amber
case 'offline': return [231, 76, 60, 230]; // red
case 'disputed': return [155, 89, 182, 220]; // purple
}
};
const layer = new PathLayer<EnergyPipeline>({
id: cacheKey,
data,
getPath: d => d.points,
getColor: d => highlightedPipelines.has(d.id) ? HIGHLIGHT_COLOR : badgeColor(d.badge),
getWidth: d => {
if (highlightedPipelines.has(d.id)) return 4;
return (d.badge === 'offline' || d.badge === 'disputed') ? 3 : 2;
},
widthMinPixels: 1.5,
widthMaxPixels: 6,
pickable: true,
// updateTriggers make DeckGL recompute per-path getColor/getWidth
// when the highlight set changes; without this, flashAssets() /
// highlightAssets() would have no visible effect on the energy layer.
updateTriggers: {
getColor: highlightSignature,
getWidth: highlightSignature,
},
onClick: info => {
const obj = info?.object as EnergyPipeline | undefined;
if (!obj?.id) return false;
// Emit an event; PipelineStatusPanel listens and opens its drawer.
// Cross-component coupling stays loose — no direct reference to the
// panel class, and if the panel isn't mounted the event is a no-op.
try {
window.dispatchEvent(new CustomEvent('energy:open-pipeline-detail', {
detail: { pipelineId: obj.id },
}));
} catch {
// Non-browser / tauri edge cases — silent no-op.
}
return true;
},
});
// Intentionally NOT caching this layer: the underlying registries can
// update via setCachedPipelineRegistries() when the panel's RPC lands,
// and cached layers keyed only on highlightSignature would serve stale
// data. With ~25 critical-asset pipelines, rebuild cost per render is
// trivial (far cheaper than a stale-data UI bug).
return layer;
}
/**
* Storage facilities scatterplot layer (energy variant only). Reads
* through the shared store so this layer and StorageFacilityMapPanel
* both see the same bootstrap-hot registry without racing on
* getHydratedData's single-use drain.
*
* Dot radius = log(capacity) so Ras Laffan (77 Mtpa) visually dominates
* Chiren (6.5 TWh) without blowing out small sites to invisibility.
* Color = derived publicBadge, same deriver as the server handler.
*/
private createEnergyStorageLayer(): ScatterplotLayer | null {
const cacheKey = 'storage-facilities-layer';
interface RawEntry {
id?: string; name?: string; operator?: string;
facilityType?: string; country?: string;
location?: { lat?: number; lon?: number };
capacityTwh?: number; capacityMb?: number; capacityMtpa?: number;
evidence?: StorageEvidenceInput;
}
interface EnergyStorageDot {
id: string;
name: string;
operator: string;
facilityType: string;
country: string;
position: [number, number];
capacityDisplay: string;
radius: number;
badge: StoragePublicBadge;
}
const { registry } = getCachedStorageFacilityRegistry() as {
registry: { facilities?: Record<string, RawEntry> } | undefined;
};
const rawEntries: RawEntry[] = Object.values(registry?.facilities ?? {});
if (rawEntries.length === 0) return null;
const data: EnergyStorageDot[] = rawEntries
.map(raw => {
const id = typeof raw.id === 'string' ? raw.id : '';
if (!id) return null;
const loc = raw.location;
if (!loc || typeof loc.lat !== 'number' || typeof loc.lon !== 'number') return null;
// Capacity → radius. Each facility type has its own unit, so
// normalize to a common "relative size" before log — Mtpa is
// already the largest numerically; TWh and Mb are comparable.
let cap = 0;
let capDisplay = '—';
if (raw.facilityType === 'ugs' && typeof raw.capacityTwh === 'number' && raw.capacityTwh > 0) {
cap = raw.capacityTwh;
capDisplay = `${raw.capacityTwh.toFixed(1)} TWh`;
} else if ((raw.facilityType === 'spr' || raw.facilityType === 'crude_tank_farm')
&& typeof raw.capacityMb === 'number' && raw.capacityMb > 0) {
cap = raw.capacityMb;
capDisplay = `${raw.capacityMb.toLocaleString()} Mb`;
} else if ((raw.facilityType === 'lng_export' || raw.facilityType === 'lng_import')
&& typeof raw.capacityMtpa === 'number' && raw.capacityMtpa > 0) {
cap = raw.capacityMtpa;
capDisplay = `${raw.capacityMtpa.toFixed(1)} Mtpa`;
}
// log-scale radius so small sites stay visible; floor + ceiling to
// keep hit targets reasonable at all zoom levels.
const radius = Math.max(6000, Math.min(26000, 5000 + Math.log(Math.max(cap, 1)) * 5500));
return {
id,
name: raw.name || id,
operator: raw.operator || '',
facilityType: raw.facilityType || 'unknown',
country: raw.country || '',
position: [loc.lon, loc.lat] as [number, number],
capacityDisplay: capDisplay,
radius,
badge: deriveStoragePublicBadge(raw.evidence),
} as EnergyStorageDot;
})
.filter((d): d is EnergyStorageDot => d != null);
const badgeColor = (b: StoragePublicBadge): [number, number, number, number] => {
switch (b) {
case 'operational': return [46, 204, 113, 220]; // green
case 'reduced': return [243, 156, 18, 230]; // amber
case 'offline': return [231, 76, 60, 240]; // red
case 'disputed': return [155, 89, 182, 230]; // purple
}
};
return new ScatterplotLayer<EnergyStorageDot>({
id: cacheKey,
data,
getPosition: d => d.position,
getFillColor: d => badgeColor(d.badge),
getRadius: d => d.radius,
stroked: true,
getLineColor: [255, 255, 255, 200],
lineWidthMinPixels: 1,
radiusMinPixels: 5,
radiusMaxPixels: 28,
pickable: true,
onClick: info => {
const obj = info?.object as EnergyStorageDot | undefined;
if (!obj?.id) return false;
// Dispatch to StorageFacilityMapPanel — same loose-coupling
// pattern as the pipelines layer.
try {
window.dispatchEvent(new CustomEvent('energy:open-storage-facility-detail', {
detail: { facilityId: obj.id },
}));
} catch {
// Silent no-op on non-browser runtimes.
}
return true;
},
});
}
/**
* Fuel shortage pins (energy variant only). One dot per active shortage
* placed at the country centroid. Color by severity (confirmed = red,
* watch = amber). Click dispatches 'energy:open-fuel-shortage-detail'
* which FuelShortagePanel listens for.
*
* Multiple shortages in the same country stack with a small angular
* offset so they don't render as one overlapping dot.
*/
private createEnergyShortagePinsLayer(): ScatterplotLayer | null {
const cacheKey = 'fuel-shortages-layer';
interface RawEntry {
id?: string; country?: string; product?: string; severity?: string;
shortDescription?: string;
resolvedAt?: string | null;
}
interface ShortagePin {
id: string;
country: string;
product: string;
severity: string;
description: string;
position: [number, number];
}
const { registry } = getCachedFuelShortageRegistry() as {
registry: { shortages?: Record<string, RawEntry> } | undefined;
};
// Exclude resolved shortages — a pin on the map is a claim of an
// ACTIVE crisis, and rendering resolved entries as active inflates
// severity counts and shows stale crisis data. Classifier writes
// resolvedAt as ISO string on resolution; raw seed uses null.
const rawEntries: RawEntry[] = Object.values(registry?.shortages ?? {})
.filter(s => !s.resolvedAt);
if (rawEntries.length === 0) return null;
// Stack multiple shortages per country by offsetting longitudes.
const perCountryCount = new Map<string, number>();
const data: ShortagePin[] = rawEntries
.map(raw => {
const id = typeof raw.id === 'string' ? raw.id : '';
if (!id) return null;
const country = raw.country;
if (typeof country !== 'string' || country.length !== 2) return null;
const centroid = getCountryCentroid(country);
if (!centroid) return null;
const idx = perCountryCount.get(country) ?? 0;
perCountryCount.set(country, idx + 1);
// ~0.8° offset per additional pin in the same country.
const offsetLon = idx === 0 ? 0 : (idx * 0.8 * (idx % 2 === 0 ? 1 : -1));
return {
id,
country,
product: raw.product || '',
severity: raw.severity || 'watch',
description: raw.shortDescription || '',
position: [centroid.lon + offsetLon, centroid.lat] as [number, number],
};
})
.filter((d): d is ShortagePin => d != null);
const severityColor = (sev: string): [number, number, number, number] => {
switch (sev) {
case 'confirmed': return [231, 76, 60, 240]; // red
case 'watch': return [243, 156, 18, 230]; // amber
default: return [127, 140, 141, 200]; // grey
}
};
return new ScatterplotLayer<ShortagePin>({
id: cacheKey,
data,
getPosition: d => d.position,
getFillColor: d => severityColor(d.severity),
// Confirmed pins slightly larger than watch to pre-attentively indicate weight.
getRadius: d => d.severity === 'confirmed' ? 55000 : 38000,
stroked: true,
getLineColor: [255, 255, 255, 230],
lineWidthMinPixels: 1.5,
radiusMinPixels: 7,
radiusMaxPixels: 24,
pickable: true,
onClick: info => {
const obj = info?.object as ShortagePin | undefined;
if (!obj?.id) return false;
try {
window.dispatchEvent(new CustomEvent('energy:open-fuel-shortage-detail', {
detail: { shortageId: obj.id },
}));
} catch {
// Silent no-op on non-browser runtimes.
}
return true;
},
});
}
/**
* All conflict-zone features paired with their bounds, built once and cached.
* Cheap (feature construction + a bounds scan — no tessellation); invalidated
* with the culled cache on countries-geometry load. The heavy per-zone cost
* (country-multipolygon tessellation) is only paid for the culled subset in
* `buildConflictZoneGeoJson`.
*/
private buildAllConflictZoneFeatures(): BoundedFeature[] {
if (this.conflictZoneBounded) return this.conflictZoneBounded;
const bounded: BoundedFeature[] = [];
// A feature with no computable bounds (empty/degenerate geometry) is
// intentionally excluded — deck.gl skips such geometry anyway, and it can't
// be viewport-tested. CONFLICT_ZONES + country features are always valid, so
// this is a safety guard, not an expected drop.
const push = (feature: GeoJSON.Feature): void => {
const bounds = geometryBounds(feature.geometry);
if (bounds) bounded.push({ bounds, feature });
};
for (const zone of CONFLICT_ZONES) {
const isoCodes = CONFLICT_COUNTRY_ISO[zone.id];
let usedCountryGeometry = false;
if (isoCodes?.length && this.countriesGeoJsonData) {
for (const feature of this.countriesGeoJsonData.features) {
const code = feature.properties?.['ISO3166-1-Alpha-2'];
if (typeof code !== 'string' || !isoCodes.includes(code)) continue;
push({
type: 'Feature',
properties: { id: zone.id, name: zone.name, intensity: zone.intensity },
geometry: feature.geometry,
});
usedCountryGeometry = true;
}
}
if (usedCountryGeometry) continue;
push({
type: 'Feature',
properties: { id: zone.id, name: zone.name, intensity: zone.intensity },
geometry: { type: 'Polygon', coordinates: [ensureClosedRing(zone.coords)] },
});
}
this.conflictZoneBounded = bounded;
return bounded;
}
/**
* #4561: bound the conflict-zone tessellation to the current viewport. Only
* zones whose bounds intersect the (padded) viewport are handed to deck.gl, so
* the synchronous tessellation cost scales with what's on screen — not the
* global zone set. Cached by a quantized viewport key so a small pan reuses the
* previous cull; `moveend` already re-runs `buildLayers`, refreshing the key.
* At world/low zoom every zone is included (culling can't reduce the count
* there — that case is bounded by low-zoom simplification, U2).
*/
private buildConflictZoneGeoJson(): GeoJSON.FeatureCollection {
const bounded = this.buildAllConflictZoneFeatures();
const mapBounds = this.maplibreMap?.getBounds();
if (!mapBounds) {
const key = 'preinit';
if (key === this.conflictZoneContentKey && this.conflictZoneGeoJson) {
return this.conflictZoneGeoJson;
}
// Pre-map-init: no viewport to cull against — render all (prior behavior).
this.conflictZoneGeoJson = { type: 'FeatureCollection', features: bounded.map((b) => b.feature) };
this.conflictZoneContentKey = key;
return this.conflictZoneGeoJson;
}
// getBounds() lng stays in the zone-data lng range only because both map
// inits set renderWorldCopies: false — off-copy zones genuinely aren't drawn,
// so culling them is correct. Flipping that flag would need the cull to
// handle wrapped longitudes (#4561 review P3-a).
const viewport: BBox = [
mapBounds.getWest(), mapBounds.getSouth(), mapBounds.getEast(), mapBounds.getNorth(),
];
const zoom = this.maplibreMap?.getZoom() ?? 2;
const tolerance = zoomToSimplifyTolerance(zoom);
// The cull (bbox tests over the static zone set) is cheap and runs every
// build; the content key = culled index set + tolerance captures exactly what
// the FeatureCollection contains, so an unchanged visible set reuses the
// cached FC ref and the deck.gl re-tessellation short-circuits (review P2).
const indices = culledIndices(bounded, viewport);
const contentKey = `${tolerance.toFixed(4)}:${indices.join(',')}`;
if (contentKey === this.conflictZoneContentKey && this.conflictZoneGeoJson) {
return this.conflictZoneGeoJson;
}
// U2: at world/low zoom the cull can't reduce the count, so RDP-simplify the
// (invisible-at-this-zoom) sub-pixel vertices to bound tessellation. New
// geometry objects — never mutate the shared country geometry.
const features: GeoJSON.Feature[] = indices.map((i) => {
const feature = bounded[i]?.feature;
if (!feature) return null;
return tolerance > 0 ? { ...feature, geometry: simplifyGeometry(feature.geometry, tolerance) } : feature;
}).filter((f): f is GeoJSON.Feature => f !== null);
this.conflictZoneGeoJson = { type: 'FeatureCollection', features };
this.conflictZoneContentKey = contentKey;
return this.conflictZoneGeoJson;
}
/**
* Viewport-culled countries geojson for the choropleth layers (#4601). Mirrors the
* conflict-zone cull (#4561): build the bounded set once, cull to the current
* viewport, and content-key cache so an unchanged visible set reuses the FC ref
* (Object.is short-circuits the deck.gl re-tessellation). Re-culled on pan/zoom via
* updateLayers(). Cull-only — no RDP simplify, so country borders stay crisp; at
* world/low zoom every country is visible so the full ref is returned unchanged.
*/
private getCulledCountriesGeoJson(): GeoJSON.FeatureCollection | null {
const data = this.countriesGeoJsonData;
if (!data) return null;
if (!this.countriesBounded) {
const bounded: BoundedFeature[] = [];
for (const feature of data.features) {
const bounds = geometryBounds(feature.geometry);
if (bounds) bounded.push({ bounds, feature });
}
this.countriesBounded = bounded;
}
const mapBounds = this.maplibreMap?.getBounds();
if (!mapBounds) return data; // pre-map-init: no viewport — render all (prior behavior)
const viewport: BBox = [
mapBounds.getWest(), mapBounds.getSouth(), mapBounds.getEast(), mapBounds.getNorth(),
];
const indices = culledIndices(this.countriesBounded, viewport);
// All countries visible (world/low zoom) — return the full ref, no new FC alloc.
if (indices.length === this.countriesBounded.length) return data;
const contentKey = indices.join(',');
if (contentKey === this.culledCountriesContentKey && this.culledCountriesGeoJson) {
return this.culledCountriesGeoJson;
}
const features = indices.map((i) => this.countriesBounded![i]!.feature);
this.culledCountriesGeoJson = { type: 'FeatureCollection', features };
this.culledCountriesContentKey = contentKey;
return this.culledCountriesGeoJson;
}
/**
* Two-phase heavy-layer data (#4558). On the immediate (deferHeavy) frame,
* stage the freshly-computed data and render the previously-committed value
* (or `empty` on first build) so the heavy deck.gl tessellation is deferred;
* the gate's deferred pass (deferHeavy=false) renders the committed real data.
* Unchanged data short-circuits in the gate (no extra frame).
*/
private resolveHeavyData<T>(key: string, compute: () => T, deferHeavy: boolean, empty: T): T {
if (deferHeavy) {
const real = compute();
this.heavyGate.stage(key, real);
return (this.heavyGate.present(key) as T | undefined) ?? empty;
}
return (this.heavyGate.present(key) as T | undefined) ?? compute();
}
private createConflictZonesLayer(data: GeoJSON.FeatureCollection): GeoJsonLayer {
const cacheKey = this.countriesGeoJsonData
? 'conflict-zones-layer-country-geometry'
: 'conflict-zones-layer';
const layer = new GeoJsonLayer({
id: cacheKey,
data,
filled: true,
stroked: true,
getFillColor: () => COLORS.conflict,
getLineColor: () => getCurrentTheme() === 'light'
? [255, 0, 0, 120] as [number, number, number, number]
: [255, 0, 0, 180] as [number, number, number, number],
getLineWidth: 2,
lineWidthMinPixels: 1,
pickable: true,
});
return layer;
}
private getBasesData(): MilitaryBaseEnriched[] {
if (this.serverBasesLoaded) return this.serverBases;
const bases = getCachedMilitaryBases() as MilitaryBaseEnriched[];
if (bases.length === 0) this.requestBaseConfigRender();
return bases;
}
private requestBaseConfigRender(): void {
if (this.baseConfigLoadPending) return;
this.baseConfigLoadPending = true;
void preloadMilitaryBases()
.then(() => {
this.baseConfigLoadPending = false;
if (!this.destroyed) this.render();
})
.catch((error) => {
this.baseConfigLoadPending = false;
console.warn('[DeckGLMap] Military base config unavailable:', error);
});
}
private createBasesLayer(): IconLayer {
const highlightedBases = this.highlightedAssets.base;
const zoom = this.maplibreMap?.getZoom() || 3;
const alphaScale = Math.min(1, (zoom - 2.5) / 2.5);
const a = Math.round(160 * Math.max(0.3, alphaScale));
const data = this.getBasesData();
return new IconLayer({
id: 'bases-layer',
data,
getPosition: (d) => [d.lon, d.lat],
getIcon: () => 'triangleUp',
iconAtlas: MARKER_ICONS.triangleUp,
iconMapping: BASES_ICON_MAPPING,
getSize: (d) => highlightedBases.has(d.id) ? 16 : 11,
getColor: (d) => {
if (highlightedBases.has(d.id)) {
return [255, 100, 100, 220] as [number, number, number, number];
}
return getMilitaryBaseColor(d.type, a);
},
sizeScale: 1,
sizeMinPixels: 6,
sizeMaxPixels: 16,
pickable: true,
});
}
private createBasesClusterLayer(): Layer[] {
if (this.serverBaseClusters.length === 0) return [];
const zoom = this.maplibreMap?.getZoom() || 3;
const alphaScale = Math.min(1, (zoom - 2.5) / 2.5);
const a = Math.round(180 * Math.max(0.3, alphaScale));
const scatterLayer = new ScatterplotLayer<ServerBaseCluster>({
id: 'bases-cluster-layer',
data: this.serverBaseClusters,
getPosition: (d) => [d.longitude, d.latitude],
getRadius: (d) => Math.max(8000, Math.log2(d.count) * 6000),
getFillColor: (d) => getMilitaryBaseColor(d.dominantType, a),
radiusMinPixels: 10,
radiusMaxPixels: 40,
pickable: true,
});
const textLayer = new TextLayer<ServerBaseCluster>({
id: 'bases-cluster-text',
data: this.serverBaseClusters,
getPosition: (d) => [d.longitude, d.latitude],
getText: (d) => String(d.count),
getSize: 12,
getColor: [255, 255, 255, 220],
fontWeight: 'bold',
getTextAnchor: 'middle',
getAlignmentBaseline: 'center',
});
return [scatterLayer, textLayer];
}
private createNuclearLayer(): IconLayer {
const highlightedNuclear = this.highlightedAssets.nuclear;
const data = NUCLEAR_FACILITIES.filter(f => f.status !== 'decommissioned');
// Nuclear: HEXAGON icons - yellow/orange color, semi-transparent
return new IconLayer({
id: 'nuclear-layer',
data,
getPosition: (d) => [d.lon, d.lat],
getIcon: () => 'hexagon',
iconAtlas: MARKER_ICONS.hexagon,
iconMapping: NUCLEAR_ICON_MAPPING,
getSize: (d) => highlightedNuclear.has(d.id) ? 15 : 11,
getColor: (d) => {
if (highlightedNuclear.has(d.id)) {
return [255, 100, 100, 220] as [number, number, number, number];
}
if (d.status === 'contested') {
return [255, 50, 50, 200] as [number, number, number, number];
}
return [255, 220, 0, 200] as [number, number, number, number]; // Semi-transparent yellow
},
sizeScale: 1,
sizeMinPixels: 6,
sizeMaxPixels: 15,
pickable: true,
});
}
private createIrradiatorsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'irradiators-layer',
data: GAMMA_IRRADIATORS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 6000,
getFillColor: [255, 100, 255, 180] as [number, number, number, number], // Magenta
radiusMinPixels: 4,
radiusMaxPixels: 10,
pickable: true,
});
}
private createSpaceportsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'spaceports-layer',
data: SPACEPORTS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 10000,
getFillColor: [200, 100, 255, 200] as [number, number, number, number], // Purple
radiusMinPixels: 5,
radiusMaxPixels: 12,
pickable: true,
});
}
private createPortsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'ports-layer',
data: PORTS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 6000,
getFillColor: (d) => {
// Color by port type (matching old Map.ts icons)
switch (d.type) {
case 'naval': return [100, 150, 255, 200] as [number, number, number, number]; // Blue - ⚓
case 'oil': return [255, 140, 0, 200] as [number, number, number, number]; // Orange - 🛢️
case 'lng': return [255, 200, 50, 200] as [number, number, number, number]; // Yellow - 🛢️
case 'container': return [0, 200, 255, 180] as [number, number, number, number]; // Cyan - 🏭
case 'mixed': return [150, 200, 150, 180] as [number, number, number, number]; // Green
case 'bulk': return [180, 150, 120, 180] as [number, number, number, number]; // Brown
default: return [0, 200, 255, 160] as [number, number, number, number];
}
},
radiusMinPixels: 4,
radiusMaxPixels: 10,
pickable: true,
});
}
private createFlightDelaysLayer(delays: AirportDelayAlert[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'flight-delays-layer',
data: delays,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => {
if (d.severity === 'severe') return 15000;
if (d.severity === 'major') return 12000;
if (d.severity === 'moderate') return 10000;
// 'unknown' = no telemetry (#3707). Keep the marker visible but
// small so it doesn't compete with real alerts.
if (d.severity === 'unknown') return 6000;
return 8000;
},
getFillColor: (d) => {
if (d.severity === 'severe') return [255, 50, 50, 200] as [number, number, number, number];
if (d.severity === 'major') return [255, 150, 0, 200] as [number, number, number, number];
if (d.severity === 'moderate') return [255, 200, 100, 180] as [number, number, number, number];
// 'unknown' renders desaturated grey — distinct from the lighter grey
// used for 'normal' so users can tell "no data" from "healthy".
if (d.severity === 'unknown') return [120, 120, 130, 120] as [number, number, number, number];
return [180, 180, 180, 150] as [number, number, number, number];
},
radiusMinPixels: 4,
radiusMaxPixels: 15,
pickable: true,
});
}
private createNotamOverlayLayer(closures: AirportDelayAlert[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'notam-overlay-layer',
data: closures,
getPosition: (d) => [d.lon, d.lat],
getRadius: 55000,
getFillColor: [255, 40, 40, 100] as [number, number, number, number],
getLineColor: [255, 40, 40, 200] as [number, number, number, number],
stroked: true,
lineWidthMinPixels: 2,
radiusMinPixels: 8,
radiusMaxPixels: 40,
pickable: true,
});
}
private createAircraftPositionsLayer(): IconLayer<PositionSample> {
return new IconLayer<PositionSample>({
id: 'aircraft-positions-layer',
data: this.aircraftPositions,
getPosition: (d) => [d.lon, d.lat],
getIcon: () => 'plane',
iconAtlas: MARKER_ICONS.plane,
iconMapping: AIRCRAFT_ICON_MAPPING,
getSize: (d) => d.onGround ? 14 : 18,
getColor: (d) => {
if (d.onGround) return [120, 120, 120, 160] as [number, number, number, number];
const [r, g, b] = altitudeToColor(d.altitudeFt);
return [r, g, b, 220] as [number, number, number, number];
},
getAngle: (d) => -d.trackDeg,
sizeMinPixels: 8,
sizeMaxPixels: 28,
sizeScale: 1,
pickable: true,
billboard: false,
});
}
private createGhostLayer<T>(id: string, data: T[], getPosition: (d: T) => [number, number], opts: { radiusMinPixels?: number } = {}): ScatterplotLayer<T> {
return new ScatterplotLayer<T>({
id: `${id}-ghost`,
data,
getPosition,
getRadius: 1,
radiusMinPixels: opts.radiusMinPixels ?? 12,
getFillColor: [0, 0, 0, 0],
pickable: true,
});
}
/** Empty sentinel layer — keeps a stable layer ID for deck.gl interleaved mode without rendering anything. */
private createEmptyGhost(id: string): ScatterplotLayer {
return new ScatterplotLayer({ id: `${id}-ghost`, data: [], getPosition: () => [0, 0], visible: false });
}
private createDatacentersLayer(): IconLayer {
const highlightedDC = this.highlightedAssets.datacenter;
const data = AI_DATA_CENTERS.filter(dc => dc.status !== 'decommissioned');
// Datacenters: SQUARE icons - purple color, semi-transparent for layering
return new IconLayer({
id: 'datacenters-layer',
data,
getPosition: (d) => [d.lon, d.lat],
getIcon: () => 'square',
iconAtlas: MARKER_ICONS.square,
iconMapping: DATACENTER_ICON_MAPPING,
getSize: (d) => highlightedDC.has(d.id) ? 14 : 10,
getColor: (d) => {
if (highlightedDC.has(d.id)) {
return [255, 100, 100, 200] as [number, number, number, number];
}
if (d.status === 'planned') {
return [136, 68, 255, 100] as [number, number, number, number]; // Transparent for planned
}
return [136, 68, 255, 140] as [number, number, number, number]; // ~55% opacity
},
sizeScale: 1,
sizeMinPixels: 6,
sizeMaxPixels: 14,
pickable: true,
});
}
private createEarthquakesLayer(earthquakes: Earthquake[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'earthquakes-layer',
data: earthquakes,
getPosition: (d) => [d.location?.longitude ?? 0, d.location?.latitude ?? 0],
getRadius: (d) => 2 ** d.magnitude * 1000,
getFillColor: (d) => {
const mag = d.magnitude;
if (mag >= 6) return [255, 0, 0, 200] as [number, number, number, number];
if (mag >= 5) return [255, 100, 0, 200] as [number, number, number, number];
return COLORS.earthquake;
},
radiusMinPixels: 4,
radiusMaxPixels: 30,
pickable: true,
});
}
private createNaturalEventsLayers(events: NaturalEvent[]): Layer[] {
const nonTC = events.filter(e => !e.stormName && !e.windKt);
const cyclones = events.filter(e => e.stormName || e.windKt);
const layers: Layer[] = [];
if (nonTC.length > 0) {
layers.push(new ScatterplotLayer({
id: 'natural-events-layer',
data: nonTC,
getPosition: (d: NaturalEvent) => [d.lon, d.lat],
getRadius: (d: NaturalEvent) => d.title.startsWith('🔴') ? 20000 : d.title.startsWith('🟠') ? 15000 : 8000,
getFillColor: (d: NaturalEvent) => {
if (d.title.startsWith('🔴')) return [255, 0, 0, 220] as [number, number, number, number];
if (d.title.startsWith('🟠')) return [255, 140, 0, 200] as [number, number, number, number];
return [255, 150, 50, 180] as [number, number, number, number];
},
radiusMinPixels: 5,
radiusMaxPixels: 18,
pickable: true,
}));
}
if (cyclones.length === 0) return layers;
// Cone polygons (render first, underneath tracks)
const coneData: { polygon: number[][]; stormName: string; _event: NaturalEvent }[] = [];
for (const e of cyclones) {
if (!e.conePolygon?.length) continue;
for (const ring of e.conePolygon) {
coneData.push({ polygon: ring, stormName: e.stormName || e.title, _event: e });
}
}
if (coneData.length > 0) {
layers.push(new PolygonLayer({
id: 'storm-cone-layer',
data: coneData,
getPolygon: (d: { polygon: number[][] }) => d.polygon,
getFillColor: [255, 255, 255, 30],
getLineColor: [255, 255, 255, 80],
lineWidthMinPixels: 1,
pickable: true,
}));
}
// Past track segments (per-segment wind coloring)
const pastSegments: { path: [number, number][]; windKt: number; stormName: string; _event: NaturalEvent }[] = [];
for (const e of cyclones) {
if (!e.pastTrack?.length) continue;
for (let i = 0; i < e.pastTrack.length - 1; i++) {
const a = e.pastTrack[i]!;
const b = e.pastTrack[i + 1]!;
pastSegments.push({
path: [[a.lon, a.lat] as [number, number], [b.lon, b.lat] as [number, number]],
windKt: b.windKt ?? a.windKt ?? 0,
stormName: e.stormName || e.title,
_event: e,
});
}
}
if (pastSegments.length > 0) {
layers.push(new PathLayer({
id: 'storm-past-track-layer',
data: pastSegments,
getPath: (d: { path: [number, number][] }) => d.path,
getColor: (d: { windKt: number }) => getWindColor(d.windKt),
getWidth: 3,
widthUnits: 'pixels' as const,
pickable: true,
}));
}
// Forecast track
const forecastPaths: { path: [number, number][]; stormName: string; _event: NaturalEvent }[] = [];
for (const e of cyclones) {
if (!e.forecastTrack?.length) continue;
forecastPaths.push({
path: [[e.lon, e.lat] as [number, number], ...e.forecastTrack.map(p => [p.lon, p.lat] as [number, number])],
stormName: e.stormName || e.title,
_event: e,
});
}
if (forecastPaths.length > 0) {
layers.push(new PathLayer({
id: 'storm-forecast-track-layer',
data: forecastPaths,
getPath: (d: { path: [number, number][] }) => d.path,
getColor: [255, 100, 100, 200],
getWidth: 2,
widthUnits: 'pixels' as const,
pickable: true,
}));
}
// Storm center markers (on top)
layers.push(new ScatterplotLayer({
id: 'storm-centers-layer',
data: cyclones,
getPosition: (d: NaturalEvent) => [d.lon, d.lat],
getRadius: 15000,
getFillColor: (d: NaturalEvent) => getWindColor(d.windKt ?? 0),
getLineColor: [255, 255, 255, 200],
lineWidthMinPixels: 2,
stroked: true,
radiusMinPixels: 6,
radiusMaxPixels: 20,
pickable: true,
}));
return layers;
}
private createFiresLayer(items: typeof this.firmsFireData): ScatterplotLayer {
return new ScatterplotLayer({
id: 'fires-layer',
data: items,
getPosition: (d: (typeof this.firmsFireData)[0]) => [d.lon, d.lat],
getRadius: (d: (typeof this.firmsFireData)[0]) => Math.min(d.frp * 200, 30000) || 5000,
getFillColor: (d: (typeof this.firmsFireData)[0]) => {
if (d.brightness > 400) return [255, 30, 0, 220] as [number, number, number, number];
if (d.brightness > 350) return [255, 140, 0, 200] as [number, number, number, number];
return [255, 220, 50, 180] as [number, number, number, number];
},
radiusMinPixels: 3,
radiusMaxPixels: 12,
pickable: true,
});
}
private createIranEventsLayer(items: IranEvent[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'iran-events-layer',
data: items,
getPosition: (d: IranEvent) => [d.longitude, d.latitude],
getRadius: (d: IranEvent) => getIranEventRadius(d.severity),
getFillColor: (d: IranEvent) => getIranEventColor(d),
radiusMinPixels: 4,
radiusMaxPixels: 16,
pickable: true,
});
}
private createWeatherLayer(alerts: WeatherAlert[]): ScatterplotLayer {
// Filter weather alerts that have centroid coordinates
const alertsWithCoords = alerts.filter(a => a.centroid && a.centroid.length === 2);
return new ScatterplotLayer({
id: 'weather-layer',
data: alertsWithCoords,
getPosition: (d) => d.centroid as [number, number], // centroid is [lon, lat]
getRadius: 25000,
getFillColor: (d) => {
if (d.severity === 'Extreme') return [255, 0, 0, 200] as [number, number, number, number];
if (d.severity === 'Severe') return [255, 100, 0, 180] as [number, number, number, number];
if (d.severity === 'Moderate') return [255, 170, 0, 160] as [number, number, number, number];
return COLORS.weather;
},
radiusMinPixels: 8,
radiusMaxPixels: 20,
pickable: true,
});
}
private createOutagesLayer(outages: InternetOutage[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'outages-layer',
data: outages,
getPosition: (d) => [d.lon, d.lat],
getRadius: 20000,
getFillColor: COLORS.outage,
radiusMinPixels: 6,
radiusMaxPixels: 18,
pickable: true,
});
}
private createTrafficAnomaliesLayer(anomalies: ProtoTrafficAnomaly[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'traffic-anomalies-layer',
data: anomalies.filter(a => a.latitude !== 0 || a.longitude !== 0),
getPosition: (d) => [d.longitude, d.latitude],
getRadius: 30000,
getFillColor: COLORS.trafficAnomaly,
radiusMinPixels: 5,
radiusMaxPixels: 14,
pickable: true,
});
}
private createDdosLocationsLayer(hits: DdosLocationHit[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'ddos-locations-layer',
data: hits.filter(h => h.latitude !== 0 || h.longitude !== 0),
getPosition: (d) => [d.longitude, d.latitude],
getRadius: (d) => 20000 + (d.percentage || 0) * 800,
getFillColor: COLORS.ddosHit,
radiusMinPixels: 5,
radiusMaxPixels: 16,
pickable: true,
});
}
private createCyberThreatsLayer(): ScatterplotLayer<CyberThreat> {
return new ScatterplotLayer<CyberThreat>({
id: 'cyber-threats-layer',
data: this.cyberThreats,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => {
switch (d.severity) {
case 'critical': return 22000;
case 'high': return 17000;
case 'medium': return 13000;
default: return 9000;
}
},
getFillColor: (d) => {
switch (d.severity) {
case 'critical': return [255, 61, 0, 225] as [number, number, number, number];
case 'high': return [255, 102, 0, 205] as [number, number, number, number];
case 'medium': return [255, 176, 0, 185] as [number, number, number, number];
default: return [255, 235, 59, 170] as [number, number, number, number];
}
},
radiusMinPixels: 6,
radiusMaxPixels: 18,
pickable: true,
stroked: true,
getLineColor: [255, 255, 255, 160] as [number, number, number, number],
lineWidthMinPixels: 1,
});
}
private createRadiationLayer(items: RadiationObservation[]): ScatterplotLayer<RadiationObservation> {
return new ScatterplotLayer<RadiationObservation>({
id: 'radiation-watch-layer',
data: items,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => {
const base = d.severity === 'spike' ? 26000 : 18000;
if (d.corroborated) return base * 1.15;
if (d.confidence === 'low') return base * 0.85;
return base;
},
getFillColor: (d) => (
d.severity === 'spike'
? [255, 48, 48, 220]
: d.confidence === 'low'
? [255, 174, 0, 150]
: [255, 174, 0, 200]
) as [number, number, number, number],
getLineColor: [255, 255, 255, 200],
stroked: true,
lineWidthMinPixels: 2,
radiusMinPixels: 6,
radiusMaxPixels: 20,
pickable: true,
});
}
private createDiseaseOutbreaksLayer(items: DiseaseOutbreakItem[]): ScatterplotLayer<{ lon: number; lat: number; item: DiseaseOutbreakItem }> {
type Point = { lon: number; lat: number; item: DiseaseOutbreakItem };
const points: Point[] = [];
for (const item of items) {
if (Number.isFinite(item.lat) && item.lat !== 0 && Number.isFinite(item.lng) && item.lng !== 0) {
points.push({ lon: item.lng, lat: item.lat, item });
} else {
const centroid = getCountryCentroid(item.countryCode ?? '');
if (centroid) points.push({ lon: centroid.lon, lat: centroid.lat, item });
}
}
return new ScatterplotLayer<Point>({
id: 'disease-outbreaks-layer',
data: points,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => d.item.alertLevel === 'alert' ? 180000 : d.item.alertLevel === 'warning' ? 130000 : 90000,
getFillColor: (d) => (
d.item.alertLevel === 'alert'
? [231, 76, 60, 200]
: d.item.alertLevel === 'warning'
? [230, 126, 34, 190]
: [241, 196, 15, 170]
) as [number, number, number, number],
getLineColor: [255, 255, 255, 120],
stroked: true,
lineWidthMinPixels: 1,
radiusMinPixels: 5,
radiusMaxPixels: 22,
pickable: true,
});
}
private createAisDensityLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'ais-density-layer',
data: this.aisDensity,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => 4000 + d.intensity * 8000,
getFillColor: (d) => {
const intensity = Math.min(Math.max(d.intensity, 0.15), 1);
const isCongested = (d.deltaPct || 0) >= 15;
const alpha = Math.round(40 + intensity * 160);
// Orange for congested areas, cyan for normal traffic
if (isCongested) {
return [255, 183, 3, alpha] as [number, number, number, number]; // #ffb703
}
return [0, 209, 255, alpha] as [number, number, number, number]; // #00d1ff
},
radiusMinPixels: 4,
radiusMaxPixels: 12,
pickable: true,
});
}
private createLiveTankersLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'live-tankers-layer',
data: this.liveTankers,
getPosition: (d) => [d.lon, d.lat],
// Radius scales loosely with deadweight class: VLCC > Aframax > Handysize.
// AIS ship type 80-89 covers all tanker subtypes; we have no DWT field
// in the AIS message itself, so this is a constant fallback. Future
// enhancement: enrich via a vessel-registry lookup.
getRadius: 2500,
getFillColor: (d) => {
// Anchored (speed < 0.5 kn) — orange, signals waiting / loading /
// potential congestion. Underway (speed >= 0.5 kn) — cyan, normal
// transit. Unknown / missing speed — gray.
if (!Number.isFinite(d.speed)) return [127, 140, 141, 200] as [number, number, number, number];
if (d.speed < 0.5) return [255, 183, 3, 220] as [number, number, number, number]; // amber
return [0, 209, 255, 220] as [number, number, number, number]; // cyan
},
radiusMinPixels: 3,
radiusMaxPixels: 8,
pickable: true,
});
}
/**
* Idempotent: ensures the 60s tanker-refresh loop is running. Called
* each time the layer is observed enabled in the layers update. First
* call kicks an immediate load; subsequent calls no-op. Pairs with
* stopLiveTankersLoop() in destroy() and on layer-disable.
*/
private ensureLiveTankersLoop(): void {
if (this.liveTankersTimer !== null) return; // already running
void this.loadLiveTankers();
this.liveTankersTimer = setInterval(() => {
void this.loadLiveTankers();
}, 60_000);
}
/**
* Stop the refresh loop and abort any in-flight fetch. Called when the
* layer is toggled off (and from destroy()) to keep the relay traffic
* scoped to active viewers.
*/
private stopLiveTankersLoop(): void {
if (this.liveTankersTimer !== null) {
clearInterval(this.liveTankersTimer);
this.liveTankersTimer = null;
}
if (this.liveTankersAbort) {
this.liveTankersAbort.abort();
this.liveTankersAbort = null;
}
}
/**
* Tanker loader — called externally (or on a 60s tick) to refresh
* `this.liveTankers`. Imports lazily so the service module isn't pulled
* into the bundle for variants where the layer is disabled.
*/
public async loadLiveTankers(): Promise<void> {
// Cancel any in-flight tick before starting another. Per skill
// closure-scoped-state-teardown-order: don't null out the abort
// controller before calling abort.
if (this.liveTankersAbort) {
this.liveTankersAbort.abort();
}
const controller = new AbortController();
this.liveTankersAbort = controller;
try {
const { fetchLiveTankers } = await import('@/services/live-tankers');
// Thread the signal so the in-flight RPC actually cancels when a
// newer tick starts (or the layer toggles off). Without this, a
// slow older refresh can race-write stale data after a newer one
// already populated this.liveTankers.
const zones = await fetchLiveTankers(undefined, { signal: controller.signal });
// Drop the result if this controller was aborted mid-flight or if
// a newer load has already replaced us. Without this guard, an
// older fetch that completed despite signal.aborted (e.g. the
// service returned cached data without checking the signal) would
// overwrite the newer one's data.
if (controller.signal.aborted || this.liveTankersAbort !== controller) {
return;
}
const flat = zones.flatMap((z) => z.tankers).map((t) => ({
mmsi: t.mmsi,
lat: t.lat,
lon: t.lon,
speed: t.speed,
shipType: t.shipType,
name: t.name,
}));
this.liveTankers = flat;
this.updateLayers();
} catch {
// Graceful: leave existing tankers in place; layer will continue
// rendering last-known data until the next successful tick.
}
}
private createGpsJammingLayer(): PolygonLayer<GpsJamHexWithPolygon> {
return new PolygonLayer<GpsJamHexWithPolygon>({
id: 'gps-jamming-layer',
data: this.gpsJammingHexes,
getPolygon: (d: GpsJamHexWithPolygon) => d.polygon,
getFillColor: (d: GpsJamHexWithPolygon) => {
if (d.level === 'high') return [255, 80, 80, 180] as [number, number, number, number];
return [255, 180, 50, 140] as [number, number, number, number];
},
extruded: false,
filled: true,
stroked: true,
getLineColor: [255, 255, 255, 80] as [number, number, number, number],
getLineWidth: 1,
lineWidthMinPixels: 1,
pickable: true,
});
}
private createAisDisruptionsLayer(): ScatterplotLayer {
// AIS spoofing/jamming events
return new ScatterplotLayer({
id: 'ais-disruptions-layer',
data: this.aisDisruptions,
getPosition: (d) => [d.lon, d.lat],
getRadius: 12000,
getFillColor: (d) => {
// Color by severity/type
if (d.severity === 'high' || d.type === 'spoofing') {
return [255, 50, 50, 220] as [number, number, number, number]; // Red
}
if (d.severity === 'medium') {
return [255, 150, 0, 200] as [number, number, number, number]; // Orange
}
return [255, 200, 100, 180] as [number, number, number, number]; // Yellow
},
radiusMinPixels: 6,
radiusMaxPixels: 14,
pickable: true,
stroked: true,
getLineColor: [255, 255, 255, 150] as [number, number, number, number],
lineWidthMinPixels: 1,
});
}
private createCableAdvisoriesLayer(advisories: CableAdvisory[]): ScatterplotLayer {
// Cable fault/maintenance advisories
return new ScatterplotLayer({
id: 'cable-advisories-layer',
data: advisories,
getPosition: (d) => [d.lon, d.lat],
getRadius: 10000,
getFillColor: (d) => {
if (d.severity === 'fault') {
return [255, 50, 50, 220] as [number, number, number, number]; // Red for faults
}
return [255, 200, 0, 200] as [number, number, number, number]; // Yellow for maintenance
},
radiusMinPixels: 5,
radiusMaxPixels: 12,
pickable: true,
stroked: true,
getLineColor: [0, 200, 255, 200] as [number, number, number, number], // Cyan outline (cable color)
lineWidthMinPixels: 2,
});
}
private createRepairShipsLayer(): ScatterplotLayer {
// Cable repair ships
return new ScatterplotLayer({
id: 'repair-ships-layer',
data: this.repairShips,
getPosition: (d) => [d.lon, d.lat],
getRadius: 8000,
getFillColor: [0, 255, 200, 200] as [number, number, number, number], // Teal
radiusMinPixels: 4,
radiusMaxPixels: 10,
pickable: true,
});
}
private createMilitaryVesselsLayer(vessels: MilitaryVessel[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'military-vessels-layer',
data: vessels,
getPosition: (d) => [d.lon, d.lat],
getRadius: 6000,
getFillColor: (d) => {
if (d.usniSource) return [255, 160, 60, 160] as [number, number, number, number]; // Orange, lower alpha for USNI-only
return COLORS.vesselMilitary;
},
radiusMinPixels: 4,
radiusMaxPixels: 10,
pickable: true,
stroked: true,
getLineColor: (d) => {
if (d.usniSource) return [255, 180, 80, 200] as [number, number, number, number]; // Orange outline
return [0, 0, 0, 0] as [number, number, number, number]; // No outline for AIS
},
lineWidthMinPixels: 2,
});
}
private createMilitaryVesselClustersLayer(clusters: MilitaryVesselCluster[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'military-vessel-clusters-layer',
data: clusters,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => 15000 + (d.vesselCount || 1) * 3000,
getFillColor: (d) => {
// Vessel types: 'exercise' | 'deployment' | 'transit' | 'unknown'
const activity = d.activityType || 'unknown';
if (activity === 'exercise' || activity === 'deployment') return [255, 100, 100, 200] as [number, number, number, number];
if (activity === 'transit') return [255, 180, 100, 180] as [number, number, number, number];
return [200, 150, 150, 160] as [number, number, number, number];
},
radiusMinPixels: 8,
radiusMaxPixels: 25,
pickable: true,
});
}
private createMilitaryFlightsLayer(flights: MilitaryFlight[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'military-flights-layer',
data: flights,
getPosition: (d) => [d.lon, d.lat],
getRadius: 8000,
getFillColor: (d) => {
if (d.onGround) return [120, 120, 120, 160] as [number, number, number, number];
const [r, g, b] = altitudeToColor(d.altitude);
return [r, g, b, 220] as [number, number, number, number];
},
radiusMinPixels: 4,
radiusMaxPixels: 12,
pickable: true,
});
}
private createMilitaryFlightTrailsLayer(flights: MilitaryFlight[]): PathLayer {
const trailed = flights.filter(f => this.activeFlightTrails.has(f.hexCode.toLowerCase()) && f.track && f.track.length > 1);
return new PathLayer({
id: 'military-flight-trails-layer',
data: trailed,
getPath: (d) => d.track!.map(([lat, lon]: [number, number]) => [lon, lat]),
getColor: (d) => { const [r, g, b] = altitudeToColor(d.altitude); return [r, g, b, 140] as [number, number, number, number]; },
getWidth: 2,
widthUnits: 'pixels' as const,
pickable: false,
});
}
private createMilitaryFlightClustersLayer(clusters: MilitaryFlightCluster[]): ScatterplotLayer {
return new ScatterplotLayer({
id: 'military-flight-clusters-layer',
data: clusters,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => 15000 + (d.flightCount || 1) * 3000,
getFillColor: (d) => {
const activity = d.activityType || 'unknown';
if (activity === 'exercise' || activity === 'patrol') return [100, 150, 255, 200] as [number, number, number, number];
if (activity === 'transport') return [255, 200, 100, 180] as [number, number, number, number];
return [150, 150, 200, 160] as [number, number, number, number];
},
radiusMinPixels: 8,
radiusMaxPixels: 25,
pickable: true,
});
}
private createWaterwaysLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'waterways-layer',
data: STRATEGIC_WATERWAYS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 10000,
getFillColor: [100, 150, 255, 180] as [number, number, number, number],
radiusMinPixels: 5,
radiusMaxPixels: 12,
pickable: true,
});
}
private createEconomicCentersLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'economic-centers-layer',
data: ECONOMIC_CENTERS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 8000,
getFillColor: [255, 215, 0, 180] as [number, number, number, number],
radiusMinPixels: 4,
radiusMaxPixels: 10,
pickable: true,
});
}
private createStockExchangesLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'stock-exchanges-layer',
data: STOCK_EXCHANGES,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => d.tier === 'mega' ? 18000 : d.tier === 'major' ? 14000 : 11000,
getFillColor: (d) => {
if (d.tier === 'mega') return [255, 215, 80, 220] as [number, number, number, number];
if (d.tier === 'major') return COLORS.stockExchange;
return [140, 210, 255, 190] as [number, number, number, number];
},
radiusMinPixels: 5,
radiusMaxPixels: 14,
pickable: true,
});
}
private createFinancialCentersLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'financial-centers-layer',
data: FINANCIAL_CENTERS,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => d.type === 'global' ? 17000 : d.type === 'regional' ? 13000 : 10000,
getFillColor: (d) => {
if (d.type === 'global') return COLORS.financialCenter;
if (d.type === 'regional') return [0, 190, 130, 185] as [number, number, number, number];
return [0, 150, 110, 165] as [number, number, number, number];
},
radiusMinPixels: 4,
radiusMaxPixels: 12,
pickable: true,
});
}
private createCentralBanksLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'central-banks-layer',
data: CENTRAL_BANKS,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => d.type === 'major' ? 15000 : d.type === 'supranational' ? 17000 : 12000,
getFillColor: (d) => {
if (d.type === 'major') return COLORS.centralBank;
if (d.type === 'supranational') return [255, 235, 140, 220] as [number, number, number, number];
return [235, 180, 80, 185] as [number, number, number, number];
},
radiusMinPixels: 4,
radiusMaxPixels: 12,
pickable: true,
});
}
private createCommodityHubsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'commodity-hubs-layer',
data: COMMODITY_HUBS,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => d.type === 'exchange' ? 14000 : d.type === 'port' ? 12000 : 10000,
getFillColor: (d) => {
if (d.type === 'exchange') return COLORS.commodityHub;
if (d.type === 'port') return [80, 170, 255, 190] as [number, number, number, number];
return [255, 110, 80, 185] as [number, number, number, number];
},
radiusMinPixels: 4,
radiusMaxPixels: 11,
pickable: true,
});
}
private async loadAptGroups(): Promise<void> {
const { APT_GROUPS } = await import('@/config/apt-groups');
this.aptGroups = APT_GROUPS;
this.aptGroupsLoaded = true;
this.render();
}
private createAPTGroupsLayer(): ScatterplotLayer {
// APT Groups - cyber threat actor markers (geopolitical variant only)
// Made subtle to avoid visual clutter - small orange dots
return new ScatterplotLayer({
id: 'apt-groups-layer',
data: this.aptGroups,
getPosition: (d) => [d.lon, d.lat],
getRadius: 6000,
getFillColor: [255, 140, 0, 140] as [number, number, number, number],
radiusMinPixels: 4,
radiusMaxPixels: 8,
pickable: true,
stroked: false,
});
}
private createMineralsLayer(): ScatterplotLayer {
// Critical minerals projects
return new ScatterplotLayer({
id: 'minerals-layer',
data: CRITICAL_MINERALS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 8000,
getFillColor: (d) => {
// Color by mineral type
switch (d.mineral) {
case 'Lithium': return [0, 200, 255, 200] as [number, number, number, number]; // Cyan
case 'Cobalt': return [100, 100, 255, 200] as [number, number, number, number]; // Blue
case 'Rare Earths': return [255, 100, 200, 200] as [number, number, number, number]; // Pink
case 'Nickel': return [100, 255, 100, 200] as [number, number, number, number]; // Green
default: return [200, 200, 200, 200] as [number, number, number, number]; // Gray
}
},
radiusMinPixels: 5,
radiusMaxPixels: 12,
pickable: true,
});
}
// Commodity variant layers
private createMiningSitesLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'mining-sites-layer',
data: MINING_SITES,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => d.status === 'producing' ? 10000 : d.status === 'development' ? 8000 : 6000,
getFillColor: (d) => getMineralColor(d.mineral),
radiusMinPixels: 5,
radiusMaxPixels: 14,
pickable: true,
stroked: true,
getLineColor: [255, 255, 255, 60] as [number, number, number, number],
lineWidthMinPixels: 1,
});
}
private createProcessingPlantsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'processing-plants-layer',
data: PROCESSING_PLANTS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 8000,
getFillColor: (d) => {
switch (d.type) {
case 'smelter': return [255, 80, 30, 210] as [number, number, number, number];
case 'refinery': return [255, 160, 50, 200] as [number, number, number, number];
case 'separation': return [160, 100, 255, 200] as [number, number, number, number];
case 'processing': return [100, 200, 150, 200] as [number, number, number, number];
default: return [200, 150, 100, 200] as [number, number, number, number];
}
},
radiusMinPixels: 5,
radiusMaxPixels: 12,
pickable: true,
stroked: true,
getLineColor: [255, 255, 255, 80] as [number, number, number, number],
lineWidthMinPixels: 1,
});
}
private createCommodityPortsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'commodity-ports-layer',
data: COMMODITY_GEO_PORTS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 12000,
getFillColor: (d) => getMineralColor(d.commodities[0]),
radiusMinPixels: 6,
radiusMaxPixels: 14,
pickable: true,
stroked: true,
getLineColor: [255, 255, 255, 100] as [number, number, number, number],
lineWidthMinPixels: 1.5,
});
}
// Tech variant layers
private createStartupHubsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'startup-hubs-layer',
data: STARTUP_HUBS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 10000,
getFillColor: COLORS.startupHub,
radiusMinPixels: 5,
radiusMaxPixels: 12,
pickable: true,
});
}
private createAcceleratorsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'accelerators-layer',
data: ACCELERATORS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 6000,
getFillColor: COLORS.accelerator,
radiusMinPixels: 3,
radiusMaxPixels: 8,
pickable: true,
});
}
private createCloudRegionsLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'cloud-regions-layer',
data: CLOUD_REGIONS,
getPosition: (d) => [d.lon, d.lat],
getRadius: 12000,
getFillColor: COLORS.cloudRegion,
radiusMinPixels: 4,
radiusMaxPixels: 12,
pickable: true,
});
}
private createProtestClusterLayers(): Layer[] {
this.updateClusterData();
const layers: Layer[] = [];
layers.push(new ScatterplotLayer<MapProtestCluster>({
id: 'protest-clusters-layer',
data: this.protestClusters,
getPosition: d => [d.lon, d.lat],
getRadius: d => 15000 + d.count * 2000,
radiusMinPixels: 6,
radiusMaxPixels: 22,
getFillColor: d => {
if (d.hasRiot) return [220, 40, 40, 200] as [number, number, number, number];
if (d.maxSeverity === 'high') return [255, 80, 60, 180] as [number, number, number, number];
if (d.maxSeverity === 'medium') return [255, 160, 40, 160] as [number, number, number, number];
return [255, 220, 80, 140] as [number, number, number, number];
},
pickable: true,
updateTriggers: { getRadius: this.lastSCZoom, getFillColor: this.lastSCZoom },
}));
const multiClusters = this.protestClusters.filter(c => c.count > 1);
if (multiClusters.length > 0) {
layers.push(new TextLayer<MapProtestCluster>({
id: 'protest-clusters-badge',
data: multiClusters,
getText: d => String(d.count),
getPosition: d => [d.lon, d.lat],
background: true,
getBackgroundColor: [0, 0, 0, 180],
backgroundPadding: [4, 2, 4, 2],
getColor: [255, 255, 255, 255],
getSize: 12,
getPixelOffset: [0, -14],
pickable: false,
fontFamily: 'system-ui, sans-serif',
fontWeight: 700,
}));
}
const pulseClusters = this.protestClusters.filter(c => c.maxSeverity === 'high' || c.hasRiot);
if (pulseClusters.length > 0) {
const pulse = 1.0 + 0.8 * (0.5 + 0.5 * Math.sin((this.pulseTime || Date.now()) / 400));
layers.push(new ScatterplotLayer<MapProtestCluster>({
id: 'protest-clusters-pulse',
data: pulseClusters,
getPosition: d => [d.lon, d.lat],
getRadius: d => 15000 + d.count * 2000,
radiusScale: pulse,
radiusMinPixels: 8,
radiusMaxPixels: 30,
stroked: true,
filled: false,
getLineColor: d => d.hasRiot ? [220, 40, 40, 120] as [number, number, number, number] : [255, 80, 60, 100] as [number, number, number, number],
lineWidthMinPixels: 1.5,
pickable: false,
updateTriggers: { radiusScale: this.pulseTime },
}));
}
layers.push(this.createEmptyGhost('protest-clusters-layer'));
return layers;
}
private createTechHQClusterLayers(): Layer[] {
this.updateClusterData();
const layers: Layer[] = [];
const zoom = this.maplibreMap?.getZoom() || 2;
layers.push(new ScatterplotLayer<MapTechHQCluster>({
id: 'tech-hq-clusters-layer',
data: this.techHQClusters,
getPosition: d => [d.lon, d.lat],
getRadius: d => 10000 + d.count * 1500,
radiusMinPixels: 5,
radiusMaxPixels: 18,
getFillColor: d => {
if (d.primaryType === 'faang') return [0, 220, 120, 200] as [number, number, number, number];
if (d.primaryType === 'unicorn') return [255, 100, 200, 180] as [number, number, number, number];
return [80, 160, 255, 180] as [number, number, number, number];
},
pickable: true,
updateTriggers: { getRadius: this.lastSCZoom },
}));
const multiClusters = this.techHQClusters.filter(c => c.count > 1);
if (multiClusters.length > 0) {
layers.push(new TextLayer<MapTechHQCluster>({
id: 'tech-hq-clusters-badge',
data: multiClusters,
getText: d => String(d.count),
getPosition: d => [d.lon, d.lat],
background: true,
getBackgroundColor: [0, 0, 0, 180],
backgroundPadding: [4, 2, 4, 2],
getColor: [255, 255, 255, 255],
getSize: 12,
getPixelOffset: [0, -14],
pickable: false,
fontFamily: 'system-ui, sans-serif',
fontWeight: 700,
}));
}
if (zoom >= 3) {
const singles = this.techHQClusters.filter(c => c.count === 1);
if (singles.length > 0) {
layers.push(new TextLayer<MapTechHQCluster>({
id: 'tech-hq-clusters-label',
data: singles,
getText: d => d.items[0]?.company ?? '',
getPosition: d => [d.lon, d.lat],
getSize: 11,
getColor: [220, 220, 220, 200],
getPixelOffset: [0, 12],
pickable: false,
fontFamily: 'system-ui, sans-serif',
}));
}
}
layers.push(this.createEmptyGhost('tech-hq-clusters-layer'));
return layers;
}
private createTechEventClusterLayers(): Layer[] {
this.updateClusterData();
const layers: Layer[] = [];
layers.push(new ScatterplotLayer<MapTechEventCluster>({
id: 'tech-event-clusters-layer',
data: this.techEventClusters,
getPosition: d => [d.lon, d.lat],
getRadius: d => 10000 + d.count * 1500,
radiusMinPixels: 5,
radiusMaxPixels: 18,
getFillColor: d => {
if (d.soonestDaysUntil <= 14) return [255, 220, 50, 200] as [number, number, number, number];
return [80, 140, 255, 180] as [number, number, number, number];
},
pickable: true,
updateTriggers: { getRadius: this.lastSCZoom },
}));
const multiClusters = this.techEventClusters.filter(c => c.count > 1);
if (multiClusters.length > 0) {
layers.push(new TextLayer<MapTechEventCluster>({
id: 'tech-event-clusters-badge',
data: multiClusters,
getText: d => String(d.count),
getPosition: d => [d.lon, d.lat],
background: true,
getBackgroundColor: [0, 0, 0, 180],
backgroundPadding: [4, 2, 4, 2],
getColor: [255, 255, 255, 255],
getSize: 12,
getPixelOffset: [0, -14],
pickable: false,
fontFamily: 'system-ui, sans-serif',
fontWeight: 700,
}));
}
layers.push(this.createEmptyGhost('tech-event-clusters-layer'));
return layers;
}
private createDatacenterClusterLayers(): Layer[] {
this.updateClusterData();
const layers: Layer[] = [];
layers.push(new ScatterplotLayer<MapDatacenterCluster>({
id: 'datacenter-clusters-layer',
data: this.datacenterClusters,
getPosition: d => [d.lon, d.lat],
getRadius: d => 15000 + d.count * 2000,
radiusMinPixels: 6,
radiusMaxPixels: 20,
getFillColor: d => {
if (d.majorityExisting) return [160, 80, 255, 180] as [number, number, number, number];
return [80, 160, 255, 180] as [number, number, number, number];
},
pickable: true,
updateTriggers: { getRadius: this.lastSCZoom },
}));
const multiClusters = this.datacenterClusters.filter(c => c.count > 1);
if (multiClusters.length > 0) {
layers.push(new TextLayer<MapDatacenterCluster>({
id: 'datacenter-clusters-badge',
data: multiClusters,
getText: d => String(d.count),
getPosition: d => [d.lon, d.lat],
background: true,
getBackgroundColor: [0, 0, 0, 180],
backgroundPadding: [4, 2, 4, 2],
getColor: [255, 255, 255, 255],
getSize: 12,
getPixelOffset: [0, -14],
pickable: false,
fontFamily: 'system-ui, sans-serif',
fontWeight: 700,
}));
}
layers.push(this.createEmptyGhost('datacenter-clusters-layer'));
return layers;
}
private createHotspotsLayers(): Layer[] {
const zoom = this.maplibreMap?.getZoom() || 2;
const zoomScale = Math.min(1, (zoom - 1) / 3);
const maxPx = 6 + Math.round(14 * zoomScale);
const baseOpacity = zoom < 2.5 ? 0.5 : zoom < 4 ? 0.7 : 1.0;
const layers: Layer[] = [];
layers.push(new ScatterplotLayer({
id: 'hotspots-layer',
data: this.hotspots,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => {
const score = d.escalationScore || 1;
return 10000 + score * 5000;
},
getFillColor: (d) => {
const score = d.escalationScore || 1;
const a = Math.round((score >= 4 ? 200 : score >= 2 ? 200 : 180) * baseOpacity);
if (score >= 4) return [255, 68, 68, a] as [number, number, number, number];
if (score >= 2) return [255, 165, 0, a] as [number, number, number, number];
return [255, 255, 0, a] as [number, number, number, number];
},
radiusMinPixels: 4,
radiusMaxPixels: maxPx,
pickable: true,
stroked: true,
getLineColor: (d) =>
d.hasBreaking ? [255, 255, 255, 255] as [number, number, number, number] : [0, 0, 0, 0] as [number, number, number, number],
lineWidthMinPixels: 2,
}));
const highHotspots = this.hotspots.filter(h => h.level === 'high' || h.hasBreaking);
if (highHotspots.length > 0) {
const pulse = 1.0 + 0.8 * (0.5 + 0.5 * Math.sin((this.pulseTime || Date.now()) / 400));
layers.push(new ScatterplotLayer({
id: 'hotspots-pulse',
data: highHotspots,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => {
const score = d.escalationScore || 1;
return 10000 + score * 5000;
},
radiusScale: pulse,
radiusMinPixels: 6,
radiusMaxPixels: 30,
stroked: true,
filled: false,
getLineColor: (d) => {
const a = Math.round(120 * baseOpacity);
return d.hasBreaking ? [255, 50, 50, a] as [number, number, number, number] : [255, 165, 0, a] as [number, number, number, number];
},
lineWidthMinPixels: 1.5,
pickable: false,
updateTriggers: { radiusScale: this.pulseTime },
}));
}
layers.push(this.createEmptyGhost('hotspots-layer'));
return layers;
}
private createGulfInvestmentsLayer(): ScatterplotLayer {
return new ScatterplotLayer<GulfInvestment>({
id: 'gulf-investments-layer',
data: GULF_INVESTMENTS,
getPosition: (d: GulfInvestment) => [d.lon, d.lat],
getRadius: (d: GulfInvestment) => {
if (!d.investmentUSD) return 20000;
if (d.investmentUSD >= 50000) return 70000;
if (d.investmentUSD >= 10000) return 55000;
if (d.investmentUSD >= 1000) return 40000;
return 25000;
},
getFillColor: (d: GulfInvestment) =>
d.investingCountry === 'SA' ? COLORS.gulfInvestmentSA : COLORS.gulfInvestmentUAE,
getLineColor: [255, 255, 255, 80] as [number, number, number, number],
lineWidthMinPixels: 1,
radiusMinPixels: 5,
radiusMaxPixels: 28,
pickable: true,
});
}
private pulseTime = 0;
private canPulse(now = Date.now()): boolean {
return now - this.startupTime > 60_000;
}
private hasRecentRiot(now = Date.now(), windowMs = 2 * 60 * 60 * 1000): boolean {
const hasRecentClusterRiot = this.protestClusters.some(c =>
c.hasRiot && c.latestRiotEventTimeMs != null && (now - c.latestRiotEventTimeMs) < windowMs
);
if (hasRecentClusterRiot) return true;
// Fallback to raw protests because syncPulseAnimation can run before cluster data refreshes.
return this.protests.some((p) => {
if (p.eventType !== 'riot' || p.sourceType === 'gdelt') return false;
const ts = p.time.getTime();
return Number.isFinite(ts) && (now - ts) < windowMs;
});
}
private needsPulseAnimation(now = Date.now()): boolean {
return this.hasRecentNews(now)
|| this.hasRecentRiot(now)
|| this.hotspots.some(h => h.hasBreaking)
|| this.positiveEvents.some(e => e.count > 10)
|| this.kindnessPoints.some(p => p.type === 'real');
}
private syncPulseAnimation(now = Date.now()): void {
if (this.renderPaused) {
if (this.newsPulseIntervalId !== null) this.stopPulseAnimation();
return;
}
const shouldPulse = this.canPulse(now) && this.needsPulseAnimation(now);
if (shouldPulse && this.newsPulseIntervalId === null) {
this.startPulseAnimation();
} else if (!shouldPulse && this.newsPulseIntervalId !== null) {
this.stopPulseAnimation();
}
}
private startPulseAnimation(): void {
if (this.newsPulseIntervalId !== null) return;
const PULSE_UPDATE_INTERVAL_MS = 500;
this.newsPulseIntervalId = setInterval(() => {
const now = Date.now();
if (!this.needsPulseAnimation(now)) {
this.pulseTime = now;
this.stopPulseAnimation();
this.rafUpdateLayers();
return;
}
this.pulseTime = now;
// Steady-state pulse rebuild: skip when input is queued (#5042 U2). The
// terminal settle branch above is never guarded — it must commit the
// static end state. pulseTime still advances so no visual state is lost.
if (shouldRunInputSensitiveMapWork(isInputPending)) this.rafUpdateLayers();
}, PULSE_UPDATE_INTERVAL_MS);
}
private stopPulseAnimation(): void {
if (this.newsPulseIntervalId !== null) {
clearInterval(this.newsPulseIntervalId);
this.newsPulseIntervalId = null;
}
}
private createNewsLocationsLayer(): ScatterplotLayer[] {
const zoom = this.maplibreMap?.getZoom() || 2;
const alphaScale = zoom < 2.5 ? 0.4 : zoom < 4 ? 0.7 : 1.0;
const filteredNewsLocations = this.filterByTime(this.newsLocations, (location) => location.timestamp);
const THREAT_RGB: Record<string, [number, number, number]> = {
critical: [239, 68, 68],
high: [249, 115, 22],
medium: [234, 179, 8],
low: [34, 197, 94],
info: [59, 130, 246],
};
const THREAT_ALPHA: Record<string, number> = {
critical: 220,
high: 190,
medium: 160,
low: 120,
info: 80,
};
const now = this.pulseTime || Date.now();
const PULSE_DURATION = 30_000;
const layers: ScatterplotLayer[] = [
new ScatterplotLayer({
id: 'news-locations-layer',
data: filteredNewsLocations,
getPosition: (d) => [d.lon, d.lat],
getRadius: 18000,
getFillColor: (d) => {
const rgb = THREAT_RGB[d.threatLevel] || [59, 130, 246];
const a = Math.round((THREAT_ALPHA[d.threatLevel] || 120) * alphaScale);
return [...rgb, a] as [number, number, number, number];
},
radiusMinPixels: 3,
radiusMaxPixels: 12,
pickable: true,
}),
];
const recentNews = filteredNewsLocations.filter(d => {
const firstSeen = this.newsLocationFirstSeen.get(d.title);
return firstSeen && (now - firstSeen) < PULSE_DURATION;
});
if (recentNews.length > 0) {
const pulse = 1.0 + 1.5 * (0.5 + 0.5 * Math.sin(now / 318));
layers.push(new ScatterplotLayer({
id: 'news-pulse-layer',
data: recentNews,
getPosition: (d) => [d.lon, d.lat],
getRadius: 18000,
radiusScale: pulse,
radiusMinPixels: 6,
radiusMaxPixels: 30,
pickable: false,
stroked: true,
filled: false,
getLineColor: (d) => {
const rgb = THREAT_RGB[d.threatLevel] || [59, 130, 246];
const firstSeen = this.newsLocationFirstSeen.get(d.title) || now;
const age = now - firstSeen;
const fadeOut = Math.max(0, 1 - age / PULSE_DURATION);
const a = Math.round(150 * fadeOut * alphaScale);
return [...rgb, a] as [number, number, number, number];
},
lineWidthMinPixels: 1.5,
updateTriggers: { pulseTime: now },
}));
}
return layers;
}
private createPositiveEventsLayers(items: PositiveGeoEvent[]): Layer[] {
const layers: Layer[] = [];
const getCategoryColor = (category: string): [number, number, number, number] => {
switch (category) {
case 'nature-wildlife':
case 'humanity-kindness':
return [34, 197, 94, 200]; // green
case 'science-health':
case 'innovation-tech':
case 'climate-wins':
return [234, 179, 8, 200]; // gold
case 'culture-community':
return [139, 92, 246, 200]; // purple
default:
return [34, 197, 94, 200]; // green default
}
};
// Dot layer (tooltip on hover via getTooltip)
layers.push(new ScatterplotLayer({
id: 'positive-events-layer',
data: items,
getPosition: (d: PositiveGeoEvent) => [d.lon, d.lat],
getRadius: 12000,
getFillColor: (d: PositiveGeoEvent) => getCategoryColor(d.category),
radiusMinPixels: 5,
radiusMaxPixels: 10,
pickable: true,
}));
// Gentle pulse ring for significant events (count > 8)
const significantEvents = items.filter(e => e.count > 8);
if (significantEvents.length > 0) {
const pulse = 1.0 + 0.4 * (0.5 + 0.5 * Math.sin((this.pulseTime || Date.now()) / 800));
layers.push(new ScatterplotLayer({
id: 'positive-events-pulse',
data: significantEvents,
getPosition: (d: PositiveGeoEvent) => [d.lon, d.lat],
getRadius: 15000,
radiusScale: pulse,
radiusMinPixels: 8,
radiusMaxPixels: 24,
stroked: true,
filled: false,
getLineColor: (d: PositiveGeoEvent) => getCategoryColor(d.category),
lineWidthMinPixels: 1.5,
pickable: false,
updateTriggers: { radiusScale: this.pulseTime },
}));
}
return layers;
}
private createKindnessLayers(items: KindnessPoint[]): Layer[] {
const layers: Layer[] = [];
if (items.length === 0) return layers;
// Dot layer (tooltip on hover via getTooltip)
layers.push(new ScatterplotLayer<KindnessPoint>({
id: 'kindness-layer',
data: items,
getPosition: (d: KindnessPoint) => [d.lon, d.lat],
getRadius: 12000,
getFillColor: [74, 222, 128, 200] as [number, number, number, number],
radiusMinPixels: 5,
radiusMaxPixels: 10,
pickable: true,
}));
// Pulse for real events
const pulse = 1.0 + 0.4 * (0.5 + 0.5 * Math.sin((this.pulseTime || Date.now()) / 800));
layers.push(new ScatterplotLayer<KindnessPoint>({
id: 'kindness-pulse',
data: items,
getPosition: (d: KindnessPoint) => [d.lon, d.lat],
getRadius: 14000,
radiusScale: pulse,
radiusMinPixels: 6,
radiusMaxPixels: 18,
stroked: true,
filled: false,
getLineColor: [74, 222, 128, 80] as [number, number, number, number],
lineWidthMinPixels: 1,
pickable: false,
updateTriggers: { radiusScale: this.pulseTime },
}));
return layers;
}
private createHappinessChoroplethLayer(): GeoJsonLayer | null {
if (!this.countriesGeoJsonData || this.happinessScores.size === 0) return null;
const scores = this.happinessScores;
return new GeoJsonLayer({
id: 'happiness-choropleth-layer',
data: this.getCulledCountriesGeoJson() ?? this.countriesGeoJsonData,
filled: true,
stroked: true,
getFillColor: (feature: { properties?: Record<string, unknown> }) => {
const code = feature.properties?.['ISO3166-1-Alpha-2'] as string | undefined;
const score = code ? scores.get(code) : undefined;
if (score == null) return [0, 0, 0, 0] as [number, number, number, number];
const t = score / 10;
return [
Math.round(40 + (1 - t) * 180),
Math.round(180 + t * 60),
Math.round(40 + (1 - t) * 100),
140,
] as [number, number, number, number];
},
getLineColor: [100, 100, 100, 60] as [number, number, number, number],
getLineWidth: 1,
lineWidthMinPixels: 0.5,
pickable: true,
updateTriggers: { getFillColor: [scores.size] },
});
}
private static readonly CII_LEVEL_HEX: Record<string, string> = {
critical: '#b91c1c', high: '#dc2626', elevated: '#f59e0b', normal: '#eab308', low: '#22c55e',
};
private createCIIChoroplethLayer(): GeoJsonLayer | null {
if (!this.countriesGeoJsonData || this.ciiScoresMap.size === 0) return null;
const scores = this.ciiScoresMap;
const colors = CII_LEVEL_COLORS;
return new GeoJsonLayer({
id: 'cii-choropleth-layer',
data: this.getCulledCountriesGeoJson() ?? this.countriesGeoJsonData,
filled: true,
stroked: true,
getFillColor: (feature: { properties?: Record<string, unknown> }) => {
const code = feature.properties?.['ISO3166-1-Alpha-2'] as string | undefined;
const entry = code ? scores.get(code) : undefined;
return entry ? (colors[entry.level as CiiLevel] ?? [0, 0, 0, 0]) : [0, 0, 0, 0];
},
getLineColor: [80, 80, 80, 80] as [number, number, number, number],
getLineWidth: 1,
lineWidthMinPixels: 0.5,
pickable: true,
updateTriggers: { getFillColor: [this.ciiScoresVersion] },
});
}
private createResilienceChoroplethLayer(): GeoJsonLayer | null {
if (!this.countriesGeoJsonData || this.resilienceScoresMap.size === 0) return null;
const scores = this.resilienceScoresMap;
return new GeoJsonLayer({
id: 'resilience-choropleth-layer',
data: this.getCulledCountriesGeoJson() ?? this.countriesGeoJsonData,
filled: true,
stroked: true,
getFillColor: (feature: { properties?: Record<string, unknown> }) => {
const code = feature.properties?.['ISO3166-1-Alpha-2'] as string | undefined;
const entry = code ? scores.get(code) : undefined;
return entry ? RESILIENCE_CHOROPLETH_COLORS[entry.level] : [0, 0, 0, 0];
},
getLineColor: [80, 80, 80, 80] as [number, number, number, number],
getLineWidth: 1,
lineWidthMinPixels: 0.5,
pickable: true,
updateTriggers: { getFillColor: [this.resilienceScoresVersion] },
});
}
private createSanctionsChoroplethLayer(): GeoJsonLayer | null {
if (!this.countriesGeoJsonData) return null;
return new GeoJsonLayer({
id: 'sanctions-choropleth-layer',
data: this.getCulledCountriesGeoJson() ?? this.countriesGeoJsonData,
filled: true,
stroked: false,
getFillColor: (feature: { properties?: Record<string, unknown> }) => {
const code = feature.properties?.['ISO3166-1-Alpha-2'] as string | undefined;
const level = code ? SANCTIONED_COUNTRIES_ALPHA2[code] : undefined;
if (level === 'severe') return [255, 0, 0, 89] as [number, number, number, number];
if (level === 'high') return [255, 100, 0, 64] as [number, number, number, number];
if (level === 'moderate') return [255, 200, 0, 51] as [number, number, number, number];
return [0, 0, 0, 0] as [number, number, number, number];
},
pickable: false,
});
}
private createScenarioHeatLayer(): GeoJsonLayer | null {
if (!this.affectedIso2Set.size || !this.countriesGeoJsonData) return null;
return new GeoJsonLayer({
id: 'scenario-heat-layer',
data: this.getCulledCountriesGeoJson() ?? this.countriesGeoJsonData,
stroked: false,
filled: true,
extruded: false,
pickable: false,
getFillColor: (feature: { properties?: Record<string, unknown> }) => {
const code = feature.properties?.['ISO3166-1-Alpha-2'] as string | undefined;
return (code && this.affectedIso2Set.has(code) ? [220, 60, 40, 80] : [0, 0, 0, 0]) as [number, number, number, number];
},
updateTriggers: { getFillColor: [this.scenarioState?.scenarioId ?? null] },
});
}
private createSpeciesRecoveryLayer(): ScatterplotLayer {
return new ScatterplotLayer({
id: 'species-recovery-layer',
data: this.speciesRecoveryZones,
getPosition: (d: (typeof this.speciesRecoveryZones)[number]) => [d.recoveryZone.lon, d.recoveryZone.lat],
getRadius: 50000,
radiusMinPixels: 8,
radiusMaxPixels: 25,
getFillColor: [74, 222, 128, 120] as [number, number, number, number],
stroked: true,
getLineColor: [74, 222, 128, 200] as [number, number, number, number],
lineWidthMinPixels: 1.5,
pickable: true,
});
}
private createRenewableInstallationsLayer(): ScatterplotLayer {
const typeColors: Record<string, [number, number, number, number]> = {
solar: [255, 200, 50, 200],
wind: [100, 200, 255, 200],
hydro: [0, 180, 180, 200],
geothermal: [255, 150, 80, 200],
};
const typeLineColors: Record<string, [number, number, number, number]> = {
solar: [255, 200, 50, 255],
wind: [100, 200, 255, 255],
hydro: [0, 180, 180, 255],
geothermal: [255, 150, 80, 255],
};
return new ScatterplotLayer({
id: 'renewable-installations-layer',
data: this.renewableInstallations,
getPosition: (d: RenewableInstallation) => [d.lon, d.lat],
getRadius: 30000,
radiusMinPixels: 5,
radiusMaxPixels: 18,
getFillColor: (d: RenewableInstallation) => typeColors[d.type] ?? [200, 200, 200, 200] as [number, number, number, number],
stroked: true,
getLineColor: (d: RenewableInstallation) => typeLineColors[d.type] ?? [200, 200, 200, 255] as [number, number, number, number],
lineWidthMinPixels: 1,
pickable: true,
});
}
private createImageryFootprintLayer(items: ImageryScene[]): PolygonLayer {
return new PolygonLayer({
id: 'satellite-imagery-layer',
data: items.filter(s => s.geometryGeojson),
getPolygon: (d: ImageryScene) => {
try {
const geom = JSON.parse(d.geometryGeojson);
if (geom.type === 'Polygon') return geom.coordinates[0];
return [];
} catch { return []; }
},
getFillColor: [0, 180, 255, 40] as [number, number, number, number],
stroked: false,
pickable: true,
});
}
private async fetchImageryForViewport(): Promise<void> {
const map = this.maplibreMap;
if (!map) return;
const bounds = map.getBounds();
const bbox = `${bounds.getWest().toFixed(4)},${bounds.getSouth().toFixed(4)},${bounds.getEast().toFixed(4)},${bounds.getNorth().toFixed(4)}`;
const version = ++this.imagerySearchVersion;
try {
const scenes = await fetchImageryScenes({ bbox, limit: 20 });
if (version !== this.imagerySearchVersion) return;
this.imageryScenes = scenes;
this.render();
} catch { /* viewport fetch failed silently */ }
}
private getTooltip(info: PickingInfo): { html: string } | null {
if (!info.object) return null;
const rawLayerId = info.layer?.id || '';
const layerId = rawLayerId.endsWith('-ghost') ? rawLayerId.slice(0, -6) : rawLayerId;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const obj = info.object as any;
const text = (value: unknown): string => escapeHtml(String(value ?? ''));
switch (layerId) {
case 'hotspots-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.subtext)}</div>` };
case 'earthquakes-layer':
return { html: `<div class="deckgl-tooltip"><strong>M${(obj.magnitude || 0).toFixed(1)} ${t('components.deckgl.tooltip.earthquake')}</strong><br/>${text(obj.place)}</div>` };
case 'military-vessels-layer':
return { html: renderMilitaryVesselTooltipHtml(obj, t) };
case 'military-flights-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.callsign || obj.registration || t('components.deckgl.tooltip.militaryAircraft'))}</strong><br/>${text(obj.type)}</div>` };
case 'military-vessel-clusters-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name || t('components.deckgl.tooltip.vesselCluster'))}</strong><br/>${obj.vesselCount || 0} ${t('components.deckgl.tooltip.vessels')}<br/>${text(obj.activityType)}</div>` };
case 'military-flight-clusters-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name || t('components.deckgl.tooltip.flightCluster'))}</strong><br/>${obj.flightCount || 0} ${t('components.deckgl.tooltip.aircraft')}<br/>${text(obj.activityType)}</div>` };
case 'protests-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.title)}</strong><br/>${text(obj.country)}</div>` };
case 'protest-clusters-layer':
if (obj.count === 1) {
const item = obj.items?.[0];
return { html: `<div class="deckgl-tooltip"><strong>${text(item?.title || t('components.deckgl.tooltip.protest'))}</strong><br/>${text(item?.city || item?.country || '')}</div>` };
}
return { html: `<div class="deckgl-tooltip"><strong>${t('components.deckgl.tooltip.protestsCount', { count: String(obj.count) })}</strong><br/>${text(obj.country)}</div>` };
case 'tech-hq-clusters-layer':
if (obj.count === 1) {
const hq = obj.items?.[0];
return { html: `<div class="deckgl-tooltip"><strong>${text(hq?.company || '')}</strong><br/>${text(hq?.city || '')}</div>` };
}
return { html: `<div class="deckgl-tooltip"><strong>${t('components.deckgl.tooltip.techHQsCount', { count: String(obj.count) })}</strong><br/>${text(obj.city)}</div>` };
case 'tech-event-clusters-layer':
if (obj.count === 1) {
const ev = obj.items?.[0];
return { html: `<div class="deckgl-tooltip"><strong>${text(ev?.title || '')}</strong><br/>${text(ev?.location || '')}</div>` };
}
return { html: `<div class="deckgl-tooltip"><strong>${t('components.deckgl.tooltip.techEventsCount', { count: String(obj.count) })}</strong><br/>${text(obj.location)}</div>` };
case 'datacenter-clusters-layer':
if (obj.count === 1) {
const dc = obj.items?.[0];
return { html: `<div class="deckgl-tooltip"><strong>${text(dc?.name || '')}</strong><br/>${text(dc?.owner || '')}</div>` };
}
return { html: `<div class="deckgl-tooltip"><strong>${t('components.deckgl.tooltip.dataCentersCount', { count: String(obj.count) })}</strong><br/>${text(obj.country)}</div>` };
case 'bases-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.country)}${obj.kind ? ` · ${text(obj.kind)}` : ''}</div>` };
case 'bases-cluster-layer':
return { html: `<div class="deckgl-tooltip"><strong>${obj.count} bases</strong></div>` };
case 'nuclear-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.type)}</div>` };
case 'datacenters-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.owner)}</div>` };
case 'cables-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${t('components.deckgl.tooltip.underseaCable')}</div>` };
case 'pipelines-layer': {
// Energy variant emits objects with {commodityType, badge}; other
// variants emit the static-config shape {type}. Differentiate by
// checking for the evidence-derived badge field.
const hasBadge = typeof obj.badge === 'string';
const commodity = hasBadge ? String(obj.commodityType || '').toLowerCase() : String(obj.type || '').toLowerCase();
const commodityLabel = commodity === 'oil'
? t('popups.pipeline.types.oil')
: commodity === 'gas'
? t('popups.pipeline.types.gas')
: commodity === 'products'
? t('popups.pipeline.types.products')
: `${text(commodity)} ${t('components.deckgl.tooltip.pipeline')}`.trim();
if (hasBadge) {
const badge = String(obj.badge).toUpperCase();
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${commodityLabel} · <strong>${text(badge)}</strong></div>` };
}
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${commodityLabel}</div>` };
}
case 'storage-facilities-layer': {
const typeLabel = {
ugs: 'UGS', spr: 'SPR',
lng_export: 'LNG export', lng_import: 'LNG import',
crude_tank_farm: 'Crude hub',
}[String(obj.facilityType)] ?? text(obj.facilityType);
const badge = String(obj.badge || 'disputed').toUpperCase();
const cap = text(obj.capacityDisplay || '—');
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${typeLabel} · ${text(obj.country)} · ${cap}<br/><strong>${text(badge)}</strong></div>` };
}
case 'fuel-shortages-layer': {
const severity = String(obj.severity || 'watch').toUpperCase();
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.country)} · ${text(obj.product)}</strong><br/>${text(obj.description)}<br/><strong>${text(severity)}</strong></div>` };
}
case 'conflict-zones-layer': {
const props = obj.properties || obj;
return { html: `<div class="deckgl-tooltip"><strong>${text(props.name)}</strong><br/>${t('components.deckgl.tooltip.conflictZone')}</div>` };
}
case 'natural-events-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.title)}</strong><br/>${text(obj.category || t('components.deckgl.tooltip.naturalEvent'))}</div>` };
case 'storm-centers-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.stormName || obj.title)}</strong><br/>${text(obj.classification || '')} ${obj.windKt ? obj.windKt + ` kt${obj.windAveragingPeriodMinutes ? ` (${obj.windAveragingPeriodMinutes}-minute mean)` : ''}` : ''}</div>` };
case 'storm-forecast-track-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.stormName)}</strong><br/>${t('popups.naturalEvent.classification')}: Forecast Track</div>` };
case 'storm-past-track-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.stormName)}</strong><br/>Past Track (${obj.windKt} kt)</div>` };
case 'storm-cone-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.stormName)}</strong><br/>Forecast Cone</div>` };
case 'ais-density-layer':
return { html: `<div class="deckgl-tooltip"><strong>${t('components.deckgl.layers.shipTraffic')}</strong><br/>${t('popups.intensity')}: ${text(obj.intensity)}</div>` };
case 'waterways-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${t('components.deckgl.layers.strategicWaterways')}</div>` };
case 'economic-centers-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.country)}</div>` };
case 'stock-exchanges-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.shortName)}</strong><br/>${text(obj.city)}, ${text(obj.country)}</div>` };
case 'financial-centers-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.type)} ${t('components.deckgl.tooltip.financialCenter')}</div>` };
case 'central-banks-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.shortName)}</strong><br/>${text(obj.city)}, ${text(obj.country)}</div>` };
case 'commodity-hubs-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.type)} · ${text(obj.city)}</div>` };
case 'startup-hubs-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.city)}</strong><br/>${text(obj.country)}</div>` };
case 'tech-hqs-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.company)}</strong><br/>${text(obj.city)}</div>` };
case 'accelerators-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.city)}</div>` };
case 'cloud-regions-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.provider)}</strong><br/>${text(obj.region)}</div>` };
case 'tech-events-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.title)}</strong><br/>${text(obj.location)}</div>` };
case 'irradiators-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.type || t('components.deckgl.layers.gammaIrradiators'))}</div>` };
case 'disease-outbreaks-layer': {
const item = (obj as { item: DiseaseOutbreakItem }).item;
if (!item) return null;
const lvlColor = item.alertLevel === 'alert' ? '#e74c3c' : item.alertLevel === 'warning' ? '#e67e22' : '#f1c40f';
const casesHtml = item.cases ? ` | ${item.cases} case${item.cases !== 1 ? 's' : ''}` : '';
const dateStr = new Date(item.publishedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
const metaHtml = `<br/><span style="opacity:.6;font-size:11px">${text(item.sourceName || '')} | ${dateStr}${casesHtml}</span>`;
const summaryHtml = item.summary ? `<br/><span style="opacity:.75">${text(item.summary.slice(0, 100))}${item.summary.length > 100 ? '…' : ''}</span>` : '';
return { html: `<div class="deckgl-tooltip"><strong style="color:${lvlColor}">${text(item.alertLevel.toUpperCase())}</strong> ${text(item.disease)}<br/>${text(item.location)}${summaryHtml}${metaHtml}</div>` };
}
case 'radiation-watch-layer': {
const severityLabel = obj.severity === 'spike' ? t('components.deckgl.layers.radiationSpike') : t('components.deckgl.layers.radiationElevated');
const delta = Number(obj.delta || 0);
const confidence = String(obj.confidence || 'low').toUpperCase();
const corroboration = obj.corroborated ? 'CONFIRMED' : obj.conflictingSources ? 'CONFLICTING' : confidence;
return { html: `<div class="deckgl-tooltip"><strong>${severityLabel}</strong><br/>${text(obj.location)}<br/>${Number(obj.value).toFixed(1)} ${text(obj.unit)} · ${delta >= 0 ? '+' : ''}${delta.toFixed(1)} vs baseline<br/>${text(corroboration)}</div>` };
}
case 'spaceports-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.country || t('components.deckgl.layers.spaceports'))}</div>` };
case 'ports-layer': {
const typeIcon = obj.type === 'naval' ? '⚓' : obj.type === 'oil' || obj.type === 'lng' ? '🛢️' : '🏭';
return { html: `<div class="deckgl-tooltip"><strong>${typeIcon} ${text(obj.name)}</strong><br/>${text(obj.type || t('components.deckgl.tooltip.port'))} - ${text(obj.country)}</div>` };
}
case 'flight-delays-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)} (${text(obj.iata)})</strong><br/>${text(obj.severity)}: ${text(obj.reason)}</div>` };
case 'notam-overlay-layer':
return { html: `<div class="deckgl-tooltip"><strong style="color:#ff2828;">⚠ NOTAM CLOSURE</strong><br/>${text(obj.name)} (${text(obj.iata)})<br/><span style="opacity:.7">${text((obj.reason || '').slice(0, 100))}</span></div>` };
case 'aircraft-positions-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.callsign || obj.icao24)}</strong><br/>${obj.altitudeFt?.toLocaleString() ?? 0} ft · ${obj.groundSpeedKts ?? 0} kts · ${Math.round(obj.trackDeg ?? 0)}°</div>` };
case 'apt-groups-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.aka)}<br/>${t('popups.sponsor')}: ${text(obj.sponsor)}</div>` };
case 'minerals-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.mineral)} - ${text(obj.country)}<br/>${text(obj.operator)}</div>` };
case 'mining-sites-layer': {
const statusLabel = obj.status === 'producing' ? '⛏️ Producing' : obj.status === 'development' ? '🔧 Development' : '🔍 Exploration';
const outputStr = obj.annualOutput ? `<br/><span style="opacity:.75">${text(obj.annualOutput)}</span>` : '';
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(obj.mineral)} · ${text(obj.country)}<br/>${statusLabel}${outputStr}</div>` };
}
case 'processing-plants-layer': {
const typeLabel = obj.type === 'smelter' ? '🏭 Smelter' : obj.type === 'refinery' ? '⚗️ Refinery' : obj.type === 'separation' ? '🧪 Separation' : '🏗️ Processing';
const capacityStr = obj.capacityTpa ? `<br/><span style="opacity:.75">${text(String((obj.capacityTpa / 1000).toFixed(0)))}k t/yr</span>` : '';
const mineralLabel = obj.mineral ?? (Array.isArray(obj.materials) ? obj.materials.join(', ') : '');
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${text(mineralLabel)} · ${text(obj.country)}<br/>${typeLabel}${capacityStr}</div>` };
}
case 'commodity-ports-layer': {
const commoditiesStr = Array.isArray(obj.commodities) ? obj.commodities.join(', ') : '';
const volumeStr = obj.annualVolumeMt ? `<br/><span style="opacity:.75">${text(String(obj.annualVolumeMt))}Mt/yr</span>` : '';
return { html: `<div class="deckgl-tooltip"><strong>⚓ ${text(obj.name)}</strong><br/>${text(obj.country)}<br/>${text(commoditiesStr)}${volumeStr}</div>` };
}
case 'ais-disruptions-layer':
return { html: `<div class="deckgl-tooltip"><strong>AIS ${text(obj.type || t('components.deckgl.tooltip.disruption'))}</strong><br/>${text(obj.severity)} ${t('popups.severity')}<br/>${text(obj.description)}</div>` };
case 'gps-jamming-layer':
return { html: `<div class="deckgl-tooltip"><strong>GPS Jamming</strong><br/>${text(obj.level)} · aircraft affected: ${Number(obj.pct).toFixed(1)}%<br/>H3: ${text(obj.h3)}</div>` };
case 'cable-advisories-layer': {
const cableName = UNDERSEA_CABLES.find(c => c.id === obj.cableId)?.name || obj.cableId;
return { html: `<div class="deckgl-tooltip"><strong>${text(cableName)}</strong><br/>${text(obj.severity || t('components.deckgl.tooltip.advisory'))}<br/>${text(obj.description)}</div>` };
}
case 'repair-ships-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name || t('components.deckgl.tooltip.repairShip'))}</strong><br/>${text(obj.status)}</div>` };
case 'weather-layer': {
const areaDesc = typeof obj.areaDesc === 'string' ? obj.areaDesc : '';
const area = areaDesc ? `<br/><small>${text(areaDesc.slice(0, 50))}${areaDesc.length > 50 ? '...' : ''}</small>` : '';
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.event || t('components.deckgl.layers.weatherAlerts'))}</strong><br/>${text(obj.severity)}${area}</div>` };
}
case 'outages-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.title || t('components.deckgl.tooltip.internetOutage'))}</strong><br/>${text(obj.country)}</div>` };
case 'traffic-anomalies-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.type || 'Traffic Anomaly')}</strong><br/>${text(obj.locationName || obj.asnName || '')}</div>` };
case 'ddos-locations-layer':
return { html: `<div class="deckgl-tooltip"><strong>DDoS: ${text(obj.countryName)}</strong><br/>${text(obj.percentage ? obj.percentage.toFixed(1) + '%' : '')}</div>` };
case 'cyber-threats-layer':
return { html: `<div class="deckgl-tooltip"><strong>${t('popups.cyberThreat.title')}</strong><br/>${text(obj.severity || t('components.deckgl.tooltip.medium'))} · ${text(obj.country || t('popups.unknown'))}</div>` };
case 'iran-events-layer':
return { html: `<div class="deckgl-tooltip"><strong>${t('components.deckgl.layers.iranAttacks')}: ${text(obj.category || '')}</strong><br/>${text((obj.title || '').slice(0, 80))}</div>` };
case 'news-locations-layer':
return { html: `<div class="deckgl-tooltip"><strong>📰 ${t('components.deckgl.tooltip.news')}</strong><br/>${text(obj.title?.slice(0, 80) || '')}</div>` };
case 'positive-events-layer': {
const catLabel = obj.category ? obj.category.replace(/-/g, ' & ') : 'Positive Event';
const countInfo = obj.count > 1 ? `<br/><span style="opacity:.7">${obj.count} sources reporting</span>` : '';
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/><span style="text-transform:capitalize">${text(catLabel)}</span>${countInfo}</div>` };
}
case 'kindness-layer':
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong></div>` };
case 'happiness-choropleth-layer': {
const hcName = obj.properties?.name ?? 'Unknown';
const hcCode = obj.properties?.['ISO3166-1-Alpha-2'];
const hcScore = hcCode ? this.happinessScores.get(hcCode as string) : undefined;
const hcScoreStr = hcScore != null ? hcScore.toFixed(1) : 'No data';
return { html: `<div class="deckgl-tooltip"><strong>${text(hcName)}</strong><br/>Happiness: ${hcScoreStr}/10${hcScore != null ? `<br/><span style="opacity:.7">${text(this.happinessSource)} (${this.happinessYear})</span>` : ''}</div>` };
}
case 'cii-choropleth-layer': {
const ciiName = obj.properties?.name ?? 'Unknown';
const ciiCode = obj.properties?.['ISO3166-1-Alpha-2'];
const ciiEntry = ciiCode ? this.ciiScoresMap.get(ciiCode as string) : undefined;
if (!ciiEntry) return { html: `<div class="deckgl-tooltip"><strong>${text(ciiName)}</strong><br/><span style="opacity:.7">No CII data</span></div>` };
const levelColor = DeckGLMap.CII_LEVEL_HEX[ciiEntry.level] ?? '#888';
return { html: `<div class="deckgl-tooltip"><strong>${text(ciiName)}</strong><br/>CII: <span style="color:${levelColor};font-weight:600">${ciiEntry.score}/100</span><br/><span style="text-transform:capitalize;opacity:.7">${text(ciiEntry.level)}</span></div>` };
}
case 'resilience-choropleth-layer': {
const resilienceName = obj.properties?.name ?? 'Unknown';
const resilienceCode = obj.properties?.['ISO3166-1-Alpha-2'];
const resilienceEntry = resilienceCode ? this.resilienceScoresMap.get(resilienceCode as string) : undefined;
if (!resilienceEntry) {
return { html: `<div class="deckgl-tooltip"><strong>${text(resilienceName)}</strong><br/><span style="opacity:.7">No resilience data</span></div>` };
}
if (resilienceEntry.level === 'insufficient_data') {
return { html: `<div class="deckgl-tooltip"><strong>${text(resilienceName)}</strong><br/><span style="opacity:.7">Insufficient data</span></div>` };
}
const [red, green, blue] = RESILIENCE_CHOROPLETH_COLORS[resilienceEntry.level];
const levelColor = `rgb(${red}, ${green}, ${blue})`;
const visualBand = formatResilienceChoroplethLevel(resilienceEntry.level);
const serverLevel = formatResilienceServerLevel(resilienceEntry.serverLevel);
const confidenceNote = resilienceEntry.lowConfidence
? '<br/><span style="opacity:.7">Low confidence</span>'
: resilienceEntry.outsideHeadlineRanking
? '<br/><span style="opacity:.7">Outside headline ranking</span>'
: '';
return {
html: `<div class="deckgl-tooltip"><strong>${text(resilienceName)}</strong><br/>Resilience: <span style="color:${levelColor};font-weight:600">${resilienceEntry.overallScore.toFixed(1)}/100</span><br/><span style="text-transform:capitalize;opacity:.7">Visual band: ${text(visualBand)}</span><br/><span style="text-transform:capitalize;opacity:.7">API level: ${text(serverLevel)}</span>${confidenceNote}</div>`,
};
}
case 'species-recovery-layer': {
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.commonName)}</strong><br/>${text(obj.recoveryZone?.name ?? obj.region)}<br/><span style="opacity:.7">Status: ${text(obj.recoveryStatus)}</span></div>` };
}
case 'renewable-installations-layer': {
const riTypeLabel = obj.type ? String(obj.type).charAt(0).toUpperCase() + String(obj.type).slice(1) : 'Renewable';
return { html: `<div class="deckgl-tooltip"><strong>${text(obj.name)}</strong><br/>${riTypeLabel} · ${obj.capacityMW?.toLocaleString() ?? '?'} MW<br/><span style="opacity:.7">${text(obj.country)} · ${obj.year}</span></div>` };
}
case 'gulf-investments-layer': {
const inv = obj as GulfInvestment;
const flag = inv.investingCountry === 'SA' ? '🇸🇦' : '🇦🇪';
const usd = inv.investmentUSD != null
? (inv.investmentUSD >= 1000 ? `$${(inv.investmentUSD / 1000).toFixed(1)}B` : `$${inv.investmentUSD}M`)
: t('components.deckgl.tooltip.undisclosed');
const stake = inv.stakePercent != null ? `<br/>${text(String(inv.stakePercent))}% ${t('components.deckgl.tooltip.stake')}` : '';
return {
html: `<div class="deckgl-tooltip">
<strong>${flag} ${text(inv.assetName)}</strong><br/>
<em>${text(inv.investingEntity)}</em><br/>
${text(inv.targetCountry)} · ${text(inv.sector)}<br/>
<strong>${usd}</strong>${stake}<br/>
<span style="text-transform:capitalize">${text(inv.status)}</span>
</div>`,
};
}
case 'satellite-imagery-layer': {
let imgHtml = `<div class="deckgl-tooltip"><strong>🛰 ${text(obj.satellite)}</strong><br/>${text(obj.datetime)}<br/>Res: ${Number(obj.resolutionM)}m \u00B7 ${text(obj.mode)}`;
if (isAllowedPreviewUrl(obj.previewUrl)) {
const safeHref = escapeHtml(new URL(obj.previewUrl).href);
imgHtml += `<br><img src="${safeHref}" referrerpolicy="no-referrer" style="max-width:180px;max-height:120px;margin-top:4px;border-radius:4px;" class="imagery-preview">`;
}
imgHtml += '</div>';
return { html: imgHtml };
}
case 'webcam-layer': {
const label = 'count' in obj
? `${obj.count} webcams`
: (obj.title || obj.name || 'Webcam');
return { html: `<div class="deckgl-tooltip"><strong>${text(label)}</strong></div>` };
}
default:
return null;
}
}
private static readonly CHOROPLETH_LAYER_IDS = new Set([
'cii-choropleth-layer',
'happiness-choropleth-layer',
'resilience-choropleth-layer',
]);
private handleClick(info: PickingInfo): void {
const isChoropleth = info.layer?.id ? DeckGLMap.CHOROPLETH_LAYER_IDS.has(info.layer.id) : false;
if (!info.object || isChoropleth) {
if (info.coordinate && this.onCountryClick) {
if (this.shouldSuppressCountryClickAfterDrag()) return;
const [lon, lat] = info.coordinate as [number, number];
let country: { code: string; name: string } | null = null;
if (isChoropleth && info.object?.properties) {
country = { code: info.object.properties['ISO3166-1-Alpha-2'] as string, name: info.object.properties.name as string };
} else {
country = resolveCountryForPointerInteraction(
{ code: this.hoveredCountryIso2, name: this.hoveredCountryName },
this.hoverQueryThrottle?.isPending() ?? false,
() => this.resolveCountryFromCoordinate(lon, lat),
);
}
// Only fire if we have a country — ocean/no-country clicks are silently ignored
if (country?.code && country?.name) {
this.onCountryClick({ lat, lon, code: country.code, name: country.name });
}
}
return;
}
const rawClickLayerId = info.layer?.id || '';
const layerId = rawClickLayerId.endsWith('-ghost') ? rawClickLayerId.slice(0, -6) : rawClickLayerId;
// Hotspots show popup with related news
if (layerId === 'hotspots-layer') {
const hotspot = info.object as Hotspot;
const relatedNews = this.getRelatedNews(hotspot);
this.popup.show({
type: 'hotspot',
data: hotspot,
relatedNews,
x: info.x,
y: info.y,
});
this.popup.loadHotspotGdeltContext(hotspot);
this.onHotspotClick?.(hotspot);
return;
}
// Handle cluster layers with single/multi logic
if (layerId === 'protest-clusters-layer') {
const cluster = info.object as MapProtestCluster;
if (cluster.items.length === 0 && cluster._clusterId != null && this.protestSC) {
try {
const leaves = this.protestSC.getLeaves(cluster._clusterId, DeckGLMap.MAX_CLUSTER_LEAVES);
cluster.items = leaves.map(l => this.protestSuperclusterSource[l.properties.index]).filter((x): x is SocialUnrestEvent => !!x);
cluster.sampled = cluster.items.length < cluster.count;
} catch (e) {
console.warn('[DeckGLMap] stale protest cluster', cluster._clusterId, e);
return;
}
}
if (cluster.count === 1 && cluster.items[0]) {
this.popup.show({ type: 'protest', data: cluster.items[0], x: info.x, y: info.y });
} else {
this.popup.show({
type: 'protestCluster',
data: {
items: cluster.items,
country: cluster.country,
count: cluster.count,
riotCount: cluster.riotCount,
highSeverityCount: cluster.highSeverityCount,
verifiedCount: cluster.verifiedCount,
totalFatalities: cluster.totalFatalities,
sampled: cluster.sampled,
},
x: info.x,
y: info.y,
});
}
return;
}
if (layerId === 'tech-hq-clusters-layer') {
const cluster = info.object as MapTechHQCluster;
if (cluster.items.length === 0 && cluster._clusterId != null && this.techHQSC) {
try {
const leaves = this.techHQSC.getLeaves(cluster._clusterId, DeckGLMap.MAX_CLUSTER_LEAVES);
cluster.items = leaves.map(l => TECH_HQS[l.properties.index]).filter(Boolean) as typeof TECH_HQS;
cluster.sampled = cluster.items.length < cluster.count;
} catch (e) {
console.warn('[DeckGLMap] stale techHQ cluster', cluster._clusterId, e);
return;
}
}
if (cluster.count === 1 && cluster.items[0]) {
this.popup.show({ type: 'techHQ', data: cluster.items[0], x: info.x, y: info.y });
} else {
this.popup.show({
type: 'techHQCluster',
data: {
items: cluster.items,
city: cluster.city,
country: cluster.country,
count: cluster.count,
faangCount: cluster.faangCount,
unicornCount: cluster.unicornCount,
publicCount: cluster.publicCount,
sampled: cluster.sampled,
},
x: info.x,
y: info.y,
});
}
return;
}
if (layerId === 'tech-event-clusters-layer') {
const cluster = info.object as MapTechEventCluster;
if (cluster.items.length === 0 && cluster._clusterId != null && this.techEventSC) {
try {
const leaves = this.techEventSC.getLeaves(cluster._clusterId, DeckGLMap.MAX_CLUSTER_LEAVES);
cluster.items = leaves.map(l => this.techEvents[l.properties.index]).filter((x): x is TechEventMarker => !!x);
cluster.sampled = cluster.items.length < cluster.count;
} catch (e) {
console.warn('[DeckGLMap] stale techEvent cluster', cluster._clusterId, e);
return;
}
}
if (cluster.count === 1 && cluster.items[0]) {
this.popup.show({ type: 'techEvent', data: cluster.items[0], x: info.x, y: info.y });
} else {
this.popup.show({
type: 'techEventCluster',
data: {
items: cluster.items,
location: cluster.location,
country: cluster.country,
count: cluster.count,
soonCount: cluster.soonCount,
sampled: cluster.sampled,
},
x: info.x,
y: info.y,
});
}
return;
}
if (layerId === 'datacenter-clusters-layer') {
const cluster = info.object as MapDatacenterCluster;
if (cluster.items.length === 0 && cluster._clusterId != null && this.datacenterSC) {
try {
const leaves = this.datacenterSC.getLeaves(cluster._clusterId, DeckGLMap.MAX_CLUSTER_LEAVES);
cluster.items = leaves.map(l => this.datacenterSCSource[l.properties.index]).filter((x): x is AIDataCenter => !!x);
cluster.sampled = cluster.items.length < cluster.count;
} catch (e) {
console.warn('[DeckGLMap] stale datacenter cluster', cluster._clusterId, e);
return;
}
}
if (cluster.count === 1 && cluster.items[0]) {
this.popup.show({ type: 'datacenter', data: cluster.items[0], x: info.x, y: info.y });
} else {
this.popup.show({
type: 'datacenterCluster',
data: {
items: cluster.items,
region: cluster.region || cluster.country,
country: cluster.country,
count: cluster.count,
totalChips: cluster.totalChips,
totalPowerMW: cluster.totalPowerMW,
existingCount: cluster.existingCount,
plannedCount: cluster.plannedCount,
sampled: cluster.sampled,
},
x: info.x,
y: info.y,
});
}
return;
}
if (layerId === 'webcam-layer' && !('count' in info.object)) {
this.showWebcamClickPopup(info.object as WebcamEntry, info.x, info.y);
return;
}
if (layerId === 'trade-routes-layer') {
const segment = info.object as TradeRouteSegment;
if (!hasPremiumAccess(getAuthState())) {
trackGateHit('trade-arc-intel');
return;
}
const waypoints = ROUTE_WAYPOINTS_MAP.get(segment.routeId) ?? [];
this.popup.showRouteBreakdown(segment, waypoints, info.x, info.y);
this.onTradeArcClick?.(segment, waypoints, info.x, info.y);
return;
}
// Map layer IDs to popup types
const layerToPopupType: Record<string, PopupType> = {
'conflict-zones-layer': 'conflict',
'bases-layer': 'base',
'nuclear-layer': 'nuclear',
'irradiators-layer': 'irradiator',
'radiation-watch-layer': 'radiation',
'datacenters-layer': 'datacenter',
'cables-layer': 'cable',
'pipelines-layer': 'pipeline',
'earthquakes-layer': 'earthquake',
'weather-layer': 'weather',
'outages-layer': 'outage',
'cyber-threats-layer': 'cyberThreat',
'iran-events-layer': 'iranEvent',
'protests-layer': 'protest',
'military-flights-layer': 'militaryFlight',
'military-vessels-layer': 'militaryVessel',
'military-vessel-clusters-layer': 'militaryVesselCluster',
'military-flight-clusters-layer': 'militaryFlightCluster',
'natural-events-layer': 'natEvent',
'storm-centers-layer': 'natEvent',
'storm-forecast-track-layer': 'natEvent',
'storm-past-track-layer': 'natEvent',
'storm-cone-layer': 'natEvent',
'waterways-layer': 'waterway',
'economic-centers-layer': 'economic',
'stock-exchanges-layer': 'stockExchange',
'financial-centers-layer': 'financialCenter',
'central-banks-layer': 'centralBank',
'commodity-hubs-layer': 'commodityHub',
'spaceports-layer': 'spaceport',
'ports-layer': 'port',
'flight-delays-layer': 'flight',
'notam-overlay-layer': 'flight',
'aircraft-positions-layer': 'aircraft',
'startup-hubs-layer': 'startupHub',
'tech-hqs-layer': 'techHQ',
'accelerators-layer': 'accelerator',
'cloud-regions-layer': 'cloudRegion',
'tech-events-layer': 'techEvent',
'apt-groups-layer': 'apt',
'minerals-layer': 'mineral',
'ais-disruptions-layer': 'ais',
'gps-jamming-layer': 'gpsJamming',
'cable-advisories-layer': 'cable-advisory',
'repair-ships-layer': 'repair-ship',
};
const popupType = layerToPopupType[layerId];
if (!popupType) return;
// For synthetic storm layers, unwrap the backing NaturalEvent
let data = info.object?._event ?? info.object;
if (layerId === 'conflict-zones-layer' && info.object.properties) {
// Find the full conflict zone data from config
const conflictId = info.object.properties.id;
const fullConflict = CONFLICT_ZONES.find(c => c.id === conflictId);
if (fullConflict) data = fullConflict;
}
// Enrich iran events with related events from same location
if (popupType === 'iranEvent' && data.locationName) {
const clickedId = data.id;
const normalizedLoc = data.locationName.trim().toLowerCase();
const related = this.iranEvents
.filter(e => e.id !== clickedId && e.locationName && e.locationName.trim().toLowerCase() === normalizedLoc)
.sort((a, b) => (Number(b.timestamp) || 0) - (Number(a.timestamp) || 0))
.slice(0, 5);
data = { ...data, relatedEvents: related };
}
// Get click coordinates relative to container
const x = info.x ?? 0;
const y = info.y ?? 0;
// Toggle flight trail on military flight click
if (popupType === 'militaryFlight') {
const hex = (data as MilitaryFlight).hexCode;
if (hex) this.toggleFlightTrail(hex);
}
this.popup.show({
type: popupType,
data: data,
x,
y,
});
// Async Wingbits live enrichment for any aircraft popup
if (popupType === 'militaryFlight') {
const hexCode = (data as { hexCode?: string }).hexCode;
if (hexCode) this.popup.loadWingbitsLiveFlight(hexCode);
}
if (popupType === 'aircraft') {
const icao24 = (data as { icao24?: string }).icao24;
if (icao24) this.popup.loadWingbitsLiveFlight(icao24);
}
if (popupType === 'conflict') {
this.popup.loadConflictHistory(data as import('@/types').ConflictZone);
}
}
private async showWebcamClickPopup(webcam: WebcamEntry, x: number, y: number): Promise<void> {
// Remove any existing popup
this.container.querySelector('.deckgl-webcam-popup')?.remove();
const popup = document.createElement('div');
popup.className = 'deckgl-webcam-popup';
popup.style.position = 'absolute';
popup.style.left = x + 'px';
popup.style.top = y + 'px';
popup.style.zIndex = '1000';
const titleEl = document.createElement('div');
titleEl.className = 'deckgl-webcam-popup-title';
titleEl.textContent = webcam.title || webcam.webcamId || '';
popup.appendChild(titleEl);
const locationEl = document.createElement('div');
locationEl.className = 'deckgl-webcam-popup-location';
locationEl.textContent = webcam.country || '';
popup.appendChild(locationEl);
const id = webcam.webcamId;
// Fetch playerUrl for when user pins
const imageData = await fetchWebcamImage(id).catch(() => null);
const pinBtn = document.createElement('button');
pinBtn.className = 'webcam-pin-btn';
if (isPinned(id)) {
pinBtn.classList.add('webcam-pin-btn--pinned');
pinBtn.textContent = '\u{1F4CC} Pinned';
pinBtn.disabled = true;
} else {
pinBtn.textContent = '\u{1F4CC} Pin';
pinBtn.addEventListener('click', (e) => {
e.stopPropagation();
pinWebcam({
webcamId: id,
title: webcam.title || imageData?.title || '',
lat: webcam.lat,
lng: webcam.lng,
category: webcam.category || 'other',
country: webcam.country || '',
playerUrl: imageData?.playerUrl || '',
});
pinBtn.classList.add('webcam-pin-btn--pinned');
pinBtn.textContent = '\u{1F4CC} Pinned';
pinBtn.disabled = true;
});
}
popup.appendChild(pinBtn);
const cleanup = () => {
popup.remove();
document.removeEventListener('click', closeHandler);
clearTimeout(autoDismiss);
};
const closeHandler = (e: MouseEvent) => {
if (!popup.contains(e.target as Node)) cleanup();
};
const autoDismiss = setTimeout(cleanup, 8000);
setTimeout(() => document.addEventListener('click', closeHandler), 0);
this.container.appendChild(popup);
}
// Utility methods
private hexToRgba(hex: string, alpha: number): [number, number, number, number] {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (result?.[1] && result[2] && result[3]) {
return [
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16),
alpha,
];
}
return [100, 100, 100, alpha];
}
// UI Creation methods
private createControls(): void {
const controls = document.createElement('div');
controls.className = 'map-controls deckgl-controls';
setTrustedHtml(controls, trustedHtml(`
<div class="zoom-controls">
<button class="map-btn zoom-in" title="${t('components.deckgl.zoomIn')}">+</button>
<button class="map-btn zoom-out" title="${t('components.deckgl.zoomOut')}">-</button>
<button class="map-btn zoom-reset" title="${t('components.deckgl.resetView')}">⌂</button>
</div>
<div class="view-selector">
<select class="view-select">
<option value="global">${t('components.deckgl.views.global')}</option>
<option value="america">${t('components.deckgl.views.americas')}</option>
<option value="mena">${t('components.deckgl.views.mena')}</option>
<option value="eu">${t('components.deckgl.views.europe')}</option>
<option value="asia">${t('components.deckgl.views.asia')}</option>
<option value="latam">${t('components.deckgl.views.latam')}</option>
<option value="africa">${t('components.deckgl.views.africa')}</option>
<option value="oceania">${t('components.deckgl.views.oceania')}</option>
</select>
</div>
`, "legacy direct innerHTML migration"));
this.container.appendChild(controls);
// Bind events - use event delegation for reliability
controls.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
if (target.classList.contains('zoom-in')) this.zoomIn();
else if (target.classList.contains('zoom-out')) this.zoomOut();
else if (target.classList.contains('zoom-reset')) this.resetView();
});
const viewSelect = controls.querySelector('.view-select') as HTMLSelectElement;
viewSelect.value = this.state.view;
viewSelect.addEventListener('change', () => {
this.setView(viewSelect.value as DeckMapView);
});
// Clear flight trails button (hidden by default)
this.clearTrailsBtn = document.createElement('button');
this.clearTrailsBtn.className = 'map-clear-trails-btn';
this.clearTrailsBtn.textContent = t('components.map.clearTrails');
this.clearTrailsBtn.style.display = 'none';
this.clearTrailsBtn.addEventListener('click', () => this.clearFlightTrails());
controls.appendChild(this.clearTrailsBtn);
}
private createTimeSlider(): void {
const slider = document.createElement('div');
slider.className = 'time-slider deckgl-time-slider';
setTrustedHtml(slider, trustedHtml(`
<div class="time-options">
<button class="time-btn ${this.state.timeRange === '1h' ? 'active' : ''}" data-range="1h">1h</button>
<button class="time-btn ${this.state.timeRange === '6h' ? 'active' : ''}" data-range="6h">6h</button>
<button class="time-btn ${this.state.timeRange === '24h' ? 'active' : ''}" data-range="24h">24h</button>
<button class="time-btn ${this.state.timeRange === '48h' ? 'active' : ''}" data-range="48h">48h</button>
<button class="time-btn ${this.state.timeRange === '7d' ? 'active' : ''}" data-range="7d">7d</button>
<button class="time-btn ${this.state.timeRange === 'all' ? 'active' : ''}" data-range="all">${t('components.deckgl.timeAll')}</button>
</div>
`, "legacy direct innerHTML migration"));
this.container.appendChild(slider);
slider.querySelectorAll('.time-btn').forEach(btn => {
btn.addEventListener('click', () => {
const range = (btn as HTMLElement).dataset.range as TimeRange;
this.setTimeRange(range);
});
});
}
private updateTimeSliderButtons(): void {
const slider = this.container.querySelector('.deckgl-time-slider');
if (!slider) return;
slider.querySelectorAll('.time-btn').forEach((btn) => {
const range = (btn as HTMLElement).dataset.range as TimeRange | undefined;
btn.classList.toggle('active', range === this.state.timeRange);
});
}
private createLayerToggles(): void {
const toggles = document.createElement('div');
toggles.className = 'layer-toggles deckgl-layer-toggles';
const layerDefs = getLayersForVariant((SITE_VARIANT || 'full') as MapVariant, 'flat');
const premiumUnlocked = hasPremiumAccess(getAuthState());
const layerConfig = layerDefs.map(def => ({
key: def.key,
label: resolveLayerLabel(def, t),
icon: def.icon,
premium: def.premium,
explainLabel: escapeHtml(`Explain ${resolveLayerLabel(def, t)} layer`),
hasExplanation: hasCuratedLayerExplanation(def.key),
}));
setTrustedHtml(toggles, trustedHtml(`
<div class="toggle-header">
<span>${t('components.deckgl.layersTitle')}</span>
<button class="layer-help-btn" aria-label="${t('components.deckgl.layerGuide')}">?</button>
<button class="toggle-collapse">▼</button>
</div>
<input type="text" class="layer-search" placeholder="${t('components.deckgl.layerSearch')}" autocomplete="off" spellcheck="false" />
<div class="toggle-list" style="max-height: 32vh; overflow-y: auto; scrollbar-width: thin;">
${layerConfig.map(({ key, label, icon, premium, explainLabel, hasExplanation }) => {
const isLocked = premium === 'locked' && !premiumUnlocked;
const isEnhanced = premium === 'enhanced' && !premiumUnlocked;
return `
<div class="layer-toggle-row" data-layer="${key}">
<label class="layer-toggle${isLocked ? ' layer-toggle-locked' : ''}" data-layer="${key}">
<input type="checkbox" ${this.state.layers[key as keyof MapLayers] ? 'checked' : ''}${isLocked ? ' disabled' : ''}>
<span class="toggle-icon">${icon}</span>
<span class="toggle-label">${label}${isLocked ? ' \uD83D\uDD12' : ''}${isEnhanced ? ' <span class="layer-pro-badge">PRO</span>' : ''}</span>
</label>
<button type="button" class="layer-explain-btn${hasExplanation ? ' has-layer-explanation' : ''}" data-layer="${key}" aria-label="${explainLabel}">i</button>
</div>`;
}).join('')}
</div>
`, "legacy direct innerHTML migration"));
const authorBadge = document.createElement('div');
authorBadge.className = 'map-author-badge';
authorBadge.textContent = '© Elie Habib · Someone™';
toggles.appendChild(authorBadge);
this.container.appendChild(toggles);
// Unlock premium layers when Pro status resolves. Pro can come from EITHER:
// 1. Clerk role === 'pro' (subscribeAuthState fires on Clerk changes)
// 2. Convex entitlement tier >= 1 (onEntitlementChange fires on Convex changes)
// Subscribing to BOTH covers Dodo subscribers whose Pro flag arrives via
// Convex (NOT via Clerk role). User-reported on energy.worldmonitor.app:
// "Pro Monthly" in settings UI but Resilience layer still showed the lock
// because subscribeAuthState alone never fires on Convex transitions.
//
// Whichever signal resolves Pro first does the unlock; the other becomes
// a no-op (early-return when not Pro; no-op .remove on already-removed
// class). queueMicrotask defers self-unsubscribe so both _unsubscribe*
// assignments complete before the unsubscribe runs. Greptile P2 fix:
// single helper instead of duplicated callback bodies.
const unlockIfPro = (): void => {
if (!hasPremiumAccess(getAuthState())) return;
toggles.querySelectorAll('.layer-toggle-locked').forEach(label => {
label.classList.remove('layer-toggle-locked');
const input = label.querySelector('input') as HTMLInputElement | null;
if (input) input.disabled = false;
const labelSpan = label.querySelector('.toggle-label');
if (labelSpan) labelSpan.textContent = labelSpan.textContent!.replace(' \uD83D\uDD12', '');
});
queueMicrotask(() => {
this._unsubscribeAuthState?.();
this._unsubscribeAuthState = null;
this._unsubscribeEntitlement?.();
this._unsubscribeEntitlement = null;
});
};
this._unsubscribeAuthState = subscribeAuthState(() => unlockIfPro());
this._unsubscribeEntitlement = onEntitlementChange(() => unlockIfPro());
// Bind toggle events
toggles.querySelectorAll('.layer-toggle input').forEach(input => {
input.addEventListener('change', () => {
const layer = (input as HTMLInputElement).closest('.layer-toggle')?.getAttribute('data-layer') as keyof MapLayers;
if (layer) {
const enabled = (input as HTMLInputElement).checked;
const prevRadar = this.state.layers.weather;
const prevCyber = this.state.layers.cyberThreats;
if (enabled && (layer === 'resilienceScore' || layer === 'ciiChoropleth')) {
const conflictingLayer = layer === 'resilienceScore' ? 'ciiChoropleth' : 'resilienceScore';
if (this.state.layers[conflictingLayer]) {
this.state.layers[conflictingLayer] = false;
const conflictingToggle = this.container.querySelector(`.layer-toggle[data-layer="${conflictingLayer}"] input`) as HTMLInputElement | null;
if (conflictingToggle) conflictingToggle.checked = false;
this.setLayerReady(conflictingLayer, false);
this.onLayerChange?.(conflictingLayer, false, 'programmatic');
}
}
this.state.layers[layer] = enabled;
if (layer === 'military' && !enabled) this.clearFlightTrails();
if (layer === 'flights') this.manageAircraftTimer(enabled);
if (this.state.layers.weather && !prevRadar) this.startWeatherRadar();
else if (!this.state.layers.weather && prevRadar) this.stopWeatherRadar();
if (this.state.layers.cyberThreats && !prevCyber && !this.aptGroupsLoaded) this.loadAptGroups();
this.render();
this.updateLegend();
this.onLayerChange?.(layer, enabled, 'user');
this.enforceLayerLimit();
}
});
});
this.enforceLayerLimit();
toggles.querySelectorAll('.layer-explain-btn').forEach(button => {
button.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
const layer = (button as HTMLElement).getAttribute('data-layer') as keyof MapLayers | null;
if (layer) this.showLayerExplanation(layer);
});
});
// Help button
const helpBtn = toggles.querySelector('.layer-help-btn');
helpBtn?.addEventListener('click', () => this.showLayerHelp());
// Collapse toggle
const collapseBtn = toggles.querySelector('.toggle-collapse');
const toggleList = toggles.querySelector('.toggle-list');
// Manual scroll: intercept wheel, prevent map zoom, scroll the list ourselves
if (toggleList) {
toggles.addEventListener('wheel', (e) => {
e.stopPropagation();
e.preventDefault();
toggleList.scrollTop += e.deltaY;
}, { passive: false });
toggles.addEventListener('touchmove', (e) => e.stopPropagation(), { passive: false });
}
bindLayerSearch(toggles);
const searchEl = toggles.querySelector('.layer-search') as HTMLElement | null;
collapseBtn?.addEventListener('click', () => {
toggleList?.classList.toggle('collapsed');
if (searchEl) searchEl.style.display = toggleList?.classList.contains('collapsed') ? 'none' : '';
if (collapseBtn) setTrustedHtml(collapseBtn, trustedHtml(toggleList?.classList.contains('collapsed') ? '▶' : '▼', "legacy direct innerHTML migration"));
});
}
private showLayerExplanation(layer: keyof MapLayers): void {
const existing = this.container.querySelector('.layer-explanation-popup') as HTMLElement | null;
if (existing?.dataset.layer === layer) {
existing.remove();
this.container.querySelector(`.layer-explain-btn[data-layer="${layer}"]`)?.classList.remove('active');
return;
}
existing?.remove();
this.container.querySelector('.layer-help-popup')?.remove();
this.container.querySelectorAll('.layer-explain-btn.active').forEach(btn => btn.classList.remove('active'));
const def = getLayersForVariant((SITE_VARIANT || 'full') as MapVariant, 'flat').find(item => item.key === layer);
const layerLabel = def ? resolveLayerLabel(def, t) : String(layer);
const explanation = getLayerExplanation(layer);
const popup = document.createElement('div');
popup.className = 'layer-explanation-popup';
popup.dataset.layer = layer;
setTrustedHtml(popup, trustedHtml(
renderLayerExplanationCard(layerLabel, explanation),
"static layer explanation metadata",
));
const closePopup = (): void => {
popup.remove();
this.container.querySelector(`.layer-explain-btn[data-layer="${layer}"]`)?.classList.remove('active');
};
popup.querySelector('.layer-explanation-close')?.addEventListener('click', closePopup);
this.container.appendChild(popup);
this.container.querySelector(`.layer-explain-btn[data-layer="${layer}"]`)?.classList.add('active');
}
/** Show layer help popup explaining each layer */
private showLayerHelp(): void {
const existing = this.container.querySelector('.layer-help-popup');
if (existing) {
existing.remove();
return;
}
this.container.querySelector('.layer-explanation-popup')?.remove();
this.container.querySelectorAll('.layer-explain-btn.active').forEach(btn => btn.classList.remove('active'));
const popup = document.createElement('div');
popup.className = 'layer-help-popup';
const label = (layerKey: string): string => t(`components.deckgl.layers.${layerKey}`).toUpperCase();
const staticLabel = (labelKey: string): string => t(`components.deckgl.layerHelp.labels.${labelKey}`).toUpperCase();
const helpItem = (layerLabel: string, descriptionKey: string): string =>
`<div class="layer-help-item"><span>${layerLabel}</span> ${t(`components.deckgl.layerHelp.descriptions.${descriptionKey}`)}</div>`;
const helpSection = (titleKey: string, items: string[], noteKey?: string): string => `
<div class="layer-help-section">
<div class="layer-help-title">${t(`components.deckgl.layerHelp.sections.${titleKey}`)}</div>
${items.join('')}
${noteKey ? `<div class="layer-help-note">${t(`components.deckgl.layerHelp.notes.${noteKey}`)}</div>` : ''}
</div>
`;
const helpHeader = `
<div class="layer-help-header">
<span>${t('components.deckgl.layerHelp.title')}</span>
<button class="layer-help-close" aria-label="Close">×</button>
</div>
`;
const techHelpContent = `
${helpHeader}
<div class="layer-help-content">
${helpSection('techEcosystem', [
helpItem(label('startupHubs'), 'techStartupHubs'),
helpItem(label('cloudRegions'), 'techCloudRegions'),
helpItem(label('techHQs'), 'techHQs'),
helpItem(label('accelerators'), 'techAccelerators'),
helpItem(label('techEvents'), 'techEvents'),
])}
${helpSection('infrastructure', [
helpItem(label('underseaCables'), 'infraCables'),
helpItem(label('aiDataCenters'), 'infraDatacenters'),
helpItem(label('internetOutages'), 'infraOutages'),
helpItem(label('cyberThreats'), 'techCyberThreats'),
])}
${helpSection('naturalEconomic', [
helpItem(label('naturalEvents'), 'naturalEventsTech'),
helpItem(label('fires'), 'techFires'),
helpItem(staticLabel('countries'), 'countriesOverlay'),
helpItem(label('dayNight'), 'dayNight'),
])}
</div>
`;
const financeHelpContent = `
${helpHeader}
<div class="layer-help-content">
${helpSection('financeCore', [
helpItem(label('stockExchanges'), 'financeExchanges'),
helpItem(label('financialCenters'), 'financeCenters'),
helpItem(label('centralBanks'), 'financeCentralBanks'),
helpItem(label('commodityHubs'), 'financeCommodityHubs'),
helpItem(label('gulfInvestments'), 'financeGulfInvestments'),
])}
${helpSection('infrastructureRisk', [
helpItem(label('underseaCables'), 'financeCables'),
helpItem(label('pipelines'), 'financePipelines'),
helpItem(label('internetOutages'), 'financeOutages'),
helpItem(label('cyberThreats'), 'financeCyberThreats'),
helpItem(label('tradeRoutes'), 'tradeRoutes'),
])}
${helpSection('macroContext', [
helpItem(label('economicCenters'), 'economicCenters'),
helpItem(label('strategicWaterways'), 'macroWaterways'),
helpItem(label('weatherAlerts'), 'weatherAlertsMarket'),
helpItem(label('naturalEvents'), 'naturalEventsMacro'),
helpItem(label('dayNight'), 'dayNight'),
])}
</div>
`;
const fullHelpContent = `
${helpHeader}
<div class="layer-help-content">
${helpSection('timeFilter', [
helpItem(staticLabel('timeRecent'), 'timeRecent'),
helpItem(staticLabel('timeExtended'), 'timeExtended'),
], 'timeAffects')}
${helpSection('geopolitical', [
helpItem(label('conflictZones'), 'geoConflicts'),
helpItem(label('intelHotspots'), 'geoHotspots'),
helpItem(staticLabel('sanctions'), 'geoSanctions'),
helpItem(label('protests'), 'geoProtests'),
helpItem(label('ucdpEvents'), 'geoUcdpEvents'),
helpItem(label('displacementFlows'), 'geoDisplacement'),
])}
${helpSection('militaryStrategic', [
helpItem(label('militaryBases'), 'militaryBases'),
helpItem(label('nuclearSites'), 'militaryNuclear'),
helpItem(label('gammaIrradiators'), 'militaryIrradiators'),
helpItem(label('militaryActivity'), 'militaryActivity'),
helpItem(label('spaceports'), 'militarySpaceports'),
])}
${helpSection('infrastructure', [
helpItem(label('underseaCables'), 'infraCablesFull'),
helpItem(label('pipelines'), 'infraPipelinesFull'),
helpItem(label('internetOutages'), 'infraOutages'),
helpItem(label('aiDataCenters'), 'infraDatacentersFull'),
helpItem(label('cyberThreats'), 'infraCyberThreats'),
])}
${helpSection('transport', [
helpItem(label('shipTraffic'), 'transportShipping'),
helpItem(label('tradeRoutes'), 'tradeRoutes'),
helpItem(label('flightDelays'), 'transportDelays'),
])}
${helpSection('naturalEconomic', [
helpItem(label('naturalEvents'), 'naturalEventsFull'),
helpItem(label('fires'), 'firesFull'),
helpItem(label('weatherAlerts'), 'weatherAlerts'),
helpItem(label('climateAnomalies'), 'climateAnomalies'),
helpItem(label('economicCenters'), 'economicCenters'),
helpItem(label('criticalMinerals'), 'mineralsFull'),
])}
${helpSection('overlays', [
helpItem(label('dayNight'), 'dayNight'),
helpItem(staticLabel('countries'), 'countriesOverlay'),
helpItem(label('strategicWaterways'), 'waterwaysLabels'),
])}
</div>
`;
setTrustedHtml(popup, trustedHtml(SITE_VARIANT === 'tech'
? techHelpContent
: SITE_VARIANT === 'finance'
? financeHelpContent
: fullHelpContent, "legacy direct innerHTML migration"));
popup.querySelector('.layer-help-close')?.addEventListener('click', () => popup.remove());
// Prevent scroll events from propagating to map
const content = popup.querySelector('.layer-help-content');
if (content) {
content.addEventListener('wheel', (e) => e.stopPropagation(), { passive: false });
content.addEventListener('touchmove', (e) => e.stopPropagation(), { passive: false });
}
// Close on click outside
setTimeout(() => {
const closeHandler = (e: MouseEvent) => {
if (!popup.contains(e.target as Node)) {
popup.remove();
document.removeEventListener('click', closeHandler);
}
};
document.addEventListener('click', closeHandler);
}, 100);
this.container.appendChild(popup);
}
private createLegend(): void {
const legend = document.createElement('div');
legend.className = 'map-legend deckgl-legend';
// SVG shapes for different marker types
const shapes = {
circle: (color: string) => `<svg width="12" height="12" viewBox="0 0 12 12"><circle cx="6" cy="6" r="5" fill="${color}"/></svg>`,
triangle: (color: string) => `<svg width="12" height="12" viewBox="0 0 12 12"><polygon points="6,1 11,10 1,10" fill="${color}"/></svg>`,
square: (color: string) => `<svg width="12" height="12" viewBox="0 0 12 12"><rect x="1" y="1" width="10" height="10" rx="1" fill="${color}"/></svg>`,
hexagon: (color: string) => `<svg width="12" height="12" viewBox="0 0 12 12"><polygon points="6,1 10.5,3.5 10.5,8.5 6,11 1.5,8.5 1.5,3.5" fill="${color}"/></svg>`,
};
const isLight = getCurrentTheme() === 'light';
const resilienceLegendItems: { shape: string; label: string; layerKey: keyof MapLayers }[] = [
{ shape: shapes.square('rgb(239, 68, 68)'), label: 'Resilience: Very Low', layerKey: 'resilienceScore' },
{ shape: shapes.square('rgb(249, 115, 22)'), label: 'Resilience: Low', layerKey: 'resilienceScore' },
{ shape: shapes.square('rgb(234, 179, 8)'), label: 'Resilience: Moderate', layerKey: 'resilienceScore' },
{ shape: shapes.square('rgb(132, 204, 22)'), label: 'Resilience: High', layerKey: 'resilienceScore' },
{ shape: shapes.square('rgb(34, 197, 94)'), label: 'Resilience: Very High', layerKey: 'resilienceScore' },
];
const legendItems: { shape: string; label: string; layerKey: keyof MapLayers }[] = SITE_VARIANT === 'tech'
? [
{ shape: shapes.circle(isLight ? 'rgb(22, 163, 74)' : 'rgb(0, 255, 150)'), label: t('components.deckgl.legend.startupHub'), layerKey: 'startupHubs' },
{ shape: shapes.circle('rgb(100, 200, 255)'), label: t('components.deckgl.legend.techHQ'), layerKey: 'techHQs' },
{ shape: shapes.circle(isLight ? 'rgb(180, 120, 0)' : 'rgb(255, 200, 0)'), label: t('components.deckgl.legend.accelerator'), layerKey: 'accelerators' },
{ shape: shapes.circle('rgb(150, 100, 255)'), label: t('components.deckgl.legend.cloudRegion'), layerKey: 'cloudRegions' },
{ shape: shapes.square('rgb(136, 68, 255)'), label: t('components.deckgl.legend.datacenter'), layerKey: 'datacenters' },
{ shape: shapes.circle('rgb(231, 76, 60)'), label: t('components.deckgl.legend.diseaseAlert'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(230, 126, 34)'), label: t('components.deckgl.legend.diseaseWarning'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(241, 196, 15)'), label: t('components.deckgl.legend.diseaseWatch'), layerKey: 'diseaseOutbreaks' },
...resilienceLegendItems,
]
: SITE_VARIANT === 'finance'
? [
{ shape: shapes.circle('rgb(255, 215, 80)'), label: t('components.deckgl.legend.stockExchange'), layerKey: 'stockExchanges' },
{ shape: shapes.circle('rgb(0, 220, 150)'), label: t('components.deckgl.legend.financialCenter'), layerKey: 'financialCenters' },
{ shape: shapes.hexagon('rgb(255, 210, 80)'), label: t('components.deckgl.legend.centralBank'), layerKey: 'centralBanks' },
{ shape: shapes.square('rgb(255, 150, 80)'), label: t('components.deckgl.legend.commodityHub'), layerKey: 'commodityHubs' },
{ shape: shapes.triangle('rgb(80, 170, 255)'), label: t('components.deckgl.legend.waterway'), layerKey: 'waterways' },
{ shape: shapes.circle('rgb(231, 76, 60)'), label: t('components.deckgl.legend.diseaseAlert'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(230, 126, 34)'), label: t('components.deckgl.legend.diseaseWarning'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(241, 196, 15)'), label: t('components.deckgl.legend.diseaseWatch'), layerKey: 'diseaseOutbreaks' },
...resilienceLegendItems,
]
: SITE_VARIANT === 'happy'
? [
{ shape: shapes.circle('rgb(34, 197, 94)'), label: 'Positive Event', layerKey: 'positiveEvents' },
{ shape: shapes.circle('rgb(234, 179, 8)'), label: 'Breakthrough', layerKey: 'positiveEvents' },
{ shape: shapes.circle('rgb(74, 222, 128)'), label: 'Act of Kindness', layerKey: 'kindness' },
{ shape: shapes.circle('rgb(255, 100, 50)'), label: 'Natural Event', layerKey: 'natural' },
{ shape: shapes.square('rgb(34, 180, 100)'), label: 'Happy Country', layerKey: 'happiness' },
{ shape: shapes.circle('rgb(74, 222, 128)'), label: 'Species Recovery Zone', layerKey: 'speciesRecovery' },
{ shape: shapes.circle('rgb(255, 200, 50)'), label: 'Renewable Installation', layerKey: 'renewableInstallations' },
{ shape: shapes.circle('rgb(160, 100, 255)'), label: t('components.deckgl.legend.aircraft'), layerKey: 'flights' },
{ shape: shapes.circle('rgb(231, 76, 60)'), label: t('components.deckgl.legend.diseaseAlert'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(230, 126, 34)'), label: t('components.deckgl.legend.diseaseWarning'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(241, 196, 15)'), label: t('components.deckgl.legend.diseaseWatch'), layerKey: 'diseaseOutbreaks' },
...resilienceLegendItems,
]
: SITE_VARIANT === 'commodity'
? [
{ shape: shapes.hexagon(isLight ? 'rgb(180, 120, 0)' : 'rgb(255, 200, 0)'), label: t('components.deckgl.legend.commodityHub'), layerKey: 'commodityHubs' },
{ shape: shapes.circle('rgb(180, 80, 80)'), label: t('components.deckgl.legend.miningSite'), layerKey: 'miningSites' },
{ shape: shapes.square('rgb(80, 160, 220)'), label: t('components.deckgl.legend.commodityPort'), layerKey: 'commodityPorts' },
{ shape: shapes.circle('rgb(255, 150, 50)'), label: t('components.deckgl.legend.pipeline'), layerKey: 'pipelines' },
{ shape: shapes.triangle('rgb(80, 170, 255)'), label: t('components.deckgl.legend.waterway'), layerKey: 'waterways' },
{ shape: shapes.circle('rgb(200, 100, 255)'), label: t('components.deckgl.legend.processingPlant'), layerKey: 'processingPlants' },
{ shape: shapes.circle('rgb(231, 76, 60)'), label: t('components.deckgl.legend.diseaseAlert'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(230, 126, 34)'), label: t('components.deckgl.legend.diseaseWarning'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(241, 196, 15)'), label: t('components.deckgl.legend.diseaseWatch'), layerKey: 'diseaseOutbreaks' },
...resilienceLegendItems,
]
: [
{ shape: shapes.circle('rgb(255, 68, 68)'), label: t('components.deckgl.legend.highAlert'), layerKey: 'hotspots' },
{ shape: shapes.circle('rgb(255, 165, 0)'), label: t('components.deckgl.legend.elevated'), layerKey: 'hotspots' },
{ shape: shapes.circle(isLight ? 'rgb(180, 120, 0)' : 'rgb(255, 255, 0)'), label: t('components.deckgl.legend.monitoring'), layerKey: 'hotspots' },
{ shape: shapes.circle('rgb(255, 100, 100)'), label: t('components.deckgl.legend.conflict'), layerKey: 'conflicts' },
{ shape: shapes.triangle('rgb(68, 136, 255)'), label: t('components.deckgl.legend.base'), layerKey: 'bases' },
{ shape: shapes.hexagon(isLight ? 'rgb(180, 120, 0)' : 'rgb(255, 220, 0)'), label: t('components.deckgl.legend.nuclear'), layerKey: 'nuclear' },
{ shape: shapes.square('rgb(136, 68, 255)'), label: t('components.deckgl.legend.datacenter'), layerKey: 'datacenters' },
{ shape: shapes.circle('rgb(160, 100, 255)'), label: t('components.deckgl.legend.aircraft'), layerKey: 'flights' },
{ shape: shapes.circle('rgb(231, 76, 60)'), label: t('components.deckgl.legend.diseaseAlert'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(230, 126, 34)'), label: t('components.deckgl.legend.diseaseWarning'), layerKey: 'diseaseOutbreaks' },
{ shape: shapes.circle('rgb(241, 196, 15)'), label: t('components.deckgl.legend.diseaseWatch'), layerKey: 'diseaseOutbreaks' },
...resilienceLegendItems,
];
setTrustedHtml(legend, trustedHtml(`
<span class="legend-label-title">${t('components.deckgl.legend.title')}</span>
${legendItems.map(({ shape, label, layerKey }) => `<span class="legend-item" data-layer="${layerKey}">${shape}<span class="legend-label">${label}</span></span>`).join('')}
`, "legacy direct innerHTML migration"));
// CII choropleth gradient legend (shown when layer is active)
const ciiLegend = document.createElement('div');
ciiLegend.className = 'cii-choropleth-legend';
ciiLegend.id = 'ciiChoroplethLegend';
ciiLegend.style.display = this.state.layers.ciiChoropleth ? 'block' : 'none';
setTrustedHtml(ciiLegend, trustedHtml(`
<span class="legend-label-title" style="font-size:9px;letter-spacing:0.5px;">CII SCALE</span>
<div style="display:flex;align-items:center;gap:2px;margin-top:2px;">
<div style="width:100%;height:8px;border-radius:3px;background:linear-gradient(to right,#28b33e,#dcc030,#e87425,#dc2626,#7f1d1d);"></div>
</div>
<div style="display:flex;justify-content:space-between;font-size:8px;opacity:0.7;margin-top:1px;">
<span>0</span><span>31</span><span>51</span><span>66</span><span>81</span><span>100</span>
</div>
`, "legacy direct innerHTML migration"));
legend.appendChild(ciiLegend);
this.container.appendChild(legend);
this.updateLegend();
}
private updateLegend(): void {
this.container.querySelectorAll<HTMLElement>('.legend-item[data-layer]').forEach(item => {
const layerKey = item.dataset.layer;
if (!layerKey || !(layerKey in this.state.layers)) return;
item.style.display = this.state.layers[layerKey as keyof MapLayers] ? '' : 'none';
});
const ciiLegend = this.container.querySelector<HTMLElement>('#ciiChoroplethLegend');
if (ciiLegend) {
ciiLegend.style.display = this.state.layers.ciiChoropleth ? 'block' : 'none';
}
}
// Public API methods (matching MapComponent interface)
public render(): void {
if (this.renderPaused) {
this.renderPending = true;
return;
}
if (this.renderRafId !== null) {
cancelAnimationFrame(this.renderRafId);
}
this.renderRafId = requestAnimationFrame(() => {
this.renderRafId = null;
this.updateLayers();
});
}
public setRenderPaused(paused: boolean): void {
if (this.renderPaused === paused) return;
this.renderPaused = paused;
if (paused) {
if (this.renderRafId !== null) {
cancelAnimationFrame(this.renderRafId);
this.renderRafId = null;
this.renderPending = true;
}
this.stopPulseAnimation();
this.stopDayNightTimer();
this.stopTradeAnimation();
return;
}
this.syncPulseAnimation();
if (this.state.layers.dayNight) this.startDayNightTimer();
if (this.state.layers.tradeRoutes) this.startTradeAnimation();
if (!paused && this.renderPending) {
this.renderPending = false;
this.render();
}
}
private updateLayers(deferred = false): void {
if (this.renderPaused || this.webglLost || !this.maplibreMap) return;
const startTime = performance.now();
let jsBuild = 0;
let layerCount = 0;
try {
const buildStart = performance.now();
// Immediate pass defers heavy data (deferHeavy=true); the gate's deferred
// pass (deferred=true) commits the real heavy data (#4558).
const built = this.buildLayers(!deferred);
jsBuild = performance.now() - buildStart;
layerCount = built.length;
this.deckOverlay?.setProps({ layers: built });
} catch { /* map may be mid-teardown (null.getProjection) */ }
if (import.meta.env.DEV) {
// Attribute a slow frame to our JS build vs deck.gl's commit (#4558).
// Sample total BEFORE triggerRepaint() so the deckCommit bucket isolates
// setProps tessellation and doesn't absorb the repaint-schedule cost.
const summary = summarizeRenderTiming({ total: performance.now() - startTime, jsBuild, layerCount });
if (summary.overBudget) console.warn(formatRenderTiming(summary));
}
this.maplibreMap.triggerRepaint();
this.updateZoomHints();
}
private updateZoomHints(): void {
const toggleList = this.container.querySelector('.deckgl-layer-toggles .toggle-list');
if (!toggleList) return;
for (const [key, enabled] of Object.entries(this.state.layers)) {
const toggle = toggleList.querySelector(`.layer-toggle[data-layer="${key}"]`) as HTMLElement | null;
if (!toggle) continue;
const zoomHidden = !!enabled && !this.isLayerVisible(key as keyof MapLayers);
toggle.classList.toggle('zoom-hidden', zoomHidden);
}
}
public setView(view: DeckMapView, zoom?: number): void {
const preset = VIEW_PRESETS[view];
if (!preset) return;
this.state.view = view;
// Eagerly write target zoom+center so getState()/getCenter() return the
// correct destination before moveend fires. Without this a 250ms URL sync
// reads the old cached zoom or an intermediate animated center and
// overwrites URL params (e.g. ?view=mena&zoom=4 → wrong coords).
this.state.zoom = zoom ?? preset.zoom;
this.pendingCenter = { lat: preset.latitude, lon: preset.longitude };
if (this.maplibreMap) {
this.maplibreMap.flyTo({
center: [preset.longitude, preset.latitude],
zoom: this.state.zoom,
duration: 1000,
});
}
const viewSelect = this.container.querySelector('.view-select') as HTMLSelectElement;
if (viewSelect) viewSelect.value = view;
this.onStateChange?.(this.getState());
}
public setZoom(zoom: number): void {
this.state.zoom = zoom;
if (this.maplibreMap) {
this.maplibreMap.setZoom(zoom);
}
}
public setCenter(lat: number, lon: number, zoom?: number): void {
if (this.maplibreMap) {
this.maplibreMap.flyTo({
center: [lon, lat],
...(zoom != null && { zoom }),
duration: 500,
});
}
}
public fitCountry(code: string): void {
const bbox = getCountryBbox(code);
if (!bbox || !this.maplibreMap) return;
const [minLon, minLat, maxLon, maxLat] = bbox;
this.maplibreMap.fitBounds([[minLon, minLat], [maxLon, maxLat]], {
padding: 40,
duration: 800,
maxZoom: 8,
});
}
public getCenter(): { lat: number; lon: number } | null {
if (this.pendingCenter) return this.pendingCenter;
if (this.maplibreMap) {
const center = this.maplibreMap.getCenter();
return { lat: center.lat, lon: center.lng };
}
return null;
}
public getBbox(): string | null {
if (!this.maplibreMap) return null;
const b = this.maplibreMap.getBounds();
return `${b.getWest().toFixed(4)},${b.getSouth().toFixed(4)},${b.getEast().toFixed(4)},${b.getNorth().toFixed(4)}`;
}
public setTimeRange(range: TimeRange): void {
this.state.timeRange = range;
this.rebuildProtestSupercluster();
this.onTimeRangeChange?.(range);
this.updateTimeSliderButtons();
this.render(); // Debounced
}
public getTimeRange(): TimeRange {
return this.state.timeRange;
}
public setLayers(layers: MapLayers): void {
const prevRadar = this.state.layers.weather;
const prevCyber = this.state.layers.cyberThreats;
this.state.layers = normalizeExclusiveChoropleths(layers, this.state.layers);
if (!this.state.layers.military) this.clearFlightTrails();
this.manageAircraftTimer(this.state.layers.flights);
if (this.state.layers.weather && !prevRadar) this.startWeatherRadar();
else if (!this.state.layers.weather && prevRadar) this.stopWeatherRadar();
if (this.state.layers.cyberThreats && !prevCyber && !this.aptGroupsLoaded) this.loadAptGroups();
this.render(); // Debounced
this.updateLegend();
Object.entries(this.state.layers).forEach(([key, value]) => {
const toggle = this.container.querySelector(`.layer-toggle[data-layer="${key}"] input`) as HTMLInputElement;
if (toggle) toggle.checked = value;
});
}
public getState(): DeckMapState {
return {
...this.state,
pan: { ...this.state.pan },
layers: { ...this.state.layers },
};
}
// Zoom controls - public for external access
public zoomIn(): void {
if (this.maplibreMap) {
this.maplibreMap.zoomIn();
}
}
public zoomOut(): void {
if (this.maplibreMap) {
this.maplibreMap.zoomOut();
}
}
private resetView(): void {
this.setView('global');
}
private createUcdpEventsLayer(events: UcdpGeoEvent[]): ScatterplotLayer<UcdpGeoEvent> {
return new ScatterplotLayer<UcdpGeoEvent>({
id: 'ucdp-events-layer',
data: events,
getPosition: (d) => [d.longitude, d.latitude],
getRadius: (d) => Math.max(4000, Math.sqrt(d.deaths_best || 1) * 3000),
getFillColor: (d) => {
switch (d.type_of_violence) {
case 'state-based': return COLORS.ucdpStateBased;
case 'non-state': return COLORS.ucdpNonState;
case 'one-sided': return COLORS.ucdpOneSided;
default: return COLORS.ucdpStateBased;
}
},
radiusMinPixels: 3,
radiusMaxPixels: 20,
pickable: false,
});
}
private createDisplacementArcsLayer(): ArcLayer<DisplacementFlow> {
const withCoords = this.displacementFlows.filter(f => f.originLat != null && f.asylumLat != null);
const top50 = withCoords.slice(0, 50);
const maxCount = Math.max(1, ...top50.map(f => f.refugees));
return new ArcLayer<DisplacementFlow>({
id: 'displacement-arcs-layer',
data: top50,
getSourcePosition: (d) => [d.originLon!, d.originLat!],
getTargetPosition: (d) => [d.asylumLon!, d.asylumLat!],
getSourceColor: getCurrentTheme() === 'light' ? [50, 80, 180, 220] : [100, 150, 255, 180],
getTargetColor: getCurrentTheme() === 'light' ? [20, 150, 100, 220] : [100, 255, 200, 180],
getWidth: (d) => Math.max(1, (d.refugees / maxCount) * 8),
widthMinPixels: 1,
widthMaxPixels: 8,
pickable: false,
});
}
private createClimateHeatmapLayer(): ScatterplotLayer<ClimateAnomaly> {
return new ScatterplotLayer<ClimateAnomaly>({
id: 'climate-heatmap-layer',
data: this.climateAnomalies,
getPosition: (d) => [d.lon, d.lat],
getRadius: (d) => 14_000 + Math.min(80_000, (Math.abs(d.tempDelta) + Math.abs(d.precipDelta) * 0.1) * 18_000),
getFillColor: (d) => {
const weight = Math.abs(d.tempDelta) + Math.abs(d.precipDelta) * 0.1;
if (weight >= 4) return [255, 50, 50, 120] as [number, number, number, number];
if (weight >= 2.5) return [255, 140, 50, 110] as [number, number, number, number];
if (weight >= 1.25) return [255, 220, 80, 95] as [number, number, number, number];
return [100, 200, 255, 85] as [number, number, number, number];
},
radiusMinPixels: 12,
radiusMaxPixels: 72,
stroked: false,
pickable: false,
});
}
private createTradeRoutesLayer(): ArcLayer<TradeRouteSegment> {
const active: [number, number, number, number] = getCurrentTheme() === 'light' ? [30, 100, 180, 200] : [100, 200, 255, 160];
const disrupted: [number, number, number, number] = getCurrentTheme() === 'light' ? [200, 40, 40, 220] : [255, 80, 80, 200];
const highRisk: [number, number, number, number] = getCurrentTheme() === 'light' ? [200, 140, 20, 200] : [255, 180, 50, 180];
const scenario: [number, number, number, number] = getCurrentTheme() === 'light' ? [220, 100, 20, 230] : [255, 140, 50, 210];
const colorFor = (status: string): [number, number, number, number] =>
status === 'disrupted' ? disrupted : status === 'high_risk' ? highRisk : active;
// When a scenario is active, override colors for routes that transit disrupted chokepoints.
// ROUTE_WAYPOINTS_MAP is module-level so getColor() is O(1) per segment instead of O(n) per frame.
const scenarioDisrupted = this.scenarioState
? new Set(this.scenarioState.disruptedChokepointIds)
: null;
const hlActive = this.highlightedRouteIds.size > 0;
const hlIds = this.highlightedRouteIds;
const dimColor = (c: [number, number, number, number]): [number, number, number, number] =>
[c[0], c[1], c[2], 40];
const getColor = (d: TradeRouteSegment): [number, number, number, number] => {
let base: [number, number, number, number];
if (scenarioDisrupted && scenarioDisrupted.size > 0) {
const waypoints = ROUTE_WAYPOINTS_MAP.get(d.routeId);
if (waypoints && waypoints.some(wp => scenarioDisrupted.has(wp))) {
base = scenario;
} else if (!hasPremiumAccess(getAuthState())) {
base = active;
} else {
base = colorFor(d.status);
}
} else if (!hasPremiumAccess(getAuthState())) {
base = active;
} else {
base = colorFor(d.status);
}
if (hlActive && !hlIds.has(d.routeId)) return dimColor(base);
return base;
};
return new ArcLayer<TradeRouteSegment>({
id: 'trade-routes-layer',
data: this.tradeRouteSegments,
getSourcePosition: (d) => d.sourcePosition,
getTargetPosition: (d) => d.targetPosition,
getSourceColor: getColor,
getTargetColor: getColor,
getWidth: (d) => {
if (hlActive && hlIds.has(d.routeId)) return 6;
return d.category === 'energy' ? 3 : 2;
},
widthMinPixels: 1,
widthMaxPixels: 8,
greatCircle: true,
pickable: true,
});
}
private buildTradeTrips(): void {
const activeColor: [number, number, number, number] = [100, 200, 255, 140];
const disruptedColor: [number, number, number, number] = [255, 80, 80, 180];
const highRiskColor: [number, number, number, number] = [255, 180, 50, 160];
const scenarioColor: [number, number, number, number] = [255, 140, 50, 170];
const isPremium = hasPremiumAccess(getAuthState());
const scenarioDisrupted = this.scenarioState
? new Set(this.scenarioState.disruptedChokepointIds)
: null;
const hlActive = this.highlightedRouteIds.size > 0;
const hlIds = this.highlightedRouteIds;
const colorForRoute = (routeId: string, status: string): [number, number, number, number] => {
let base: [number, number, number, number];
if (scenarioDisrupted && scenarioDisrupted.size > 0) {
const waypoints = ROUTE_WAYPOINTS_MAP.get(routeId);
if (waypoints && waypoints.some(wp => scenarioDisrupted.has(wp))) {
base = scenarioColor;
} else if (!isPremium) {
base = activeColor;
} else {
base = status === 'disrupted' ? disruptedColor : status === 'high_risk' ? highRiskColor : activeColor;
}
} else if (!isPremium) {
base = activeColor;
} else {
base = status === 'disrupted' ? disruptedColor : status === 'high_risk' ? highRiskColor : activeColor;
}
if (hlActive && !hlIds.has(routeId)) return [base[0], base[1], base[2], 40];
return base;
};
const widthFor = (category: string): number =>
category === 'energy' ? 4 : category === 'container' ? 2.5 : 2;
const routeGroups = new Map<string, TradeRouteSegment[]>();
for (const seg of this.tradeRouteSegments) {
const existing = routeGroups.get(seg.routeId);
if (existing) existing.push(seg);
else routeGroups.set(seg.routeId, [seg]);
}
const trips: TripData[] = [];
for (const [, segments] of routeGroups) {
const sorted = segments.sort((a, b) => a.segmentIndex - b.segmentIndex);
const fullPath: [number, number][] = [];
for (let i = 0; i < sorted.length; i++) {
const seg = sorted[i]!;
const arcPoints = interpolateGreatCircle(
seg.sourcePosition,
seg.targetPosition,
TRADE_GC_INTERPOLATION_POINTS,
);
if (i === 0) {
fullPath.push(...arcPoints);
} else {
fullPath.push(...arcPoints.slice(1));
}
}
const first = sorted[0]!;
trips.push({
path: fullPath,
phase: stableTradeRoutePhase(first.routeId),
color: colorForRoute(first.routeId, first.status),
width: widthFor(first.category),
});
}
this.tradeTrips = trips;
}
private createTradeRouteTripsLayer(): ScatterplotLayer<TripData> | null {
if (this.prefersReducedTradeMotion()) return null;
if (this.tradeTrips.length === 0) this.buildTradeTrips();
return new ScatterplotLayer<TripData>({
id: 'trade-route-trips-layer',
data: this.tradeTrips,
getPosition: (d: TripData) => positionAlongPath(
d.path,
((this.tradeAnimationTime + d.phase) % TRADE_ANIMATION_CYCLE) / TRADE_ANIMATION_CYCLE,
),
// deck.gl preserves layer state by id across new layer instances; the
// accessor closes over animation time, so this trigger keeps positions live.
updateTriggers: { getPosition: [this.tradeAnimationTime] },
getFillColor: (d: TripData) => d.color,
getRadius: (d: TripData) => d.width * 20_000,
radiusMinPixels: 3,
radiusMaxPixels: 9,
pickable: false,
});
}
private prefersReducedTradeMotion(): boolean {
return this.tradeReducedMotionMedia?.matches ?? window.matchMedia(PREFERS_REDUCED_MOTION_QUERY).matches;
}
private startTradeAnimation(): void {
if (this.tradeAnimationFrame !== null) return;
if (this.renderPaused || this.prefersReducedTradeMotion()) return;
let lastTime = performance.now();
const animate = (now: number) => {
if (this.destroyed) {
this.tradeAnimationFrame = null;
return;
}
const delta = Math.min(now - lastTime, TRADE_ANIMATION_MAX_DELTA_MS);
lastTime = now;
this.tradeAnimationTime = (this.tradeAnimationTime + delta * TRADE_ANIMATION_SPEED) % TRADE_ANIMATION_CYCLE;
this.tradeAnimationFrame = requestAnimationFrame(animate);
this.tradeAnimationFrameCount++;
// Skip this decorative rebuild when input is queued so the pending
// interaction handler runs sooner (#5042 U2). Frame-predictive and
// discrete-only; graceful no-op where isInputPending is unsupported.
if (shouldRenderTradeAnimationFrame(this.tradeAnimationFrameCount, isInputPending)) this.render();
};
this.tradeAnimationFrame = requestAnimationFrame(animate);
}
private stopTradeAnimation(): void {
if (this.tradeAnimationFrame !== null) {
cancelAnimationFrame(this.tradeAnimationFrame);
this.tradeAnimationFrame = null;
}
// Reset so the every-other-frame render gate restarts at a deterministic
// parity; otherwise a stop/start cycle can delay the first repaint a frame.
this.tradeAnimationFrameCount = 0;
}
private createTradeChokepointsLayer(): ScatterplotLayer {
const routeWaypointIds = new Set<string>();
for (const seg of this.tradeRouteSegments) {
const waypoints = ROUTE_WAYPOINTS_MAP.get(seg.routeId);
if (waypoints) for (const wp of waypoints) routeWaypointIds.add(wp);
}
const chokepoints = STRATEGIC_WATERWAYS.filter(w => routeWaypointIds.has(w.id));
const isLight = getCurrentTheme() === 'light';
return new ScatterplotLayer({
id: 'trade-chokepoints-layer',
data: chokepoints,
getPosition: (d: { lon: number; lat: number }) => [d.lon, d.lat],
getFillColor: isLight ? [200, 140, 20, 200] : [255, 180, 50, 180],
getLineColor: isLight ? [100, 70, 10, 255] : [255, 220, 120, 255],
getRadius: 30000,
stroked: true,
lineWidthMinPixels: 1,
radiusMinPixels: 4,
radiusMaxPixels: 12,
pickable: false,
});
}
private rebuildHighlightedMarkers(): void {
if (this.highlightedRouteIds.size === 0) { this.highlightedMarkers = []; return; }
const cpIds = new Set<string>();
for (const routeId of this.highlightedRouteIds) {
const waypoints = ROUTE_WAYPOINTS_MAP.get(routeId);
if (waypoints) for (const wp of waypoints) cpIds.add(wp);
}
this.highlightedMarkers = STRATEGIC_WATERWAYS
.filter(w => cpIds.has(w.id))
.map(w => {
const score = this.storedChokepointData?.chokepoints?.find(cp => cp.id === w.id)?.disruptionScore ?? 0;
return { id: w.id, lon: w.lon, lat: w.lat, name: w.name, score };
});
}
private createHighlightedChokepointMarkers(): ScatterplotLayer | null {
if (this.highlightedMarkers.length === 0) return null;
const pulse = Math.sin(this.tradeAnimationTime * CHOKEPOINT_PULSE_FREQ) * CHOKEPOINT_PULSE_AMP + 1;
return new ScatterplotLayer({
id: 'highlighted-chokepoint-markers',
data: this.highlightedMarkers,
getPosition: (d: HighlightedMarker) => [d.lon, d.lat],
getRadius: (d: HighlightedMarker) => (d.score >= 70 ? 12000 : d.score > 30 ? 10000 : 8000) * pulse,
getFillColor: (d: HighlightedMarker) => d.score >= 70
? [255, 60, 60, 180] as [number, number, number, number]
: d.score > 30
? [255, 180, 50, 160] as [number, number, number, number]
: [60, 200, 120, 140] as [number, number, number, number],
radiusUnits: 'meters' as const,
pickable: false,
stroked: true,
getLineColor: (d: HighlightedMarker) => d.score >= 70
? [255, 80, 80, 255] as [number, number, number, number]
: d.score > 30
? [255, 200, 80, 255] as [number, number, number, number]
: [80, 220, 140, 255] as [number, number, number, number],
getLineWidth: 2,
lineWidthUnits: 'pixels' as const,
updateTriggers: {
getRadius: [this.tradeAnimationTime],
getFillColor: [this.storedChokepointData],
},
});
}
private createBypassArcsLayer(): ArcLayer | null {
if (this.bypassArcData.length === 0) return null;
return new ArcLayer({
id: 'bypass-arcs-layer',
data: this.bypassArcData,
getSourcePosition: (d: BypassArcDatum) => d.source,
getTargetPosition: (d: BypassArcDatum) => d.target,
getSourceColor: [60, 200, 120, 160],
getTargetColor: [60, 200, 120, 160],
getWidth: 3,
widthMinPixels: 2,
greatCircle: true,
pickable: false,
});
}
private computeNightPolygon(): [number, number][] {
const now = new Date();
const JD = now.getTime() / 86400000 + 2440587.5;
const D = JD - 2451545.0; // Days since J2000.0
// Solar mean anomaly (radians)
const g = ((357.529 + 0.98560028 * D) % 360) * Math.PI / 180;
// Solar ecliptic longitude (degrees)
const q = (280.459 + 0.98564736 * D) % 360;
const L = q + 1.915 * Math.sin(g) + 0.020 * Math.sin(2 * g);
const LRad = L * Math.PI / 180;
// Obliquity of ecliptic (radians)
const eRad = (23.439 - 0.00000036 * D) * Math.PI / 180;
// Solar declination (radians)
const decl = Math.asin(Math.sin(eRad) * Math.sin(LRad));
// Solar right ascension (radians)
const RA = Math.atan2(Math.cos(eRad) * Math.sin(LRad), Math.cos(LRad));
// Greenwich Mean Sidereal Time (degrees)
const GMST = ((18.697374558 + 24.06570982441908 * D) % 24) * 15;
// Sub-solar longitude (degrees, normalized to [-180, 180])
let sunLng = RA * 180 / Math.PI - GMST;
sunLng = ((sunLng % 360) + 540) % 360 - 180;
// Trace terminator line (1° steps for smooth curve at high zoom)
const tanDecl = Math.tan(decl);
const points: [number, number][] = [];
// Near equinox (|tanDecl| ≈ 0), the terminator is nearly a great circle
// through the poles — use a vertical line at the subsolar meridian ±90°
if (Math.abs(tanDecl) < 1e-6) {
for (let lat = -90; lat <= 90; lat += 1) {
points.push([sunLng + 90, lat]);
}
for (let lat = 90; lat >= -90; lat -= 1) {
points.push([sunLng - 90, lat]);
}
return points;
}
for (let lng = -180; lng <= 180; lng += 1) {
const ha = (lng - sunLng) * Math.PI / 180;
const lat = Math.atan(-Math.cos(ha) / tanDecl) * 180 / Math.PI;
points.push([lng, lat]);
}
// Close polygon around the dark pole
const darkPoleLat = decl > 0 ? -90 : 90;
points.push([180, darkPoleLat]);
points.push([-180, darkPoleLat]);
return points;
}
private createDayNightLayer(): PolygonLayer {
const nightPolygon = this.cachedNightPolygon ?? (this.cachedNightPolygon = this.computeNightPolygon());
const isLight = getCurrentTheme() === 'light';
return new PolygonLayer({
id: 'day-night-layer',
data: [{ polygon: nightPolygon }],
getPolygon: (d: { polygon: [number, number][] }) => d.polygon,
getFillColor: isLight ? [0, 0, 40, 35] : [0, 0, 20, 55],
filled: true,
stroked: true,
getLineColor: isLight ? [100, 100, 100, 40] : [200, 200, 255, 25],
getLineWidth: 1,
lineWidthUnits: 'pixels' as const,
pickable: false,
});
}
private createChinaCorridorSelectionLayers(
overlay: ChinaCorridorOverlayProjection,
): [PolygonLayer, ScatterplotLayer] {
return [
new PolygonLayer({
id: `china-corridor-boundary-${overlay.id}`,
data: [{ polygon: overlay.polygon }],
getPolygon: (item: { polygon: [number, number][] }) => item.polygon,
filled: true,
stroked: true,
getFillColor: [40, 165, 220, 35],
getLineColor: [40, 190, 240, 230],
getLineWidth: 2,
lineWidthUnits: 'pixels' as const,
pickable: false,
}),
new ScatterplotLayer({
id: `china-corridor-nodes-${overlay.id}`,
data: overlay.nodes,
getPosition: (item: { position: [number, number] }) => item.position,
getFillColor: [255, 190, 70, 220],
getLineColor: [20, 30, 40, 230],
getRadius: 5,
radiusUnits: 'pixels' as const,
lineWidthUnits: 'pixels' as const,
getLineWidth: 1,
stroked: true,
pickable: false,
}),
];
}
// Data setters - all use render() for debouncing
public setEarthquakes(earthquakes: Earthquake[]): void {
this.earthquakes = earthquakes;
this.render();
}
public setWeatherAlerts(alerts: WeatherAlert[]): void {
this.weatherAlerts = alerts;
this.render();
}
public setImageryScenes(scenes: ImageryScene[]): void {
this.imageryScenes = scenes;
this.render();
}
public setOutages(outages: InternetOutage[]): void {
this.outages = outages;
this.render();
}
public setTrafficAnomalies(anomalies: ProtoTrafficAnomaly[]): void {
this.trafficAnomalies = anomalies;
this.render();
}
public setDdosLocations(hits: DdosLocationHit[]): void {
this.ddosLocations = hits;
this.render();
}
public setCyberThreats(threats: CyberThreat[]): void {
this.cyberThreats = threats;
this.render();
}
public setIranEvents(events: IranEvent[]): void {
this.iranEvents = events;
this.render();
}
public setAisData(disruptions: AisDisruptionEvent[], density: AisDensityZone[]): void {
this.aisDisruptions = disruptions;
this.aisDensity = density;
this.render();
}
public setCableActivity(advisories: CableAdvisory[], repairShips: RepairShip[]): void {
this.cableAdvisories = advisories;
this.repairShips = repairShips;
this.render();
}
public setCableHealth(healthMap: Record<string, CableHealthRecord>): void {
this.healthByCableId = healthMap;
this.layerCache.delete('cables-layer');
this.render();
}
public setProtests(events: SocialUnrestEvent[]): void {
this.protests = events;
this.rebuildProtestSupercluster();
this.render();
this.syncPulseAnimation();
}
public setFlightDelays(delays: AirportDelayAlert[]): void {
this.flightDelays = delays;
this.render();
}
public setAircraftPositions(positions: PositionSample[]): void {
this.aircraftPositions = positions;
this.render();
}
public setMilitaryFlights(flights: MilitaryFlight[], clusters: MilitaryFlightCluster[] = []): void {
this.militaryFlights = flights;
this.militaryFlightClusters = clusters;
// Prune trails for aircraft no longer in the dataset
if (this.activeFlightTrails.size > 0) {
const currentHexes = new Set(flights.map(f => f.hexCode.toLowerCase()));
for (const hex of this.activeFlightTrails) {
if (!currentHexes.has(hex)) this.activeFlightTrails.delete(hex);
}
this.updateClearTrailsBtn();
}
this.render();
}
public toggleFlightTrail(hexCode: string): void {
const key = hexCode.toLowerCase();
if (this.activeFlightTrails.has(key)) {
this.activeFlightTrails.delete(key);
} else {
this.activeFlightTrails.add(key);
}
this.updateClearTrailsBtn();
this.render();
}
public clearFlightTrails(): void {
if (this.activeFlightTrails.size === 0) return;
this.activeFlightTrails.clear();
this.updateClearTrailsBtn();
this.render();
}
private updateClearTrailsBtn(): void {
if (!this.clearTrailsBtn) return;
this.clearTrailsBtn.style.display = this.activeFlightTrails.size > 0 ? '' : 'none';
}
public setMilitaryVessels(vessels: MilitaryVessel[], clusters: MilitaryVesselCluster[] = []): void {
this.militaryVessels = vessels;
this.militaryVesselClusters = clusters;
this.render();
}
private fetchServerBases(): void {
if (!this.maplibreMap) return;
const mapLayers = this.state.layers;
if (!mapLayers.bases) return;
const zoom = this.maplibreMap.getZoom();
if (zoom < 3) return;
const bounds = this.maplibreMap.getBounds();
const sw = bounds.getSouthWest();
const ne = bounds.getNorthEast();
fetchMilitaryBases(sw.lat, sw.lng, ne.lat, ne.lng, zoom).then((result) => {
if (!result) return;
this.serverBases = result.bases;
this.serverBaseClusters = result.clusters;
this.serverBasesLoaded = true;
this.render();
}).catch((err) => {
console.error('[bases] fetch error', err);
});
}
private manageAircraftTimer(enabled: boolean): void {
if (enabled) {
if (!this.aircraftFetchTimer) {
this.aircraftFetchTimer = setInterval(() => {
this.lastAircraftFetchCenter = null; // force refresh on poll
this.fetchViewportAircraft();
}, 120_000); // Match server cache TTL (120s anonymous OpenSky tier)
this.debouncedFetchAircraft();
}
} else {
if (this.aircraftFetchTimer) {
clearInterval(this.aircraftFetchTimer);
this.aircraftFetchTimer = null;
}
this.aircraftPositions = [];
}
}
private hasAircraftViewportChanged(): boolean {
if (!this.maplibreMap) return false;
if (!this.lastAircraftFetchCenter) return true;
const center = this.maplibreMap.getCenter();
const zoom = this.maplibreMap.getZoom();
if (Math.abs(zoom - this.lastAircraftFetchZoom) >= 1) return true;
const [prevLng, prevLat] = this.lastAircraftFetchCenter;
// Threshold scales with zoom — higher zoom = smaller movement triggers fetch
const threshold = Math.max(0.1, 2 / 2 ** Math.max(0, zoom - 3));
return Math.abs(center.lat - prevLat) > threshold || Math.abs(center.lng - prevLng) > threshold;
}
private fetchViewportAircraft(): void {
if (!this.maplibreMap) return;
if (!this.state.layers.flights) return;
const zoom = this.maplibreMap.getZoom();
if (zoom < 2) {
if (this.aircraftPositions.length > 0) {
this.aircraftPositions = [];
this.render();
}
return;
}
if (!this.hasAircraftViewportChanged()) return;
const bounds = this.maplibreMap.getBounds();
const sw = bounds.getSouthWest();
const ne = bounds.getNorthEast();
const seq = ++this.aircraftFetchSeq;
this.setLayerLoading('flights', true);
fetchAircraftPositions({
swLat: sw.lat, swLon: sw.lng,
neLat: ne.lat, neLon: ne.lng,
}).then((positions) => {
if (seq !== this.aircraftFetchSeq) return; // discard stale response
this.aircraftPositions = positions;
this.onAircraftPositionsUpdate?.(positions);
const center = this.maplibreMap?.getCenter();
if (center) {
this.lastAircraftFetchCenter = [center.lng, center.lat];
this.lastAircraftFetchZoom = this.maplibreMap!.getZoom();
}
this.setLayerReady('flights', positions.length > 0);
this.render();
}).catch((err) => {
console.error('[aircraft] fetch error', err);
this.setLayerLoading('flights', false);
});
}
public setNaturalEvents(events: NaturalEvent[]): void {
this.naturalEvents = events;
this.render();
}
public setFires(fires: Array<{ lat: number; lon: number; brightness: number; frp: number; confidence: number; region: string; acq_date: string; daynight: string }>): void {
this.firmsFireData = fires;
this.render();
}
public setTechEvents(events: TechEventMarker[]): void {
this.techEvents = events;
this.rebuildTechEventSupercluster();
this.render();
}
public setUcdpEvents(events: UcdpGeoEvent[]): void {
this.ucdpEvents = events;
this.render();
}
public setDisplacementFlows(flows: DisplacementFlow[]): void {
this.displacementFlows = flows;
this.render();
}
public setClimateAnomalies(anomalies: ClimateAnomaly[]): void {
this.climateAnomalies = anomalies;
this.render();
}
public setRadiationObservations(observations: RadiationObservation[]): void {
this.radiationObservations = observations;
this.render();
}
public setWebcams(markers: Array<WebcamEntry | WebcamCluster>): void {
this.webcamData = markers;
this.render();
}
public async setGpsJamming(hexes: GpsJamHex[]): Promise<void> {
const seq = ++this.gpsJammingLoadSeq;
if (hexes.length === 0) {
this.gpsJammingHexes = [];
this.render();
return;
}
try {
const { cellToBoundary } = await import('h3-js');
if (seq !== this.gpsJammingLoadSeq) return;
// Precompute each hex boundary once per data refresh (every ~5 min)
// instead of calling cellToBoundary per hex on every buildLayers()/render.
this.gpsJammingHexes = hexes.map(h => ({
...h,
polygon: cellToBoundary(h.h3, true) as [number, number][],
}));
this.render();
} catch (err) {
if (seq !== this.gpsJammingLoadSeq) return;
this.gpsJammingHexes = [];
this.render();
console.warn('[DeckGLMap] failed to prepare GPS jamming polygons:', (err as Error)?.message);
throw err;
}
}
public setDiseaseOutbreaks(outbreaks: DiseaseOutbreakItem[]): void {
this.diseaseOutbreaks = outbreaks;
this.render();
}
public setNewsLocations(data: Array<{ lat: number; lon: number; title: string; threatLevel: string; timestamp?: Date }>): void {
const now = Date.now();
for (const d of data) {
if (!this.newsLocationFirstSeen.has(d.title)) {
this.newsLocationFirstSeen.set(d.title, now);
}
}
for (const [key, ts] of this.newsLocationFirstSeen) {
if (now - ts > 60_000) this.newsLocationFirstSeen.delete(key);
}
this.newsLocations = data;
this.render();
this.syncPulseAnimation(now);
}
public setPositiveEvents(events: PositiveGeoEvent[]): void {
this.positiveEvents = events;
this.syncPulseAnimation();
this.render();
}
public setKindnessData(points: KindnessPoint[]): void {
this.kindnessPoints = points;
this.syncPulseAnimation();
this.render();
}
public setChokepointData(data: GetChokepointStatusResponse | null): void {
this.popup.setChokepointData(data);
this.storedChokepointData = data;
this.rebuildHighlightedMarkers();
if (this.storedChokepointData) this.refreshTradeRouteStatus(this.storedChokepointData);
}
public setChinaCorridorSelection(corridor: ChinaCorridorControlTower | null): void {
const overlay = corridor ? projectChinaCorridorOverlay(corridor) : null;
this.selectedChinaCorridorOverlay = overlay;
this.render();
if (!overlay || !this.maplibreMap) return;
const [minLon, minLat, maxLon, maxLat] = overlay.bounds;
this.maplibreMap.fitBounds([[minLon, minLat], [maxLon, maxLat]], {
padding: 48,
duration: 700,
maxZoom: 6,
});
}
private refreshTradeRouteStatus(data: GetChokepointStatusResponse): void {
const scoreMap = new Map(data.chokepoints.map(cp => [cp.id, cp.disruptionScore ?? 0]));
const initialSegments = resolveTradeRouteSegments();
this.tradeRouteSegments = initialSegments.map(seg => {
const waypoints = ROUTE_WAYPOINTS_MAP.get(seg.routeId) ?? [];
const maxScore = waypoints.reduce((max, id) => Math.max(max, scoreMap.get(id) ?? 0), 0);
const status: TradeRouteStatus = maxScore >= 70 ? 'disrupted' : maxScore > 30 ? 'high_risk' : 'active';
return { ...seg, status };
});
this.buildTradeTrips();
this.render();
}
/**
* Activate or deactivate a scenario visual overlay.
* When active, trade route arcs transiting disrupted chokepoints shift to
* an orange scenario color. Pass null to restore normal colors.
*/
public setScenarioState(state: ScenarioVisualState | null): void {
this.scenarioState = state;
this.affectedIso2Set = new Set(state?.affectedIso2s ?? []);
this.buildTradeTrips();
this.render();
}
public highlightRoute(routeIds: string[]): void {
this.highlightedRouteIds = new Set(routeIds);
this.rebuildHighlightedMarkers();
this.buildTradeTrips();
this.render();
}
public clearHighlightedRoute(): void {
if (this.highlightedRouteIds.size === 0) return;
this.highlightedRouteIds.clear();
this.rebuildHighlightedMarkers();
this.buildTradeTrips();
this.render();
}
public setBypassRoutes(corridors: Array<{fromPort: [number, number]; toPort: [number, number]}>): void {
this.bypassArcData = corridors.map(c => ({
source: c.fromPort,
target: c.toPort,
}));
this.render();
}
public clearBypassRoutes(): void {
if (this.bypassArcData.length === 0) return;
this.bypassArcData = [];
this.render();
}
public zoomToRoutes(routeIds: string[]): void {
if (!this.maplibreMap || routeIds.length === 0) return;
const ids = new Set(routeIds);
let minLng = 180, maxLng = -180, minLat = 90, maxLat = -90;
let found = false;
for (const seg of this.tradeRouteSegments) {
if (!ids.has(seg.routeId)) continue;
found = true;
const [sLng, sLat] = seg.sourcePosition;
const [tLng, tLat] = seg.targetPosition;
if (sLng < minLng) minLng = sLng;
if (sLng > maxLng) maxLng = sLng;
if (sLat < minLat) minLat = sLat;
if (sLat > maxLat) maxLat = sLat;
if (tLng < minLng) minLng = tLng;
if (tLng > maxLng) maxLng = tLng;
if (tLat < minLat) minLat = tLat;
if (tLat > maxLat) maxLat = tLat;
}
if (!found) return;
this.maplibreMap.fitBounds([[minLng, minLat], [maxLng, maxLat]], {
padding: 60,
duration: 1000,
});
}
public setHappinessScores(data: HappinessData): void {
this.happinessScores = data.scores;
this.happinessYear = data.year;
this.happinessSource = data.source;
this.render();
}
public setCIIScores(scores: Array<{ code: string; score: number; level: string }>): void {
this.ciiScoresMap = new Map(scores.map(s => [s.code, { score: s.score, level: s.level }]));
this.ciiScoresVersion++;
this.render();
}
public setResilienceRanking(items: ResilienceRankingItem[], greyedOut: ResilienceRankingItem[] = []): void {
this.resilienceScoresMap = buildResilienceChoroplethMap(items, greyedOut);
this.resilienceScoresVersion++;
this.render();
}
public setSpeciesRecoveryZones(species: SpeciesRecovery[]): void {
this.speciesRecoveryZones = species.filter(
(s): s is SpeciesRecovery & { recoveryZone: { name: string; lat: number; lon: number } } =>
s.recoveryZone != null
);
this.render();
}
public setRenewableInstallations(installations: RenewableInstallation[]): void {
this.renewableInstallations = installations;
this.render();
}
public updateHotspotActivity(news: NewsItem[]): void {
this.news = news; // Store for related news lookup
// Update hotspot "breaking" indicators based on recent news
const breakingKeywords = new Set<string>();
const recentNews = news.filter(n =>
Date.now() - n.pubDate.getTime() < 2 * 60 * 60 * 1000 // Last 2 hours
);
// Count matches per hotspot for escalation tracking
const matchCounts = new Map<string, number>();
recentNews.forEach(item => {
const tokens = tokenizeForMatch(item.title);
this.hotspots.forEach(hotspot => {
if (matchesAnyKeyword(tokens, hotspot.keywords)) {
breakingKeywords.add(hotspot.id);
matchCounts.set(hotspot.id, (matchCounts.get(hotspot.id) || 0) + 1);
}
});
});
this.hotspots.forEach(h => {
h.hasBreaking = breakingKeywords.has(h.id);
const matchCount = matchCounts.get(h.id) || 0;
// Calculate a simple velocity metric (matches per hour normalized)
const velocity = matchCount > 0 ? matchCount / 2 : 0; // 2 hour window
updateHotspotEscalation(h.id, matchCount, h.hasBreaking || false, velocity);
});
this.render();
this.syncPulseAnimation();
}
/** Get news items related to a hotspot by keyword matching */
private getRelatedNews(hotspot: Hotspot): NewsItem[] {
const conflictTopics = ['gaza', 'ukraine', 'ukrainian', 'russia', 'russian', 'israel', 'israeli', 'iran', 'iranian', 'china', 'chinese', 'taiwan', 'taiwanese', 'korea', 'korean', 'syria', 'syrian'];
return this.news
.map((item) => {
const tokens = tokenizeForMatch(item.title);
const matchedKeywords = findMatchingKeywords(tokens, hotspot.keywords);
if (matchedKeywords.length === 0) return null;
const conflictMatches = conflictTopics.filter(t =>
matchKeyword(tokens, t) && !hotspot.keywords.some(k => k.toLowerCase().includes(t))
);
if (conflictMatches.length > 0) {
const strongLocalMatch = matchedKeywords.some(kw =>
kw.toLowerCase() === hotspot.name.toLowerCase() ||
hotspot.agencies?.some(a => matchKeyword(tokens, a))
);
if (!strongLocalMatch) return null;
}
const score = matchedKeywords.length;
return { item, score };
})
.filter((x): x is { item: NewsItem; score: number } => x !== null)
.sort((a, b) => b.score - a.score)
.slice(0, 5)
.map(x => x.item);
}
public updateMilitaryForEscalation(flights: MilitaryFlight[], vessels: MilitaryVessel[]): void {
setMilitaryData(flights, vessels);
}
public getHotspotDynamicScore(hotspotId: string) {
return getHotspotEscalation(hotspotId);
}
/** Get military flight clusters for rendering/analysis */
public getMilitaryFlightClusters(): MilitaryFlightCluster[] {
return this.militaryFlightClusters;
}
/** Get military vessel clusters for rendering/analysis */
public getMilitaryVesselClusters(): MilitaryVesselCluster[] {
return this.militaryVesselClusters;
}
public highlightAssets(assets: RelatedAsset[] | null): void {
// Clear previous highlights
Object.values(this.highlightedAssets).forEach(set => set.clear());
if (assets) {
assets.forEach(asset => {
if (asset?.type && this.highlightedAssets[asset.type]) {
this.highlightedAssets[asset.type].add(asset.id);
}
});
}
this.render(); // Debounced
}
public setOnHotspotClick(callback: (hotspot: Hotspot) => void): void {
this.onHotspotClick = callback;
}
public setOnTradeArcClick(cb: (segment: TradeRouteSegment, waypoints: string[], x: number, y: number) => void): void {
this.onTradeArcClick = cb;
}
public setOnTimeRangeChange(callback: (range: TimeRange) => void): void {
this.onTimeRangeChange = callback;
}
public setOnLayerChange(callback: (layer: keyof MapLayers, enabled: boolean, source: 'user' | 'programmatic') => void): void {
this.onLayerChange = callback;
}
public setOnStateChange(callback: (state: DeckMapState) => void): void {
this.onStateChange = callback;
}
public setOnAircraftPositionsUpdate(callback: (positions: PositionSample[]) => void): void {
this.onAircraftPositionsUpdate = callback;
}
public getHotspotLevels(): Record<string, string> {
const levels: Record<string, string> = {};
this.hotspots.forEach(h => {
levels[h.name] = h.level || 'low';
});
return levels;
}
public setHotspotLevels(levels: Record<string, string>): void {
this.hotspots.forEach(h => {
if (levels[h.name]) {
h.level = levels[h.name] as 'low' | 'elevated' | 'high';
}
});
this.render(); // Debounced
}
public initEscalationGetters(): void {
setCIIGetter(getCachedCountryScoreValue);
setGeoAlertGetter(getAlertsNearLocation);
}
private layerWarningShown = false;
private lastActiveLayerCount = 0;
private enforceLayerLimit(): void {
const WARN_THRESHOLD = 13;
const togglesEl = this.container.querySelector('.deckgl-layer-toggles');
if (!togglesEl) return;
const activeCount = Array.from(togglesEl.querySelectorAll<HTMLInputElement>('.layer-toggle input'))
.filter(i => {
const toggle = i.closest('.layer-toggle') as HTMLElement | null;
const row = i.closest('.layer-toggle-row') as HTMLElement | null;
return toggle?.style.display !== 'none' && row?.style.display !== 'none';
})
.filter(i => i.checked).length;
const increasing = activeCount > this.lastActiveLayerCount;
this.lastActiveLayerCount = activeCount;
if (activeCount >= WARN_THRESHOLD && increasing && !this.layerWarningShown) {
this.layerWarningShown = true;
showLayerWarning(WARN_THRESHOLD);
} else if (activeCount < WARN_THRESHOLD) {
this.layerWarningShown = false;
}
}
// UI visibility methods
public hideLayerToggle(layer: keyof MapLayers): void {
const toggle = this.container.querySelector(`.layer-toggle[data-layer="${layer}"]`);
if (toggle) {
const row = toggle.closest('.layer-toggle-row') as HTMLElement | null;
const target = (row ?? toggle) as HTMLElement;
target.style.display = 'none';
toggle.setAttribute('data-layer-hidden', '');
}
}
public setLayerLoading(layer: keyof MapLayers, loading: boolean): void {
const toggle = this.container.querySelector(`.layer-toggle[data-layer="${layer}"]`);
if (toggle) toggle.classList.toggle('loading', loading);
}
public setLayerReady(layer: keyof MapLayers, hasData: boolean): void {
const toggle = this.container.querySelector(`.layer-toggle[data-layer="${layer}"]`);
if (!toggle) return;
toggle.classList.remove('loading');
// Match old Map.ts behavior: set 'active' only when layer enabled AND has data
if (this.state.layers[layer] && hasData) {
toggle.classList.add('active');
} else {
toggle.classList.remove('active');
}
}
public flashAssets(assetType: AssetType, ids: string[]): void {
if (!this.highlightedAssets[assetType]) return;
ids.forEach(id => this.highlightedAssets[assetType].add(id));
this.render();
setTimeout(() => {
ids.forEach(id => this.highlightedAssets[assetType]?.delete(id));
this.render();
}, 3000);
}
// Enable layer programmatically
public enableLayer(layer: keyof MapLayers): void {
if (!this.state.layers[layer]) {
if (layer === 'resilienceScore' && this.state.layers.ciiChoropleth) {
this.state.layers.ciiChoropleth = false;
const ciiToggle = this.container.querySelector(`.layer-toggle[data-layer="ciiChoropleth"] input`) as HTMLInputElement | null;
if (ciiToggle) ciiToggle.checked = false;
this.setLayerReady('ciiChoropleth', false);
this.onLayerChange?.('ciiChoropleth', false, 'programmatic');
} else if (layer === 'ciiChoropleth' && this.state.layers.resilienceScore) {
this.state.layers.resilienceScore = false;
const resilienceToggle = this.container.querySelector(`.layer-toggle[data-layer="resilienceScore"] input`) as HTMLInputElement | null;
if (resilienceToggle) resilienceToggle.checked = false;
this.setLayerReady('resilienceScore', false);
this.onLayerChange?.('resilienceScore', false, 'programmatic');
}
this.state.layers[layer] = true;
const toggle = this.container.querySelector(`.layer-toggle[data-layer="${layer}"] input`) as HTMLInputElement;
if (toggle) toggle.checked = true;
if (layer === 'weather') this.startWeatherRadar();
if (layer === 'cyberThreats' && !this.aptGroupsLoaded) this.loadAptGroups();
if (layer === 'flights') this.manageAircraftTimer(true);
this.render();
this.updateLegend();
this.onLayerChange?.(layer, true, 'programmatic');
this.enforceLayerLimit();
}
}
// Toggle layer on/off programmatically
public toggleLayer(layer: keyof MapLayers): void {
const prevRadar = this.state.layers.weather;
const prevCyber = this.state.layers.cyberThreats;
const nextEnabled = !this.state.layers[layer];
if (nextEnabled && layer === 'resilienceScore' && this.state.layers.ciiChoropleth) {
this.state.layers.ciiChoropleth = false;
const ciiToggle = this.container.querySelector(`.layer-toggle[data-layer="ciiChoropleth"] input`) as HTMLInputElement | null;
if (ciiToggle) ciiToggle.checked = false;
this.setLayerReady('ciiChoropleth', false);
this.onLayerChange?.('ciiChoropleth', false, 'programmatic');
} else if (nextEnabled && layer === 'ciiChoropleth' && this.state.layers.resilienceScore) {
this.state.layers.resilienceScore = false;
const resilienceToggle = this.container.querySelector(`.layer-toggle[data-layer="resilienceScore"] input`) as HTMLInputElement | null;
if (resilienceToggle) resilienceToggle.checked = false;
this.setLayerReady('resilienceScore', false);
this.onLayerChange?.('resilienceScore', false, 'programmatic');
}
this.state.layers[layer] = !this.state.layers[layer];
if (layer === 'military' && !this.state.layers[layer]) this.clearFlightTrails();
const toggle = this.container.querySelector(`.layer-toggle[data-layer="${layer}"] input`) as HTMLInputElement;
if (toggle) toggle.checked = this.state.layers[layer];
if (this.state.layers.weather && !prevRadar) this.startWeatherRadar();
else if (!this.state.layers.weather && prevRadar) this.stopWeatherRadar();
if (this.state.layers.cyberThreats && !prevCyber && !this.aptGroupsLoaded) this.loadAptGroups();
if (layer === 'flights') this.manageAircraftTimer(this.state.layers.flights);
this.render();
this.updateLegend();
this.onLayerChange?.(layer, this.state.layers[layer], 'programmatic');
this.enforceLayerLimit();
}
// Update legend visibility based on which layers are currently active
// Get center coordinates for programmatic popup positioning
private getContainerCenter(): { x: number; y: number } {
const rect = this.container.getBoundingClientRect();
return { x: rect.width / 2, y: rect.height / 2 };
}
// Project lat/lon to screen coordinates without moving the map
private projectToScreen(lat: number, lon: number): { x: number; y: number } | null {
if (!this.maplibreMap) return null;
const point = this.maplibreMap.project([lon, lat]);
return { x: point.x, y: point.y };
}
// Pan to a chokepoint/waterway and open its popup (chokepoint deep-link target).
// Unlike the trigger* methods below, this pans first so the waterway lands at
// the container centre — which is where the popup is anchored.
//
// MapContainer can replay a queued chokepoint deep-link during the deferred
// renderer window — after `new DeckGLMap()` but before initMapLibre() has
// constructed maplibreMap, when setCenter() silently no-ops. Defer the whole
// pan+popup until the renderer is ready instead of dropping the pan.
public openChokepoint(id: string): void {
const waterway = STRATEGIC_WATERWAYS.find(w => w.id === id || w.chokepointId === id);
if (!waterway) return;
const reveal = () => {
if (this.destroyed || !this.maplibreMap) return;
this.setCenter(waterway.lat, waterway.lon, 5);
const { x, y } = this.getContainerCenter();
this.popup.show({ type: 'waterway', data: waterway, x, y });
};
if (this.maplibreMap) reveal();
else void this.whenReady().then(reveal).catch(() => {});
}
// Trigger click methods - show popup at item location without moving the map
public triggerHotspotClick(id: string): void {
const hotspot = this.hotspots.find(h => h.id === id);
if (!hotspot) return;
// Get screen position for popup
const screenPos = this.projectToScreen(hotspot.lat, hotspot.lon);
const { x, y } = screenPos || this.getContainerCenter();
// Get related news and show popup
const relatedNews = this.getRelatedNews(hotspot);
this.popup.show({
type: 'hotspot',
data: hotspot,
relatedNews,
x,
y,
});
this.popup.loadHotspotGdeltContext(hotspot);
this.onHotspotClick?.(hotspot);
}
public triggerConflictClick(id: string): void {
const conflict = CONFLICT_ZONES.find(c => c.id === id);
if (conflict) {
// Don't pan - show popup at projected screen position or center
const screenPos = this.projectToScreen(conflict.center[1], conflict.center[0]);
const { x, y } = screenPos || this.getContainerCenter();
this.popup.show({ type: 'conflict', data: conflict, x, y });
this.popup.loadConflictHistory(conflict);
}
}
public triggerBaseClick(id: string): void {
const base = this.serverBases.find(b => b.id === id) || getCachedMilitaryBases().find(b => b.id === id);
if (base) {
const screenPos = this.projectToScreen(base.lat, base.lon);
const { x, y } = screenPos || this.getContainerCenter();
this.popup.show({ type: 'base', data: base, x, y });
} else {
this.requestBaseConfigRender();
}
}
public triggerPipelineClick(id: string): void {
const pipeline = PIPELINES.find(p => p.id === id);
if (pipeline && pipeline.points.length > 0) {
const midIdx = Math.floor(pipeline.points.length / 2);
const midPoint = pipeline.points[midIdx];
// Don't pan - show popup at projected screen position or center
const screenPos = midPoint ? this.projectToScreen(midPoint[1], midPoint[0]) : null;
const { x, y } = screenPos || this.getContainerCenter();
this.popup.show({ type: 'pipeline', data: pipeline, x, y });
}
}
public triggerCableClick(id: string): void {
const cable = UNDERSEA_CABLES.find(c => c.id === id);
if (cable && cable.points.length > 0) {
const midIdx = Math.floor(cable.points.length / 2);
const midPoint = cable.points[midIdx];
// Don't pan - show popup at projected screen position or center
const screenPos = midPoint ? this.projectToScreen(midPoint[1], midPoint[0]) : null;
const { x, y } = screenPos || this.getContainerCenter();
this.popup.show({ type: 'cable', data: cable, x, y });
}
}
public triggerDatacenterClick(id: string): void {
const dc = AI_DATA_CENTERS.find(d => d.id === id);
if (dc) {
// Don't pan - show popup at projected screen position or center
const screenPos = this.projectToScreen(dc.lat, dc.lon);
const { x, y } = screenPos || this.getContainerCenter();
this.popup.show({ type: 'datacenter', data: dc, x, y });
}
}
public triggerNuclearClick(id: string): void {
const facility = NUCLEAR_FACILITIES.find(n => n.id === id);
if (facility) {
// Don't pan - show popup at projected screen position or center
const screenPos = this.projectToScreen(facility.lat, facility.lon);
const { x, y } = screenPos || this.getContainerCenter();
this.popup.show({ type: 'nuclear', data: facility, x, y });
}
}
public triggerIrradiatorClick(id: string): void {
const irradiator = GAMMA_IRRADIATORS.find(i => i.id === id);
if (irradiator) {
// Don't pan - show popup at projected screen position or center
const screenPos = this.projectToScreen(irradiator.lat, irradiator.lon);
const { x, y } = screenPos || this.getContainerCenter();
this.popup.show({ type: 'irradiator', data: irradiator, x, y });
}
}
public flashLocation(lat: number, lon: number, durationMs = 2000): void {
// Don't pan - project coordinates to screen position
const screenPos = this.projectToScreen(lat, lon);
if (!screenPos) return;
// Flash effect by temporarily adding a highlight at the location
const flashMarker = document.createElement('div');
flashMarker.className = 'flash-location-marker';
flashMarker.style.cssText = `
position: absolute;
width: 40px;
height: 40px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.5);
border: 2px solid #fff;
animation: flash-pulse 0.5s ease-out infinite;
pointer-events: none;
z-index: 1000;
left: ${screenPos.x}px;
top: ${screenPos.y}px;
transform: translate(-50%, -50%);
`;
// Add animation keyframes if not present
if (!document.getElementById('flash-animation-styles')) {
const style = document.createElement('style');
style.id = 'flash-animation-styles';
style.textContent = `
@keyframes flash-pulse {
0% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
100% { transform: translate(-50%, -50%) scale(2); opacity: 0; }
}
`;
document.head.appendChild(style);
}
const wrapper = this.container.querySelector('.deckgl-map-wrapper');
if (wrapper) {
wrapper.appendChild(flashMarker);
setTimeout(() => flashMarker.remove(), durationMs);
}
}
// --- Country click + highlight ---
private shouldSuppressCountryClickAfterDrag(): boolean {
return shouldSuppressCountryClick(this.countryClickGesture);
}
public setOnCountryClick(cb: (country: CountryClickPayload) => void): void {
this.onCountryClick = cb;
}
public setOnMapContextMenu(cb: (payload: { lat: number; lon: number; screenX: number; screenY: number; countryCode?: string; countryName?: string }) => void): void {
this.onMapContextMenu = cb;
}
private resolveCountryFromCoordinate(lon: number, lat: number): { code: string; name: string } | null {
const fromGeometry = getCountryAtCoordinates(lat, lon);
if (fromGeometry) return fromGeometry;
if (!this.maplibreMap || !this.countryGeoJsonLoaded) return null;
try {
if (!this.maplibreMap.getLayer('country-interactive')) return null;
const point = this.maplibreMap.project([lon, lat]);
const features = this.maplibreMap.queryRenderedFeatures(point, { layers: ['country-interactive'] });
const properties = (features?.[0]?.properties ?? {}) as Record<string, unknown>;
const code = typeof properties['ISO3166-1-Alpha-2'] === 'string'
? properties['ISO3166-1-Alpha-2'].trim().toUpperCase()
: '';
const name = typeof properties.name === 'string'
? properties.name.trim()
: '';
if (!code || !name) return null;
return { code, name };
} catch {
return null;
}
}
private loadCountryBoundaries(): void {
if (!this.maplibreMap || this.countryGeoJsonLoaded) return;
this.countryGeoJsonLoaded = true;
getCountriesGeoJson()
.then((geojson) => {
if (!this.maplibreMap || !geojson) return;
if (this.maplibreMap.getSource('country-boundaries')) return;
this.countriesGeoJsonData = geojson;
this.conflictZoneGeoJson = null;
this.conflictZoneBounded = null;
this.conflictZoneContentKey = null;
this.countriesBounded = null;
this.culledCountriesGeoJson = null;
this.culledCountriesContentKey = '';
this.maplibreMap.addSource('country-boundaries', {
type: 'geojson',
data: geojson,
});
this.maplibreMap.addLayer({
id: 'country-interactive',
type: 'fill',
source: 'country-boundaries',
paint: {
'fill-color': '#3b82f6',
'fill-opacity': 0,
},
});
if (!this.chrome) {
this.maplibreMap.addLayer({
id: 'country-embed-outline',
type: 'line',
source: 'country-boundaries',
paint: {
'line-color': getCurrentTheme() === 'light' ? '#334155' : '#94a3b8',
'line-width': 0.8,
'line-opacity': getCurrentTheme() === 'light' ? 0.26 : 0.32,
},
});
}
this.maplibreMap.addLayer({
id: 'country-hover-fill',
type: 'fill',
source: 'country-boundaries',
paint: {
'fill-color': '#ffffff',
'fill-opacity': 0.05,
},
filter: ['==', ['get', 'ISO3166-1-Alpha-2'], ''],
});
this.maplibreMap.addLayer({
id: 'country-hover-border',
type: 'line',
source: 'country-boundaries',
paint: {
'line-color': '#ffffff',
'line-width': 1.5,
'line-opacity': 0.22,
},
filter: ['==', ['get', 'ISO3166-1-Alpha-2'], ''],
});
this.maplibreMap.addLayer({
id: 'country-highlight-fill',
type: 'fill',
source: 'country-boundaries',
paint: {
'fill-color': '#3b82f6',
'fill-opacity': 0.12,
},
filter: ['==', ['get', 'ISO3166-1-Alpha-2'], ''],
});
this.maplibreMap.addLayer({
id: 'country-highlight-border',
type: 'line',
source: 'country-boundaries',
paint: {
'line-color': '#3b82f6',
'line-width': 1.5,
'line-opacity': 0.5,
},
filter: ['==', ['get', 'ISO3166-1-Alpha-2'], ''],
});
if (!this.countryHoverSetup) this.setupCountryHover();
const paintProvider = getMapProvider();
const paintMapTheme = getMapTheme(paintProvider);
this.updateCountryLayerPaint(isLightMapTheme(paintMapTheme) ? 'light' : 'dark');
if (this.highlightedCountryCode) this.highlightCountry(this.highlightedCountryCode);
this.render();
})
.catch((err) => console.warn('[DeckGLMap] Failed to load country boundaries:', err));
}
private setupCountryHover(): void {
if (!this.maplibreMap || this.countryHoverSetup) return;
this.countryHoverSetup = true;
const map = this.maplibreMap;
let hoveredIso2: string | null = null;
const clearHover = () => {
this.hoveredCountryIso2 = null;
this.hoveredCountryName = null;
map.getCanvas().style.cursor = '';
if (!map.getLayer('country-hover-fill')) return;
const noMatch = ['==', ['get', 'ISO3166-1-Alpha-2'], ''] as maplibregl.FilterSpecification;
map.setFilter('country-hover-fill', noMatch);
map.setFilter('country-hover-border', noMatch);
};
// rAF-throttle the per-mousemove feature query (#5042 U3). The canvas is the
// dominant input-delay surface and queryRenderedFeatures is synchronous, so
// coalesce to at most one query per frame; the latest pointer position wins.
const runHoverQuery = (point: maplibregl.Point) => {
if (!this.onCountryClick) return;
try {
if (!map.getLayer('country-interactive')) return;
const features = map.queryRenderedFeatures(point, { layers: ['country-interactive'] });
const props = features?.[0]?.properties;
const iso2 = props?.['ISO3166-1-Alpha-2'] as string | undefined;
const name = props?.['name'] as string | undefined;
if (iso2 && iso2 !== hoveredIso2) {
hoveredIso2 = iso2;
this.hoveredCountryIso2 = iso2;
this.hoveredCountryName = name ?? null;
const filter = ['==', ['get', 'ISO3166-1-Alpha-2'], iso2] as maplibregl.FilterSpecification;
map.setFilter('country-hover-fill', filter);
map.setFilter('country-hover-border', filter);
map.getCanvas().style.cursor = 'pointer';
} else if (!iso2 && hoveredIso2) {
hoveredIso2 = null;
clearHover();
}
} catch { /* style not done loading during theme switch */ }
};
const hoverQueryThrottle = createCountryHoverQueryController<maplibregl.Point>(
rafSchedule,
runHoverQuery,
);
this.hoverQueryThrottle = hoverQueryThrottle;
map.on('mousemove', (e) => {
if (!this.onCountryClick) {
hoverQueryThrottle.cancel();
return;
}
hoverQueryThrottle.queue(e.point);
});
map.on('mouseout', () => {
// Cancel a queued query so a deferred rAF cannot re-highlight a country the
// pointer has already left (R8); clearHover stays immediate.
hoverQueryThrottle.cancel();
if (hoveredIso2) {
hoveredIso2 = null;
try { clearHover(); } catch { /* style not done loading */ }
}
});
}
private countryPulseRaf: number | null = null;
private hoverQueryThrottle: CountryHoverQueryController<maplibregl.Point> | null = null;
private getHighlightRestOpacity(): { fill: number; border: number } {
const theme = isLightMapTheme(getMapTheme(getMapProvider())) ? 'light' : 'dark';
return { fill: theme === 'light' ? 0.18 : 0.12, border: 0.5 };
}
public highlightCountry(code: string): void {
this.highlightedCountryCode = code;
if (!this.maplibreMap || !this.countryGeoJsonLoaded) return;
try {
if (!this.maplibreMap.getLayer('country-highlight-fill')) return;
const filter = ['==', ['get', 'ISO3166-1-Alpha-2'], code] as maplibregl.FilterSpecification;
this.maplibreMap.setFilter('country-highlight-fill', filter);
this.maplibreMap.setFilter('country-highlight-border', filter);
this.pulseCountryHighlight();
} catch { /* style not yet loaded */ }
}
public clearCountryHighlight(): void {
this.highlightedCountryCode = null;
if (this.countryPulseRaf) { cancelAnimationFrame(this.countryPulseRaf); this.countryPulseRaf = null; }
if (!this.maplibreMap) return;
try {
if (!this.maplibreMap.getLayer('country-highlight-fill')) return;
const rest = this.getHighlightRestOpacity();
const noMatch = ['==', ['get', 'ISO3166-1-Alpha-2'], ''] as maplibregl.FilterSpecification;
this.maplibreMap.setFilter('country-highlight-fill', noMatch);
this.maplibreMap.setFilter('country-highlight-border', noMatch);
this.maplibreMap.setPaintProperty('country-highlight-fill', 'fill-opacity', rest.fill);
this.maplibreMap.setPaintProperty('country-highlight-border', 'line-opacity', rest.border);
} catch { /* style unloaded or map torn down between panel close and highlight clear */ }
}
private pulseCountryHighlight(): void {
if (this.countryPulseRaf) { cancelAnimationFrame(this.countryPulseRaf); this.countryPulseRaf = null; }
const map = this.maplibreMap;
if (!map) return;
const rest = this.getHighlightRestOpacity();
const start = performance.now();
const duration = 3000;
const step = (now: number) => {
try {
if (!map.getLayer('country-highlight-fill')) { this.countryPulseRaf = null; return; }
} catch { this.countryPulseRaf = null; return; }
const t = (now - start) / duration;
if (t >= 1) {
this.countryPulseRaf = null;
map.setPaintProperty('country-highlight-fill', 'fill-opacity', rest.fill);
map.setPaintProperty('country-highlight-border', 'line-opacity', rest.border);
return;
}
const pulse = Math.sin(t * Math.PI * 3) ** 2;
const fade = 1 - t * t;
const fillOp = rest.fill + 0.25 * pulse * fade;
const borderOp = rest.border + 0.5 * pulse * fade;
map.setPaintProperty('country-highlight-fill', 'fill-opacity', fillOp);
map.setPaintProperty('country-highlight-border', 'line-opacity', borderOp);
this.countryPulseRaf = requestAnimationFrame(step);
};
this.countryPulseRaf = requestAnimationFrame(step);
}
private async switchBasemap(): Promise<void> {
const map = this.maplibreMap;
if (!map) return;
const seq = ++this.basemapSwitchSeq;
const provider = getMapProvider();
const mapTheme = getMapTheme(provider);
const style = isHappyVariant
? (getCurrentTheme() === 'light' ? HAPPY_LIGHT_STYLE : HAPPY_DARK_STYLE)
: (this.usedFallbackStyle && provider === 'auto')
? (isLightMapTheme(mapTheme) ? FALLBACK_LIGHT_STYLE : FALLBACK_DARK_STYLE)
: await getStyleForProvider(provider, mapTheme);
if (this.maplibreMap !== map || seq !== this.basemapSwitchSeq) return;
if (this.countryPulseRaf) { cancelAnimationFrame(this.countryPulseRaf); this.countryPulseRaf = null; }
this.countryGeoJsonLoaded = false;
map.setStyle(style, { diff: false });
map.once('style.load', () => {
localizeMapLabels(this.maplibreMap);
this.loadCountryBoundaries();
if (this.radarActive) this.applyRadarLayer();
const paintTheme = isLightMapTheme(mapTheme) ? 'light' as const : 'dark' as const;
this.updateCountryLayerPaint(paintTheme);
this.render();
});
if (!isHappyVariant && provider !== 'openfreemap' && !this.usedFallbackStyle) {
this.monitorTileLoading(mapTheme);
}
}
private monitorTileLoading(mapTheme: string): void {
if (!this.maplibreMap) return;
const gen = ++this.tileMonitorGeneration;
let ok = false;
let errCount = 0;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const map = this.maplibreMap;
const cleanup = () => {
map.off('error', onError);
map.off('data', onData);
if (timeoutId) { clearTimeout(timeoutId); timeoutId = null; }
};
const onError = (e: { error?: Error; message?: string }) => {
if (gen !== this.tileMonitorGeneration) { cleanup(); return; }
const msg = e.error?.message ?? e.message ?? '';
if (msg.includes('Failed to fetch') || msg.includes('AJAXError') || msg.includes('CORS') || msg.includes('NetworkError') || msg.includes('403') || msg.includes('Forbidden')) {
errCount++;
if (!ok && errCount >= 2) {
cleanup();
this.switchToFallbackStyle(mapTheme);
}
}
};
const onData = (e: { dataType?: string }) => {
if (gen !== this.tileMonitorGeneration) { cleanup(); return; }
if (e.dataType === 'source') { ok = true; cleanup(); }
};
map.on('error', onError);
map.on('data', onData);
timeoutId = setTimeout(() => {
timeoutId = null;
if (gen !== this.tileMonitorGeneration) return;
cleanup();
if (!ok) this.switchToFallbackStyle(mapTheme);
}, 10000);
}
private switchToFallbackStyle(mapTheme: string): void {
if (this.usedFallbackStyle || !this.maplibreMap) return;
this.usedFallbackStyle = true;
const fallback = isLightMapTheme(mapTheme) ? FALLBACK_LIGHT_STYLE : FALLBACK_DARK_STYLE;
console.warn(`[DeckGLMap] Basemap tiles failed, falling back to OpenFreeMap: ${fallback}`);
if (this.countryPulseRaf) { cancelAnimationFrame(this.countryPulseRaf); this.countryPulseRaf = null; }
this.countryGeoJsonLoaded = false;
this.maplibreMap.setStyle(fallback, { diff: false });
this.maplibreMap.once('style.load', () => {
localizeMapLabels(this.maplibreMap);
this.loadCountryBoundaries();
if (this.radarActive) this.applyRadarLayer();
const paintTheme = isLightMapTheme(mapTheme) ? 'light' as const : 'dark' as const;
this.updateCountryLayerPaint(paintTheme);
this.render();
});
}
public reloadBasemap(): void {
this.basemapSwitchSeq++;
if (!this.maplibreMap) return;
this.usedFallbackStyle = false;
void this.switchBasemap();
}
private updateCountryLayerPaint(theme: 'dark' | 'light'): void {
if (!this.maplibreMap || !this.countryGeoJsonLoaded) return;
if (!this.maplibreMap.style || !this.maplibreMap.getLayer('country-hover-fill')) return;
const hoverFillOpacity = theme === 'light' ? 0.08 : 0.05;
const hoverBorderOpacity = theme === 'light' ? 0.35 : 0.22;
const highlightOpacity = theme === 'light' ? 0.18 : 0.12;
this.maplibreMap.setPaintProperty('country-hover-fill', 'fill-opacity', hoverFillOpacity);
this.maplibreMap.setPaintProperty('country-hover-border', 'line-opacity', hoverBorderOpacity);
this.maplibreMap.setPaintProperty('country-highlight-fill', 'fill-opacity', highlightOpacity);
if (this.maplibreMap.getLayer('country-embed-outline')) {
this.maplibreMap.setPaintProperty('country-embed-outline', 'line-color', theme === 'light' ? '#334155' : '#94a3b8');
this.maplibreMap.setPaintProperty('country-embed-outline', 'line-opacity', theme === 'light' ? 0.26 : 0.32);
}
}
public destroy(): void {
this.destroyed = true;
this.stopTradeAnimation();
this.activeFlightTrails.clear();
this.clearTrailsBtn = null;
this._unsubscribeAuthState?.();
this._unsubscribeAuthState = null;
this._unsubscribeEntitlement?.();
this._unsubscribeEntitlement = null;
window.removeEventListener('theme-changed', this.handleThemeChange);
window.removeEventListener('map-theme-changed', this.handleMapThemeChange);
this.tradeReducedMotionMedia?.removeEventListener('change', this.handleTradeMotionPreferenceChange);
this.tradeReducedMotionMedia = null;
this.debouncedRebuildLayers.cancel();
this.debouncedFetchBases.cancel();
this.debouncedFetchAircraft.cancel();
this.rafUpdateLayers.cancel();
this.hoverQueryThrottle?.cancel();
this.heavyGate.cancel();
if (this.renderRafId !== null) {
cancelAnimationFrame(this.renderRafId);
this.renderRafId = null;
}
if (this.countryPulseRaf !== null) {
cancelAnimationFrame(this.countryPulseRaf);
this.countryPulseRaf = null;
}
if (this.moveTimeoutId) {
clearTimeout(this.moveTimeoutId);
this.moveTimeoutId = null;
}
if (this.styleLoadTimeoutId) {
clearTimeout(this.styleLoadTimeoutId);
this.styleLoadTimeoutId = null;
}
this.stopPulseAnimation();
this.stopDayNightTimer();
this.stopWeatherRadar();
if (this.aircraftFetchTimer) {
clearInterval(this.aircraftFetchTimer);
this.aircraftFetchTimer = null;
}
this.stopLiveTankersLoop();
this.layerCache.clear();
this.deckOverlay?.finalize();
this.deckOverlay = null;
this.detachMapLibreInteractionHandlers();
this.maplibreMap?.remove();
this.maplibreMap = null;
setTrustedHtml(this.container, trustedHtml('', "legacy direct innerHTML migration"));
}
}
|