Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use client'
import { animated, to, useSpring } from '@react-spring/web'
import { css } from '@styled/css'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useIsSpectator } from '@/contexts/SpectatorModeContext'
import { useTheme } from '@/contexts/ThemeContext'
import { useVisualDebugSafe } from '@/contexts/VisualDebugContext'
import type { ContinentId } from '../continents'
import { useCelebrationAnimation } from '../features/celebration'
import { useCrosshairRotation } from '../features/crosshair'
import { CustomCursor, HeatCrosshair } from '../features/cursor'
import { AutoZoomDebugOverlay, HotColdDebugPanel, SafeZoneDebugOverlay } from '../features/debug'
import { type MapGameContextValue, MapGameProvider } from '../features/game'
import { useHintAnimation, useStruggleDetection } from '../features/hint'
import {
calculatePointerLockMovement,
checkDragThreshold,
useInteractionStateMachine,
} from '../features/interaction'
import { getRenderedViewport, LabelLayer, useD3ForceLabels } from '../features/labels'
import {
EXPANDED_MAGNIFIER_MARGIN,
getAdjustedMagnifiedDimensions,
getExpandedMagnifierDimensions,
getMagnifierDimensions,
type MagnifierContextValue,
MagnifierOverlayWithHandlers,
MagnifierProvider,
type UseMagnifierTouchHandlersOptions,
useMagnifierStyle,
ZoomLinesOverlay,
} from '../features/magnifier'
import { NetworkCursors } from '../features/multiplayer'
import { usePrecisionCalculations } from '../features/precision'
import { useGiveUpReveal } from '../features/reveal'
import { useGameSettings } from '../features/settings'
import { useSpeechAnnouncements } from '../features/speech'
import {
useCanUsePrecisionMode,
useHasAnyFinePointer,
useIsTouchDevice,
} from '../hooks/useDeviceCapabilities'
import { useHotColdFeedback } from '../hooks/useHotColdFeedback'
import { useMagnifierZoom } from '../hooks/useMagnifierZoom'
import { usePointerLock } from '../hooks/usePointerLock'
import { useRegionDetection } from '../hooks/useRegionDetection'
import { useHasRegionHint, useRegionHint } from '../hooks/useRegionHint'
import { useSpeakHint } from '../hooks/useSpeakHint'
import {
ASSISTANCE_LEVELS,
calculateFitCropViewBox,
calculateSafeZoneViewBox,
filterRegionsByContinent,
getCountryFlagEmoji,
parseViewBox,
type SafeZoneMargins,
USA_MAP,
WORLD_MAP,
} from '../maps'
import type { HintMap } from '../messages'
import { useKnowYourWorld } from '../Provider'
import type { MapData, MapRegion } from '../types'
import { type BoundingBox as DebugBoundingBox, findOptimalZoom } from '../utils/adaptiveZoomSearch'
import { classifyCelebration } from '../utils/celebration'
import {
calculateMaxZoomAtThreshold,
calculateScreenPixelRatio,
isAboveThreshold,
} from '../utils/screenPixelRatio'
import { CelebrationOverlay } from './CelebrationOverlay'
import { DevCropTool } from './DevCropTool'
import { RegionPath } from './RegionPath'
import { RegionRenderProvider } from './RegionRenderContext'
// Debug flag: show technical info in magnifier (gated by isVisualDebugEnabled at runtime)
const SHOW_MAGNIFIER_DEBUG_INFO = true
// Debug flag: show bounding boxes with importance scores (gated by isVisualDebugEnabled at runtime)
const SHOW_DEBUG_BOUNDING_BOXES = true
// Debug flag: show safe zone rectangles (gated by isVisualDebugEnabled at runtime)
const SHOW_SAFE_ZONE_DEBUG = true
// Precision mode threshold: screen pixel ratio that triggers pointer lock recommendation
const PRECISION_MODE_THRESHOLD = 20
// Game nav height offset - buttons should appear below the nav when in full-viewport mode
const NAV_HEIGHT_OFFSET = 150
// Safe zone margins - areas reserved for floating UI elements (in pixels)
// These define where the crop region should NOT appear, ensuring findable regions
// are visible and not obscured by UI controls
const SAFE_ZONE_MARGINS: SafeZoneMargins = {
top: 290, // Space for nav (~150px) + floating prompt (~140px with name input + controls row)
right: 0, // Controls now in floating prompt, no right margin needed
bottom: 0, // Error banner can overlap map
left: 0, // Progress at top-left is small, doesn't need full-height margin
}
interface MapRendererProps {
mapData: MapData
regionsFound: string[]
currentPrompt: string | null
assistanceLevel: 'learning' | 'guided' | 'helpful' | 'standard' | 'none' // Controls gameplay features (hints, hot/cold)
selectedMap: 'world' | 'usa' // Map ID for calculating excluded regions
selectedContinent: string // Continent ID for calculating excluded regions
onRegionClick: (regionId: string, regionName: string) => void
guessHistory: Array<{
playerId: string
regionId: string
correct: boolean
}>
playerMetadata: Record<
string,
{
id: string
name: string
emoji: string
color: string
userId?: string // Session ID that owns this player
}
>
// Give up reveal animation
giveUpReveal: {
regionId: string
regionName: string
timestamp: number
} | null
// Hint highlight animation
hintActive: {
regionId: string
timestamp: number
} | null
// Give up callback
onGiveUp: () => void
// Force simulation tuning parameters
forceTuning?: {
showArrows?: boolean
centeringStrength?: number
collisionPadding?: number
simulationIterations?: number
useObstacles?: boolean
obstaclePadding?: number
}
// Debug flags
showDebugBoundingBoxes?: boolean
// Multiplayer cursor sharing
gameMode?: 'cooperative' | 'race' | 'turn-based'
currentPlayer?: string // The player whose turn it is (for turn-based mode)
localPlayerId?: string // The local player's ID (to filter out our own cursor from others)
// Keyed by userId (session ID) to support multiple devices in coop mode
otherPlayerCursors?: Record<
string,
{
x: number
y: number
playerId: string
hoveredRegionId: string | null
} | null
>
onCursorUpdate?: (
cursorPosition: { x: number; y: number } | null,
hoveredRegionId: string | null
) => void
// Unanimous give-up voting (for cooperative multiplayer)
giveUpVotes?: string[] // Session/viewer IDs (userIds) who have voted to give up
activeUserIds?: string[] // All unique session IDs participating (to show "1/2 sessions voted")
viewerId?: string // This viewer's userId (to check if local session has voted)
// Member players mapping (userId -> players) for cursor emoji display
memberPlayers?: Record<string, Array<{ id: string; name: string; emoji: string; color: string }>>
/** When true, hints are locked (e.g., user hasn't typed required name confirmation yet) */
hintsLocked?: boolean
/** When true, fill the parent container with position: absolute */
fillContainer?: boolean
/** Current difficulty level for display (deprecated - use assistanceLevel) */
difficulty?: string
/** Map display name */
mapName?: string
}
export function MapRenderer({
mapData,
regionsFound,
currentPrompt,
assistanceLevel,
selectedMap,
selectedContinent,
onRegionClick,
guessHistory,
playerMetadata,
giveUpReveal,
hintActive,
onGiveUp,
forceTuning = {},
showDebugBoundingBoxes = SHOW_DEBUG_BOUNDING_BOXES,
gameMode,
currentPlayer,
localPlayerId,
otherPlayerCursors = {},
onCursorUpdate,
giveUpVotes = [],
activeUserIds = [],
viewerId,
memberPlayers = {},
hintsLocked = false,
fillContainer = false,
difficulty,
mapName,
}: MapRendererProps) {
const isSpectator = useIsSpectator()
// Get context for sharing state with GameInfoPanel
const {
setControlsState,
sharedContainerRef,
isInTakeover,
celebration,
setCelebration,
promptStartTime,
puzzlePieceTarget,
setPuzzlePieceTarget,
} = useKnowYourWorld()
// Extract force tuning parameters with defaults
const {
showArrows = false,
centeringStrength = 2.0,
collisionPadding = 5,
simulationIterations = 200,
useObstacles = true,
obstaclePadding = 10,
} = forceTuning
const { resolvedTheme } = useTheme()
const isDark = resolvedTheme === 'dark'
// Visual debug mode from global context (enabled when user toggles it on, in dev or with ?debug=1)
const { isVisualDebugEnabled } = useVisualDebugSafe()
// Effective debug flags - combine prop with context
// Props allow component-level override, context allows global toggle
const effectiveShowDebugBoundingBoxes = showDebugBoundingBoxes && isVisualDebugEnabled
const effectiveShowMagnifierDebugInfo = SHOW_MAGNIFIER_DEBUG_INFO && isVisualDebugEnabled
const effectiveShowSafeZoneDebug = SHOW_SAFE_ZONE_DEBUG && isVisualDebugEnabled
// Calculate excluded regions (regions filtered out by size/continent)
const excludedRegions = useMemo(() => {
// Get full unfiltered map data
const fullMapData = selectedMap === 'world' ? WORLD_MAP : USA_MAP
let allRegions = fullMapData.regions
// Apply continent filter if world map
if (selectedMap === 'world' && selectedContinent !== 'all') {
allRegions = filterRegionsByContinent(allRegions, selectedContinent as ContinentId)
}
// Find regions in full data that aren't in filtered data
const includedRegionIds = new Set(mapData.regions.map((r) => r.id))
const excluded = allRegions.filter((r) => !includedRegionIds.has(r.id))
return excluded
}, [mapData, selectedMap, selectedContinent])
// Get current assistance level config
const currentAssistanceLevel = useMemo(() => {
return ASSISTANCE_LEVELS.find((level) => level.id === assistanceLevel) || ASSISTANCE_LEVELS[1] // Default to 'helpful'
}, [assistanceLevel])
// Whether hot/cold is allowed by the assistance level (not user preference)
const assistanceAllowsHotCold = currentAssistanceLevel?.hotColdEnabled ?? false
// Create a set of excluded region IDs for quick lookup
const excludedRegionIds = useMemo(
() => new Set(excludedRegions.map((r) => r.id)),
[excludedRegions]
)
const svgRef = useRef<SVGSVGElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
// Pre-computed largest piece sizes for multi-piece regions
// Maps regionId -> {width, height} of the largest piece
// Defined early because useRegionDetection needs it
const largestPieceSizesRef = useRef<Map<string, { width: number; height: number }>>(new Map())
// Region detection hook
// Note: hoveredRegion and setHoveredRegion are no longer used from this hook
// State machine (interaction.hoveredRegionId) is now authoritative for hovered region
const { detectRegions } = useRegionDetection({
svgRef,
containerRef,
mapData,
detectionBoxSize: 50,
smallRegionThreshold: 15,
smallRegionAreaThreshold: 200,
largestPieceSizesCache: largestPieceSizesRef.current,
regionsFound,
})
// State that needs to be available for hooks
const cursorPositionRef = useRef<{ x: number; y: number } | null>(null)
const initialCapturePositionRef = useRef<{ x: number; y: number } | null>(null)
const [cursorSquish, setCursorSquish] = useState({ x: 1, y: 1 })
// Device capability hooks for adaptive UI
const isTouchDevice = useIsTouchDevice() // For touch-specific UI (magnifier expansion)
const canUsePrecisionMode = useCanUsePrecisionMode() // For precision mode UI/behavior
const hasAnyFinePointer = useHasAnyFinePointer() // For hot/cold feedback visibility
// Interaction state machine - replaces scattered boolean flags with explicit states
const interaction = useInteractionStateMachine({
initialMode: isTouchDevice ? 'mobile' : 'desktop',
})
// Sync state machine mode with isTouchDevice after hydration
// isTouchDevice returns false during SSR, then changes to true after hydration on touch devices
// Note: We extract specific values to avoid infinite loop - `interaction` object changes identity on every state change
const interactionMode = interaction.state.mode
const setInteractionMode = interaction.setMode
useEffect(() => {
const targetMode = isTouchDevice ? 'mobile' : 'desktop'
if (interactionMode !== targetMode) {
setInteractionMode(targetMode)
}
}, [isTouchDevice, interactionMode, setInteractionMode])
// Derive boolean flags from state machine for compatibility with existing code
// State machine is the SINGLE SOURCE OF TRUTH for interaction state
const isReleasingPointerLock = interaction.isReleasingPointerLock
const isDesktopMapDragging = interaction.isDesktopDragging
const isMobileMapDragging = interaction.isMapPanning
const mobileMapDragTriggeredMagnifier = interaction.magnifierTriggeredByDrag
// NOTE: isPinching and isMagnifierDragging should come from state machine,
// but currently still duplicated in useMagnifierState. Using state machine values here.
const isPinchingFromMachine = interaction.isPinching
const isMagnifierDraggingFromMachine = interaction.isMagnifierDragging
// Cursor position from state machine - authoritative source for render
// (cursorPositionRef is still used for synchronous access in event handlers)
const cursorPositionFromMachine = interaction.cursorPosition
// Shadow the old cursorPosition variable - state machine is now authoritative for render
const cursorPosition = cursorPositionFromMachine
// Hovered region from state machine - authoritative source for render
const hoveredRegionFromMachine = interaction.hoveredRegionId
// Shadow the old hoveredRegion variable - state machine is now authoritative
const hoveredRegion = hoveredRegionFromMachine
// Setter for hoveredRegion - dispatches to state machine
// Used by RegionPath mouse handlers and MagnifierRegions onHover
const setHoveredRegion = useCallback(
(regionId: string | null) => {
// Dispatch MOUSE_MOVE with just regionId (no position change)
// This updates hoveredRegion/touchedRegion in the state machine
// The state machine handles mobile vs desktop mode internally
if (isTouchDevice) {
interaction.dispatch({
type: 'TOUCH_MOVE',
position: cursorPositionRef.current ?? { x: 0, y: 0 },
touchCount: 1,
regionId,
})
} else {
interaction.dispatch({
type: 'MOUSE_MOVE',
position: cursorPositionRef.current ?? { x: 0, y: 0 },
regionId,
})
}
},
[interaction, isTouchDevice]
)
// Memoize pointer lock callbacks to prevent render loop
const handleLockAcquired = useCallback(() => {
// Save initial cursor position
if (cursorPositionRef.current) {
initialCapturePositionRef.current = { ...cursorPositionRef.current }
}
// Note: Zoom update now handled by useMagnifierZoom hook
}, [])
const handleLockReleased = useCallback(() => {
// Reset cursor squish
setCursorSquish({ x: 1, y: 1 })
// Note: isReleasingPointerLock now managed by interaction state machine
// The POINTER_LOCK_RELEASED event is dispatched via useEffect sync
// Note: Zoom recalculation now handled by useMagnifierZoom hook
}, [])
// Pointer lock hook (needed by zoom hook)
// Pass canUsePrecisionMode to prevent pointer lock on unsupported devices
const { pointerLocked, requestPointerLock, exitPointerLock } = usePointerLock({
containerRef,
canUsePrecisionMode,
onLockAcquired: handleLockAcquired,
onLockReleased: handleLockReleased,
})
// Magnifier zoom hook
// Disable threshold capping when precision mode isn't available (touch-only devices)
const { targetZoom, setTargetZoom, zoomSpring, getCurrentZoom, uncappedAdaptiveZoomRef } =
useMagnifierZoom({
containerRef,
svgRef,
viewBox: mapData.viewBox,
threshold: PRECISION_MODE_THRESHOLD,
pointerLocked,
initialZoom: 10,
disableThresholdCapping: !canUsePrecisionMode,
})
// Precision mode calculations (no circular dependency - receives state as inputs)
const precisionCalcs = usePrecisionCalculations({
containerRef,
svgRef,
viewBox: mapData.viewBox,
currentZoom: targetZoom,
pointerLocked,
})
// Sync pointer lock state to interaction state machine
// This dispatches events when the native pointer lock state changes
// Note: Extract dispatch to avoid infinite loop - `interaction` object changes identity on every state change
const interactionDispatch = interaction.dispatch
const prevPointerLockedRef = useRef(pointerLocked)
useEffect(() => {
if (pointerLocked !== prevPointerLockedRef.current) {
if (pointerLocked) {
interactionDispatch({ type: 'POINTER_LOCK_ACQUIRED' })
} else if (prevPointerLockedRef.current) {
// Only dispatch if we were previously locked (not on initial mount)
interactionDispatch({ type: 'POINTER_LOCK_RELEASED' })
}
prevPointerLockedRef.current = pointerLocked
}
}, [pointerLocked, interactionDispatch])
// Sync precision threshold state to interaction state machine
// This keeps the state machine informed about when precision mode should be recommended
useEffect(() => {
interactionDispatch({
type: 'PRECISION_THRESHOLD_UPDATE',
atThreshold: precisionCalcs.isAtThreshold,
screenPixelRatio: precisionCalcs.screenPixelRatio,
})
}, [precisionCalcs.isAtThreshold, precisionCalcs.screenPixelRatio, interactionDispatch])
const [svgDimensions, setSvgDimensions] = useState({
width: 1000,
height: 500,
})
// cursorPosition now comes from state machine (cursorPositionFromMachine defined below)
// The useState was removed as part of state machine migration
// ============================================================================
// Magnifier State (from Interaction State Machine)
// ============================================================================
// All magnifier display state now comes from the state machine.
// The old useMagnifierState hook is no longer needed.
// Unified showMagnifier from state machine (works for both mobile and desktop)
// State machine now syncs magnifier.isVisible with phase transitions, so this is simple
const showMagnifier = interaction.showMagnifier
// Magnifier display state from state machine
const targetOpacity = interaction.magnifierOpacity
const isMagnifierExpanded = interaction.isMagnifierExpanded
// Wrapper callbacks that dispatch to the state machine
// These maintain the same API for child components via context
const setShowMagnifier = useCallback(
(show: boolean) => {
if (show) {
interaction.dispatch({ type: 'MAGNIFIER_SHOW' })
} else {
interaction.dispatch({ type: 'MAGNIFIER_HIDE' })
}
},
[interaction]
)
const setTargetOpacity = useCallback(
(opacity: number) => {
interaction.dispatch({ type: 'MAGNIFIER_SET_OPACITY', opacity })
},
[interaction]
)
const setIsMagnifierExpanded = useCallback(
(expanded: boolean) => {
interaction.dispatch({ type: 'MAGNIFIER_SET_EXPANDED', expanded })
},
[interaction]
)
// Touch tracking refs (these remain local, not in state machine)
const magnifierTouchStartRef = useRef<{ x: number; y: number } | null>(null)
const magnifierDidMoveRef = useRef(false)
const pinchStartDistanceRef = useRef<number | null>(null)
const pinchStartZoomRef = useRef<number | null>(null)
// Ref to magnifier element for tap position calculation
const magnifierRef = useRef<HTMLDivElement>(null)
// Refs for scale probe elements (for empirical 1:1 tracking measurement)
const scaleProbe1Ref = useRef<SVGCircleElement>(null)
const scaleProbe2Ref = useRef<SVGCircleElement>(null)
// Refs for closed-loop anchor probe tracking (1:1 touch tracking)
const anchorProbeRef = useRef<SVGCircleElement>(null)
const anchorSvgPositionRef = useRef<{ x: number; y: number } | null>(null)
// Initialize magnifier position within the safe zone (below nav/floating UI)
const [targetTop, setTargetTop] = useState(SAFE_ZONE_MARGINS.top)
const [targetLeft, setTargetLeft] = useState(SAFE_ZONE_MARGINS.left + 20)
const [smallestRegionSize, setSmallestRegionSize] = useState<number>(Infinity)
// shiftPressed now comes from state machine (interaction.isShiftPressed)
// Desktop click-and-drag magnifier state
// Note: isDesktopMapDragging is derived from interaction state machine above
const desktopDragStartRef = useRef<{ x: number; y: number } | null>(null)
const desktopDragDidMoveRef = useRef(false)
// Track last drag position - magnifier stays visible until cursor moves threshold away
const lastDragPositionRef = useRef<{ x: number; y: number } | null>(null)
const DRAG_START_THRESHOLD = 5 // Pixels to move before counting as drag (not click)
const MAGNIFIER_DISMISS_THRESHOLD = 50 // Pixels to move away from last drag pos to dismiss
// Track whether current target region needs magnification
const [targetNeedsMagnification, setTargetNeedsMagnification] = useState(false)
// Mobile map drag state - now derived from state machine (interaction.isMapPanning)
// Note: isMobileMapDragging and mobileMapDragTriggeredMagnifier are defined at line ~344 from state machine
const mapTouchStartRef = useRef<{ x: number; y: number } | null>(null)
const MOBILE_DRAG_THRESHOLD = 10 // pixels before we consider it a drag
const AUTO_EXIT_ZOOM_THRESHOLD = 1.5 // Exit expanded mode when zoom drops below this
// Auto-exit expanded magnifier mode when zoom approaches 1x
useEffect(() => {
if (isMagnifierExpanded && targetZoom < AUTO_EXIT_ZOOM_THRESHOLD) {
console.log(
'[MapRenderer] Auto-exiting expanded magnifier mode - zoom dropped below threshold:',
targetZoom
)
setIsMagnifierExpanded(false)
}
}, [isMagnifierExpanded, targetZoom])
// Give up reveal animation (extracted hook)
const { giveUpFlashProgress, isGiveUpAnimating, giveUpZoomTarget } = useGiveUpReveal({
giveUpReveal,
svgRef,
containerRef,
fillContainer,
})
// Hint animation (extracted hook)
const { hintFlashProgress, isHintAnimating } = useHintAnimation({
hintActive,
})
// Celebration animation (extracted hook)
const { celebrationFlashProgress } = useCelebrationAnimation({ celebration })
const pendingCelebrationClick = useRef<{
regionId: string
regionName: string
} | null>(null)
// Debug: Track bounding boxes for visualization
const [debugBoundingBoxes, setDebugBoundingBoxes] = useState<DebugBoundingBox[]>([])
// Debug: Track full zoom search result for detailed panel
const [zoomSearchDebugInfo, setZoomSearchDebugInfo] = useState<ReturnType<
typeof findOptimalZoom
> | null>(null)
// Hint feature state
const [showHintBubble, setShowHintBubble] = useState(false)
// Determine which hint map to use:
// - For USA map, use 'usa'
// - For World map with specific continent, use the continent name (e.g., 'europe', 'africa')
// - For World map with 'all' continents, use 'world'
const hintMapKey: HintMap =
selectedMap === 'usa'
? 'usa'
: selectedContinent !== 'all'
? (selectedContinent as HintMap)
: 'world'
// Get hint for current region (if available) - with cycling support
const {
currentHint: hintText,
hintIndex,
totalHints,
nextHint,
hasMoreHints,
} = useRegionHint(hintMapKey, currentPrompt)
const hasHint = useHasRegionHint(hintMapKey, currentPrompt)
// Get the current region name for audio hints
const currentRegionName = useMemo(() => {
if (!currentPrompt) return null
const region = mapData.regions.find((r) => r.id === currentPrompt)
return region?.name ?? null
}, [currentPrompt, mapData.regions])
// Get flag emoji for cursor label (world map only)
const currentFlagEmoji = useMemo(() => {
if (selectedMap !== 'world' || !currentPrompt) return ''
return getCountryFlagEmoji(currentPrompt)
}, [selectedMap, currentPrompt])
// Speech synthesis for reading hints aloud
const {
speak,
speakWithRegionName,
stop: stopSpeaking,
isSpeaking,
isSupported: isSpeechSupported,
hasAccentOption,
} = useSpeakHint(hintMapKey, currentPrompt)
// Game settings (localStorage persisted)
const {
autoSpeak,
withAccent,
autoHint,
hotColdEnabled,
effectiveHotColdEnabled,
setAutoSpeak: handleAutoSpeakChange,
setWithAccent: handleWithAccentChange,
setAutoHint: handleAutoHintChange,
setHotColdEnabled: handleHotColdChange,
toggleAutoSpeak: handleAutoSpeakToggle,
toggleWithAccent: handleWithAccentToggle,
toggleAutoHint: handleAutoHintToggle,
toggleHotCold: handleHotColdToggle,
autoHintRef,
autoSpeakRef,
withAccentRef,
hotColdEnabledRef,
} = useGameSettings({
assistanceLevel,
assistanceAllowsHotCold,
})
// Whether hot/cold button should be shown at all
// Shows on all devices - mobile uses magnifier for hot/cold feedback
const showHotCold = isSpeechSupported && assistanceAllowsHotCold
// Speech announcements (auto-speak, "You found", hint cycling, etc.)
const { handleSpeakClick } = useSpeechAnnouncements({
isSpeechSupported,
isSpeaking,
speak,
speakWithRegionName,
stopSpeaking,
currentPrompt,
currentRegionName,
hintText,
hintIndex,
withAccent,
autoSpeak,
showHintBubble,
setShowHintBubble,
hasHint,
hintsLocked,
autoHintRef,
autoSpeakRef,
withAccentRef,
celebration,
puzzlePieceTarget,
})
// Hot/cold audio feedback hook
// Enabled if: 1) assistance level allows it, 2) user toggle is on
// 3) either has fine pointer (desktop) OR magnifier/drag is active (mobile)
// Use continent name for language lookup if available, otherwise use selectedMap
const hotColdMapName = selectedContinent || selectedMap
const {
checkPosition: checkHotCold,
reset: resetHotCold,
lastFeedbackType: hotColdFeedbackType,
getSearchMetrics,
} = useHotColdFeedback({
// In turn-based mode, only enable hot/cold for the player whose turn it is
// Desktop: hasAnyFinePointer enables mouse-based hot/cold
// Mobile: showMagnifier OR isMobileMapDragging enables touch-based hot/cold
enabled:
assistanceAllowsHotCold &&
hotColdEnabled &&
(hasAnyFinePointer || showMagnifier || isMobileMapDragging) &&
(gameMode !== 'turn-based' || currentPlayer === localPlayerId),
targetRegionId: currentPrompt,
isSpeaking,
mapName: hotColdMapName,
regions: mapData.regions,
})
// Reset hot/cold feedback when prompt changes
useEffect(() => {
resetHotCold()
}, [currentPrompt, resetHotCold])
// Struggle detection: Give additional hints when user is having trouble
useStruggleDetection({
effectiveHotColdEnabled,
hasMoreHints,
currentPrompt,
getSearchMetrics,
nextHint,
promptStartTime,
})
// Update context with controls state for GameInfoPanel
useEffect(() => {
setControlsState({
isPointerLocked: pointerLocked,
fakeCursorPosition: cursorPosition,
showHotCold,
hotColdEnabled,
hotColdFeedbackType,
onHotColdToggle: handleHotColdToggle,
hasHint,
currentHint: hintText,
isGiveUpAnimating,
// Speech/audio state
isSpeechSupported,
hasAccentOption,
isSpeaking,
onSpeak: handleSpeakClick,
onStopSpeaking: stopSpeaking,
// Auto settings
autoSpeak,
onAutoSpeakToggle: handleAutoSpeakToggle,
withAccent,
onWithAccentToggle: handleWithAccentToggle,
autoHint,
onAutoHintToggle: handleAutoHintToggle,
})
}, [
pointerLocked,
cursorPosition,
showHotCold,
hotColdEnabled,
hotColdFeedbackType,
handleHotColdToggle,
hasHint,
hintText,
isGiveUpAnimating,
setControlsState,
// Speech/audio deps
isSpeechSupported,
hasAccentOption,
isSpeaking,
handleSpeakClick,
stopSpeaking,
// Auto settings deps
autoSpeak,
handleAutoSpeakToggle,
withAccent,
handleWithAccentToggle,
autoHint,
handleAutoHintToggle,
])
// Configuration
const MAX_ZOOM = 1000 // Maximum zoom level (for Gibraltar at 0.08px!)
const HIGH_ZOOM_THRESHOLD = 100 // Show gold border above this zoom level
// Movement speed multiplier based on smallest region size
// When pointer lock is active, apply this multiplier to movementX/movementY
// For sub-pixel regions (< 1px): 3% speed (ultra precision)
// For tiny regions (1-5px): 10% speed (high precision)
// For small regions (5-15px): 25% speed (moderate precision)
const getMovementMultiplier = (size: number): number => {
if (size < 1) return 0.03 // Ultra precision for sub-pixel regions like Gibraltar (0.08px)
if (size < 5) return 0.1 // High precision for regions like Jersey (0.82px)
if (size < 15) return 0.25 // Moderate precision for regions like Rhode Island (11px)
return 1.0 // Normal speed for larger regions
}
// Pre-compute largest piece sizes for multi-piece regions
useEffect(() => {
if (!svgRef.current) return
const largestPieceSizes = new Map<string, { width: number; height: number }>()
mapData.regions.forEach((region) => {
const pathData = region.path
// Split on z followed by m (Safari doesn't support lookbehind, so use replace + split)
const withSeparator = pathData.replace(/z\s*m/gi, 'z|||m')
const rawPieces = withSeparator.split('|||')
if (rawPieces.length > 1) {
// Multi-piece region: use the FIRST piece (mainland), not largest
// The first piece is typically the mainland, with islands as subsequent pieces
const svg = svgRef.current
if (!svg) return
// Just measure the first piece
const tempPath = document.createElementNS('http://www.w3.org/2000/svg', 'path')
tempPath.setAttribute('d', rawPieces[0]) // First piece already has 'm' command
tempPath.style.visibility = 'hidden'
svg.appendChild(tempPath)
const bbox = tempPath.getBoundingClientRect()
const firstPieceSize = { width: bbox.width, height: bbox.height }
svg.removeChild(tempPath)
largestPieceSizes.set(region.id, firstPieceSize)
}
})
largestPieceSizesRef.current = largestPieceSizes
}, [mapData])
// Check if pointer lock is supported (not available on touch devices like iPad)
const isPointerLockSupported = typeof document !== 'undefined' && 'pointerLockElement' in document
// Request pointer lock on first click
const handleContainerClick = (e: React.MouseEvent<HTMLDivElement>) => {
if (isSpectator) return
console.log('[handleContainerClick] Called', {
suppressNextClick: suppressNextClickRef.current,
pointerLocked,
isPointerLockSupported,
target: (e.target as Element)?.tagName,
currentTarget: (e.currentTarget as Element)?.tagName,
})
// If we just finished a drag, suppress this click (user was dragging, not clicking)
if (suppressNextClickRef.current) {
console.log('[handleContainerClick] Suppressed - drag just finished')
suppressNextClickRef.current = false
return
}
// Silently request pointer lock if not already locked (and supported)
// This makes the first gameplay click also enable precision mode
// On devices without pointer lock (iPad), skip this and process clicks normally
if (!pointerLocked && isPointerLockSupported) {
console.log('[handleContainerClick] Requesting pointer lock')
requestPointerLock()
return // Don't process region click on the first click that requests lock
}
// When pointer lock is active, browser doesn't deliver click events to SVG children
// We need to manually detect which region is under the cursor
if (pointerLocked && cursorPositionRef.current && containerRef.current && svgRef.current) {
const { x: cursorX, y: cursorY } = cursorPositionRef.current
// Use the same detection logic as hover tracking (50px detection box)
const { detectedRegions, regionUnderCursor } = detectRegions(cursorX, cursorY)
if (regionUnderCursor && !celebration) {
// Find the region data to get the name
const region = mapData.regions.find((r) => r.id === regionUnderCursor)
if (region) {
handleRegionClickWithCelebration(regionUnderCursor, region.name)
}
}
}
}
// Calculate leftover area (space not covered by UI) for magnifier sizing
const leftoverWidth = svgDimensions.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverHeight = svgDimensions.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
// Calculate target magnifier dimensions based on expanded state
const { width: normalWidth, height: normalHeight } = getMagnifierDimensions(
leftoverWidth,
leftoverHeight
)
const { width: expandedWidth, height: expandedHeight } = getExpandedMagnifierDimensions(
leftoverWidth,
leftoverHeight
)
const targetWidth = isMagnifierExpanded ? expandedWidth : normalWidth
const targetHeight = isMagnifierExpanded ? expandedHeight : normalHeight
// When expanded, center the magnifier in the leftover area (with margin)
const expandedTop = SAFE_ZONE_MARGINS.top + EXPANDED_MAGNIFIER_MARGIN
const expandedLeft = SAFE_ZONE_MARGINS.left + EXPANDED_MAGNIFIER_MARGIN
// Animated spring values for smooth transitions
// Note: Zoom animation is now handled by useMagnifierZoom hook
// This spring handles: opacity, position, dimensions, and movement multiplier
const [magnifierSpring, magnifierApi] = useSpring(
() => ({
opacity: targetOpacity,
top: isMagnifierExpanded ? expandedTop : targetTop,
left: isMagnifierExpanded ? expandedLeft : targetLeft,
width: targetWidth,
height: targetHeight,
movementMultiplier: getMovementMultiplier(smallestRegionSize),
config: (key) => {
if (key === 'opacity') {
return targetOpacity === 1
? { duration: 100 } // Fade in: 0.1 seconds
: { duration: 1000 } // Fade out: 1 second
}
if (key === 'movementMultiplier') {
// Movement multiplier: slower transitions for smooth damping changes
// Lower tension = slower animation, higher friction = less overshoot
return { tension: 60, friction: 20 }
}
if (key === 'width' || key === 'height') {
// Size transitions: smooth spring for resize animation
return { tension: 200, friction: 25 }
}
// Position: medium speed
return { tension: 200, friction: 25 }
},
}),
[
targetOpacity,
targetTop,
targetLeft,
targetWidth,
targetHeight,
smallestRegionSize,
isMagnifierExpanded,
expandedTop,
expandedLeft,
]
)
// Calculate the display viewBox using fit-crop-with-fill strategy
// This ensures the custom crop region is visible while filling the container
// When fillContainer is true (playing phase), we use safe zone margins to ensure
// the crop region doesn't appear under floating UI elements
const displayViewBox = useMemo(() => {
// Need container dimensions to calculate aspect ratio
if (svgDimensions.width <= 0 || svgDimensions.height <= 0) {
return mapData.viewBox
}
const originalBounds = parseViewBox(mapData.originalViewBox)
// Use custom crop if defined, otherwise use the full original map bounds
// This ensures the map always fits within the leftover area (not under UI elements)
const cropRegion = mapData.customCrop ? parseViewBox(mapData.customCrop) : originalBounds
// In full-viewport mode (fillContainer), use safe zone calculation to ensure
// the crop region fits within the area not covered by floating UI elements
if (fillContainer) {
const result = calculateSafeZoneViewBox(
svgDimensions.width,
svgDimensions.height,
SAFE_ZONE_MARGINS,
cropRegion,
originalBounds
)
return result
}
// If not fillContainer and no custom crop, just use regular viewBox
if (!mapData.customCrop) {
return mapData.viewBox
}
// Otherwise use standard fit-crop calculation (for setup phase, etc.)
const containerAspect = svgDimensions.width / svgDimensions.height
const result = calculateFitCropViewBox(originalBounds, cropRegion, containerAspect)
return result
}, [mapData.customCrop, mapData.originalViewBox, mapData.viewBox, svgDimensions, fillContainer])
// Parse the display viewBox once - used throughout for animation and calculations
// This eliminates 24 redundant .split(' ').map(Number) calls per render
const parsedViewBox = useMemo(() => {
const parts = displayViewBox.split(' ').map(Number)
return {
x: parts[0] || 0,
y: parts[1] || 0,
width: parts[2] || 1000,
height: parts[3] || 500,
}
}, [displayViewBox])
// Compute which regions network cursors are hovering over
// Returns a map of regionId -> { playerId, color } for regions with network hovers
const networkHoveredRegions = useMemo(() => {
const result: Record<string, { playerId: string; color: string }> = {}
// Cursors are keyed by userId (session ID), playerId is in the position data
Object.entries(otherPlayerCursors).forEach(([cursorUserId, position]) => {
// Skip our own cursor (by viewerId) and null positions
if (cursorUserId === viewerId || !position) return
// In turn-based mode, only show hover when it's not our turn
if (gameMode === 'turn-based' && currentPlayer === localPlayerId) return
// Get player color from the playerId in the cursor data
// First check playerMetadata, then fall back to memberPlayers (for remote players)
let player = playerMetadata[position.playerId]
if (!player) {
// Player not in local playerMetadata - look through memberPlayers
for (const players of Object.values(memberPlayers)) {
const found = players.find((p) => p.id === position.playerId)
if (found) {
player = found
break
}
}
}
if (!player) return
// Use the transmitted hoveredRegionId directly (avoids hit-testing discrepancies
// due to pixel scaling/rendering differences between clients)
if (position.hoveredRegionId) {
result[position.hoveredRegionId] = {
playerId: position.playerId,
color: player.color,
}
}
})
return result
}, [
otherPlayerCursors,
viewerId,
gameMode,
currentPlayer,
localPlayerId,
playerMetadata,
memberPlayers,
])
// giveUpZoomTarget now comes from useGiveUpReveal hook
// Spring for main map zoom animation (used during give-up reveal)
// Uses CSS transform for reliable animation instead of viewBox manipulation
const mainMapSpring = useSpring({
scale: giveUpZoomTarget.scale,
translateX: giveUpZoomTarget.translateX,
translateY: giveUpZoomTarget.translateY,
config: { tension: 120, friction: 20 },
})
// Get crosshair heat styling from the REAL hot/cold feedback system (memoized)
const {
crosshairStyle: crosshairHeatStyle,
borderStyle: magnifierBorderStyle,
rotationSpeedDegPerSec: targetSpeedDegPerSec,
} = useMagnifierStyle({
feedbackType: hotColdFeedbackType,
isDark,
hotColdEnabled: effectiveHotColdEnabled,
})
// Crosshair rotation animation (spring-for-speed, manual-integration-for-angle pattern)
const { rotationAngle } = useCrosshairRotation({
targetSpeedDegPerSec,
})
// Note: Zoom animation with pause/resume is now handled by useMagnifierZoom hook
// This effect updates the remaining spring properties: opacity, position, dimensions, movement multiplier
useEffect(() => {
magnifierApi.start({
opacity: targetOpacity,
top: isMagnifierExpanded ? expandedTop : targetTop,
left: isMagnifierExpanded ? expandedLeft : targetLeft,
width: targetWidth,
height: targetHeight,
movementMultiplier: getMovementMultiplier(smallestRegionSize),
})
}, [
targetOpacity,
targetTop,
targetLeft,
targetWidth,
targetHeight,
smallestRegionSize,
magnifierApi,
isMagnifierExpanded,
expandedTop,
expandedLeft,
])
// Check if current target region needs magnification
useEffect(() => {
if (!currentPrompt || !svgRef.current || !containerRef.current) {
setTargetNeedsMagnification(false)
return
}
// Find the path element for the target region
const svgElement = svgRef.current
const path = svgElement.querySelector(`path[data-region-id="${currentPrompt}"]`)
if (!path || !(path instanceof SVGGeometryElement)) {
setTargetNeedsMagnification(false)
return
}
// Get the bounding box size
const bbox = path.getBoundingClientRect()
const pixelWidth = bbox.width
const pixelHeight = bbox.height
const pixelArea = pixelWidth * pixelHeight
// Use same thresholds as region detection
const SMALL_REGION_THRESHOLD = 15 // pixels
const SMALL_REGION_AREA_THRESHOLD = 200 // px²
const isVerySmall =
pixelWidth < SMALL_REGION_THRESHOLD ||
pixelHeight < SMALL_REGION_THRESHOLD ||
pixelArea < SMALL_REGION_AREA_THRESHOLD
setTargetNeedsMagnification(isVerySmall)
}, [currentPrompt, svgDimensions]) // Re-check when prompt or SVG size changes
// Give up reveal animation is now handled by useGiveUpReveal hook
// Hint animation is now handled by useHintAnimation hook
// Celebration animation is now handled by useCelebrationAnimation hook
// Handle celebration completion - call the actual click after animation
const handleCelebrationComplete = useCallback(() => {
console.log('[handleCelebrationComplete] Called', {
pending: pendingCelebrationClick.current,
})
const pending = pendingCelebrationClick.current
if (pending) {
console.log('[handleCelebrationComplete] Clearing celebration and calling onRegionClick')
// Clear celebration state (hook will reset flash progress automatically)
setCelebration(null)
// Then fire the actual click
onRegionClick(pending.regionId, pending.regionName)
pendingCelebrationClick.current = null
} else {
console.log('[handleCelebrationComplete] No pending click - nothing to do')
}
}, [setCelebration, onRegionClick])
// Wrapper function to intercept clicks and trigger celebration for correct regions
const handleRegionClickWithCelebration = useCallback(
(regionId: string, regionName: string) => {
console.log('[handleRegionClickWithCelebration] Called with:', {
regionId,
regionName,
currentPrompt,
celebration: celebration
? { regionId: celebration.regionId, type: celebration.type }
: null,
puzzlePieceTarget: puzzlePieceTarget ? { regionId: puzzlePieceTarget.regionId } : null,
})
// If we're already celebrating or puzzle piece animating, ignore clicks
if (celebration || puzzlePieceTarget) {
console.log('[handleRegionClickWithCelebration] Blocked - already celebrating or animating')
return
}
// Check if this is the correct region
if (regionId === currentPrompt) {
// Correct! Calculate celebration type
const metrics = getSearchMetrics(promptStartTime.current)
const celebrationType = classifyCelebration(metrics)
// Store pending click for after celebration
pendingCelebrationClick.current = { regionId, regionName }
// In Learning mode, show puzzle piece animation first
if (assistanceLevel === 'learning' && svgRef.current) {
// Query the actual DOM element to get its bounding boxes
const pathElement = svgRef.current.querySelector(`path[data-region-id="${regionId}"]`)
if (pathElement && pathElement instanceof SVGGraphicsElement) {
// Get the actual screen bounding rect of the rendered path
const pathRect = pathElement.getBoundingClientRect()
// Get the SVG coordinate bounding box (for viewBox)
const svgBBox = pathElement.getBBox()
console.log('[PuzzlePiece] Direct DOM measurement:', {
regionId,
screenRect: {
left: pathRect.left,
top: pathRect.top,
width: pathRect.width,
height: pathRect.height,
},
svgBBox: {
x: svgBBox.x,
y: svgBBox.y,
width: svgBBox.width,
height: svgBBox.height,
},
})
setPuzzlePieceTarget({
regionId,
regionName,
celebrationType,
// Target is the actual screen rect of the region on the map
x: pathRect.left,
y: pathRect.top,
width: pathRect.width,
height: pathRect.height,
// SVG coordinate bounding box for correct viewBox
svgBBox: {
x: svgBBox.x,
y: svgBBox.y,
width: svgBBox.width,
height: svgBBox.height,
},
})
} else {
// Fallback: start celebration immediately if path not found
setCelebration({
regionId,
regionName,
type: celebrationType,
startTime: Date.now(),
})
}
} else if (assistanceLevel === 'learning') {
// Learning mode but refs not ready - start celebration immediately
setCelebration({
regionId,
regionName,
type: celebrationType,
startTime: Date.now(),
})
} else {
// Other modes: Start celebration immediately
setCelebration({
regionId,
regionName,
type: celebrationType,
startTime: Date.now(),
})
}
} else {
// Wrong region - handle immediately
onRegionClick(regionId, regionName)
}
},
[
celebration,
puzzlePieceTarget,
currentPrompt,
getSearchMetrics,
promptStartTime,
setCelebration,
setPuzzlePieceTarget,
onRegionClick,
assistanceLevel,
]
)
// Get center of celebrating region for confetti origin
const getCelebrationRegionCenter = useCallback((): {
x: number
y: number
} => {
if (!celebration || !svgRef.current || !containerRef.current) {
return { x: window.innerWidth / 2, y: window.innerHeight / 2 }
}
const region = mapData.regions.find((r) => r.id === celebration.regionId)
if (!region) {
return { x: window.innerWidth / 2, y: window.innerHeight / 2 }
}
// Convert SVG coordinates to screen coordinates
const svgRect = svgRef.current.getBoundingClientRect()
const containerRect = containerRef.current.getBoundingClientRect()
const { x: viewBoxX, y: viewBoxY, width: viewBoxW, height: viewBoxH } = parsedViewBox
const viewport = getRenderedViewport(svgRect, viewBoxX, viewBoxY, viewBoxW, viewBoxH)
const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
// Get absolute screen position
const screenX = containerRect.left + (region.center[0] - viewBoxX) * viewport.scale + svgOffsetX
const screenY = containerRect.top + (region.center[1] - viewBoxY) * viewport.scale + svgOffsetY
return { x: screenX, y: screenY }
}, [celebration, mapData.regions, parsedViewBox])
// Keyboard shortcuts - Shift for magnifier, H for hint
useEffect(() => {
if (isSpectator) return
const handleKeyDown = (e: KeyboardEvent) => {
// Don't trigger shortcuts if user is typing in an input
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
return
}
if (e.key === 'Shift' && !e.repeat) {
interactionDispatch({ type: 'SHIFT_KEY_DOWN' })
}
// 'H' key to toggle hint bubble
if ((e.key === 'h' || e.key === 'H') && !e.repeat && hasHint) {
setShowHintBubble((prev) => !prev)
}
}
const handleKeyUp = (e: KeyboardEvent) => {
if (e.key === 'Shift') {
interactionDispatch({ type: 'SHIFT_KEY_UP' })
}
}
window.addEventListener('keydown', handleKeyDown)
window.addEventListener('keyup', handleKeyUp)
return () => {
window.removeEventListener('keydown', handleKeyDown)
window.removeEventListener('keyup', handleKeyUp)
}
}, [hasHint, interactionDispatch, isSpectator])
// Use the labels feature module for D3 force-based label positioning
const { labelPositions, smallRegionLabelPositions } = useD3ForceLabels({
mapData,
excludedRegions,
excludedRegionIds,
regionsFound,
guessHistory,
displayViewBox,
svgDimensions,
svgRef,
containerRef,
forceTuning,
})
// Measure container element to get available space for viewBox calculation
// IMPORTANT: We measure the container, not the SVG, to avoid circular dependency:
// The SVG fills the container, and the viewBox is calculated based on container aspect ratio
useEffect(() => {
if (!containerRef.current) return
const updateDimensions = () => {
const rect = containerRef.current?.getBoundingClientRect()
if (rect) {
setSvgDimensions({ width: rect.width, height: rect.height })
}
}
// Use ResizeObserver to detect panel resizing (not just window resize)
const observer = new ResizeObserver(() => {
requestAnimationFrame(() => {
updateDimensions()
})
})
observer.observe(containerRef.current)
// Initial measurement
updateDimensions()
return () => observer.disconnect()
}, []) // No dependencies - container size doesn't depend on viewBox
// Use memoized viewBox dimensions for label offset calculations and sea background
const { x: viewBoxX, y: viewBoxY, width: viewBoxWidth, height: viewBoxHeight } = parsedViewBox
const showOutline = (region: MapRegion): boolean => {
// Learning/Guided/Helpful modes: always show outlines
if (
assistanceLevel === 'learning' ||
assistanceLevel === 'guided' ||
assistanceLevel === 'helpful'
)
return true
// Standard/None modes: only show outline on hover or if found
return hoveredRegion === region.id || regionsFound.includes(region.id)
}
// Helper: Get the player who found a specific region
const getPlayerWhoFoundRegion = (regionId: string): string | null => {
const guess = guessHistory.find((g) => g.regionId === regionId && g.correct)
return guess?.playerId || null
}
// Desktop click-and-drag handlers for magnifier
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
// Only handle left click, and not on touch devices
if (e.button !== 0 || isTouchDevice) return
let cursorX: number
let cursorY: number
if (pointerLocked && cursorPositionRef.current) {
// When pointer is locked, use the tracked cursor position
cursorX = cursorPositionRef.current.x
cursorY = cursorPositionRef.current.y
} else {
// Normal mode: use click position
const containerRect = containerRef.current?.getBoundingClientRect()
if (!containerRect) return
cursorX = e.clientX - containerRect.left
cursorY = e.clientY - containerRect.top
}
// Dispatch mouse down to state machine
interaction.dispatch({
type: 'MOUSE_DOWN',
position: { x: cursorX, y: cursorY },
})
desktopDragStartRef.current = { x: cursorX, y: cursorY }
desktopDragDidMoveRef.current = false
}
// Track if we should suppress the next click (because user was dragging)
const suppressNextClickRef = useRef(false)
const handleMouseUp = (e: React.MouseEvent<HTMLDivElement>) => {
// Dispatch mouse up to state machine
interaction.dispatch({ type: 'MOUSE_UP' })
// If user was dragging, save the last position for threshold-based dismissal
// and suppress the click event that will follow
if (isDesktopMapDragging && cursorPositionRef.current) {
lastDragPositionRef.current = { ...cursorPositionRef.current }
suppressNextClickRef.current = true
}
// Reset drag state (hasDragged reset handled by state machine via MOUSE_UP)
desktopDragStartRef.current = null
desktopDragDidMoveRef.current = false
}
// Handle mouse movement to track cursor and show magnifier when needed
const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
if (isSpectator) return
if (!svgRef.current || !containerRef.current) return
// Don't process mouse movement during pointer lock release animation
if (isReleasingPointerLock) return
// Dispatch MOUSE_ENTER when cursor first enters (was null, now has position)
if (!cursorPositionRef.current && interaction.state.mode === 'desktop') {
interaction.dispatch({ type: 'MOUSE_ENTER' })
}
const containerRect = containerRef.current.getBoundingClientRect()
const svgRect = svgRef.current.getBoundingClientRect()
// Get cursor position relative to container
let cursorX: number
let cursorY: number
if (pointerLocked) {
// When pointer is locked, use movement deltas with precision multiplier
const lastX = cursorPositionRef.current?.x ?? containerRect.width / 2
const lastY = cursorPositionRef.current?.y ?? containerRect.height / 2
const currentMultiplier = magnifierSpring.movementMultiplier.get()
// Calculate SVG offset within container (SVG may be smaller due to aspect ratio)
const svgOffsetX = svgRect.left - containerRect.left
const svgOffsetY = svgRect.top - containerRect.top
// Use utility to calculate dampened movement, squish, and escape
const movement = calculatePointerLockMovement({
lastX,
lastY,
movementX: e.movementX,
movementY: e.movementY,
currentMultiplier,
bounds: {
svgOffsetX,
svgOffsetY,
svgWidth: svgRect.width,
svgHeight: svgRect.height,
},
})
cursorX = movement.cursorX
cursorY = movement.cursorY
// Check if cursor should escape through boundary
if (movement.shouldEscape && !isReleasingPointerLock) {
// Start animation back to initial capture position
interaction.dispatch({ type: 'EDGE_ESCAPE' })
// Animate cursor back to initial position before releasing
if (initialCapturePositionRef.current) {
const startPos = { x: cursorX, y: cursorY }
const endPos = initialCapturePositionRef.current
const duration = 200 // ms
const startTime = performance.now()
const animate = (currentTime: number) => {
const elapsed = currentTime - startTime
const progress = Math.min(elapsed / duration, 1)
const eased = 1 - (1 - progress) ** 3 // Ease out cubic
const interpolatedX = startPos.x + (endPos.x - startPos.x) * eased
const interpolatedY = startPos.y + (endPos.y - startPos.y) * eased
cursorPositionRef.current = { x: interpolatedX, y: interpolatedY }
interaction.dispatch({
type: 'MOUSE_MOVE',
position: { x: interpolatedX, y: interpolatedY },
regionId: null,
})
if (progress < 1) {
requestAnimationFrame(animate)
} else {
document.exitPointerLock()
}
}
requestAnimationFrame(animate)
} else {
document.exitPointerLock()
}
return
}
// Update squish state for visual effect
setCursorSquish({ x: movement.squishX, y: movement.squishY })
// Desktop drag detection in pointer lock mode
if (desktopDragStartRef.current && !isDesktopMapDragging) {
if (
checkDragThreshold(
cursorX,
cursorY,
desktopDragStartRef.current.x,
desktopDragStartRef.current.y,
DRAG_START_THRESHOLD
)
) {
desktopDragDidMoveRef.current = true
interaction.dispatch({ type: 'DRAG_THRESHOLD_EXCEEDED' })
lastDragPositionRef.current = null
}
}
// Check if cursor has moved far enough from last drag position to dismiss magnifier
if (lastDragPositionRef.current && !isDesktopMapDragging && !interaction.isShiftPressed) {
if (
checkDragThreshold(
cursorX,
cursorY,
lastDragPositionRef.current.x,
lastDragPositionRef.current.y,
MAGNIFIER_DISMISS_THRESHOLD
)
) {
lastDragPositionRef.current = null
}
}
} else {
// Normal mode: use absolute position
cursorX = e.clientX - containerRect.left
cursorY = e.clientY - containerRect.top
// Desktop drag detection: check if user has moved enough from drag start point
if (desktopDragStartRef.current && !isDesktopMapDragging) {
if (
checkDragThreshold(
cursorX,
cursorY,
desktopDragStartRef.current.x,
desktopDragStartRef.current.y,
DRAG_START_THRESHOLD
)
) {
desktopDragDidMoveRef.current = true
interaction.dispatch({ type: 'DRAG_THRESHOLD_EXCEEDED' })
lastDragPositionRef.current = null
}
}
// Check if cursor has moved far enough from last drag position to dismiss magnifier
if (lastDragPositionRef.current && !isDesktopMapDragging && !interaction.isShiftPressed) {
if (
checkDragThreshold(
cursorX,
cursorY,
lastDragPositionRef.current.x,
lastDragPositionRef.current.y,
MAGNIFIER_DISMISS_THRESHOLD
)
) {
lastDragPositionRef.current = null
}
}
}
// Check if cursor is over the SVG
const isOverSvg =
cursorX >= svgRect.left - containerRect.left &&
cursorX <= svgRect.right - containerRect.left &&
cursorY >= svgRect.top - containerRect.top &&
cursorY <= svgRect.bottom - containerRect.top
// Don't hide magnifier if mouse is still in container (just moved to padding/magnifier area)
// Only update cursor position and check for regions if over SVG
if (!isOverSvg) {
// Keep magnifier visible but frozen at last position
// It will be hidden by handleMouseLeave when mouse exits container
return
}
// No velocity tracking needed - zoom adapts immediately to region size
// Update cursor position ref for next frame (synchronous access for handlers)
cursorPositionRef.current = { x: cursorX, y: cursorY }
// Use region detection hook to find regions near cursor
const detectionResult = detectRegions(cursorX, cursorY)
const {
detectedRegions: detectedRegionObjects,
regionUnderCursor,
regionUnderCursorArea,
regionsInBox,
hasSmallRegion,
detectedSmallestSize,
totalRegionArea,
} = detectionResult
// Show magnifier when:
// 1. Shift key is held down (manual override on desktop)
// 2. Current target region needs magnification AND there's a small region nearby
// 3. User is dragging on the map on mobile (always show magnifier for mobile drag)
// 4. User is click-dragging on the map on desktop
// 5. User recently finished a drag and cursor is still near the drag end position
const isNearLastDragPosition = lastDragPositionRef.current !== null
const shouldShow =
interaction.isShiftPressed ||
isMobileMapDragging ||
isDesktopMapDragging ||
isNearLastDragPosition ||
(targetNeedsMagnification && hasSmallRegion)
// Update smallest region size for adaptive cursor dampening
// Use hysteresis to prevent rapid flickering at boundaries
if (shouldShow && detectedSmallestSize !== Infinity) {
// Only update if the new size is significantly different (>20% change)
// This prevents jitter when moving near region boundaries
const currentSize = smallestRegionSize
const sizeRatio = currentSize === Infinity ? 0 : detectedSmallestSize / currentSize
const significantChange = currentSize === Infinity || sizeRatio < 0.8 || sizeRatio > 1.25
if (significantChange) {
setSmallestRegionSize(detectedSmallestSize)
}
} else if (smallestRegionSize !== Infinity) {
// When leaving precision area, don't immediately jump to Infinity
// Instead, set to a large value that will smoothly transition via spring
setSmallestRegionSize(100) // Large enough that multiplier becomes 1.0
}
// Dispatch MOUSE_MOVE to state machine with position and region
// This updates both cursor position and hovered region in a single dispatch
interaction.dispatch({
type: 'MOUSE_MOVE',
position: { x: cursorX, y: cursorY },
regionId: regionUnderCursor,
})
// hoveredRegion is now derived from state machine (interaction.hoveredRegionId)
// MOUSE_MOVE dispatch above already updated it with regionId
// Hot/cold audio feedback
// Only run if enabled, we have a target region, device has a fine pointer (mouse),
// and user can actually see/interact with the map (not during animations or takeover)
if (
hotColdEnabledRef.current &&
currentPrompt &&
hasAnyFinePointer &&
!isGiveUpAnimating &&
!isInTakeover
) {
// Find target region's SVG center
const targetRegion = mapData.regions.find((r) => r.id === currentPrompt)
if (targetRegion) {
// Parse viewBox for coordinate conversion
const { x: viewBoxX, y: viewBoxY, width: viewBoxW, height: viewBoxH } = parsedViewBox
// Convert SVG center to pixel coordinates
const viewport = getRenderedViewport(svgRect, viewBoxX, viewBoxY, viewBoxW, viewBoxH)
const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
const targetPixelX = (targetRegion.center[0] - viewBoxX) * viewport.scale + svgOffsetX
const targetPixelY = (targetRegion.center[1] - viewBoxY) * viewport.scale + svgOffsetY
// Calculate cursor position in SVG coordinates for finding closest region (for accent)
const cursorSvgX = (cursorX - svgOffsetX) / viewport.scale + viewBoxX
const cursorSvgY = (cursorY - svgOffsetY) / viewport.scale + viewBoxY
checkHotCold({
cursorPosition: { x: cursorX, y: cursorY },
targetCenter: { x: targetPixelX, y: targetPixelY },
hoveredRegionId: regionUnderCursor,
cursorSvgPosition: { x: cursorSvgX, y: cursorSvgY },
})
}
}
// Send cursor position to other players (in SVG coordinates)
// In turn-based mode, only broadcast when it's our turn
// We do this AFTER detectRegions so we can include the exact hovered region
const shouldBroadcastCursor =
onCursorUpdate &&
svgRef.current &&
(gameMode !== 'turn-based' || currentPlayer === localPlayerId)
if (shouldBroadcastCursor) {
const { x: viewBoxX, y: viewBoxY, width: viewBoxW, height: viewBoxH } = parsedViewBox
// Account for preserveAspectRatio letterboxing when converting to SVG coords
const viewport = getRenderedViewport(svgRect, viewBoxX, viewBoxY, viewBoxW, viewBoxH)
const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
// Use inverse of viewport.scale to convert pixels to viewBox units
const cursorSvgX = (cursorX - svgOffsetX) / viewport.scale + viewBoxX
const cursorSvgY = (cursorY - svgOffsetY) / viewport.scale + viewBoxY
// Pass the exact region under cursor (from local hit-testing) so other clients
// don't need to re-do hit-testing which can yield different results due to scaling
onCursorUpdate({ x: cursorSvgX, y: cursorSvgY }, regionUnderCursor)
}
if (shouldShow) {
// Filter out found regions from zoom calculations
// Found regions shouldn't influence how much we zoom in
const unfoundRegionObjects = detectedRegionObjects.filter((r) => !regionsFound.includes(r.id))
// Use adaptive zoom search utility to find optimal zoom
const zoomSearchResult = findOptimalZoom({
detectedRegions: unfoundRegionObjects,
detectedSmallestSize,
cursorX,
cursorY,
containerRect,
svgRect,
mapData,
svgElement: svgRef.current!,
largestPieceSizesCache: largestPieceSizesRef.current,
maxZoom: MAX_ZOOM,
minZoom: 1,
pointerLocked,
})
let adaptiveZoom = zoomSearchResult.zoom
const boundingBoxes = zoomSearchResult.boundingBoxes
// Save bounding boxes for rendering
setDebugBoundingBoxes(boundingBoxes)
// Save full zoom search result for debug panel
setZoomSearchDebugInfo(zoomSearchResult)
// Calculate leftover rectangle dimensions (area not covered by UI elements)
const leftoverWidth = containerRect.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverHeight = containerRect.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
// Calculate magnifier dimensions based on leftover rectangle (responsive to its aspect ratio)
const { width: magnifierWidth, height: magnifierHeight } = getMagnifierDimensions(
leftoverWidth,
leftoverHeight
)
// Lazy magnifier positioning: only move if cursor would be obscured
// Check if cursor is within current magnifier bounds (with padding)
const padding = 10 // pixels of buffer around magnifier
const currentMagLeft = targetLeft
const currentMagTop = targetTop
const currentMagRight = currentMagLeft + magnifierWidth
const currentMagBottom = currentMagTop + magnifierHeight
const cursorInMagnifier =
cursorX >= currentMagLeft - padding &&
cursorX <= currentMagRight + padding &&
cursorY >= currentMagTop - padding &&
cursorY <= currentMagBottom + padding
// Only calculate new position if cursor would be obscured
let newTop = targetTop
let newLeft = targetLeft
if (cursorInMagnifier) {
// Calculate leftover rectangle bounds (where magnifier can safely be positioned)
const leftoverTop = SAFE_ZONE_MARGINS.top
const leftoverBottom =
containerRect.height - SAFE_ZONE_MARGINS.bottom - magnifierHeight - 20
const leftoverLeft = SAFE_ZONE_MARGINS.left + 20
const leftoverRight = containerRect.width - SAFE_ZONE_MARGINS.right - magnifierWidth - 20
// Calculate the center of the leftover rectangle for positioning decisions
const leftoverCenterX = (leftoverLeft + leftoverRight + magnifierWidth) / 2
const leftoverCenterY = (leftoverTop + leftoverBottom + magnifierHeight) / 2
// Move to opposite corner from cursor (relative to leftover rectangle center)
const isLeftHalf = cursorX < leftoverCenterX
const isTopHalf = cursorY < leftoverCenterY
// Default: opposite corner from cursor, within leftover bounds
newTop = isTopHalf ? leftoverBottom : leftoverTop
newLeft = isLeftHalf ? leftoverRight : leftoverLeft
// When hint bubble is shown, blacklist the upper-right corner
// If magnifier would go to top-right (cursor in bottom-left), go to bottom-right instead
const wouldGoToTopRight = !isTopHalf && isLeftHalf
if (showHintBubble && wouldGoToTopRight) {
newTop = leftoverBottom // Move to bottom
// newLeft stays at right
}
}
// Store uncapped adaptive zoom before potentially capping it
uncappedAdaptiveZoomRef.current = adaptiveZoom
// Cap zoom if not in pointer lock mode to prevent excessive screen pixel ratios
if (!pointerLocked && containerRef.current && svgRef.current) {
const containerRect = containerRef.current.getBoundingClientRect()
const svgRect = svgRef.current.getBoundingClientRect()
// Calculate leftover rectangle dimensions for magnifier sizing
const leftoverWidthForCap =
containerRect.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverHeightForCap =
containerRect.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
const { width: magnifierWidth } = getMagnifierDimensions(
leftoverWidthForCap,
leftoverHeightForCap
)
const viewBoxWidth = parsedViewBox.width
if (viewBoxWidth && !Number.isNaN(viewBoxWidth)) {
// Calculate what the screen pixel ratio would be at this zoom
const screenPixelRatio = calculateScreenPixelRatio({
magnifierWidth,
viewBoxWidth,
svgWidth: svgRect.width,
zoom: adaptiveZoom,
})
// If it exceeds threshold, cap the zoom to stay at threshold
if (isAboveThreshold(screenPixelRatio, PRECISION_MODE_THRESHOLD)) {
const maxZoom = calculateMaxZoomAtThreshold(
PRECISION_MODE_THRESHOLD,
magnifierWidth,
svgRect.width
)
adaptiveZoom = Math.min(adaptiveZoom, maxZoom)
// Zoom cap log removed to reduce spam
}
}
}
setTargetZoom(adaptiveZoom)
setShowMagnifier(true)
setTargetOpacity(1)
setTargetTop(newTop)
setTargetLeft(newLeft)
} else {
setShowMagnifier(false)
setTargetOpacity(0)
setDebugBoundingBoxes([]) // Clear bounding boxes when hiding
}
}
const handleMouseLeave = () => {
// Don't hide magnifier when pointer is locked
// The cursor is locked to the container, so mouse leave events are not meaningful
if (pointerLocked) {
return
}
// Dispatch mouse leave to state machine (handles hasDragged reset)
// State machine sets cursor to null on MOUSE_LEAVE
interaction.dispatch({ type: 'MOUSE_LEAVE' })
// Reset desktop drag state when mouse leaves
desktopDragStartRef.current = null
desktopDragDidMoveRef.current = false
lastDragPositionRef.current = null
setShowMagnifier(false)
setTargetOpacity(0)
setDebugBoundingBoxes([]) // Clear bounding boxes when leaving
cursorPositionRef.current = null
// Notify other players that cursor left
// In turn-based mode, only broadcast when it's our turn
if (onCursorUpdate && (gameMode !== 'turn-based' || currentPlayer === localPlayerId)) {
onCursorUpdate(null, null)
}
}
// Mobile map touch handlers - detect drag gestures to show magnifier
const handleMapTouchStart = useCallback(
(e: React.TouchEvent<HTMLDivElement>) => {
// Only handle single-finger touch
if (e.touches.length !== 1) return
const touch = e.touches[0]
mapTouchStartRef.current = { x: touch.clientX, y: touch.clientY }
// Dispatch state machine event
interaction.dispatch({
type: 'TOUCH_START',
position: { x: touch.clientX, y: touch.clientY },
touchCount: e.touches.length,
regionId: null, // Will be determined during move/tap
})
},
[interaction]
)
const handleMapTouchMove = useCallback(
(e: React.TouchEvent<HTMLDivElement>) => {
if (!mapTouchStartRef.current || !svgRef.current || !containerRef.current) return
if (e.touches.length !== 1) return
const touch = e.touches[0]
const dx = touch.clientX - mapTouchStartRef.current.x
const dy = touch.clientY - mapTouchStartRef.current.y
const distance = Math.sqrt(dx * dx + dy * dy)
// Once we detect a drag (moved past threshold), show magnifier and update cursor
if (distance >= MOBILE_DRAG_THRESHOLD) {
// Note: touchAction: 'none' CSS prevents browser gestures without needing preventDefault()
// Update cursor position based on touch location
const containerRect = containerRef.current.getBoundingClientRect()
const cursorX = touch.clientX - containerRect.left
const cursorY = touch.clientY - containerRect.top
cursorPositionRef.current = { x: cursorX, y: cursorY }
// Detect region under cursor BEFORE dispatching to state machine
const detectionResult = detectRegions(cursorX, cursorY)
const {
detectedRegions: detectedRegionObjects,
detectedSmallestSize,
regionUnderCursor,
} = detectionResult
// Dispatch state machine events for touch move (includes regionId for hover state)
interaction.dispatch({
type: 'TOUCH_MOVE',
position: { x: touch.clientX, y: touch.clientY },
touchCount: e.touches.length,
regionId: regionUnderCursor,
})
if (!isMobileMapDragging) {
interaction.dispatch({ type: 'PAN_THRESHOLD_EXCEEDED' })
}
// Set up magnifier opacity for mobile drag
// Note: State machine now sets magnifier.isVisible=true when entering mapPanning phase,
// and also sets targetOpacity=1, but we call setTargetOpacity here for any animations
setTargetOpacity(1)
// hoveredRegion is now derived from state machine (interaction.hoveredRegionId)
// TOUCH_MOVE dispatch above already updated it with regionId
// Hot/cold feedback for mobile magnifier
if (hotColdEnabledRef.current && currentPrompt && !isGiveUpAnimating && !isInTakeover) {
const targetRegion = mapData.regions.find((r) => r.id === currentPrompt)
if (targetRegion) {
const svgRect = svgRef.current.getBoundingClientRect()
const { x: viewBoxX, y: viewBoxY, width: viewBoxW, height: viewBoxH } = parsedViewBox
const viewport = getRenderedViewport(svgRect, viewBoxX, viewBoxY, viewBoxW, viewBoxH)
const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
const targetPixelX = (targetRegion.center[0] - viewBoxX) * viewport.scale + svgOffsetX
const targetPixelY = (targetRegion.center[1] - viewBoxY) * viewport.scale + svgOffsetY
const cursorSvgX = (cursorX - svgOffsetX) / viewport.scale + viewBoxX
const cursorSvgY = (cursorY - svgOffsetY) / viewport.scale + viewBoxY
checkHotCold({
cursorPosition: { x: cursorX, y: cursorY },
targetCenter: { x: targetPixelX, y: targetPixelY },
hoveredRegionId: regionUnderCursor,
cursorSvgPosition: { x: cursorSvgX, y: cursorSvgY },
})
}
}
// Filter out found regions from zoom calculations (same as desktop)
const unfoundRegionObjects = detectedRegionObjects.filter(
(r) => !regionsFound.includes(r.id)
)
// Use adaptive zoom search utility to find optimal zoom (same algorithm as desktop)
const svgRect = svgRef.current.getBoundingClientRect()
// Broadcast cursor position to other players (in SVG coordinates)
// In turn-based mode, only broadcast when it's our turn
const shouldBroadcastCursor =
onCursorUpdate && (gameMode !== 'turn-based' || currentPlayer === localPlayerId)
if (shouldBroadcastCursor) {
const { x: viewBoxX, y: viewBoxY, width: viewBoxW, height: viewBoxH } = parsedViewBox
const viewport = getRenderedViewport(svgRect, viewBoxX, viewBoxY, viewBoxW, viewBoxH)
const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
const cursorSvgX = (cursorX - svgOffsetX) / viewport.scale + viewBoxX
const cursorSvgY = (cursorY - svgOffsetY) / viewport.scale + viewBoxY
onCursorUpdate({ x: cursorSvgX, y: cursorSvgY }, regionUnderCursor)
}
const zoomSearchResult = findOptimalZoom({
detectedRegions: unfoundRegionObjects,
detectedSmallestSize,
cursorX,
cursorY,
containerRect,
svgRect,
mapData,
svgElement: svgRef.current,
largestPieceSizesCache: largestPieceSizesRef.current,
maxZoom: MAX_ZOOM,
minZoom: 1,
pointerLocked: false, // Mobile never uses pointer lock
})
setTargetZoom(zoomSearchResult.zoom)
// Calculate leftover rectangle dimensions (area not covered by UI elements)
const leftoverWidth = containerRect.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverHeight =
containerRect.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
// Get magnifier dimensions based on leftover rectangle (responsive to its aspect ratio)
const { width: magnifierWidth, height: magnifierHeight } = getMagnifierDimensions(
leftoverWidth,
leftoverHeight
)
// Lazy positioning like desktop - only move magnifier when cursor would be obscured
// Exception: always position on first show (when drag just started)
const isFirstShow = !isMobileMapDragging // State hasn't updated yet on first frame
// Check if cursor would be obscured by magnifier
const padding = 30 // Extra padding around magnifier to trigger movement early
const currentMagLeft = targetLeft
const currentMagTop = targetTop
const currentMagRight = currentMagLeft + magnifierWidth
const currentMagBottom = currentMagTop + magnifierHeight
const cursorInMagnifier =
cursorX >= currentMagLeft - padding &&
cursorX <= currentMagRight + padding &&
cursorY >= currentMagTop - padding &&
cursorY <= currentMagBottom + padding
// Only calculate new position if first show OR cursor would be obscured
if (isFirstShow || cursorInMagnifier) {
// Calculate leftover rectangle bounds (where magnifier can safely be positioned)
const leftoverTop = SAFE_ZONE_MARGINS.top
const leftoverBottom =
containerRect.height - SAFE_ZONE_MARGINS.bottom - magnifierHeight - 20
const leftoverLeft = SAFE_ZONE_MARGINS.left + 20
const leftoverRight = containerRect.width - SAFE_ZONE_MARGINS.right - magnifierWidth - 20
// Calculate the center of the leftover rectangle for positioning decisions
const leftoverCenterX = (leftoverLeft + leftoverRight + magnifierWidth) / 2
const leftoverCenterY = (leftoverTop + leftoverBottom + magnifierHeight) / 2
// Position magnifier away from touch point (relative to leftover rectangle center)
const isLeftHalf = cursorX < leftoverCenterX
const isTopHalf = cursorY < leftoverCenterY
// Place magnifier in opposite corner from where user is touching, within leftover bounds
const newTop = isTopHalf ? leftoverBottom : leftoverTop
const newLeft = isLeftHalf ? leftoverRight : leftoverLeft
setTargetTop(newTop)
setTargetLeft(newLeft)
}
}
},
[
isMobileMapDragging,
MOBILE_DRAG_THRESHOLD,
detectRegions,
MAX_ZOOM,
getMagnifierDimensions,
regionsFound,
mapData,
targetLeft,
targetTop,
currentPrompt,
isGiveUpAnimating,
isInTakeover,
displayViewBox,
checkHotCold,
onCursorUpdate,
gameMode,
currentPlayer,
localPlayerId,
interaction,
]
)
// Helper to dismiss the magnifier (used by tap-to-dismiss and after selection)
const dismissMagnifier = useCallback(() => {
// Clear cursor position ref
cursorPositionRef.current = null
if (isTouchDevice) {
// Mobile: MAGNIFIER_DEACTIVATED handles:
// - Setting phase to idle
// - Setting magnifier.isVisible = false
// - Setting magnifier.targetOpacity = 0
// - Setting magnifier.isExpanded = false
// - Clearing touchCenter and magnifierTriggeredByDrag
interaction.dispatch({ type: 'MAGNIFIER_DEACTIVATED' })
} else {
// Desktop: MAGNIFIER_HIDE just hides the magnifier display
interaction.dispatch({ type: 'MAGNIFIER_HIDE' })
}
// Notify other players that cursor is no longer active
// In turn-based mode, only broadcast when it's our turn
if (onCursorUpdate && (gameMode !== 'turn-based' || currentPlayer === localPlayerId)) {
onCursorUpdate(null, null)
}
}, [onCursorUpdate, gameMode, currentPlayer, localPlayerId, interaction, isTouchDevice])
const handleMapTouchEnd = useCallback(() => {
const wasDraggingMap = isMobileMapDragging
const wasDraggingMagnifier = interaction.isMagnifierDragging
const wasPinching = interaction.isPinching
const phaseBefore = interaction.state.mode === 'mobile' ? interaction.state.phase : 'N/A'
console.log('[handleMapTouchEnd] Called', {
wasDraggingMap,
wasDraggingMagnifier,
wasPinching,
showMagnifier,
phaseBefore,
hasCursor: !!cursorPositionRef.current,
})
mapTouchStartRef.current = null
// Dispatch state machine event for touch end
interaction.dispatch({ type: 'TOUCH_END', touchCount: 0 })
// Check if we were interacting with map or magnifier (drag/pinch)
// If interacting with magnifier, the touch end event shouldn't have come here
// (magnifier should capture it) but if it does, we should NOT dismiss the magnifier
if (wasDraggingMap || wasDraggingMagnifier || wasPinching) {
// State machine handles the transition:
// - mapPanning → magnifierActive (sets magnifierTriggeredByDrag: true)
// - magnifierPanning → magnifierActive
// - magnifierPinching → magnifierActive
// Keep magnifier visible - user can tap "Select" button or tap elsewhere to dismiss
console.log('[handleMapTouchEnd] Was dragging/pinching - keeping magnifier')
} else if (showMagnifier && cursorPositionRef.current) {
// User tapped on map (not a drag) while magnifier is visible - dismiss the magnifier
console.log('[handleMapTouchEnd] Dismissing magnifier (tap on map while visible)')
dismissMagnifier()
}
}, [isMobileMapDragging, showMagnifier, dismissMagnifier, interaction])
// Touch handler options - passed to MagnifierOverlayWithHandlers
// which calls useMagnifierTouchHandlers inside the context providers
const touchHandlerOptions = useMemo<UseMagnifierTouchHandlersOptions>(
() => ({
onCursorUpdate,
gameMode,
currentPlayer,
localPlayerId,
checkHotCold,
isInTakeover,
displayViewBox,
regionsFound,
hotColdEnabledRef,
largestPieceSizesRef,
detectRegions,
}),
[
onCursorUpdate,
gameMode,
currentPlayer,
localPlayerId,
checkHotCold,
isInTakeover,
displayViewBox,
regionsFound,
hotColdEnabledRef,
largestPieceSizesRef,
detectRegions,
]
)
// NOTE: handleMagnifierTouchStart, handleMagnifierTouchMove, handleMagnifierTouchEnd
// have been moved to useMagnifierTouchHandlers hook in features/magnifier/
// The hook is called by MagnifierOverlayWithHandlers inside the context providers
// Helper to select the region at the crosshairs (center of magnifier view)
const selectRegionAtCrosshairs = useCallback(() => {
if (!cursorPositionRef.current || !svgRef.current || !containerRef.current) return
// Run region detection at the current cursor position (center of magnifier)
const { regionUnderCursor } = detectRegions(
cursorPositionRef.current.x,
cursorPositionRef.current.y
)
if (regionUnderCursor && !celebration) {
const region = mapData.regions.find((r) => r.id === regionUnderCursor)
if (region) {
handleRegionClickWithCelebration(regionUnderCursor, region.name)
}
}
// Dismiss magnifier after selection attempt
dismissMagnifier()
}, [
detectRegions,
mapData.regions,
handleRegionClickWithCelebration,
celebration,
dismissMagnifier,
])
// ============================================================================
// Context Values
// ============================================================================
// Magnifier context value - provides magnifier-specific state to child components
const magnifierContextValue = useMemo<MagnifierContextValue>(
() => ({
// Refs
containerRef,
svgRef,
magnifierRef,
cursorPositionRef,
scaleProbe1Ref,
scaleProbe2Ref,
anchorProbeRef,
anchorSvgPositionRef,
// Position & Animation (cursorPosition comes from state machine)
cursorPosition,
zoomSpring,
magnifierSpring,
parsedViewBox,
safeZoneMargins: SAFE_ZONE_MARGINS,
// Magnifier State
showMagnifier,
setShowMagnifier,
isMagnifierExpanded,
setIsMagnifierExpanded,
targetOpacity,
setTargetOpacity,
targetZoom,
setTargetZoom,
// Interaction State Machine
interaction,
// Derived Interaction State
mobileMapDragTriggeredMagnifier,
isMobileMapDragging,
isMagnifierDragging: isMagnifierDraggingFromMachine,
pointerLocked,
// Device & Theme
isDark,
isTouchDevice,
canUsePrecisionMode,
// Precision Mode
precisionModeThreshold: PRECISION_MODE_THRESHOLD,
precisionCalcs,
// Zoom Controls
getCurrentZoom,
highZoomThreshold: HIGH_ZOOM_THRESHOLD,
}),
[
containerRef,
svgRef,
magnifierRef,
cursorPositionRef,
scaleProbe1Ref,
scaleProbe2Ref,
anchorProbeRef,
anchorSvgPositionRef,
cursorPosition,
zoomSpring,
magnifierSpring,
parsedViewBox,
showMagnifier,
setShowMagnifier,
isMagnifierExpanded,
setIsMagnifierExpanded,
targetOpacity,
setTargetOpacity,
targetZoom,
setTargetZoom,
interaction,
mobileMapDragTriggeredMagnifier,
isMobileMapDragging,
isMagnifierDraggingFromMachine,
pointerLocked,
isDark,
isTouchDevice,
canUsePrecisionMode,
precisionCalcs,
getCurrentZoom,
]
)
// Map game context value - provides game-specific state to child components
const mapGameContextValue = useMemo<MapGameContextValue>(
() => ({
// Map Data
mapData,
displayViewBox,
// Game Progress
regionsFound,
hoveredRegion,
setHoveredRegion,
currentPrompt,
// Animations
celebration,
giveUpReveal,
isGiveUpAnimating,
celebrationFlashProgress,
giveUpFlashProgress,
// Hot/Cold
effectiveHotColdEnabled,
hotColdFeedbackType,
magnifierBorderStyle,
crosshairHeatStyle,
// Debug
effectiveShowDebugBoundingBoxes,
effectiveShowMagnifierDebugInfo,
debugBoundingBoxes,
// Multiplayer
gameMode,
currentPlayer,
localPlayerId,
// Callbacks
getPlayerWhoFoundRegion,
showOutline,
handleRegionClickWithCelebration,
selectRegionAtCrosshairs,
requestPointerLock,
}),
[
mapData,
displayViewBox,
regionsFound,
hoveredRegion,
setHoveredRegion,
currentPrompt,
celebration,
giveUpReveal,
isGiveUpAnimating,
celebrationFlashProgress,
giveUpFlashProgress,
effectiveHotColdEnabled,
hotColdFeedbackType,
magnifierBorderStyle,
crosshairHeatStyle,
effectiveShowDebugBoundingBoxes,
effectiveShowMagnifierDebugInfo,
debugBoundingBoxes,
gameMode,
currentPlayer,
localPlayerId,
getPlayerWhoFoundRegion,
showOutline,
handleRegionClickWithCelebration,
selectRegionAtCrosshairs,
requestPointerLock,
]
)
return (
<div
ref={containerRef}
data-component="map-renderer"
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onClick={handleContainerClick}
onTouchStart={handleMapTouchStart}
onTouchMove={handleMapTouchMove}
onTouchEnd={handleMapTouchEnd}
className={css({
position: fillContainer ? 'absolute' : 'relative',
top: fillContainer ? 0 : undefined,
left: fillContainer ? 0 : undefined,
right: fillContainer ? 0 : undefined,
bottom: fillContainer ? 0 : undefined,
width: '100%',
height: '100%',
flex: fillContainer ? undefined : 1, // Fill available space in parent flex container
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
// Prevent text selection during drag operations
userSelect: 'none',
// Disable all default touch gestures - we handle touch events ourselves
touchAction: 'none',
// Prevent pull-to-refresh on mobile
overscrollBehavior: 'none',
})}
style={{
// Vendor-prefixed properties for text selection prevention (not supported in Panda CSS)
WebkitUserSelect: 'none',
WebkitTouchCallout: 'none',
// Sea/ocean background with wavy CSS pattern at screen pixel scale
backgroundColor: isDark ? '#1e3a5f' : '#a8d4f0',
backgroundImage: isDark
? `repeating-linear-gradient(
15deg,
transparent,
transparent 18px,
rgba(45, 74, 111, 0.5) 18px,
rgba(45, 74, 111, 0.5) 20px,
transparent 20px,
transparent 48px,
rgba(45, 74, 111, 0.4) 48px,
rgba(45, 74, 111, 0.4) 50px,
transparent 50px,
transparent 78px,
rgba(45, 74, 111, 0.3) 78px,
rgba(45, 74, 111, 0.3) 80px
)`
: `repeating-linear-gradient(
15deg,
transparent,
transparent 18px,
rgba(143, 196, 232, 0.5) 18px,
rgba(143, 196, 232, 0.5) 20px,
transparent 20px,
transparent 48px,
rgba(143, 196, 232, 0.4) 48px,
rgba(143, 196, 232, 0.4) 50px,
transparent 50px,
transparent 78px,
rgba(143, 196, 232, 0.3) 78px,
rgba(143, 196, 232, 0.3) 80px
)`,
backgroundSize: '100px 100px',
}}
>
<animated.svg
ref={svgRef}
viewBox={displayViewBox}
className={css({
// Fill the entire container - viewBox controls what portion of map is visible
width: '100%',
height: '100%',
// Hide native cursor on desktop since we show custom crosshair
cursor: hasAnyFinePointer ? 'none' : 'pointer',
transformOrigin: 'center center',
})}
style={{
// No aspectRatio - the SVG fills the container and viewBox is calculated
// to match the container's aspect ratio via calculateFitCropViewBox
// CSS transform for zoom animation during give-up reveal
transform: to(
[mainMapSpring.scale, mainMapSpring.translateX, mainMapSpring.translateY],
(s, tx, ty) => `scale(${s}) translate(${tx / s}px, ${ty / s}px)`
),
}}
>
{/* Render all regions (included + excluded) */}
<RegionRenderProvider
isDark={isDark}
pointerLocked={pointerLocked}
hasAnyFinePointer={hasAnyFinePointer}
giveUpFlashProgress={giveUpFlashProgress}
hintFlashProgress={hintFlashProgress}
celebrationFlashProgress={celebrationFlashProgress}
isGiveUpAnimating={isGiveUpAnimating}
celebrationActive={!!celebration}
>
{[...mapData.regions, ...excludedRegions].map((region) => {
const isExcluded = excludedRegionIds.has(region.id)
const isFound = regionsFound.includes(region.id) || isExcluded
const playerId = !isExcluded && isFound ? getPlayerWhoFoundRegion(region.id) : null
return (
<RegionPath
key={region.id}
region={region}
isExcluded={isExcluded}
isFound={isFound}
playerId={playerId}
isBeingRevealed={giveUpReveal?.regionId === region.id}
isBeingHinted={hintActive?.regionId === region.id}
isCelebrating={celebration?.regionId === region.id}
isHovered={hoveredRegion === region.id}
networkHover={networkHoveredRegions[region.id]}
showOutline={showOutline(region)}
onMouseEnter={() => setHoveredRegion(region.id)}
onMouseLeave={() => setHoveredRegion(null)}
onClick={() => handleRegionClickWithCelebration(region.id, region.name)}
/>
)
})}
</RegionRenderProvider>
{/* Debug: Render bounding boxes (only if enabled) */}
{effectiveShowDebugBoundingBoxes &&
debugBoundingBoxes.map((bbox) => {
// Color based on acceptance and importance
// Green = accepted, Orange = high importance, Yellow = medium, Gray = low
const importance = bbox.importance ?? 0
let strokeColor = '#888888' // Default gray for low importance
let fillColor = 'rgba(136, 136, 136, 0.1)'
if (bbox.wasAccepted) {
strokeColor = '#00ff00' // Green for accepted region
fillColor = 'rgba(0, 255, 0, 0.15)'
} else if (importance > 1.5) {
strokeColor = '#ff6600' // Orange for high importance (2.0× boost + close)
fillColor = 'rgba(255, 102, 0, 0.1)'
} else if (importance > 0.5) {
strokeColor = '#ffcc00' // Yellow for medium importance
fillColor = 'rgba(255, 204, 0, 0.1)'
}
return (
<g key={`bbox-${bbox.regionId}`}>
<rect
x={bbox.x}
y={bbox.y}
width={bbox.width}
height={bbox.height}
fill={fillColor}
stroke={strokeColor}
strokeWidth={viewBoxWidth / 500}
vectorEffect="non-scaling-stroke"
strokeDasharray="3,3"
pointerEvents="none"
opacity={0.9}
/>
</g>
)
})}
{/* Arrow marker definition */}
<defs>
<marker id="arrowhead" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">
<polygon points="0 0, 10 3, 0 6" fill={isDark ? '#60a5fa' : '#3b82f6'} />
</marker>
<marker
id="arrowhead-found"
markerWidth="10"
markerHeight="10"
refX="8"
refY="3"
orient="auto"
>
<polygon points="0 0, 10 3, 0 6" fill="#16a34a" />
</marker>
{/* Player emoji patterns for region backgrounds */}
{Object.values(playerMetadata).map((player) => (
<pattern
key={`pattern-${player.id}`}
id={`player-pattern-${player.id}`}
width="60"
height="60"
patternUnits="userSpaceOnUse"
>
<rect width="60" height="60" fill={player.color} opacity="0.2" />
<text
x="30"
y="30"
fontSize="50"
textAnchor="middle"
dominantBaseline="middle"
opacity="0.5"
>
{player.emoji}
</text>
</pattern>
))}
</defs>
{/* Magnifier region indicator on main map */}
{showMagnifier && cursorPosition && svgRef.current && containerRef.current && (
<animated.rect
x={zoomSpring.to((zoom: number) => {
const containerRect = containerRef.current!.getBoundingClientRect()
const svgRect = svgRef.current!.getBoundingClientRect()
const {
x: viewBoxX,
y: viewBoxY,
width: viewBoxWidth,
height: viewBoxHeight,
} = parsedViewBox
// Account for preserveAspectRatio letterboxing
const viewport = getRenderedViewport(
svgRect,
viewBoxX,
viewBoxY,
viewBoxWidth,
viewBoxHeight
)
const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
const cursorSvgX = (cursorPosition.x - svgOffsetX) / viewport.scale + viewBoxX
// Calculate leftover dimensions for magnifier sizing
const leftoverW =
containerRect.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverH =
containerRect.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
const { width: magnifiedWidth } = getAdjustedMagnifiedDimensions(
viewBoxWidth,
viewBoxHeight,
zoom,
leftoverW,
leftoverH
)
return cursorSvgX - magnifiedWidth / 2
})}
y={zoomSpring.to((zoom: number) => {
const containerRect = containerRef.current!.getBoundingClientRect()
const svgRect = svgRef.current!.getBoundingClientRect()
const {
x: viewBoxX,
y: viewBoxY,
width: viewBoxWidth,
height: viewBoxHeight,
} = parsedViewBox
// Account for preserveAspectRatio letterboxing
const viewport = getRenderedViewport(
svgRect,
viewBoxX,
viewBoxY,
viewBoxWidth,
viewBoxHeight
)
const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
const cursorSvgY = (cursorPosition.y - svgOffsetY) / viewport.scale + viewBoxY
// Calculate leftover dimensions for magnifier sizing
const leftoverW =
containerRect.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverH =
containerRect.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
const { height: magnifiedHeight } = getAdjustedMagnifiedDimensions(
viewBoxWidth,
viewBoxHeight,
zoom,
leftoverW,
leftoverH
)
return cursorSvgY - magnifiedHeight / 2
})}
width={zoomSpring.to((zoom: number) => {
const containerRect = containerRef.current!.getBoundingClientRect()
const { width: viewBoxWidth, height: viewBoxHeight } = parsedViewBox
// Calculate leftover dimensions for magnifier sizing
const leftoverW =
containerRect.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverH =
containerRect.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
const { width } = getAdjustedMagnifiedDimensions(
viewBoxWidth,
viewBoxHeight,
zoom,
leftoverW,
leftoverH
)
return width
})}
height={zoomSpring.to((zoom: number) => {
const containerRect = containerRef.current!.getBoundingClientRect()
const { width: viewBoxWidth, height: viewBoxHeight } = parsedViewBox
// Calculate leftover dimensions for magnifier sizing
const leftoverW =
containerRect.width - SAFE_ZONE_MARGINS.left - SAFE_ZONE_MARGINS.right
const leftoverH =
containerRect.height - SAFE_ZONE_MARGINS.top - SAFE_ZONE_MARGINS.bottom
const { height } = getAdjustedMagnifiedDimensions(
viewBoxWidth,
viewBoxHeight,
zoom,
leftoverW,
leftoverH
)
return height
})}
fill="none"
stroke={isDark ? '#60a5fa' : '#3b82f6'}
strokeWidth={viewBoxWidth / 500}
vectorEffect="non-scaling-stroke"
strokeDasharray="5,5"
pointerEvents="none"
opacity={0.8}
/>
)}
</animated.svg>
{/* Labels for found regions - rendered via LabelLayer component */}
<LabelLayer
labelPositions={labelPositions}
smallRegionLabelPositions={smallRegionLabelPositions}
cursorPosition={cursorPosition}
hoveredRegion={hoveredRegion}
regionsFound={regionsFound}
isGiveUpAnimating={isGiveUpAnimating}
isDark={isDark}
playerMetadata={playerMetadata}
hasAnyFinePointer={hasAnyFinePointer}
celebration={celebration}
onRegionClick={handleRegionClickWithCelebration}
onHover={setHoveredRegion}
/>
{/* Debug: Bounding box labels as HTML overlays */}
{effectiveShowDebugBoundingBoxes &&
containerRef.current &&
svgRef.current &&
debugBoundingBoxes.map((bbox) => {
const importance = bbox.importance ?? 0
let strokeColor = '#888888'
if (bbox.wasAccepted) {
strokeColor = '#00ff00'
} else if (importance > 1.5) {
strokeColor = '#ff6600'
} else if (importance > 0.5) {
strokeColor = '#ffcc00'
}
// Convert SVG coordinates to pixel coordinates (accounting for preserveAspectRatio)
const containerRect = containerRef.current!.getBoundingClientRect()
const svgRect = svgRef.current!.getBoundingClientRect()
const {
x: viewBoxX,
y: viewBoxY,
width: viewBoxWidth,
height: viewBoxHeight,
} = parsedViewBox
const viewport = getRenderedViewport(
svgRect,
viewBoxX,
viewBoxY,
viewBoxWidth,
viewBoxHeight
)
const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
// Convert bbox center from SVG coords to pixels
const centerX = (bbox.x + bbox.width / 2 - viewBoxX) * viewport.scale + svgOffsetX
const centerY = (bbox.y + bbox.height / 2 - viewBoxY) * viewport.scale + svgOffsetY
return (
<div
key={`bbox-label-${bbox.regionId}`}
style={{
position: 'absolute',
left: `${centerX}px`,
top: `${centerY}px`,
transform: 'translate(-50%, -50%)',
pointerEvents: 'none',
zIndex: 15,
fontSize: '10px',
fontWeight: 'bold',
color: strokeColor,
textAlign: 'center',
textShadow: '0 0 2px black, 0 0 2px black, 0 0 2px black',
whiteSpace: 'nowrap',
}}
>
<div>{bbox.regionId}</div>
<div style={{ fontSize: '8px', fontWeight: 'normal' }}>{importance.toFixed(2)}</div>
</div>
)
})}
{/* Custom Cursor - Visible on desktop when cursor is on the map */}
{cursorPosition && hasAnyFinePointer && (
<CustomCursor
position={cursorPosition}
squish={cursorSquish}
rotationAngle={rotationAngle}
heatStyle={crosshairHeatStyle}
isDark={isDark}
regionName={currentRegionName}
flagEmoji={currentFlagEmoji}
/>
)}
{/* Heat crosshair overlay on main map - shows when hot/cold enabled (desktop non-pointer-lock) */}
{effectiveHotColdEnabled && cursorPosition && !pointerLocked && hasAnyFinePointer && (
<div
data-element="main-map-heat-crosshair"
style={{
position: 'absolute',
left: `${cursorPosition.x}px`,
top: `${cursorPosition.y}px`,
pointerEvents: 'none',
zIndex: 150,
transform: 'translate(-50%, -50%)',
}}
>
<HeatCrosshair
size={40}
rotationAngle={rotationAngle}
heatStyle={crosshairHeatStyle}
shadowIntensity={0.6}
/>
</div>
)}
{/* Magnifier overlay - centers on cursor position */}
{/* Wrapped in providers to enable context-based state access */}
{cursorPosition && (
<MagnifierProvider value={magnifierContextValue}>
<MapGameProvider value={mapGameContextValue}>
{/* MagnifierOverlayWithHandlers calls useMagnifierTouchHandlers inside context */}
<MagnifierOverlayWithHandlers
rotationAngle={rotationAngle}
touchHandlerOptions={touchHandlerOptions}
/>
{/* Zoom lines connecting indicator to magnifier - creates "pop out" effect */}
{showMagnifier && (
<ZoomLinesOverlay
svgRef={svgRef}
containerRef={containerRef}
cursorPosition={cursorPosition}
parsedViewBox={parsedViewBox}
safeZoneMargins={SAFE_ZONE_MARGINS}
targetTop={targetTop}
targetLeft={targetLeft}
targetOpacity={targetOpacity}
currentZoom={getCurrentZoom()}
highZoomThreshold={HIGH_ZOOM_THRESHOLD}
isDark={isDark}
/>
)}
</MapGameProvider>
</MagnifierProvider>
)}
{/* Debug: Auto zoom detection visualization (dev only) */}
{effectiveShowMagnifierDebugInfo && cursorPosition && containerRef.current && (
<AutoZoomDebugOverlay
cursorPosition={cursorPosition}
containerRef={containerRef}
detectRegions={detectRegions}
zoomSearchDebugInfo={zoomSearchDebugInfo}
targetLeft={targetLeft}
getCurrentZoom={getCurrentZoom}
targetZoom={targetZoom}
/>
)}
{/* Hot/Cold Debug Panel - shows enable conditions and current state */}
{isVisualDebugEnabled && (
<HotColdDebugPanel
assistanceAllowsHotCold={assistanceAllowsHotCold}
assistanceLevel={assistanceLevel}
hotColdEnabled={hotColdEnabled}
hasAnyFinePointer={hasAnyFinePointer}
showMagnifier={showMagnifier}
isMobileMapDragging={isMobileMapDragging}
gameMode={gameMode}
currentPlayer={currentPlayer}
localPlayerId={localPlayerId}
hotColdFeedbackType={hotColdFeedbackType}
currentPrompt={currentPrompt}
/>
)}
{/* Other players' cursors - show in multiplayer when not exclusively our turn */}
<NetworkCursors
svgRef={svgRef}
containerRef={containerRef}
parsedViewBox={parsedViewBox}
otherPlayerCursors={otherPlayerCursors}
viewerId={viewerId}
gameMode={gameMode}
currentPlayer={currentPlayer}
localPlayerId={localPlayerId}
playerMetadata={playerMetadata}
memberPlayers={memberPlayers}
/>
{/* Dev-only crop tool for getting custom viewBox coordinates */}
<DevCropTool
svgRef={svgRef}
containerRef={containerRef}
viewBox={displayViewBox}
mapId={selectedMap}
continentId={selectedContinent}
/>
{/* Debug overlay showing safe zone rectangles */}
{effectiveShowSafeZoneDebug && fillContainer && (
<SafeZoneDebugOverlay
svgDimensions={svgDimensions}
safeZoneMargins={SAFE_ZONE_MARGINS}
displayViewBox={displayViewBox}
mapData={mapData}
/>
)}
{/* Celebration overlay - shows confetti and sound when region is found */}
{celebration && (
<CelebrationOverlay
celebration={celebration}
regionCenter={getCelebrationRegionCenter()}
onComplete={handleCelebrationComplete}
reducedMotion={false}
/>
)}
</div>
)
}
|