All files / src/edit EditStage.ts

64.57% Statements 1706/2642
65.41% Branches 435/665
58.16% Functions 114/196
64.57% Lines 1706/2642

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 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343                                                      2x 2x 2x 2x   2x 2x 2x 2x 2x   2x 2x   2x 2x                               2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x                                                                                                                                                                                                                                                                           2x     2x     2x   2x   2x             2x                 2x 3x 3x 3x     2x     2x   2x   2x   2x   2x             2x   2x   2x           86x 86x 86x     2x   2x 2x 2x 2x 2x 2x   2x 2x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x 24x   24x 24x 24x   24x 24x 24x 24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x   24x   24x 24x   24x   24x   24x           24x 24x   24x 24x 24x   24x 24x   24x 24x 24x   24x 24x   24x   24x 24x 24x 24x   24x   24x   24x 24x   24x   24x   24x 24x   24x   24x   24x   24x 24x 24x 24x 24x 24x 24x   2x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 23x 1x 1x 1x 1x 1x 1x 1x 1x 24x 1x 4x 4x 4x 1x 24x 24x 24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 23x 1x 24x 24x 24x 24x 72x 72x 72x 72x 72x 72x 72x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x     24x 24x 24x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x       1x       1x 1x 24x 24x 24x 24x 24x 24x 24x 24x   24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x 24x 24x 24x 24x     2x 24x 24x                     2x 129x 129x 129x 129x 129x 129x 516x 516x 129x 129x 129x 129x   2x 24x 24x 24x 24x 24x     24x 24x 24x       24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x                 24x 24x                       2x 24x 24x 24x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 1x 1x 24x 1x 1x 1x 1x 24x   24x 1x 1x 1x 24x   2x 24x 24x 24x 24x 24x 24x 24x     24x 24x 24x   2x 24x 24x 24x             2x     22x 22x   22x 22x 22x 22x 22x     22x 22x       22x 22x 22x 22x     2x 24x 24x 24x 24x     2x             2x                                                             2x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 8x 8x 8x 8x 46x 46x 46x 46x   2x 13x 13x 13x 13x 13x 13x 13x     2x 11x 11x 11x 11x 11x 11x 11x 11x 11x     2x                           2x 2x 2x   2x       2x         2x               2x                     2x                             2x                                 2x 299x 299x 299x 299x 299x 299x     299x       299x             2x                       2x                                 2x                                                 2x 24x 13x 13x 13x 24x     2x 13x 13x 13x 13x 13x 13x   13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 52x 52x 52x 52x 52x 13x 26x 26x 26x 26x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x   2x                   2x                                 2x 21x 21x 42x 42x 42x 42x 42x 42x 42x 21x     2x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x             2x 153x 153x 153x   2x               2x         2x         2x           2x                                                                                         2x                           2x 133x 35x 14x 14x 35x 133x     2x 14x 14x   2x 14x 14x 14x 14x 14x 14x 14x 14x   14x 13x 13x 13x                                       13x   14x 14x     14x 14x 14x 14x 14x 14x 14x     14x 14x                                                 14x 14x 5x 14x 14x 14x         14x 14x         14x   14x     1x 1x 1x 1x 1x 1x 14x 14x             2x 14x 14x 14x 56x 56x 56x 56x 56x 56x   56x 56x 56x 56x         56x 56x 56x 56x 56x 56x 56x 14x   2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     2x 14x       14x       14x   14x             2x 14x       14x 14x   2x                   2x                             2x                                     2x       2x         2x                   2x         2x 24x 24x       24x                                                                                       24x 24x                                                       24x 24x                                                                                               24x 24x     24x 24x           24x 24x     24x 24x 24x 24x                               24x 24x 24x         24x 24x                   2x 48x       48x 48x       48x                                                                                 48x 48x                                     48x 48x                                     48x 48x         48x 48x     48x 48x           48x 48x     2x                                         2x                                 2x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 1x 3x 3x 1x       3x     2x 2x 2x 2x             2x                                                       2x                                                                         2x 2x             2x     2x 2x 2x 2x 1x 1x 1x 1x 2x   2x 23x 23x 23x 11x 11x   12x 23x 12x 23x 23x 23x     23x 1x 1x   1x 12x 2x 1x 11x   9x   9x 1x       1x 1x 1x 9x   8x   8x   8x         8x   3x 3x 3x 2x 8x   5x   3x 3x 3x 3x   3x 5x             2x   2x   2x   2x 2x 2x 23x 10x 10x 10x 23x   2x                     2x 1x 1x 1x   2x 1x 1x 1x 1x     2x                                                               2x 127x 127x 127x             127x 127x 127x 127x 127x                         127x 127x 127x     127x 127x 127x 127x 127x 127x             127x 127x             2x                 2x 127x 127x 127x 127x 127x           2x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 127x 381x 381x 381x 127x             2x 181x 181x 181x 181x 181x           2x 90x 90x 90x     2x 90x 90x 4x 90x 1x 1x 1x 4x 90x     2x 46x 46x 46x 46x 46x 46x 46x               2x 15x 15x 15x 15x 15x 15x 15x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x               2x                       2x                                 2x 50x 50x 50x   2x 144x 144x 144x 144x     2x 14x 5x 5x 5x 14x 14x             2x 25x 25x 25x 25x 25x 25x 25x 25x     2x 231x 231x     2x 25x 7x 7x 5x 5x 5x 5x 5x 5x 5x 7x 7x 25x                 2x 31x 31x 31x 31x 14x 14x 14x 17x 17x 17x 31x 31x 31x 31x 31x 31x 31x 31x 1x 1x 1x 1x 31x     31x 31x     2x 15x 15x 15x 15x 15x           2x 2x 2x 2x 15x 15x 15x     2x 1x 1x 1x 1x 1x 1x 1x     2x                 2x 5x 5x 5x 5x     2x 4x 4x 4x 4x 4x     2x 2x 2x 2x 2x 2x 2x 2x     2x 5x 5x 5x 5x     2x 1x 1x 1x 1x     2x                     2x 1x 1x 1x 1x   2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x               2x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 217x 31x 31x   2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     2x                     2x 1x 1x 1x 1x 1x 1x 1x 1x 1x   2x 8x 1x 1x 1x 1x 1x 8x     2x 14x 14x 14x 14x 14x 5x 5x 5x 5x 5x 5x 5x 14x 14x 14x     2x 129x 129x 129x 120x 120x 120x 120x 9x 9x 129x 2x 2x 2x 7x 7x 7x 7x 7x 7x 7x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x     2x 137x 137x 137x   137x 137x 137x 137x 137x 93x 44x 137x 137x 93x 93x 93x 93x 93x 93x 24x   69x 2x 67x 93x 93x 93x 93x 44x 137x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 137x 6x 6x 6x 6x 6x 2x 4x 6x 6x 137x 38x 38x 38x 38x 44x 137x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 137x 14x 14x 14x 14x 14x 14x 14x 14x 14x 44x 137x   2x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x     41x 44x                               44x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x   2x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x   2x 128x 128x 128x 128x 113x 113x 113x 113x 113x 113x 113x 113x 113x 15x 15x 15x   15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x     15x 15x 15x 15x 15x 15x 15x 15x 15x     128x 128x 128x 128x 128x                                     128x   2x 127x 127x 127x 127x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 174x 127x 127x 47x   47x 7x 7x 7x 7x 47x 127x 127x 127x 127x 127x 127x 127x 127x             2x 1x 1x 1x 1x     2x 2x 2x 2x 2x     2x 2x 4x 4x 2x               2x 287x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 287x 287x   2x 146x 146x 146x 299x 299x 299x 299x 29x 14x 14x 299x 299x 299x 299x 299x 299x 5x 5x 5x 5x 5x 5x 5x   299x 299x 299x 299x 299x 299x 299x 299x 299x 299x 299x 299x 299x 12x 12x 12x   287x     287x 287x 287x 287x 287x 287x 287x 287x   287x 287x 287x 287x 287x 287x 287x 287x 287x 146x 146x 144x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x 146x   2x 12x 12x 12x     12x 12x 12x 12x                       2x 12x   12x 11x 11x 11x 11x 9x 9x 9x 9x 9x 8x 6x 4x 4x 4x 4x 4x 5x 5x 5x 2x 2x 11x 12x 11x 11x         4x 4x 4x 4x 4x 4x 4x 3x 3x 7x 7x 7x 11x         12x 12x 12x 12x                 2x 127x 127x                                                                                               127x 127x 127x 127x                                             127x 127x                                             127x     127x 127x     2x                 2x 129x 129x 129x   2x 129x 129x 129x 129x 126x 2x 2x 2x 2x 2x 2x 2x 2x 129x 129x 129x 129x 129x 129x 24x 105x 129x 129x   129x 129x   129x 129x 129x           2x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x 24x 24x 24x 2x  
/**
 * The stage where the reader edits the reference (SPECS §27.3, §27.4).
 *
 * The third caller of the stage dialog, after the enlarged model and a
 * figure's *customise*: the picture, a sidebar of what is done to it, the grip
 * between them. **One map and its tracks** — the file's whole-genome picture
 * (§27.9), drawn through the edit, with a pieces bar along its top and its left
 * and the lanes placed on the map under it, drawn through the same lens — and
 * never a deck.
 *
 * Every act is a step on the file's {@link EditStore}, so the stage holds no
 * edit of its own: it draws what the store folds into, and a step made here is
 * a step the heading's chip counts and a workspace carries. What the stage does
 * hold is the hand: the view, the selection, the drag, and the preview a drag
 * draws — the map rearranged under the pointer through the edit it would make,
 * with nothing kept until the drop.
 *
 * **Escape never closes it.** It cancels, innermost first — a drag, then the
 * selection — and the stage is closed by its ✕. Its keys are live only while it
 * is open, and printed on the controls that perform them (§26.4).
 */
 
import type { GroupSettings } from '../annotations/groups'
import type { ManualStore } from '../annotations/manual'
import type { MapId } from '../annotations/placement'
import type { AnnotationStore } from '../annotations/store'
import type { AnnotationClient } from '../annotations/worker/client'
import { EditedAssembly, isGap, lengthsOf, wholeOriginal, type AsideReason, type EditStep, type Piece, type ReferenceEdit } from '../genome/edit'
import { formatLocus, formatPosition } from '../genome/assembly'
import { bpAt } from '../render/locus'
import { Scale } from '../render/scale'
import type { EditStore } from '../state/referenceEdit'
import { AnnotationLanes, type LaneGeometry } from '../ui/AnnotationLanes'
import { el } from '../ui/dom'
import { TAB_WALKS, tabStep } from '../ui/tabWalk'
import { icon, iconButton } from '../ui/icons'
import { closeMenu, openMenu, type MenuItem } from '../ui/Menu'
import type { Modal } from '../ui/Modal'
import { stageDialog } from '../ui/StageDialog'
import { fmt } from '../units'
import type { GenomeLinksResult, PictureResult, StageWindowSide } from '../worker/protocol'
import { BAR_NAMES, BAR_THICKNESS, drawBar, drawOverlay, readInk, type StageInk } from './draw'
import {
  dropPlace,
  dropStep,
  endTargets,
  isWholeSequence,
  landed,
  partStretch,
  sequenceStretch,
  shiftStep,
  snapUnit,
  stretchBetween,
  stretchUnits,
  type Snapped,
  type SnapTarget,
  type Stretch,
} from './gestures'
import { LensGrid, type GridLayout } from './grid'
import { adjustableEnds, adjustSuggestion } from './adjust'
import { pointKey, pointsOf, refinedSuggestion, type RefinedPoint, type RefinePoint } from './refine'
import { LiveDotplot } from './LiveDotplot'
import { sequenceSets } from './dotplotLines'
import { ExportCard, type ExportCardProps } from './ExportCard'
import { readSequenceEvidence, type SequenceEvidence } from './sequenceEvidence'
import { drawSuggestions, markSpots, type MarkedSuggestion } from './marks'
import { paintPicture, paintWindow, pictureColours, windowSide, type WindowRead } from './paint'
import { Rail, type RailItem } from './rail'
import { INITIAL_WEIGHTS, learn, suggest, type Suggested, type Suggestion } from './suggest'
import { stepText } from './words'
import type { Learned } from '../state/referenceEdit'
import { recall, remember } from '../state/UiMemory'
 
/** The lanes the stage draws, as the map they were placed on has them. */
export interface StageLanes {
  store: AnnotationStore
  map?: MapId
  manual?: ManualStore
  client?: AnnotationClient
  groups?: GroupSettings
}
 
/** A read of the picture in flight, and the way to stop it. */
export interface PictureRequest {
  promise: Promise<PictureResult>
  cancel(): void
}
 
export interface EditStageProps {
  /** The file's own name, for the heading. */
  title: string
  memoryKey: () => string
  store: EditStore
  /**
   * Start reading the whole-genome picture, reporting progress as it goes —
   * of these sequences of the map alone, where they are given: one genome of a
   * metagenome and the contigs it may bring in (§27.10).
   */
  readPicture(onProgress: (done: number, total: number, note?: string) => void, contigs?: string[], cells?: number): PictureRequest
  /**
   * On one genome of a metagenome (§27.10): read every contact of the file for
   * where the genome's contigs, and the others, belong — without being asked
   * where `auto`, as on a file small enough to read in a moment.
   */
  genomeLinks?: {
    read(contigs: string[], onProgress: (done: number, total: number) => void): { promise: Promise<GenomeLinksResult>; cancel(): void }
    auto: boolean
  }
  /**
   * Count the suggestions for an edit off the stage's thread (§27.12), against
   * what the method weighs of the picture — kept where it was read, under the
   * picture's id (`PictureResult.methodKept`). Absent, a picture that carries
   * the method's data is weighed here.
   */
  suggest?(input: SuggestRequest): { promise: Promise<Suggested>; cancel(): void }
  /**
   * Read the window on screen finer than the picture (§27.9): a rung whose
   * bins are about a pixel, through the stage's edit. Absent, a zoom past the
   * picture's cell shows the cell enlarged.
   */
  readWindow?(request: WindowRequest): { promise: Promise<WindowRead | null>; cancel(): void }
  /**
   * Place a suggestion's points again at the finer rungs (§27.5), through the
   * stage's edit, off its thread: one answer a point, `null` where no finer
   * rung could. Absent, a suggestion is placed to the picture's cell.
   */
  refine?(request: RefineRequest): { promise: Promise<Array<RefinedPoint | null>>; cancel(): void }
  /** The map lifted through an edit, every rung, as an `.mcool` (§27.8). */
  liftContacts?: ExportCardProps['liftContacts']
  /** On a metagenome: the contig → MAG table every genome's edit makes (§27.10). */
  binning?: ExportCardProps['binning']
  /** The file's sequences the reader declared circular (§8.15), whose origin the stage may set (§27.4). */
  circular?: () => readonly string[]
  /** The map's colours, as its Map card has them. */
  colormap: string
  lanes?: StageLanes
  onClose(): void
}
 
/** What a finer read of the window on screen is asked for (§27.9). */
export interface WindowRequest {
  edit: ReferenceEdit
  /** Names the edit, so the map drawn through it is kept while it stands. */
  key: string
  /** Base pairs a pixel: the rung wanted is the coarsest no coarser. */
  binsize: number
  /** The picture's cell, which a rung must be finer than to be worth reading. */
  coarser: number
  rows: StageWindowSide
  cols: StageWindowSide
  balance: boolean
}
 
/** What a count of the suggestions off the stage's thread is asked for. */
export interface RefineRequest {
  edit: ReferenceEdit
  points: RefinePoint[]
  /** The picture's cell, in base pairs: where the method placed them. */
  cell: number
  /** The finest bin the map is deep enough to show. */
  least: number
  balance: boolean
}
 
export interface SuggestRequest {
  picture: number
  edit: ReferenceEdit
  layout: GridLayout
  weights?: number[]
  evidence?: SequenceEvidence
}
 
/** What is selected: a stretch on the diagonal, or a box of two off it. */
type Selection = { kind: 'stretch'; stretch: Stretch } | { kind: 'box'; rows: Stretch; cols: Stretch }
 
/** A drag in progress. */
type Drag =
  | { kind: 'pan'; x: number; y: number }
  | { kind: 'along'; anchor: number; x: number; y: number; moved: boolean }
  | { kind: 'box'; ax: number; ay: number; x: number; y: number; moved: boolean }
  /** An end of a suggestion dragged to adjust it (§27.6): which suggestion, which end. */
  | { kind: 'adjust'; key: string; end: 0 | 1; x: number; y: number; moved: boolean }
  | {
      kind: 'move'
      stretch: Stretch
      units: [number, number]
      /** Where along the stretch it was taken hold of, in units. */
      grip: number
      x: number
      y: number
      moved: boolean
      strand: 1 | -1
      copy: boolean
      /** ⇧ held: at an edge between two sequences it goes into one, joined to its end, rather than between them (§27.4). */
      fuse: boolean
      /** Pressed on what was selected already: a press that does not travel widens it to its sequence, or narrows it back. */
      again: boolean
      /** Where it would go is between two sequences: ⇧ would join it instead. */
      between?: boolean
      step: EditStep | null
      /** The unit the stretch would start at, before the step. */
      mark: number | null
    }
 
/** The fewest contacts a contig's links say anything with, on a genome's card (§27.10). */
const LEAST_LINKS = 5
 
/** The share of a contig's contacts with a genome from which it is offered to it. */
const BELONGS = 0.4
 
/** Pixels within which the pointer snaps along an axis (§27.4). */
const SNAP_PX = 8
/** Pixels from the diagonal within which a drag selects along it. */
const DIAGONAL_PX = 12
/** Travel, in pixels, before a press becomes a drag. */
const DRAG_PX = 4
 
/**
 * How wide a picture cell must be on screen, in pixels, before the window is
 * read again finer than the picture (§27.9): below it the picture shows as
 * much as a pixel can.
 */
const WINDOW_CELL_PX = 2
 
/**
 * What a value of a window read at `binsize` is multiplied by to be on the
 * picture's scale (§27.9). A picture cell is the sum of `stride²` pixels of
 * its rung; a pixel of a rung `k` times coarser than the window's holds, raw,
 * the sum of `k²` of the window's — and, balanced, about `k` of them, since
 * balancing sets each rung's rows to the same total over `k` times fewer bins.
 */
export function windowScale(picture: Pick<PictureResult, 'binsize' | 'stride' | 'balanced'>, binsize: number): number {
  const k = picture.binsize / picture.stride / binsize
  return picture.stride * picture.stride * (picture.balanced ? k : k * k)
}
 
/** The picture's sizes a reader may choose, cells a side, the finest first (§27.9). */
const PICTURE_CELL_CHOICES: readonly number[] = [16_384, 8_192, 4_096, 2_048]
 
/** Where the picture's size is kept for a file. */
const PICTURE_CELLS_SCOPE = 'map:edit-cells'
/** The fewest cells a view may show a side. */
const MIN_SPAN = 12
/** Pixels within which the pointer snaps to a corner, measured in the plane (§27.4). */
const CORNER_PX = 10
/** The rail's width, beside the map. */
const RAIL_WIDTH = 150
/** The confidence auto mode applies at and above (§27.6). */
const AUTO_THRESHOLD = 0.5
/**
 * The least confidence a suggestion is offered at: one a curator would take one
 * time in seven or less is noise on the map, drawn where the reader is judging.
 * Still ranked — an answer about another can raise it — and still listed among
 * those turned down, to be offered again.
 */
const OFFER_FLOOR = 0.15
/** The most steps one run of auto mode makes. */
const AUTO_MOST = 40
/** The most suggestions, best first, whose points are placed at the finer rungs after a count (§27.5). */
const PLACE_MOST = 24
 
/** Who presses accept (§27.6). */
type Mode = 'manual' | 'review' | 'auto'
 
/** A confidence, as the stage writes it. */
function percent(confidence: number): string {
  return `${Math.round(confidence * 100)}%`
}
 
/** A suggestion's kind, in a word. */
const KIND_WORD: Record<Suggestion['kind'], string> = { split: 'split', turn: 'turn', move: 'move', join: 'join' }
 
const REASONS: Array<{ why: AsideReason; label: string; title: string }> = [
  { why: 'debris', label: 'debris', title: 'Short, unplaceable sequence the assembler left over' },
  { why: 'contaminant', label: 'contaminant', title: 'Not this organism’s: a vector, a bacterium, a sample from next door' },
  { why: 'haplotig', label: 'haplotig', title: 'The other copy of a stretch already in the assembly' },
  { why: 'unplaced', label: 'unplaced', title: 'Belongs to this genome, but the map cannot say where' },
]
 
export class EditStage {
  private readonly props: EditStageProps
  private readonly modal: Modal
  private readonly root: HTMLElement
  private readonly side: HTMLElement
  private readonly plot: HTMLElement
  private readonly readoutEl: HTMLElement
  private readonly statusEl: HTMLElement
  private readonly pictureCanvas: HTMLCanvasElement
  private readonly overlayCanvas: HTMLCanvasElement
  private readonly topBar: HTMLCanvasElement
  private readonly leftBar: HTMLCanvasElement
  /** A band per lane stack, lighting the selection on the tracks as on the map. */
  private readonly laneBands: Record<'top' | 'right' | 'bottom' | 'left', HTMLElement>
  private readonly lanes: AnnotationLanes | null
  private readonly undoButton: HTMLButtonElement
  private readonly redoButton: HTMLButtonElement
  private readonly selectionCard: HTMLElement
  private readonly historyCard: HTMLElement
  private readonly sequencesCard: HTMLElement
  private readonly pictureCard: HTMLElement
  private readonly suggestionsCard: HTMLElement
  /** On one genome of a metagenome: where its contigs and the others belong (§27.10). */
  private readonly genomeCard: HTMLElement
  private readonly exportCard: ExportCard
  private readonly modes: Record<Mode, HTMLButtonElement>
  private readonly modesEl: HTMLElement
  /** The corner dot plot against another reference, where the session holds one (§27.3). */
  private readonly dotplot: LiveDotplot | null
  private readonly rail: Rail
  private readonly reviewBar: HTMLElement
 
  private request: PictureRequest | null = null
  private picture: PictureResult | null = null
  private colours: Uint32Array | null = null
  private layout: GridLayout | null = null
  private grid: LensGrid | null = null
  /** The grid a drag is previewing, and where its stretch is in it. */
  private preview: { grid: LensGrid; units: [number, number] | null } | null = null
  private readonly sx = new Scale([0, 1], 1)
  private readonly sy = new Scale([0, 1], 1)
  private size = 0
  private dpr = 1
  private image: ImageData | null = null
  private pictureDirty = true
  private frame = 0
  private selection: Selection | null = null
  private hover: { x: Snapped; y: Snapped; px: number; py: number } | null = null
  private drag: Drag | null = null
  private space = false
  private alt = false
  private ink: StageInk | null = null
  /** Where the map sits in the plot, for the bands over the lanes around it. */
  private mapAt: { x: number; y: number } = { x: 0, y: 0 }
  /** The grid the lanes were last pointed at. */
  private lanesGrid: LensGrid | null = null
  /** What the method weighs, read with the picture (§27.5) — here, or kept where it was read under the picture's id. */
  private method: NonNullable<PictureResult['method']> | null = null
  private methodKept: number | null = null
  /** A count of the suggestions in flight off the stage's thread. */
  private recountRequest: { cancel(): void } | null = null
  /** Auto mode applying, one suggestion and one count at a time. */
  private autoRunning = false
  /** Suggestions whose ends the hand has dragged, by key, until the edit changes (§27.6). */
  private readonly adjustments = new Map<string, Suggestion>()
  /**
   * Where the finer rungs placed the points of the suggestions offered, for
   * the edit as it stands (§27.5), by point — `null` where they could not —
   * and the suggestions as they make them, until the placements change.
   */
  private readonly placements = new Map<string, RefinedPoint | null>()
  private placedMemo = new WeakMap<Suggestion, Suggestion>()
  /** The placement being read; the count it was for, which a newer one drops; and the whole run, which auto mode waits on. */
  private refineRequest: { cancel(): void } | null = null
  private refineRound = 0
  private refining: Promise<void> | null = null
  /** Names this stage's edits to the reader's worker, a new one each time the edit changes (§27.9). */
  private readonly token = Math.random().toString(36).slice(2)
  private editVersion = 0
  /** The window on screen read finer than the picture, for the edit `key` names; the read in flight; its timer. */
  private windowRead: { key: string; read: WindowRead; view: [number, number, number, number]; asked: number } | null = null
  private windowRequest: { cancel(): void } | null = null
  private windowTimer = 0
  /** The sequence whose name is being typed, on the sequences card; and a line about the last name refused. */
  private renaming: string | null = null
  private sequencesNote = ''
  /** The sequences the picture was read of, where not the whole map. */
  private drawn: Set<string> | null = null
  /** Where a genome's contigs and the others belong, read for the contigs `linksOf` names. */
  private links: GenomeLinksResult | null = null
  private linksOf = ''
  private linksRequest: { cancel(): void } | null = null
  private linksDone: number | null = null
  /** What the session's sequence says about the assembly (§27.5), once read; `null` until then or without one. */
  private evidence: SequenceEvidence | null = null
  /** Whether the sequence is being read for it. */
  private readingEvidence = false
  /** The suggestions for the edit as it stands, and a recount pending. */
  private suggested: Suggested | null = null
  private suggesting = 0
  /** What the reader's answers have taught the stage about this file (§27.6). */
  private learned: Learned
  /** The stretch a line hovered in the corner dot plot lies along, lit on the map (§27.3). */
  private linked: Stretch | null = null
  /** The suggestion lit — hovered on the map, the rail or the list — by key. */
  private lit: string | null = null
  private mode: Mode = 'manual'
  /** The suggestion review mode is on, by key. */
  private current: string | null = null
  /** Space held in review mode: the map as it would be with the current suggestion done. */
  private previewing = false
  /** What the rail was last painted from, so a frame that changes none of it leaves it be. */
  private railSignature = ''
  /** A move begun on a pieces bar: where the press was, on the page, until it travels. */
  private barPress: { x: number; y: number } | null = null
  private closed = false
  private readonly stopStore: () => void
  private readonly observer: ResizeObserver | null
  private readonly onKey: (event: KeyboardEvent) => void
  private readonly onKeyUp: (event: KeyboardEvent) => void
  private readonly onBlur: () => void
 
  constructor(props: EditStageProps) {
    this.props = props
 
    this.pictureCanvas = el('canvas', { class: 'edit-picture' })
    this.overlayCanvas = el('canvas', { class: 'edit-overlay', attrs: { tabindex: '0', 'aria-label': 'The edited map' } })
    this.topBar = el('canvas', { class: 'edit-bar edit-bar-top' })
    this.leftBar = el('canvas', { class: 'edit-bar edit-bar-left' })
    this.laneBands = {
      top: el('div', { class: 'edit-lane-band hidden' }),
      right: el('div', { class: 'edit-lane-band hidden' }),
      bottom: el('div', { class: 'edit-lane-band hidden' }),
      left: el('div', { class: 'edit-lane-band hidden' }),
    }
    this.statusEl = el('div', { class: 'edit-status' })
    this.plot = el(
      'div',
      { class: 'edit-plot' },
      this.topBar,
      this.leftBar,
      this.pictureCanvas,
      this.overlayCanvas,
      this.statusEl,
    )
 
    this.lanes =
      props.lanes === undefined
        ? null
        : new AnnotationLanes({
            store: props.lanes.store,
            ...(props.lanes.map === undefined ? {} : { map: props.lanes.map }),
            ...(props.lanes.manual === undefined ? {} : { manual: props.lanes.manual }),
            ...(props.lanes.client === undefined ? {} : { client: props.lanes.client }),
            ...(props.lanes.groups === undefined ? {} : { groups: props.lanes.groups }),
            onChange: () => this.schedule(),
          })
    if (this.lanes !== null) {
      for (const canvas of Object.values(this.lanes.canvases)) {
        canvas.classList.add('edit-lane')
        this.plot.append(canvas)
      }
    }
    this.plot.append(...Object.values(this.laneBands))
    this.rail = new Rail({ hover: (key) => this.setLit(key), pick: (key) => this.pick(key) })
    this.plot.append(this.rail.element)
    this.learned = props.store.learned
 
    this.readoutEl = el('div', { class: 'edit-readout', attrs: { 'aria-live': 'polite' } })
    const fitButton = iconButton('maximize', 'Show the whole assembly (0, or a double click)', () => this.fit(), {
      class: 'btn btn-icon',
      size: 15,
    })
    const zoomOut = iconButton('zoom-out', 'Zoom out (−)', () => this.zoomBy(2), { class: 'btn btn-icon', size: 15 })
    const zoomIn = iconButton('zoom-in', 'Zoom in (+)', () => this.zoomBy(0.5), { class: 'btn btn-icon', size: 15 })
    this.undoButton = iconButton('undo-2', 'Undo the last step (⌘Z)', () => props.store.undo(), {
      class: 'btn btn-icon',
      size: 15,
    })
    this.redoButton = iconButton('redo-2', 'Redo it (⇧⌘Z)', () => props.store.redo(), {
      class: 'btn btn-icon',
      size: 15,
    })
    const toolbar = el(
      'div',
      { class: 'edit-toolbar' },
      el('div', { class: 'edit-tools' }, fitButton, zoomOut, zoomIn),
      this.readoutEl,
      el('div', { class: 'edit-tools' }, this.undoButton, this.redoButton),
    )
    this.reviewBar = el('div', { class: 'edit-review hidden', attrs: { 'aria-live': 'polite' } })
    this.root = el('div', { class: 'edit-stage' }, toolbar, this.reviewBar, this.plot)
 
    this.selectionCard = el('section', { class: 'edit-card' })
    this.historyCard = el('section', { class: 'edit-card' })
    this.sequencesCard = el('section', { class: 'edit-card edit-sequences-card' })
    this.pictureCard = el('section', { class: 'edit-card edit-picture-card' })
    this.suggestionsCard = el('section', { class: 'edit-card edit-suggestions-card' })
    this.genomeCard = el('section', { class: 'edit-card edit-genome-card' })
    this.exportCard = new ExportCard({
      title: props.title,
      store: props.store,
      ...(props.lanes === undefined
        ? {}
        : { annotations: { store: props.lanes.store, ...(props.lanes.client === undefined ? {} : { client: props.lanes.client }) } }),
      ...(props.liftContacts === undefined ? {} : { liftContacts: props.liftContacts }),
      ...(props.binning === undefined ? {} : { binning: props.binning }),
    })
    const mode = (name: Mode, title: string): HTMLButtonElement =>
      el('button', {
        class: 'btn btn-toggle',
        text: name,
        title,
        attrs: { type: 'button', 'aria-pressed': String(name === 'manual') },
        on: { click: () => this.setMode(name) },
      })
    this.modes = {
      manual: mode('manual', 'The suggestions are guides — drawn, labelled, snapped to — and never apply themselves'),
      review: mode('review', 'Work through the suggestions, best first: Y takes one, N turns it down, and every answer teaches the ranking'),
      auto: mode('auto', `Apply every suggestion at ${percent(AUTO_THRESHOLD)} or more, best first — each a step to undo like any other`),
    }
    this.modesEl = el('div', { class: 'edit-modes', attrs: { role: 'group', 'aria-label': 'Who presses accept' } }, ...Object.values(this.modes))
    this.side = el('div', { class: 'edit-side-body' })
    this.arrangeSide()
 
    this.wireCanvas()
    this.wireBar(this.topBar, 'top')
    this.wireBar(this.leftBar, 'left')
    // The assembly against another reference the session holds, through the
    // edit, in the map's corner (§27.3).
    const lanes = props.lanes
    this.dotplot =
      lanes?.client === undefined
        ? null
        : LiveDotplot.of({
            store: lanes.store,
            client: lanes.client,
            assembly: () => this.props.store.assembly,
            framing: () => ({
              uri: props.title,
              rows: [0, 0],
              cols: [0, 0],
              binsize: 0,
              binsPerCell: 1,
              balance: false,
              value: 'count',
              normalise: null,
              level: 'bin',
              label: `${props.title} · sequences, no contact map`,
            }),
            say: (text) => {
              if (text === null) this.paintReadout()
              else this.readoutEl.textContent = text
            },
            frame: (sequence, from, to) => {
              const units = this.grid === null ? null : stretchUnits(this.grid, { sequence, from, to })
              if (units !== null) this.frameUnits(units[0], units[1])
            },
            light: (stretch) => {
              this.linked = stretch
              this.schedule()
            },
            memoryKey: props.memoryKey(),
          })
    if (this.dotplot !== null) this.plot.append(this.dotplot.element)
    this.onKey = (event) => this.key(event)
    this.onKeyUp = (event) => this.keyUp(event)
    this.onBlur = () => this.letGo()
    window.addEventListener('keydown', this.onKey, true)
    window.addEventListener('keyup', this.onKeyUp, true)
    window.addEventListener('blur', this.onBlur)
    this.stopStore = props.store.subscribe(() => this.edited())
 
    this.modal = stageDialog({
      // One genome of a metagenome is edited on its own (§27.10), and says so.
      title: props.store.edit.original.genome === undefined ? `Edit the reference · ${props.title}` : `Edit ${props.store.edit.original.genome} · ${props.title}`,
      variant: 'modal-edit',
      stage: this.root,
      stageClass: 'edit-stage-body',
      side: this.side,
      sideClass: 'edit-side',
      memoryKey: props.memoryKey,
      scope: 'edit:side',
      onResize: () => this.resized(),
      onEscape: () => this.escape(),
      onClose: () => this.teardown(),
    })
 
    this.observer =
      typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => this.resized())
    this.observer?.observe(this.plot)
    this.paintSide()
    this.read()
    requestAnimationFrame(() => this.resized())
  }
 
  /** Close the stage, as its ✕ does. */
  close(): void {
    this.modal.close()
  }
 
  // -------------------------------------------------------------------------
  // The picture
  // -------------------------------------------------------------------------
 
  /**
   * The picture's size, chosen: a coarser picture is read faster over a slow
   * link and weighed faster, and a zoom past its cell reads the window on
   * screen finer anyway (§27.9).
   */
  private cellsChoice(): HTMLElement {
    const select = el('select', {
      class: 'select edit-cells-select',
      attrs: { 'aria-label': 'Cells a side of the picture' },
      on: { change: () => this.setCells(Number(select.value)) },
    }) as HTMLSelectElement
    for (const cells of PICTURE_CELL_CHOICES) {
      select.append(el('option', { text: `${cells.toLocaleString('en-US')}${cells === PICTURE_CELL_CHOICES[0] ? ' (the finest)' : ''}`, attrs: { value: String(cells) } }))
    }
    select.value = String(this.cells())
    select.disabled = this.request !== null
    return el('label', { class: 'edit-cells' }, el('span', { text: 'cells a side' }), select)
  }
 
  private read(): void {
    this.request?.cancel()
    const genome = this.props.store.edit.original.genome
    const reading = genome === undefined ? 'reading the whole map for the stage' : `reading ${genome}’s contigs for the stage`
    this.showStatus(`${reading}…`, 0, true)
    const contigs = this.drawnContigs()
    // What the pass reads, as the worker says it on the way in (§27.12): the
    // stored pixels and the resolution, so a long read is a known one.
    let what = ''
    const request = this.props.readPicture(
      (done, total, note) => {
        if (note !== undefined) what = note
        if (this.request === request && total > 0) this.showStatus(what === '' ? `${reading}…` : `${reading}: ${what}…`, done / total, true)
      },
      contigs,
      this.cells(),
    )
    this.request = request
    request.promise
      .then((picture) => {
        if (this.closed || this.request !== request) return
        this.request = null
        this.picture = picture
        this.drawn = contigs === undefined ? null : new Set(contigs)
        this.method = picture.method ?? null
        this.methodKept = picture.methodKept ?? null
        this.dropPlacements()
        this.layout = { binsize: picture.binsize, sequences: picture.sequences }
        this.colours = pictureColours(this.props.colormap, { low: picture.low, high: picture.high }, picture.vmin, picture.vmax)
        this.hideStatus()
        this.rebuild(true)
        this.countNow()
        this.paintSide()
        void this.readEvidence()
        if (this.props.genomeLinks?.auto === true && this.linksOf !== this.linksKey()) this.readLinks()
      })
      .catch((error: unknown) => {
        if (this.closed || this.request !== request) return
        this.request = null
        const cancelled = error instanceof Error && error.name === 'AbortError'
        this.showStatus(
          cancelled ? 'The picture was not read.' : `The picture could not be read: ${error instanceof Error ? error.message : String(error)}`,
          null,
          false,
        )
      })
  }
 
  /**
   * The session's sequence read for what it says about the assembly — the
   * telomeres at its ends, the gaps of `N` inside it — and the suggestions
   * counted again with it (§27.5). Nothing where the session has no sequence.
   *
   * The file's own sequence, chosen as the corner plot chooses it
   * (`sequenceSets`): the set naming the most of the map's sequences, not the
   * first one loaded, which may be the other reference the plot sets it
   * against.
   */
  private async readEvidence(): Promise<void> {
    const lanes = this.props.lanes
    const client = lanes?.client
    const entry = lanes === undefined ? null : sequenceSets(lanes.store.entries).own
    const original = this.props.store.edit.original
    if (client === undefined || entry === null || this.readingEvidence) return
    this.readingEvidence = true
    this.paintPicture()
    try {
      const evidence = await readSequenceEvidence(
        entry.source.name,
        original.names,
        original.lengths,
        async (sequence, start, end) => {
          const got = await client.request<'bases'>({ kind: 'bases', entry: entry.id, regions: [{ contig: sequence, start, end }] })
          return got.regions[0]?.bases ?? null
        },
        { cancelled: () => this.closed },
      )
      if (evidence === null || this.closed) return
      this.evidence = evidence
      this.countNow()
      this.paintSide()
      this.schedule()
    } catch {
      // A sequence that cannot be read is no evidence either way.
    } finally {
      this.readingEvidence = false
      if (!this.closed) this.paintPicture()
    }
  }
 
  private showStatus(text: string, fraction: number | null, cancellable: boolean): void {
    const bar = el('div', { class: 'edit-status-bar' })
    if (fraction !== null) bar.append(el('div', { class: 'edit-status-fill', style: { width: `${Math.round(fraction * 100)}%` } }))
    const children: HTMLElement[] = [el('div', { class: 'edit-status-text', text: fraction === null ? text : `${text} ${Math.round(fraction * 100)}%` })]
    if (fraction !== null) children.push(bar)
    if (cancellable) {
      children.push(el('button', { class: 'btn', text: 'cancel', attrs: { type: 'button' }, on: { click: () => this.request?.cancel() } }))
    } else {
      children.push(el('button', { class: 'btn', text: 'read it again', attrs: { type: 'button' }, on: { click: () => this.read() } }))
    }
    this.statusEl.replaceChildren(...children)
    this.statusEl.classList.remove('hidden')
  }
 
  private hideStatus(): void {
    this.statusEl.classList.add('hidden')
    this.statusEl.replaceChildren()
  }
 
  // -------------------------------------------------------------------------
  // The edit
  // -------------------------------------------------------------------------
 
  /** The store changed: a step made, undone or redone. */
  private edited(): void {
    // An adjusted suggestion was for the edit as it stood; so was a finer read,
    // and where the finer rungs placed the points, named as the edit named them.
    this.adjustments.clear()
    this.dropPlacements()
    // The corner dot plot's lines, moved through the edit as it now stands.
    this.dotplot?.refresh()
    this.editVersion++
    this.windowRead = null
    this.windowRequest?.cancel()
    this.windowRequest = null
    // A contig brought in from another genome is not in the picture yet: it
    // is read again, with it (§27.10).
    const drawn = this.drawn
    if (drawn !== null && this.request === null && (this.drawnContigs() ?? []).some((name) => !drawn.has(name))) {
      this.read()
      return
    }
    this.rebuild(false)
    this.paintSide()
    this.scheduleSuggestions()
  }
 
  /** The sequences the picture is of, where not the whole map: a genome's contigs and those it may bring in. */
  private drawnContigs(): string[] | undefined {
    const original = this.props.store.edit.original
    if (original.genome === undefined) return undefined
    return [...original.names, ...(original.elsewhere ?? []).map((contig) => contig.name)]
  }
 
  /** The contigs a genome's links are read for: its own and those brought in. */
  private linksKey(): string {
    const original = this.props.store.edit.original
    const brought = this.props.store.assembly.sequences.flatMap((sequence) => sequence.parts.flatMap((part) => (isGap(part) ? [] : [part.sequence])))
    return [...new Set([...original.names, ...brought])].sort().join('\n')
  }
 
  /** Read every contact for where the genome's contigs and the others belong (§27.10). */
  private readLinks(): void {
    const links = this.props.genomeLinks
    if (links === undefined || this.closed) return
    this.linksRequest?.cancel()
    const key = this.linksKey()
    this.linksDone = 0
    const request = links.read(key.split('\n'), (done, total) => {
      if (this.linksRequest !== request || !(total > 0)) return
      this.linksDone = done / total
      this.paintGenome()
    })
    this.linksRequest = request
    this.paintGenome()
    request.promise
      .then((result) => {
        if (this.closed || this.linksRequest !== request) return
        this.links = result
        this.linksOf = key
      })
      .catch(() => {
        // Cancelled, or the file would not be read: the card says to read again.
      })
      .finally(() => {
        if (this.linksRequest !== request) return
        this.linksRequest = null
        this.linksDone = null
        if (!this.closed) this.paintGenome()
      })
  }
 
  /** The grid for the store's assembly, keeping the view where it can be kept. */
  private rebuild(first: boolean): void {
    if (this.layout === null) return
    const before = this.grid
    const whole = before === null || (this.sx.domain[0] <= 0 && this.sx.domain[1] >= before.n && this.sy.domain[0] <= 0 && this.sy.domain[1] >= before.n)
    this.grid = LensGrid.of(this.props.store.assembly, this.layout)
    const n = Math.max(1, this.grid.n)
    const x = this.sx.domain
    const y = this.sy.domain
    this.sx.setFull([0, n])
    this.sy.setFull([0, n])
    if (!first && !whole) {
      this.sx.setDomain(x)
      this.sy.setDomain(y)
      this.clampView()
    }
    if (this.selection !== null && !this.selectionFits(this.selection)) this.selection = null
    this.pictureDirty = true
    this.schedule()
  }
 
  private selectionFits(selection: Selection): boolean {
    const assembly = this.props.store.assembly
    const fits = (stretch: Stretch): boolean => {
      const length = assembly.lengthOf(stretch.sequence)
      return length !== null && stretch.to <= length && stretch.from < stretch.to
    }
    return selection.kind === 'stretch' ? fits(selection.stretch) : fits(selection.rows) && fits(selection.cols)
  }
 
  /** Make a step, and have the selection follow what it moved. */
  private step(step: EditStep): void {
    const before = this.props.store.assembly
    this.props.store.apply(step)
    const after = this.props.store.assembly
    const followed = landed(before, after, step)
    this.selection = followed === null ? (step.op === 'cut' ? this.selection : null) : { kind: 'stretch', stretch: followed }
    if (this.selection !== null && !this.selectionFits(this.selection)) this.selection = null
    this.paintSide()
    this.schedule()
  }
 
  /** Steps made one after another, each named against the assembly the one before left. */
  private steps(make: Array<(assembly: EditedAssembly) => EditStep | null>): void {
    for (const next of make) {
      const step = next(this.props.store.assembly)
      if (step !== null) this.props.store.apply(step)
    }
    this.selection = null
    this.paintSide()
    this.schedule()
  }
 
  // -------------------------------------------------------------------------
  // The acts
  // -------------------------------------------------------------------------
 
  private turn(stretch: Stretch): void {
    this.step({ op: 'invert', sequence: stretch.sequence, from: stretch.from, to: stretch.to })
  }
 
  private copy(stretch: Stretch): void {
    this.step({ op: 'duplicate', sequence: stretch.sequence, from: stretch.from, to: stretch.to, into: stretch.sequence, at: stretch.to, strand: 1 })
  }
 
  private setAside(stretch: Stretch, why: AsideReason): void {
    this.step({ op: 'aside', sequence: stretch.sequence, from: stretch.from, to: stretch.to, why })
  }
 
  /** The reasons a stretch can be set aside for, as a menu. */
  private asideMenu(stretch: Stretch, x: number, y: number): void {
    openMenu(x, y, [
      { label: `set aside ${formatLocus({ contig: stretch.sequence, start: stretch.from, end: stretch.to })} as` },
      ...REASONS.map((reason) => ({ label: reason.label, title: reason.title, run: () => this.setAside(stretch, reason.why) })),
    ])
  }
 
  /** Where the pointer is, as an edited position, when it is on the map. */
  private pointerPlace(): { sequence: string; at: number } | null {
    const grid = this.grid
    const hover = this.hover
    if (grid === null || hover === null) return null
    const place = grid.place(Math.min(grid.n - 1e-9, Math.max(0, hover.x.unit)))
    if (place === null || place.bp <= 0) return null
    const length = this.props.store.assembly.lengthOf(place.sequence) ?? 0
    const at = Math.round(place.bp)
    return at > 0 && at < length ? { sequence: place.sequence, at } : null
  }
 
  private cutHere(): void {
    const place = this.pointerPlace()
    if (place !== null) {
      this.step({ op: 'cut', sequence: place.sequence, at: place.at })
      return
    }
    const selection = this.selection
    if (selection?.kind !== 'stretch') return
    const { sequence, from, to } = selection.stretch
    this.steps([
      () => ({ op: 'cut', sequence, at: to }),
      () => ({ op: 'cut', sequence, at: from }),
    ])
  }
 
  private splitHere(): void {
    const place = this.pointerPlace()
    if (place !== null) {
      this.step({ op: 'split', sequence: place.sequence, at: place.at })
      return
    }
    const selection = this.selection
    if (selection?.kind !== 'stretch') return
    this.splitOut(selection.stretch)
  }
 
  /**
   * Whether an edited sequence is a circle (§8.15): declared one by a layout
   * it was read from, or every part of it a piece of one sequence of the file
   * the reader declared circular, the whole of it — as it is, or started
   * elsewhere by an origin already set.
   */
  private circularOf(name: string): boolean {
    const assembly = this.props.store.assembly
    const sequence = assembly.sequence(name)
    if (sequence === null) return false
    if (sequence.circular === true) return true
    const declared = this.props.circular?.() ?? []
    if (declared.length === 0 || sequence.parts.some((part) => isGap(part))) return false
    const pieces = sequence.parts.filter((part) => !isGap(part)) as Array<{ sequence: string }>
    const of = pieces[0]?.sequence
    if (of === undefined || !declared.includes(of) || pieces.some((piece) => piece.sequence !== of)) return false
    const original = this.props.store.edit.original
    const index = original.names.indexOf(of)
    return index >= 0 && assembly.lengthOf(name) === original.lengths[index]
  }
 
  /**
   * `O`: a circle started at the pointer — or at the selection's start — its
   * first base there and the rest after it round the circle (§27.4). Said, and
   * nothing done, on a sequence that is not one.
   */
  private originHere(): void {
    const selection = this.selection
    const place = this.pointerPlace() ?? (selection?.kind === 'stretch' && selection.stretch.from > 0 ? { sequence: selection.stretch.sequence, at: selection.stretch.from } : null)
    if (place === null) return
    if (!this.circularOf(place.sequence)) {
      this.readoutEl.textContent = `O starts a circle elsewhere, and ${place.sequence} is not one: tick it circular on the Chromosomes table first`
      return
    }
    this.step({ op: 'rotate', sequence: place.sequence, at: place.at })
  }
 
  /** A stretch made a sequence of its own: split after it, then before it. */
  private splitOut(stretch: Stretch): void {
    const index = this.props.store.assembly.sequences.findIndex((sequence) => sequence.name === stretch.sequence)
    if (index < 0) return
    this.steps([
      (assembly) => {
        const length = assembly.lengthOf(stretch.sequence) ?? 0
        return stretch.to < length ? { op: 'split', sequence: stretch.sequence, at: stretch.to } : null
      },
      (assembly) => {
        // The split may have renamed it: it is at the same place in the order.
        const name = assembly.sequences[index]?.name
        return name === undefined || stretch.from === 0 ? null : { op: 'split', sequence: name, at: stretch.from }
      },
    ])
  }
 
  /** Two stretches of one sequence, each taking the other's place. */
  private swap(rows: Stretch, cols: Stretch): void {
    if (rows.sequence !== cols.sequence) return
    const [first, second] = rows.from <= cols.from ? [rows, cols] : [cols, rows]
    if (first.to > second.from) return
    const index = this.props.store.assembly.sequences.findIndex((sequence) => sequence.name === first.sequence)
    const gap = second.from - first.to
    this.steps([
      () => ({ op: 'move', sequence: first.sequence, from: second.from, to: second.to, into: first.sequence, at: first.from, strand: 1 }),
      (assembly) => {
        const name = assembly.sequences[index]?.name
        if (name === undefined) return null
        const moved = second.to - second.from
        const from = first.from + moved
        const to = from + (first.to - first.from)
        // After the stretch between, where the second one was: measured with
        // the first taken out.
        return { op: 'move', sequence: name, from, to, into: name, at: from + gap, strand: 1 }
      },
    ])
  }
 
  // -------------------------------------------------------------------------
  // The view
  // -------------------------------------------------------------------------
 
  private resized(): void {
    if (this.closed) return
    this.layoutPlot()
    this.pictureDirty = true
    this.schedule()
  }
 
  /** Place the map, its bars and its lanes in the plot's box. */
  private layoutPlot(): void {
    const box = this.plot.getBoundingClientRect()
    const thickness = (edge: 'top' | 'right' | 'bottom' | 'left'): number => this.lanes?.thicknessOf(edge) ?? 0
    const top = thickness('top')
    const right = thickness('right')
    const bottom = thickness('bottom')
    const left = thickness('left')
    // The rail takes the room left of the map and its lanes (§27.3).
    const rail = RAIL_WIDTH
    const size = Math.max(
      160,
      Math.floor(Math.min(box.width - rail - left - BAR_THICKNESS - right - 12, box.height - top - BAR_THICKNESS - bottom - 12)),
    )
    this.size = size
    this.dpr = window.devicePixelRatio > 0 ? window.devicePixelRatio : 1
    const x = Math.max(0, Math.floor((box.width - (rail + left + BAR_THICKNESS + size + right)) / 2)) + rail + left + BAR_THICKNESS
    const y = top + BAR_THICKNESS + 4
    const place = (node: HTMLElement, px: number, py: number, width: number, height: number): void => {
      node.style.left = `${px}px`
      node.style.top = `${py}px`
      node.style.width = `${width}px`
      node.style.height = `${height}px`
    }
    for (const canvas of [this.pictureCanvas, this.overlayCanvas]) {
      place(canvas, x, y, size, size)
      canvas.width = Math.round(size * this.dpr)
      canvas.height = Math.round(size * this.dpr)
    }
    place(this.topBar, x, y - BAR_THICKNESS, size, BAR_THICKNESS)
    this.topBar.width = Math.round(size * this.dpr)
    this.topBar.height = Math.round(BAR_THICKNESS * this.dpr)
    place(this.leftBar, x - BAR_THICKNESS, y, BAR_THICKNESS, size)
    this.leftBar.width = Math.round(BAR_THICKNESS * this.dpr)
    this.leftBar.height = Math.round(size * this.dpr)
    if (this.lanes !== null) {
      const canvases = this.lanes.canvases
      canvases.top.style.left = `${x}px`
      canvases.top.style.top = `${y - BAR_THICKNESS - top}px`
      canvases.bottom.style.left = `${x}px`
      canvases.bottom.style.top = `${y + size}px`
      canvases.left.style.left = `${x - BAR_THICKNESS - left}px`
      canvases.left.style.top = `${y}px`
      canvases.right.style.left = `${x + size}px`
      canvases.right.style.top = `${y}px`
    }
    this.rail.place(x - BAR_THICKNESS - left - rail, y, rail - 4, size, this.dpr)
    this.railSignature = ''
    this.mapAt = { x, y }
    this.dotplot?.place(x, y, size)
    this.sx.setPixels(size)
    this.sy.setPixels(size)
    this.image = null
  }
 
  private fit(): void {
    const grid = this.grid
    if (grid === null) return
    this.sx.setDomain([0, Math.max(1, grid.n)])
    this.sy.setDomain([0, Math.max(1, grid.n)])
    this.pictureDirty = true
    this.schedule()
  }
 
  /** Zoom both axes by `factor` about a point, in units — the middle of the view by default. */
  private zoomBy(factor: number, about?: { x: number; y: number }): void {
    const grid = this.grid
    if (grid === null) return
    const [x0, x1] = this.sx.domain
    const [y0, y1] = this.sy.domain
    const span = Math.min(grid.n, Math.max(MIN_SPAN, (x1 - x0) * factor))
    const cx = about?.x ?? (x0 + x1) / 2
    const cy = about?.y ?? (y0 + y1) / 2
    const kx = (cx - x0) / (x1 - x0)
    const ky = (cy - y0) / (y1 - y0)
    this.sx.setDomain([cx - kx * span, cx - kx * span + span])
    this.sy.setDomain([cy - ky * span, cy - ky * span + span])
    this.clampView()
    this.pictureDirty = true
    this.schedule()
  }
 
  private clampView(): void {
    const n = Math.max(1, this.grid?.n ?? 1)
    for (const scale of [this.sx, this.sy]) {
      const [d0, d1] = scale.domain
      const span = Math.min(n, d1 - d0)
      let start = d0
      if (start < 0) start = 0
      if (start + span > n) start = n - span
      scale.setDomain([start, start + span])
    }
  }
 
  /** Frame a stretch of the axis, with a little room either side. */
  private frameUnits(a: number, b: number): void {
    const grid = this.grid
    if (grid === null) return
    const span = Math.min(grid.n, Math.max(MIN_SPAN, (b - a) * 1.25))
    const centre = (a + b) / 2
    this.sx.setDomain([centre - span / 2, centre + span / 2])
    this.sy.setDomain([centre - span / 2, centre + span / 2])
    this.clampView()
    this.pictureDirty = true
    this.schedule()
  }
 
  /**
   * How many cells a side the picture may have, as the reader set it on the
   * picture card (§27.3's settings, the resolution the stage works at): the
   * finest rung that fits them is read. Kept per file, beside the edit.
   */
  private cells(): number {
    const kept = recall<number>(this.props.memoryKey(), PICTURE_CELLS_SCOPE)
    return typeof kept === 'number' && PICTURE_CELL_CHOICES.includes(kept) ? kept : PICTURE_CELL_CHOICES[0]
  }
 
  private setCells(cells: number): void {
    if (cells === this.cells()) return
    remember(this.props.memoryKey(), PICTURE_CELLS_SCOPE, cells === PICTURE_CELL_CHOICES[0] ? null : cells)
    this.windowRead = null
    this.read()
  }
 
  /** A picture cell's width on screen, in CSS pixels. */
  private cellPx(): number {
    const [x0, x1] = this.sx.domain
    return this.size / Math.max(1e-9, x1 - x0)
  }
 
  private windowKey(): string {
    return `${this.token}:${this.editVersion}`
  }
 
  /** Once the view has settled, read the window on screen finer than the picture, where it is zoomed past a cell (§27.9). */
  private considerWindow(): void {
    window.clearTimeout(this.windowTimer)
    if (this.props.readWindow === undefined || this.closed) return
    this.windowTimer = window.setTimeout(() => this.readWindow(), 200)
  }
 
  private readWindow(): void {
    const grid = this.grid
    const picture = this.picture
    const ask = this.props.readWindow
    if (grid === null || picture === null || ask === undefined || this.closed || this.preview !== null || this.drag !== null) return
    const cellPx = this.cellPx()
    if (cellPx < WINDOW_CELL_PX) return
    const [x0, x1] = this.sx.domain
    const [y0, y1] = this.sy.domain
    // A bin a device pixel — finer shows nothing more — and never finer than
    // the map is deep enough to show; and only where that is half a cell or
    // less, since a read about as coarse as the picture shows the picture.
    const bpPerPixel = Math.max(1, Math.floor(picture.binsize / (cellPx * this.dpr)), picture.least ?? 0)
    if (2 * bpPerPixel > picture.binsize) return
    const key = this.windowKey()
    const held = this.windowRead
    const inside = (view: readonly number[]): boolean => view[0] <= x0 && view[1] >= x1 && view[2] <= y0 && view[3] >= y1
    // Held already: this edit, the view inside it, and as fine as asked or the finest there is.
    if (held !== null && held.key === key && inside(held.view) && (held.read.binsize <= 2 * bpPerPixel || held.read.binsize > held.asked)) return
    const padX = (x1 - x0) / 3
    const padY = (y1 - y0) / 3
    const view: [number, number, number, number] = [x0 - padX, x1 + padX, y0 - padY, y1 + padY]
    const rows = this.windowSideOf(grid, view[2], view[3])
    const cols = this.windowSideOf(grid, view[0], view[1])
    if (rows === null || cols === null) return
    this.windowRequest?.cancel()
    const request = ask({ edit: this.props.store.edit, key, binsize: bpPerPixel, coarser: picture.binsize, rows, cols, balance: picture.balanced })
    this.windowRequest = request
    request.promise.then(
      (read) => {
        if (this.closed || this.windowRequest !== request) return
        this.windowRequest = null
        if (read === null || key !== this.windowKey()) return
        this.windowRead = { key, read, view, asked: bpPerPixel }
        this.pictureDirty = true
        this.schedule()
        this.paintPicture()
      },
      () => {
        if (this.windowRequest === request) this.windowRequest = null
      },
    )
  }
 
  /** A stretch of the axis as the places in the edited assembly it begins and ends at. */
  private windowSideOf(grid: LensGrid, from: number, to: number): StageWindowSide | null {
    const lo = Math.max(0, from)
    const hi = Math.min(grid.n, to)
    if (!(hi > lo)) return null
    const first = grid.place(lo)
    const last = grid.place(Math.max(lo, hi - 1e-6))
    if (first === null || last === null) return null
    return { from: { sequence: first.sequence, bp: Math.max(0, first.bp) }, to: { sequence: last.sequence, bp: Math.max(0, last.bp) } }
  }
 
  // -------------------------------------------------------------------------
  // Drawing
  // -------------------------------------------------------------------------
 
  private schedule(): void {
    if (this.frame !== 0 || this.closed) return
    this.frame = requestAnimationFrame(() => {
      this.frame = 0
      this.draw()
    })
  }
 
  /** The grid on screen: the preview while a drag has one, else the edit's. */
  private get shown(): LensGrid | null {
    return this.preview?.grid ?? this.grid
  }
 
  private draw(): void {
    const grid = this.shown
    if (this.size === 0) this.layoutPlot()
    this.ink ??= readInk(this.root)
    const ink = this.ink
    const size = this.size
    const dpr = this.dpr
    const picture = this.picture
    if (grid === null || picture === null || this.colours === null) return
 
    if (this.pictureDirty) {
      this.pictureDirty = false
      const ctx = this.pictureCanvas.getContext('2d')
      if (ctx !== null) {
        const width = this.pictureCanvas.width
        const height = this.pictureCanvas.height
        if (this.image === null || this.image.width !== width || this.image.height !== height) {
          this.image = ctx.createImageData(width, height)
        }
        const target = new Uint32Array(this.image.data.buffer)
        const [x0, x1] = this.sx.domain
        const [y0, y1] = this.sy.domain
        paintPicture(target, { x0, x1, y0, y1, width, height }, grid.cellMap, grid.cellMap, picture.levels, this.colours)
        // Closer than a cell, the window read finer, where it reaches (§27.9).
        const held = this.windowRead
        if (held !== null && this.preview === null && held.key === this.windowKey() && this.cellPx() >= WINDOW_CELL_PX) {
          const rows = windowSide(grid, y0, y1, height, held.read.rows, held.read.binsize)
          const cols = windowSide(grid, x0, x1, width, held.read.cols, held.read.binsize)
          paintWindow(target, width, rows, cols, held.read, windowScale(picture, held.read.binsize), { low: picture.low, high: picture.high }, this.colours)
        }
        ctx.putImageData(this.image, 0, 0)
        this.considerWindow()
      }
    }
 
    const toX = (unit: number): number => this.sx.toPixel(unit)
    const toY = (unit: number): number => this.sy.toPixel(unit)
    // Where the view is, on the element — as a map says its locus on its own —
    // so a script driving the stage can point at a place by its unit.
    const [vx0, vx1] = this.sx.domain
    const [vy0, vy1] = this.sy.domain
    this.overlayCanvas.dataset.cells = String(grid.n)
    this.overlayCanvas.dataset.view = [vx0, vx1, vy0, vy1].map((value) => value.toFixed(3)).join(' ')
    const overlay = this.overlayCanvas.getContext('2d')
    const lit = this.litUnits(grid)
    const linked = this.linkedUnits(grid)
    // The suggestions are about the edit as it stands: while a drag or a
    // preview shows another, they are not drawn over it.
    const marks = this.preview === null ? this.marks() : []
    if (overlay !== null) {
      overlay.setTransform(dpr, 0, 0, dpr, 0, 0)
      const box = this.selection?.kind === 'box' && this.drag === null ? this.boxUnits(grid, this.selection) : this.dragBox()
      drawOverlay(overlay, {
        size,
        grid,
        toX,
        toY,
        ink,
        under: (ctx) => drawSuggestions(ctx, { size, toX, toY, ink, marks }),
        square: box === null ? lit : null,
        box,
        linked,
        cross:
          this.hover === null || (this.drag !== null && this.drag.kind === 'move')
            ? null
            : {
                x: this.hover.x.unit,
                y: this.hover.y.unit,
                snappedX: this.hover.x.target !== null,
                snappedY: this.hover.y.target !== null,
              },
      })
    }
 
    const mark = this.drag?.kind === 'move' ? this.drag.mark : null
    const ticks = marks.flatMap(({ suggestion, lit: shining }) =>
      [...suggestion.breaks, ...(suggestion.target === null ? [] : [suggestion.target])].map((unit) => ({ unit, lit: shining })),
    )
    const top = this.topBar.getContext('2d')
    if (top !== null) {
      top.setTransform(dpr, 0, 0, dpr, 0, 0)
      const cols = this.selection?.kind === 'box' ? this.boxUnits(grid, this.selection)?.cols ?? null : lit
      drawBar(top, 'top', size, grid, toX, ink, this.drag?.kind === 'box' ? (this.dragBox()?.cols ?? null) : cols, this.preview === null ? mark : null, ticks, linked)
    }
    const left = this.leftBar.getContext('2d')
    if (left !== null) {
      left.setTransform(dpr, 0, 0, dpr, 0, 0)
      const rows = this.selection?.kind === 'box' ? this.boxUnits(grid, this.selection)?.rows ?? null : lit
      drawBar(left, 'left', size, grid, toY, ink, this.drag?.kind === 'box' ? (this.dragBox()?.rows ?? null) : rows, null, ticks, linked)
    }
    this.paintRail(marks, toY, ink)
 
    if (this.lanes !== null) {
      // The lanes are drawn through whichever grid is on screen, the preview's
      // included, so a track moves with the stretch under the hand.
      if (this.lanesGrid !== grid) {
        this.lanes.setAxes({ rows: grid.axis, cols: grid.axis })
        this.lanesGrid = grid
      }
      this.lanes.draw(this.laneGeometry())
    }
    this.paintLaneBands(lit, toX, toY)
  }
 
  /**
   * The selection across the lanes, so a stretch is lit on the tracks as it is
   * on the map and the bars (§27.4): along the columns for the stacks above
   * and below, along the rows for the stacks either side.
   */
  private paintLaneBands(lit: [number, number] | null, toX: (unit: number) => number, toY: (unit: number) => number): void {
    const size = this.size
    const { x, y } = this.mapAt
    for (const edge of ['top', 'right', 'bottom', 'left'] as const) {
      const band = this.laneBands[edge]
      const thickness = this.lanes?.thicknessOf(edge) ?? 0
      if (lit === null || thickness === 0) {
        band.classList.add('hidden')
        continue
      }
      const horizontal = edge === 'top' || edge === 'bottom'
      const to = horizontal ? toX : toY
      const a = Math.max(0, to(lit[0]))
      const b = Math.min(size, to(lit[1]))
      if (!(b > a)) {
        band.classList.add('hidden')
        continue
      }
      const across =
        edge === 'top' ? y - BAR_THICKNESS - thickness : edge === 'bottom' ? y + size : edge === 'left' ? x - BAR_THICKNESS - thickness : x + size
      band.style.left = `${horizontal ? x + a : across}px`
      band.style.top = `${horizontal ? across : y + a}px`
      band.style.width = `${horizontal ? b - a : thickness}px`
      band.style.height = `${horizontal ? thickness : b - a}px`
      band.classList.remove('hidden')
    }
  }
 
  private laneGeometry(): LaneGeometry {
    const size = this.size
    const rect = { x: 0, y: 0, width: size, height: size }
    const hover =
      this.hover === null ? null : { row: Math.floor(this.hover.y.unit), col: Math.floor(this.hover.x.unit) }
    return {
      plot: rect,
      data: rect,
      colScale: this.sx,
      rowScale: this.sy,
      cssWidth: size,
      cssHeight: size,
      hover,
      anchors: null,
      crosshair: this.hover !== null,
      echo: null,
      echoAnchors: null,
      laneEcho: null,
      guide: null,
      border: null,
      handles: false,
      grip: null,
      scaling: null,
      palette: { guide: this.ink?.dim ?? '#555', halo: this.ink?.background ?? '#fff', crosshair: this.ink?.accent ?? '#1f5fa9' },
    }
  }
 
  /** The selection on the diagonal, in units of the grid shown. */
  private litUnits(grid: LensGrid): [number, number] | null {
    if (this.drag?.kind === 'along') {
      const stretch = stretchBetween(grid, this.drag.anchor, this.alongEnd(this.drag.anchor, this.drag.x, this.drag.y))
      return stretch === null ? null : stretchUnits(grid, stretch)
    }
    if (this.drag?.kind === 'move') {
      if (this.preview !== null) return this.preview.units
      return this.drag.units
    }
    if (this.selection?.kind !== 'stretch') return null
    return stretchUnits(grid, this.selection.stretch)
  }
 
  /**
   * What the corner dot plot's hovered line lights on the map (§27.3): the
   * piece it lies along — the contig, where nothing is edited yet — in units;
   * not while a drag or a preview shows another edit than the one it was drawn through.
   */
  private linkedUnits(grid: LensGrid): [number, number] | null {
    if (this.linked === null || this.preview !== null || this.drag !== null) return null
    const units = stretchUnits(grid, this.linked)
    if (units === null) return null
    const piece = partStretch(grid, (units[0] + units[1]) / 2)
    return (piece === null ? null : stretchUnits(grid, piece)) ?? units
  }
 
  private boxUnits(
    grid: LensGrid,
    selection: Extract<Selection, { kind: 'box' }>,
  ): { rows: [number, number]; cols: [number, number] } | null {
    const rows = stretchUnits(grid, selection.rows)
    const cols = stretchUnits(grid, selection.cols)
    return rows === null || cols === null ? null : { rows, cols }
  }
 
  /** The box being drawn, in units, while a box drag is under way. */
  private dragBox(): { rows: [number, number]; cols: [number, number] } | null {
    const drag = this.drag
    if (drag?.kind !== 'box' || !drag.moved) return null
    const x = this.snapX(this.sx.toUnit(drag.x)).unit
    const y = this.snapY(this.sy.toUnit(drag.y)).unit
    return {
      rows: [Math.min(drag.ay, y), Math.max(drag.ay, y)],
      cols: [Math.min(drag.ax, x), Math.max(drag.ax, x)],
    }
  }
 
  // -------------------------------------------------------------------------
  // The hand
  // -------------------------------------------------------------------------
 
  private targets(): SnapTarget[] {
    const grid = this.grid
    if (grid === null) return []
    const out = endTargets(grid)
    if (this.selection?.kind === 'stretch') {
      const units = stretchUnits(grid, this.selection.stretch)
      if (units !== null) out.push({ unit: units[0], kind: 'selection' }, { unit: units[1], kind: 'selection' })
    }
    // Every point a suggestion names: its breakpoints, and where it would put a stretch.
    for (const suggestion of this.open()) {
      for (const unit of suggestion.breaks) out.push({ unit, kind: 'suggestion', key: suggestion.key })
      if (suggestion.target !== null) out.push({ unit: suggestion.target, kind: 'suggestion', key: suggestion.key })
      for (const corner of suggestion.corners) {
        out.push({ unit: corner.row, kind: 'suggestion', key: suggestion.key }, { unit: corner.col, kind: 'suggestion', key: suggestion.key })
      }
    }
    return out
  }
 
  private snapX(unit: number): Snapped {
    return snapUnit(unit, this.targets(), SNAP_PX * this.sx.unitsPerPixel, this.alt)
  }
 
  private snapY(unit: number): Snapped {
    return snapUnit(unit, this.targets(), SNAP_PX * this.sy.unitsPerPixel, this.alt)
  }
 
  /** A pointer position projected onto the diagonal, snapped. */
  private alongUnit(px: number, py: number): Snapped {
    return this.snapX((this.sx.toUnit(px) + this.sy.toUnit(py)) / 2)
  }
 
  /**
   * The far end of a drag along the diagonal: snapped, unless it would snap
   * onto the very target the drag began at — at the whole-genome scale eight
   * pixels are a hundred kilobases, and a stretch that small near a sequence's
   * edge would otherwise come out empty however far the hand went.
   */
  private alongEnd(anchor: number, px: number, py: number): number {
    const snapped = this.alongUnit(px, py).unit
    return snapped === anchor ? Math.round((this.sx.toUnit(px) + this.sy.toUnit(py)) / 2) : snapped
  }
 
  private wireCanvas(): void {
    const canvas = this.overlayCanvas
    const local = (event: MouseEvent): { x: number; y: number } => {
      const rect = canvas.getBoundingClientRect()
      return { x: event.clientX - rect.left, y: event.clientY - rect.top }
    }
    canvas.addEventListener('pointerdown', (event) => {
      if (this.grid === null) return
      canvas.focus({ preventScroll: true })
      closeMenu()
      const { x, y } = local(event)
      if (event.button === 1 || (event.button === 0 && this.space)) {
        this.drag = { kind: 'pan', x, y }
      } else if (event.button === 0 && this.endUnder(x, y) !== null) {
        const grab = this.endUnder(x, y) as { key: string; end: 0 | 1 }
        this.drag = { kind: 'adjust', ...grab, x, y, moved: false }
      } else if (event.button === 0) {
        this.alt = event.altKey
        const ux = this.sx.toUnit(x)
        const uy = this.sy.toUnit(y)
        const lit = this.selection?.kind === 'stretch' ? stretchUnits(this.grid, this.selection.stretch) : null
        const diagonal = Math.abs(x - y - (this.sx.toPixel(0) - this.sy.toPixel(0))) / Math.SQRT2
        if (lit !== null && ux >= lit[0] && ux <= lit[1] && uy >= lit[0] && uy <= lit[1] && this.selection?.kind === 'stretch') {
          const along = (ux + uy) / 2
          this.drag = {
            kind: 'move',
            stretch: this.selection.stretch,
            units: lit,
            grip: along - lit[0],
            x,
            y,
            moved: false,
            strand: 1,
            copy: event.altKey,
            fuse: event.shiftKey,
            again: true,
            step: null,
            mark: null,
          }
        } else if (diagonal <= DIAGONAL_PX) {
          this.drag = { kind: 'along', anchor: this.alongUnit(x, y).unit, x, y, moved: false }
        } else {
          this.drag = { kind: 'box', ax: this.snapX(ux).unit, ay: this.snapY(uy).unit, x, y, moved: false }
        }
      } else {
        return
      }
      canvas.setPointerCapture(event.pointerId)
      event.preventDefault()
      this.schedule()
    })
    canvas.addEventListener('pointermove', (event) => {
      const { x, y } = local(event)
      this.alt = event.altKey
      this.pointAt(x, y)
      const drag = this.drag
      if (drag === null) return
      if (drag.kind === 'pan') {
        this.sx.panByPixels(x - drag.x)
        this.sy.panByPixels(y - drag.y)
        this.clampView()
        drag.x = x
        drag.y = y
        this.pictureDirty = true
      } else {
        // Until it has travelled, `x` and `y` are where the press was.
        if (!drag.moved && Math.hypot(x - drag.x, y - drag.y) < DRAG_PX) return
        drag.moved = true
        drag.x = x
        drag.y = y
        if (drag.kind === 'move') {
          drag.copy = event.altKey
          drag.fuse = event.shiftKey
          this.updateMove(drag)
        } else if (drag.kind === 'adjust') {
          this.updateAdjust(drag)
        }
      }
      this.schedule()
    })
    const finish = (event: PointerEvent): void => {
      const drag = this.drag
      if (drag === null) return
      if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId)
      this.drag = null
      const grid = this.grid
      if (grid === null) return
      const { x, y } = local(event)
      if (drag.kind === 'along') {
        const unit = this.alongEnd(drag.anchor, x, y)
        const stretch = drag.moved ? stretchBetween(grid, drag.anchor, unit) : partStretch(grid, (this.sx.toUnit(x) + this.sy.toUnit(y)) / 2)
        this.selection = stretch === null ? null : { kind: 'stretch', stretch }
      } else if (drag.kind === 'box') {
        const cx = this.snapX(this.sx.toUnit(x)).unit
        const cy = this.snapY(this.sy.toUnit(y)).unit
        if (drag.moved) {
          const rows = stretchBetween(grid, drag.ay, cy)
          const cols = stretchBetween(grid, drag.ax, cx)
          this.selection = rows !== null && cols !== null ? { kind: 'box', rows, cols } : null
        } else {
          // A press on a corner names the stretch between its two ends (§27.4),
          // where both are in one sequence; two parts boxed where they are not.
          const same = grid.sequenceAt(cx) !== null && grid.sequenceAt(cx) === grid.sequenceAt(cy)
          if (same) {
            const stretch = stretchBetween(grid, Math.min(cx, cy), Math.max(cx, cy))
            this.selection = stretch === null ? null : { kind: 'stretch', stretch }
          } else {
            const rows = partStretch(grid, this.sy.toUnit(y))
            const cols = partStretch(grid, this.sx.toUnit(x))
            this.selection = rows !== null && cols !== null ? { kind: 'box', rows, cols } : null
          }
        }
      } else if (drag.kind === 'adjust') {
        // Kept as the hand left it, to be answered: nothing is made until it is taken.
        this.paintReadout()
      } else if (drag.kind === 'move') {
        const step = drag.moved ? drag.step : null
        this.preview = null
        this.pictureDirty = true
        if (step !== null) {
          this.step(step)
          return
        }
        if (!drag.moved && drag.again) this.widen((this.sx.toUnit(x) + this.sy.toUnit(y)) / 2)
      }
      this.paintSide()
      this.schedule()
    }
    canvas.addEventListener('pointerup', finish)
    canvas.addEventListener('pointercancel', (event) => {
      if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId)
      this.cancelDrag()
    })
    canvas.addEventListener('pointerleave', () => {
      if (this.drag !== null) return
      this.hover = null
      this.setLit(null)
      this.paintReadout()
      this.schedule()
    })
    canvas.addEventListener('dblclick', (event) => {
      event.preventDefault()
      this.fit()
    })
    canvas.addEventListener(
      'wheel',
      (event) => {
        if (this.grid === null) return
        event.preventDefault()
        const { x, y } = local(event)
        if (event.shiftKey || Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
          const dx = event.shiftKey ? event.deltaY : event.deltaX
          this.sx.panByPixels(-dx)
          this.sy.panByPixels(-dx)
          this.clampView()
          this.pictureDirty = true
          this.schedule()
          return
        }
        const factor = Math.exp(event.deltaY * (event.deltaMode === 1 ? 0.05 : 0.002))
        this.zoomBy(factor, { x: this.sx.toUnit(x), y: this.sy.toUnit(y) })
      },
      { passive: false },
    )
    canvas.addEventListener('contextmenu', (event) => {
      event.preventDefault()
      const { x, y } = local(event)
      this.pointAt(x, y)
      openMenu(event.clientX, event.clientY, this.menuItems(event.clientX, event.clientY))
    })
  }
 
  /**
   * A pieces bar as a handle on the pieces it draws (§27.3, §27.4): a press
   * selects the piece under it, or holds the selection where it is inside it,
   * and a drag moves what is held — the map's own move, with the pointer set
   * on the diagonal at the bar's place, so the ghost, the snapping, the preview
   * under the hand, `I` on the way and ⌥ for a copy are the same ones; a
   * double click turns the piece; hovering names it and where it came from.
   */
  private wireBar(canvas: HTMLCanvasElement, side: 'top' | 'left'): void {
    const unitOf = (event: MouseEvent): number => {
      const rect = canvas.getBoundingClientRect()
      return side === 'top' ? this.sx.toUnit(event.clientX - rect.left) : this.sy.toUnit(event.clientY - rect.top)
    }
    const onDiagonal = (unit: number): { x: number; y: number } => ({ x: this.sx.toPixel(unit), y: this.sy.toPixel(unit) })
    const onNames = (event: MouseEvent): boolean => {
      const rect = canvas.getBoundingClientRect()
      return (side === 'top' ? event.clientY - rect.top : event.clientX - rect.left) < BAR_NAMES
    }
    canvas.addEventListener('pointerdown', (event) => {
      const grid = this.grid
      if (grid === null || event.button !== 0) return
      closeMenu()
      this.overlayCanvas.focus({ preventScroll: true })
      const unit = unitOf(event)
      this.dotplot?.focusOn(null)
      // The row of names is the sequence's, whole (§27.4); the row of pieces, a piece's.
      const onName = onNames(event)
      const held = this.selection?.kind === 'stretch' ? this.selection.stretch : null
      const lit = held === null ? null : stretchUnits(grid, held)
      const whole = onName ? sequenceStretch(grid, unit) : null
      const inside = !onName && held !== null && lit !== null && unit >= lit[0] && unit <= lit[1]
      const stretch = whole ?? (inside ? held : partStretch(grid, unit))
      if (stretch === null) return
      const units = inside && lit !== null ? lit : stretchUnits(grid, stretch)
      if (!inside) {
        this.selection = { kind: 'stretch', stretch }
        this.paintSide()
      }
      if (units !== null) {
        this.drag = {
          kind: 'move',
          stretch,
          units,
          grip: unit - units[0],
          ...onDiagonal(unit),
          moved: false,
          strand: 1,
          copy: event.altKey,
          fuse: event.shiftKey,
          again: inside,
          step: null,
          mark: null,
        }
        this.barPress = { x: event.clientX, y: event.clientY }
        canvas.setPointerCapture(event.pointerId)
        canvas.classList.add('is-dragging')
      }
      event.preventDefault()
      this.schedule()
    })
    canvas.addEventListener('pointermove', (event) => {
      const drag = this.drag
      if (drag?.kind === 'move' && this.barPress !== null) {
        if (!drag.moved && Math.hypot(event.clientX - this.barPress.x, event.clientY - this.barPress.y) < DRAG_PX) return
        drag.moved = true
        Object.assign(drag, onDiagonal(unitOf(event)))
        drag.copy = event.altKey
        drag.fuse = event.shiftKey
        this.updateMove(drag)
        this.schedule()
        return
      }
      if (this.drag !== null) return
      const unit = unitOf(event)
      this.describeBar(unit)
      // What is under the pointer lit in the corner dot plot (§27.3): over a
      // name the sequence whole, over the pieces the piece.
      const grid = this.grid
      this.dotplot?.focusOn(grid === null ? null : onNames(event) ? sequenceStretch(grid, unit) : partStretch(grid, unit))
    })
    const finish = (event: PointerEvent): void => {
      if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId)
      canvas.classList.remove('is-dragging')
      const drag = this.drag
      this.barPress = null
      if (drag?.kind !== 'move') return
      this.drag = null
      const step = drag.moved ? drag.step : null
      this.preview = null
      this.pictureDirty = true
      if (step !== null) {
        this.step(step)
        return
      }
      if (!drag.moved && drag.again) this.widen(unitOf(event))
      this.paintReadout()
      this.paintSide()
      this.schedule()
    }
    canvas.addEventListener('pointerup', finish)
    canvas.addEventListener('pointercancel', (event) => {
      if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId)
      canvas.classList.remove('is-dragging')
      this.barPress = null
      this.cancelDrag()
    })
    canvas.addEventListener('pointerleave', () => {
      this.dotplot?.focusOn(null)
      if (this.drag === null) this.paintReadout()
    })
    canvas.addEventListener('dblclick', (event) => {
      event.preventDefault()
      const grid = this.grid
      if (grid === null) return
      const stretch = partStretch(grid, unitOf(event))
      if (stretch !== null) this.turn(stretch)
    })
  }
 
  /** The readout over a pieces bar: the piece under the pointer, where it came from, and what the bar does with it. */
  private describeBar(unit: number): void {
    const grid = this.grid
    if (grid === null) return
    const place = grid.place(Math.min(grid.n - 1e-9, Math.max(0, unit)))
    const stretch = partStretch(grid, unit)
    const piece = place?.part.piece ?? null
    if (place === null || stretch === null || piece === null) {
      this.readoutEl.textContent = place === null ? this.summary() : `${place.sequence} · gap`
      return
    }
    const here = formatLocus({ contig: stretch.sequence, start: stretch.from, end: stretch.to })
    const from = formatLocus({ contig: piece.sequence, start: piece.start, end: piece.end })
    const origin = from === here && piece.strand === 1 ? '' : ` ← ${from}${piece.strand === -1 ? ', turned' : ''}`
    this.readoutEl.textContent = `${here}${origin} · drag to move it, double-click to turn it · its name above, the whole of ${stretch.sequence}`
  }
 
  /**
   * A press that did not travel, on what was selected already (§27.4): a piece
   * — or any stretch short of its sequence — widens to the whole sequence; the
   * whole sequence narrows back to the piece under the pointer.
   */
  private widen(unit: number): void {
    const grid = this.grid
    const held = this.selection?.kind === 'stretch' ? this.selection.stretch : null
    if (grid === null || held === null) return
    const whole = sequenceStretch(grid, unit)
    const part = partStretch(grid, unit)
    if (whole === null || part === null || whole.sequence !== held.sequence) return
    const next = isWholeSequence(this.props.store.assembly, held) ? part : whole
    if (next.from === held.from && next.to === held.to) return
    this.selection = { kind: 'stretch', stretch: next }
  }
 
  /**
   * ↑ or ↓ (§27.4): what is selected one place earlier or later — a whole
   * sequence in the order, a piece among its sequence's — joining nothing.
   * Where it cannot go, the readout says why.
   */
  private shiftSelection(delta: -1 | 1): void {
    const held = this.selection?.kind === 'stretch' ? this.selection.stretch : null
    if (held === null) return
    const assembly = this.props.store.assembly
    const step = shiftStep(assembly, held, delta)
    if (step !== null) {
      this.step(step)
      const units = this.grid === null || this.selection?.kind !== 'stretch' ? null : stretchUnits(this.grid, this.selection.stretch)
      if (units !== null && !this.inView(units)) this.frameUnits(units[0], units[1])
      return
    }
    const whole = isWholeSequence(assembly, held)
    const pieces = assembly.piecesIn(held.sequence, 0, assembly.lengthOf(held.sequence) ?? 0).length
    this.readoutEl.textContent = whole
      ? `${held.sequence} is ${delta < 0 ? 'first' : 'last'} already`
      : pieces > 1 && assembly.piecesIn(held.sequence, held.from, held.to).length === 1
        ? `it is the ${delta < 0 ? 'first' : 'last'} piece of ${held.sequence} already: ↑ ↓ never take it out`
        : '↑ ↓ move a whole sequence, or a piece among its sequence’s pieces'
  }
 
  /** Whether a stretch of the axis is on screen, both of its ends. */
  private inView(units: readonly [number, number]): boolean {
    const [a, b] = [this.sx.toPixel(units[0]), this.sx.toPixel(units[1])]
    return a >= 0 && b <= this.size
  }
 
  /**
   * The pointer at `(x, y)` on the map, snapped, and said in the readout: to a
   * suggestion's corner in the plane where one is within reach (§27.4), else
   * along each axis; and a suggestion's mark under it lit, with its label.
   */
  private pointAt(x: number, y: number): void {
    if (this.grid === null) return
    const spots = this.preview === null && this.drag?.kind !== 'move' ? markSpots({ size: this.size, toX: (u) => this.sx.toPixel(u), toY: (u) => this.sy.toPixel(u), marks: this.marks() }) : []
    let nearest: (typeof spots)[number] | null = null
    let distance = Number.POSITIVE_INFINITY
    for (const spot of spots) {
      const d = Math.hypot(spot.x - x, spot.y - y)
      if (d < distance) {
        nearest = spot
        distance = d
      }
    }
    const within = nearest !== null && distance <= CORNER_PX ? nearest : null
    if (within !== null && within.corner && !this.alt) {
      const target = { kind: 'suggestion' as const, key: within.key }
      this.hover = { x: { unit: within.col, target: { ...target, unit: within.col } }, y: { unit: within.row, target: { ...target, unit: within.row } }, px: x, py: y }
    } else {
      this.hover = { x: this.snapX(this.sx.toUnit(x)), y: this.snapY(this.sy.toUnit(y)), px: x, py: y }
    }
    if (this.drag === null) this.setLit(within?.key ?? this.hover.x.target?.key ?? this.hover.y.target?.key ?? null)
    // An end a drag would take hold of says so under the pointer (§27.6).
    this.overlayCanvas.classList.toggle('is-on-end', this.drag === null && this.endUnder(x, y) !== null)
    this.overlayCanvas.classList.toggle('is-adjusting', this.drag?.kind === 'adjust')
    this.paintReadout()
    this.schedule()
  }
 
  /** Recompute a move's drop and its preview as the pointer travels. */
  private updateMove(drag: Extract<Drag, { kind: 'move' }>): void {
    const grid = this.grid
    if (grid === null) return
    const along = (this.sx.toUnit(drag.x) + this.sy.toUnit(drag.y)) / 2
    const length = drag.units[1] - drag.units[0]
    // Where the stretch's start would go, snapped by whichever of its two ends
    // is nearer a target — a stretch is dropped against an edge either way.
    const start = along - drag.grip
    const reach = SNAP_PX * this.sx.unitsPerPixel
    const ends = endTargets(grid)
    const byStart = snapUnit(start, ends, reach, this.alt && !drag.copy)
    const byEnd = snapUnit(start + length, ends, reach, this.alt && !drag.copy)
    const unit =
      byEnd.target !== null && (byStart.target === null || Math.abs(byEnd.unit - (start + length)) < Math.abs(byStart.unit - start))
        ? byEnd.unit - length
        : byStart.unit
    // Before the step, a start past the stretch is measured with it still in.
    const at = unit > drag.units[0] ? unit + length : unit
    drag.mark = Math.max(0, Math.min(grid.n, at))
    // A copy goes into a sequence, as a join does: only a move has a place between.
    const place = dropPlace(grid, drag.mark, along, drag.fuse || drag.copy)
    const step = place === null ? null : dropStep(this.props.store.assembly, drag.stretch, place, drag.strand, drag.copy)
    drag.between = place !== null && 'before' in place
    drag.step = step
    if (step === null) {
      this.preview = null
    } else {
      const assembly = this.props.store.assembly
      const next = EditedAssembly.of(this.props.store.tentative(step))
      const previewGrid = LensGrid.of(next, this.layout as GridLayout)
      const where = landed(assembly, next, step)
      this.preview = { grid: previewGrid, units: where === null ? null : stretchUnits(previewGrid, where) }
    }
    this.pictureDirty = true
    this.paintReadout()
  }
 
  private cancelDrag(): boolean {
    if (this.drag === null) return false
    this.drag = null
    this.preview = null
    this.pictureDirty = true
    this.paintReadout()
    this.schedule()
    return true
  }
 
  /** Escape: the innermost thing in progress, and never the stage. */
  private escape(): void {
    closeMenu()
    if (this.cancelDrag()) return
    if (this.selection !== null) {
      this.selection = null
      this.paintSide()
      this.schedule()
    }
  }
 
  private key(event: KeyboardEvent): void {
    if (this.closed) return
    const target = event.target as HTMLElement | null
    if (target !== null && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT' || target.isContentEditable)) {
      return
    }
    // Only the dialog on top answers.
    const dialogs = document.querySelectorAll('.modal-backdrop')
    if (dialogs.length > 0 && !dialogs[dialogs.length - 1].contains(this.root)) return
    const mod = event.metaKey || event.ctrlKey
    const key = event.key
    let handled = true
    if (key === 'Alt') {
      this.alt = true
      handled = false
    } else if (key === ' ') {
      this.space = true
      this.overlayCanvas.classList.add('is-panning')
      // In review, held: the map as it would be with the suggestion taken.
      if (this.mode === 'review' && !event.repeat) this.startPreview()
    } else if (mod && (key === 'z' || key === 'Z')) {
      if (event.shiftKey) this.props.store.redo()
      else this.props.store.undo()
    } else if (mod && (key === 'y' || key === 'Y')) {
      this.props.store.redo()
    } else if (mod) {
      handled = false
    } else if (key === 'i' || key === 'I') {
      if (this.drag?.kind === 'move') {
        this.drag.strand = this.drag.strand === 1 ? -1 : 1
        this.updateMove(this.drag)
        this.schedule()
      } else if (this.selection?.kind === 'stretch') {
        this.turn(this.selection.stretch)
      } else handled = false
    } else if (key === 'c' || key === 'C') {
      this.cutHere()
    } else if (key === 's' || key === 'S') {
      this.splitHere()
    } else if (key === 'o' || key === 'O') {
      this.originHere()
    } else if (key === 'Backspace' || key === 'Delete') {
      if (this.selection?.kind === 'stretch') {
        const rect = this.overlayCanvas.getBoundingClientRect()
        this.asideMenu(this.selection.stretch, rect.left + rect.width / 2, rect.top + rect.height / 2)
      } else handled = false
    } else if (key === 'y' || key === 'Y' || key === 'n' || key === 'N') {
      // Review answers the one it is on; elsewhere, the one lit under the hand.
      const suggestion = this.byKey(this.mode === 'review' ? this.current : this.lit)
      if (suggestion === null) handled = false
      else if (key === 'y' || key === 'Y') this.accept(suggestion)
      else this.reject(suggestion)
    } else if (this.mode === 'review' && (key === 'ArrowRight' || key === 'ArrowLeft')) {
      this.moveCurrent(key === 'ArrowRight' ? 1 : -1)
    } else if (key === 'ArrowUp' || key === 'ArrowDown') {
      // A sequence's grip on the card moves its own sequence; elsewhere, what is selected.
      const grip = target?.closest?.('.edit-sequence-grip') as HTMLElement | null | undefined
      const named = grip?.dataset.sequence
      if (named !== undefined) this.selectWhole(named)
      if (this.selection?.kind === 'stretch') this.shiftSelection(key === 'ArrowUp' ? -1 : 1)
      else handled = false
      if (named !== undefined) this.focusGrip(this.selection?.kind === 'stretch' ? this.selection.stretch.sequence : named)
    } else if (key === 'Shift') {
      if (this.drag?.kind === 'move') {
        this.drag.fuse = true
        this.updateMove(this.drag)
        this.schedule()
      }
      handled = false
    } else if (key === '0') {
      this.fit()
    } else if (key === '+' || key === '=') {
      this.zoomBy(0.5)
    } else if (key === '-' || key === '_') {
      this.zoomBy(2)
    } else {
      handled = false
    }
    if (handled) {
      event.preventDefault()
      event.stopPropagation()
    }
  }
 
  private keyUp(event: KeyboardEvent): void {
    if (event.key === 'Alt') this.alt = false
    if (event.key === 'Shift' && this.drag?.kind === 'move') {
      this.drag.fuse = false
      this.updateMove(this.drag)
      this.schedule()
    }
    if (event.key === ' ') this.letGoOfSpace()
  }
 
  /** The window left with keys held: no key-up comes for them, so they are let go of here. */
  private letGo(): void {
    this.alt = false
    this.letGoOfSpace()
  }
 
  private letGoOfSpace(): void {
    this.space = false
    this.overlayCanvas.classList.remove('is-panning')
    this.stopPreview()
  }
 
  /** The right-click menu: what can be done with what is selected, or here. */
  private menuItems(clientX: number, clientY: number): MenuItem[] {
    const items: MenuItem[] = []
    const selection = this.selection
    if (selection?.kind === 'stretch') {
      const stretch = selection.stretch
      items.push(
        { label: formatLocus({ contig: stretch.sequence, start: stretch.from, end: stretch.to }) },
        { label: 'turn it round', hint: 'I', run: () => this.turn(stretch) },
        { label: 'copy it after itself', run: () => this.copy(stretch) },
        { label: 'make it a sequence of its own', run: () => this.splitOut(stretch) },
        { label: 'set it aside…', hint: 'delete', run: () => this.asideMenu(stretch, clientX, clientY) },
      )
    }
    const place = this.pointerPlace()
    if (place !== null) {
      items.push(
        { label: formatPosition(place.sequence, place.at) },
        { label: 'cut here', hint: 'C', run: () => this.step({ op: 'cut', sequence: place.sequence, at: place.at }) },
        { label: 'split into two sequences here', hint: 'S', run: () => this.step({ op: 'split', sequence: place.sequence, at: place.at }) },
        ...(this.circularOf(place.sequence)
          ? [{ label: 'start the circle here', hint: 'O', run: () => this.step({ op: 'rotate', sequence: place.sequence, at: place.at }) }]
          : []),
      )
    }
    return items
  }
 
  // -------------------------------------------------------------------------
  // Words
  // -------------------------------------------------------------------------
 
  /** The line over the map: where the pointer is, or what the drag would do. */
  private paintReadout(): void {
    const grid = this.grid
    const drag = this.drag
    if (drag?.kind === 'move' && drag.moved) {
      this.readoutEl.textContent =
        drag.step === null
          ? 'drop it here to leave it where it is'
          : `${stepText(drag.step)}${drag.between === true ? ' · ⇧ to join it instead' : ''}${drag.copy ? '' : ' · ⌥ to copy'} · I to turn it`
      return
    }
    const hover = this.hover
    if (grid === null || hover === null) {
      this.readoutEl.textContent = this.summary()
      return
    }
    const describe = (unit: number): string => {
      const place = grid.place(Math.min(grid.n - 1e-9, Math.max(0, unit)))
      if (place === null) return ''
      const here = formatPosition(place.sequence, Math.floor(place.bp))
      const piece = place.part.piece
      const segment = place.part.segment
      if (piece === null || segment === null) return `${here} · gap`
      const original = Math.floor(Math.max(piece.start, Math.min(piece.end - 1, bpAt(segment, unit))))
      const same = piece.sequence === place.sequence && piece.strand === 1 && original === Math.floor(place.bp)
      return same ? here : `${here} ← ${formatPosition(piece.sequence, original)}${piece.strand === -1 ? ', turned' : ''}`
    }
    const offDiagonal = Math.abs(hover.px - hover.py - (this.sx.toPixel(0) - this.sy.toPixel(0))) > DIAGONAL_PX * Math.SQRT2
    const row = offDiagonal ? describe(hover.y.unit) : ''
    const edge = hover.x.target?.kind === 'end' ? this.edgeName(grid, hover.x.unit) : null
    const col = edge ?? describe(hover.x.unit)
    // A suggestion's point names the suggestion: its number, its kind; a corner
    // is two points at once.
    const onKey = hover.x.target?.kind === 'suggestion' ? hover.x.target.key : hover.y.target?.kind === 'suggestion' ? hover.y.target.key : undefined
    const suggestion = onKey === undefined ? null : this.byKey(onKey)
    const number = suggestion === null ? 0 : this.open().findIndex((open) => open.key === suggestion.key) + 1
    const corner = suggestion !== null && hover.x.target?.kind === 'suggestion' && hover.y.target?.kind === 'suggestion' && offDiagonal
    const snapped =
      suggestion !== null
        ? `${corner ? 'corner of' : 'snapped to'} ${number} · ${KIND_WORD[suggestion.kind]} · `
        : hover.x.target !== null && edge === null
          ? 'edit end · '
          : this.alt
            ? 'free · '
            : ''
    this.readoutEl.textContent = `${snapped}${col}${row === '' ? '' : ` × ${row}`}`
  }
 
  /**
   * A unit the pointer snapped to, named as the edge between two sequences where
   * it is one — the end of one and the start of the next is one place, and the
   * readout says both — or `null` for a junction inside a sequence.
   */
  private edgeName(grid: LensGrid, unit: number): string | null {
    const before = grid.sequenceAt(unit - 0.5)
    const after = grid.sequenceAt(unit)
    if (before === after) return null
    if (before === null && after !== null) return `the start of ${after.name}`
    if (after === null && before !== null) return `the end of ${before.name}`
    return before !== null && after !== null ? `between ${before.name} and ${after.name}` : null
  }
 
  private summary(): string {
    const assembly = this.props.store.assembly
    const total = assembly.sequences.reduce((sum, sequence) => sum + (assembly.lengthOf(sequence.name) ?? 0), 0)
    const steps = this.props.store.applied
    return `${assembly.sequences.length.toLocaleString('en-US')} sequences · ${fmt.bp(total)}${steps > 0 ? ` · ${steps} ${steps === 1 ? 'step' : 'steps'}` : ' · as in the file'}`
  }
 
  // -------------------------------------------------------------------------
  // The sidebar
  // -------------------------------------------------------------------------
 
  private paintSide(): void {
    this.paintSuggestions()
    this.paintReview()
    this.paintSelection()
    this.paintHistory()
    this.paintSequences()
    this.paintGenome()
    this.paintPicture()
    this.paintReadout()
    const store = this.props.store
    this.undoButton.disabled = !store.canUndo
    this.redoButton.disabled = !store.canRedo
    for (const [name, button] of Object.entries(this.modes) as Array<[Mode, HTMLButtonElement]>) {
      button.setAttribute('aria-pressed', String(name === this.mode))
      button.disabled = name !== 'manual' && this.suggested === null
    }
  }
 
  // -------------------------------------------------------------------------
  // Suggestions
  // -------------------------------------------------------------------------
 
  /** The suggestions offered: not turned down, and at the floor or above, best first. */
  private open(): Suggestion[] {
    const rejected = new Set(this.learned.rejected)
    return (this.suggested?.list ?? [])
      .filter((suggestion) => !rejected.has(suggestion.key) && suggestion.confidence >= OFFER_FLOOR)
      .map((suggestion) => this.effective(suggestion))
  }
 
  /**
   * A suggestion as the hand left it: its ends where they were dragged, the
   * confidence and what it rests on the method's latest count's (§27.6).
   */
  private effective(suggestion: Suggestion): Suggestion {
    const moved = this.adjustments.get(suggestion.key)
    return moved === undefined ? this.placed(suggestion) : { ...moved, confidence: suggestion.confidence, features: suggestion.features, gain: suggestion.gain }
  }
 
  /** A suggestion with its points where the finer rungs placed them (§27.5), where they have. */
  private placed(suggestion: Suggestion): Suggestion {
    const grid = this.grid
    if (grid === null || this.placements.size === 0) return suggestion
    let placed = this.placedMemo.get(suggestion)
    if (placed === undefined) {
      placed = refinedSuggestion(grid, suggestion, (point) => this.placements.get(pointKey(point)))
      this.placedMemo.set(suggestion, placed)
    }
    return placed
  }
 
  /** Let go of where the finer rungs placed the points: the edit, or the picture, they were read for is gone. */
  private dropPlacements(): void {
    this.refineRequest?.cancel()
    this.refineRequest = null
    this.refineRound++
    this.refining = null
    this.placements.clear()
    this.placedMemo = new WeakMap()
  }
 
  /**
   * Place the points of the suggestions offered at the finer rungs (§27.5),
   * best first, one suggestion a read, off the stage's thread: each is said in
   * the list as it comes in. A newer count, or an edit, drops what is still to
   * come; a point placed already is not asked again.
   */
  private placeSuggestions(): void {
    this.refineRequest?.cancel()
    this.refineRequest = null
    const round = ++this.refineRound
    const ask = this.props.refine
    const picture = this.picture
    const suggested = this.suggested
    if (ask === undefined || picture === null || suggested === null) {
      this.refining = null
      return
    }
    const rejected = new Set(this.learned.rejected)
    const offered = suggested.list.filter((suggestion) => !rejected.has(suggestion.key) && suggestion.confidence >= OFFER_FLOOR).slice(0, PLACE_MOST)
    const edit = this.props.store.edit
    const assembly = EditedAssembly.of(edit)
    const cell = picture.binsize
    const run = async (): Promise<void> => {
      for (const suggestion of offered) {
        const points = pointsOf(suggestion, assembly, cell, this.evidence).filter((point) => !this.placements.has(pointKey(point)))
        if (points.length === 0) continue
        const request = ask({ edit, points, cell, least: picture.least ?? 0, balance: picture.balanced })
        this.refineRequest = request
        this.paintSuggestions()
        let placed: Array<RefinedPoint | null>
        try {
          placed = await request.promise
        } catch {
          if (this.refineRequest === request) this.refineRequest = null
          return
        }
        if (this.closed || round !== this.refineRound || this.props.store.edit !== edit) return
        this.refineRequest = null
        points.forEach((point, i) => this.placements.set(pointKey(point), placed[i] ?? null))
        this.placedMemo = new WeakMap()
        this.railSignature = ''
        this.paintSide()
        this.schedule()
      }
    }
    const running = run().finally(() => {
      if (this.refineRound !== round || this.closed) return
      this.refining = null
      this.paintSuggestions()
    })
    this.refining = running
  }
 
  /**
   * An end of the suggestion review is on within reach of the pointer, that a
   * drag would take hold of (§27.6). In review only: there the suggestion is
   * the one thing being answered, where in manual its ends sit on the very
   * places a selection's square is pressed to move it.
   */
  private endUnder(x: number, y: number): { key: string; end: 0 | 1 } | null {
    if (this.mode !== 'review' || this.preview !== null) return null
    const suggestion = this.byKey(this.current)
    if (suggestion === null) return null
    const ends = adjustableEnds(suggestion)
    for (let i = 0; i < ends.length; i++) {
      if (Math.hypot(this.sx.toPixel(ends[i]) - x, this.sy.toPixel(ends[i]) - y) <= CORNER_PX) return { key: suggestion.key, end: i === 0 ? 0 : 1 }
    }
    return null
  }
 
  /** An end of a suggestion followed to where the pointer is, snapped along the diagonal (§27.6). */
  private updateAdjust(drag: Extract<Drag, { kind: 'adjust' }>): void {
    const grid = this.grid
    const suggestion = this.byKey(drag.key)
    if (grid === null || suggestion === null) return
    const unit = this.alongUnit(drag.x, drag.y).unit
    const next = adjustSuggestion(grid, suggestion, drag.end, unit)
    if (next !== null) {
      this.adjustments.set(drag.key, next)
      // Dragged past the other end, it is the other end now.
      if (suggestion.stretch !== null && next.stretch !== null) drag.end = unit <= next.stretch[0] ? 0 : 1
    }
    const number = this.open().findIndex((open) => open.key === drag.key) + 1
    this.readoutEl.textContent = `adjusting ${number} · ${(next ?? suggestion).words}${next === null ? ' · not here' : ''}`
    this.railSignature = ''
  }
 
  /** The ones turned down, which the list strikes through. */
  private declined(): Suggestion[] {
    const rejected = new Set(this.learned.rejected)
    return (this.suggested?.list ?? []).filter((suggestion) => rejected.has(suggestion.key))
  }
 
  private byKey(key: string | null | undefined): Suggestion | null {
    if (key === null || key === undefined) return null
    const found = this.suggested?.list.find((suggestion) => suggestion.key === key)
    return found === undefined ? null : this.effective(found)
  }
 
  /** The suggestions as the map draws them, numbered as the rail and the list number them. */
  private marks(): MarkedSuggestion[] {
    return this.open().map((suggestion, i) => ({
      suggestion,
      number: i + 1,
      lit: suggestion.key === this.lit || suggestion.key === this.current,
    }))
  }
 
  /**
   * Count the suggestions now rather than once the hand has let go: when the
   * picture or the sequence's evidence arrives. Here, the count is in before
   * this returns; kept where it was read, it is on its way.
   */
  private countNow(): void {
    window.clearTimeout(this.suggesting)
    this.suggesting = 0
    void this.recount().then(() => {
      if (this.closed) return
      this.paintSide()
      this.schedule()
    })
  }
 
  /** Whether there is anything to weigh suggestions against: the method's data here, or kept where it was read. */
  private weighs(): boolean {
    return this.method !== null || (this.methodKept !== null && this.props.suggest !== undefined)
  }
 
  /** Count the suggestions again once the hand has let go — after an edit, or an answer. */
  private scheduleSuggestions(): void {
    if (!this.weighs() || this.closed) return
    window.clearTimeout(this.suggesting)
    this.suggesting = window.setTimeout(() => {
      this.suggesting = 0
      if (this.closed) return
      void this.recount().then(() => {
        if (this.closed) return
        this.paintSide()
        this.schedule()
      })
    }, 30)
    this.paintSuggestions()
  }
 
  /**
   * The suggestions for the edit as it stands (§27.5): counted where the
   * method's data is kept — off the stage's thread, so a hand on the map is
   * never held up by them (§27.12) — or here where the picture brought it.
   * Settles once they are in; a count overtaken by another edit is dropped
   * for the one that follows it.
   */
  private recount(): Promise<void> {
    const grid = this.grid
    if (grid === null || this.closed) return Promise.resolve()
    const weights = this.learned.weights ?? INITIAL_WEIGHTS
    if (this.method !== null) {
      this.tookSuggestions(suggest({ ...this.method, grid, weights, ...(this.evidence === null ? {} : { evidence: this.evidence }) }))
      return Promise.resolve()
    }
    const kept = this.methodKept
    const ask = this.props.suggest
    const layout = this.layout
    if (kept === null || ask === undefined || layout === null) return Promise.resolve()
    this.recountRequest?.cancel()
    const edit = this.props.store.edit
    const request = ask({ picture: kept, edit, layout, weights: [...weights], ...(this.evidence === null ? {} : { evidence: this.evidence }) })
    this.recountRequest = request
    this.paintSuggestions()
    return request.promise.then(
      (suggested) => {
        if (this.closed || this.recountRequest !== request) return
        this.recountRequest = null
        if (this.props.store.edit === edit) this.tookSuggestions(suggested)
      },
      () => {
        if (this.recountRequest === request) this.recountRequest = null
      },
    )
  }
 
  /** A count of the suggestions, taken: the one review is on and the one lit kept where they still are. */
  private tookSuggestions(suggested: Suggested): void {
    this.suggested = suggested
    this.placeSuggestions()
    const open = this.open()
    if (this.current !== null && !open.some((suggestion) => suggestion.key === this.current)) this.current = null
    if (this.mode === 'review' && this.current === null) {
      // The next best, and framed (§27.6), as entering review and → and ←
      // frame theirs. It used to become the one review was on without the map
      // moving to it, so after a `Y` or an `N` the line under the toolbar
      // named a suggestion the map was not showing, and the next answer was
      // given looking at the last one's place.
      this.current = open[0]?.key ?? null
      const next = this.byKey(this.current)
      if (next !== null) this.frameSuggestion(next)
    }
    if (this.lit !== null && this.byKey(this.lit) === null) this.lit = null
    this.railSignature = ''
  }
 
  /** Light a suggestion — its marks, its label and its row at once — or none. */
  private setLit(key: string | null): void {
    if (key === this.lit) return
    this.lit = key
    for (const row of this.suggestionsCard.querySelectorAll<HTMLElement>('.edit-suggestion')) {
      row.classList.toggle('is-lit', row.dataset.key === key)
    }
    this.schedule()
  }
 
  /** A suggestion pressed, on the rail or in the list: framed, and the one review is on. */
  private pick(key: string): void {
    const suggestion = this.byKey(key)
    if (suggestion === null) return
    if (this.mode === 'review') this.current = key
    this.frameSuggestion(suggestion)
    this.paintSide()
  }
 
  /** Frame what a suggestion concerns, with room round it to see the evidence. */
  private frameSuggestion(suggestion: Suggestion): void {
    const [a, b] = suggestion.extent
    const room = Math.max(12, (b - a) * 0.4)
    this.frameUnits(a - room, b + room)
  }
 
  /** Take a suggestion: its step made, with what it rested on kept in the history. */
  private accept(suggestion: Suggestion, by: 'suggestion' | 'auto' = 'suggestion'): void {
    if (by === 'suggestion') this.answer(suggestion, true)
    if (this.current === suggestion.key) this.current = null
    this.selection = null
    this.props.store.apply(suggestion.step, by, `${suggestion.words} · ${percent(suggestion.confidence)} · ${suggestion.evidence.join(', ')}`)
  }
 
  /** Turn a suggestion down: gone from the map, struck through in the list, and learned from. */
  private reject(suggestion: Suggestion): void {
    this.answer(suggestion, false)
    this.learned = { ...this.learned, rejected: [...this.learned.rejected, suggestion.key] }
    this.props.store.keepLearned(this.learned)
    if (this.current === suggestion.key) this.current = null
    if (this.lit === suggestion.key) this.lit = null
    this.scheduleSuggestions()
  }
 
  /** An answer, learned: one step of the confidence model towards it (§27.6). */
  private answer(suggestion: Suggestion, accepted: boolean): void {
    const weights = learn(this.learned.weights ?? INITIAL_WEIGHTS, suggestion.features, accepted)
    this.learned = { ...this.learned, weights, answers: this.learned.answers + 1 }
    this.props.store.keepLearned(this.learned)
  }
 
  /** A suggestion turned down, offered again. */
  private restore(key: string): void {
    this.learned = { ...this.learned, rejected: this.learned.rejected.filter((held) => held !== key) }
    this.props.store.keepLearned(this.learned)
    this.scheduleSuggestions()
  }
 
  /** Everything the answers taught, forgotten: the initial weights, nothing turned down. */
  private forget(): void {
    this.learned = { weights: null, answers: 0, rejected: [] }
    this.props.store.keepLearned(this.learned)
    this.scheduleSuggestions()
  }
 
  /**
   * Auto mode's run (§27.6): the best suggestion at the threshold or above,
   * applied as a step marked `auto`, the rest counted again, until none is left
   * above it.
   */
  private async runAuto(): Promise<void> {
    if (this.autoRunning) return
    this.autoRunning = true
    try {
      for (let k = 0; k < AUTO_MOST; k++) {
        // Each taken as the finer rungs place it, where they do.
        if (this.refining !== null) await this.refining
        if (this.closed) return
        const next = this.open().find((suggestion) => suggestion.confidence >= AUTO_THRESHOLD)
        if (next === undefined) break
        const before = this.props.store.applied
        this.accept(next, 'auto')
        window.clearTimeout(this.suggesting)
        this.suggesting = 0
        if (this.props.store.applied === before) break
        await this.recount()
        if (this.closed) return
      }
    } finally {
      this.autoRunning = false
    }
    this.paintSide()
    this.schedule()
  }
 
  /**
   * The sidebar's cards, in their order (§27.3): what is selected, the
   * sequences, the history, then the suggestions — first instead while review
   * or auto mode is answering them — the export and the picture. Moved rather
   * than built again, so a card keeps its scroll and whatever is typed in it.
   */
  private arrangeSide(): void {
    const answering = this.mode !== 'manual'
    const cards = [
      this.modesEl,
      ...(answering ? [this.suggestionsCard] : []),
      this.selectionCard,
      this.sequencesCard,
      ...(this.props.store.edit.original.genome === undefined ? [] : [this.genomeCard]),
      this.historyCard,
      ...(answering ? [] : [this.suggestionsCard]),
      this.exportCard.element,
      this.pictureCard,
    ]
    cards.forEach((card, i) => {
      if (this.side.children[i] !== card) this.side.insertBefore(card, this.side.children[i] ?? null)
    })
  }
 
  private setMode(mode: Mode): void {
    if (mode !== 'manual' && this.suggested === null) return
    this.mode = mode
    this.arrangeSide()
    this.stopPreview()
    this.current = mode === 'review' ? (this.open()[0]?.key ?? null) : null
    const current = this.byKey(this.current)
    if (current !== null) this.frameSuggestion(current)
    this.paintSide()
    this.schedule()
  }
 
  /** Review's next suggestion, or the one before. */
  private moveCurrent(delta: 1 | -1): void {
    const open = this.open()
    if (open.length === 0) return
    const at = open.findIndex((suggestion) => suggestion.key === this.current)
    const next = open[(Math.max(0, at) + delta + open.length) % open.length]
    this.current = next.key
    this.frameSuggestion(next)
    this.paintSide()
  }
 
  /** Space held in review: the map, its bars and its lanes, as they would be with the suggestion taken. */
  private startPreview(): void {
    const current = this.byKey(this.current)
    const layout = this.layout
    if (current === null || layout === null || this.drag !== null) return
    this.previewing = true
    this.preview = { grid: LensGrid.of(EditedAssembly.of(this.props.store.tentative(current.step)), layout), units: null }
    this.pictureDirty = true
    this.paintReview()
    this.schedule()
  }
 
  private stopPreview(): void {
    if (!this.previewing) return
    this.previewing = false
    this.preview = null
    this.pictureDirty = true
    this.paintReview()
    this.schedule()
  }
 
  /** The rail, painted again only when something it shows has changed. */
  private paintRail(marks: readonly MarkedSuggestion[], toY: (unit: number) => number, ink: StageInk): void {
    const [y0, y1] = this.sy.domain
    const signature = `${y0.toFixed(3)}:${y1.toFixed(3)}:${this.lit}:${this.current}:${marks.map((m) => m.suggestion.key).join('|')}`
    if (signature === this.railSignature) return
    this.railSignature = signature
    const items: RailItem[] = marks.map(({ suggestion, number }) => ({
      key: suggestion.key,
      number,
      text: `${KIND_WORD[suggestion.kind]} ${percent(suggestion.confidence)}`,
      title: suggestion.words,
      extent: suggestion.extent,
      lit: suggestion.key === this.lit,
      current: suggestion.key === this.current,
    }))
    this.rail.paint(items, toY, ink)
  }
 
  /** The line under the toolbar that says where review is, and what its keys do. */
  private paintReview(): void {
    const bar = this.reviewBar
    const current = this.byKey(this.current)
    if (this.mode !== 'review') {
      bar.classList.add('hidden')
      bar.replaceChildren()
      return
    }
    bar.classList.remove('hidden')
    const open = this.open()
    if (current === null) {
      bar.replaceChildren(el('span', { class: 'edit-review-words', text: open.length === 0 ? 'review · nothing left to answer' : 'review' }))
      return
    }
    const key = (text: string): HTMLElement => el('kbd', { class: 'kbd', text })
    bar.replaceChildren(
      el('span', { class: 'edit-review-where', text: `${open.findIndex((one) => one.key === current.key) + 1} of ${open.length}` }),
      el('span', { class: 'edit-review-words', text: `${current.words} · ${percent(current.confidence)}` }),
      el(
        'span',
        { class: 'edit-review-keys' },
        this.previewing ? el('span', { class: 'edit-review-state', text: 'as it would be' }) : '',
        key('Y'),
        ' take it ',
        key('N'),
        ' turn it down ',
        key('←'),
        key('→'),
        ' the others ',
        key('space'),
        ' held: as it would be',
        adjustableEnds(current).length > 0 ? ' · drag its ends to adjust it' : '',
      ),
    )
  }
 
  /** The card of suggestions: the list, best first, each with its answer. */
  private paintSuggestions(): void {
    const card = this.suggestionsCard
    const open = this.open()
    const weighing = this.suggesting !== 0 || this.recountRequest !== null || this.autoRunning
    // Their points being placed at the finer rungs (§27.5), after the count.
    const placing = !weighing && this.refineRequest !== null
    const head = el('h3', {
      class: 'edit-card-head',
      text:
        this.suggested === null
          ? `suggestions${weighing ? ' · weighing…' : ''}`
          : `suggestions · ${open.length}${weighing ? ' · weighing…' : placing ? ' · placing…' : ''}`,
    })
    if (!this.weighs() || this.suggested === null) {
      card.replaceChildren(
        head,
        el('p', {
          class: 'edit-empty',
          text:
            this.picture === null
              ? 'Weighed once the picture is read: the map’s own contact law, then every junction the reference makes, and every two ends that might meet.'
              : // The first count, where the data is kept, is on its way.
                this.weighs() && weighing
                ? 'Weighing the map’s own contact law, then every junction the reference makes, and every two ends that might meet…'
                : 'The map gave the method nothing to weigh.',
        }),
      )
      return
    }
    const children: HTMLElement[] = [head]
    if (this.mode === 'auto') {
      const ready = open.filter((suggestion) => suggestion.confidence >= AUTO_THRESHOLD).length
      const run = this.act(
        ready === 0 ? `none at ${percent(AUTO_THRESHOLD)} or more` : `apply ${ready} at ${percent(AUTO_THRESHOLD)} or more`,
        'play',
        'Apply them best first, counting again after each: every one a step marked auto, to undo like any other',
        () => void this.runAuto(),
      )
      run.disabled = ready === 0 || this.autoRunning
      children.push(el('div', { class: 'edit-acts' }, run))
    }
    if (open.length === 0) {
      children.push(
        el('p', {
          class: 'edit-empty',
          text:
            this.declined().length > 0
              ? 'Nothing left to answer: what was turned down is below, to offer again. Drag along the diagonal to edit by hand.'
              : 'Nothing to suggest: every junction the reference makes is one the map supports, and no two ends it leaves apart meet. Drag along the diagonal to edit by hand.',
        }),
      )
    } else {
      const list = el('ol', { class: 'edit-suggestions' })
      open.forEach((suggestion, i) => list.append(this.suggestionRow(suggestion, i + 1)))
      children.push(list)
    }
    const declined = this.declined()
    if (declined.length > 0) {
      const details = el('details', { class: 'edit-declined' })
      details.append(el('summary', { text: `turned down · ${declined.length}` }))
      const list = el('ul', { class: 'edit-declined-list' })
      for (const suggestion of declined) {
        const restore = el('button', {
          class: 'btn btn-icon',
          title: 'Offer it again',
          attrs: { type: 'button', 'aria-label': `Offer ${suggestion.words} again` },
          on: { click: () => this.restore(suggestion.key) },
        })
        restore.append(icon('undo-2', { size: 13 }))
        list.append(el('li', {}, el('span', { class: 'edit-declined-words', text: suggestion.words }), restore))
      }
      details.append(list)
      children.push(details)
    }
    if (this.learned.answers > 0) {
      children.push(
        el(
          'p',
          { class: 'edit-note' },
          `ranked by what ${this.learned.answers} ${this.learned.answers === 1 ? 'answer' : 'answers'} taught it · `,
          el('button', { class: 'btn-link', text: 'forget', attrs: { type: 'button' }, title: 'Back to the initial weights, with nothing turned down', on: { click: () => this.forget() } }),
        ),
      )
    }
    card.replaceChildren(...children)
  }
 
  private suggestionRow(suggestion: Suggestion, number: number): HTMLElement {
    const lit = suggestion.key === this.lit
    const current = suggestion.key === this.current
    const row = el('li', {
      class: `edit-suggestion${lit ? ' is-lit' : ''}${current ? ' is-current' : ''}`,
      attrs: { 'data-key': suggestion.key },
      on: { pointerenter: () => this.setLit(suggestion.key), pointerleave: () => this.setLit(null) },
    })
    const main = el('button', {
      class: 'edit-suggestion-main',
      title: 'Frame it on the map',
      attrs: { type: 'button' },
      on: { click: () => this.pick(suggestion.key), focus: () => this.setLit(suggestion.key) },
    })
    const kindIcon = { split: 'split', turn: 'flip-horizontal', move: 'move', join: 'merge' } as const
    main.append(
      el('span', { class: 'edit-suggestion-n', text: String(number) }),
      icon(kindIcon[suggestion.kind], { size: 14 }),
      el('span', { class: 'edit-suggestion-words', text: suggestion.words }),
      el('span', { class: 'edit-suggestion-confidence', text: percent(suggestion.confidence) }),
    )
    // `adjusted` is the way back as well as the word (§27.6): its ends put
    // back where the method found them, from the chip that says they moved.
    const chipOf = (chip: string): HTMLElement => {
      if (chip !== 'adjusted' || !this.adjustments.has(suggestion.key)) return el('span', { class: 'edit-chip', text: chip })
      const back = el('button', {
        class: 'edit-chip edit-chip-button',
        title: 'Put its ends back where the method found them',
        attrs: { type: 'button' },
        on: {
          click: () => {
            this.adjustments.delete(suggestion.key)
            this.railSignature = ''
            this.paintSide()
            this.schedule()
          },
        },
      })
      back.append(el('span', { text: 'adjusted' }), icon('undo-2', { size: 11 }))
      return back
    }
    const chips = el('div', { class: 'edit-suggestion-chips' }, ...suggestion.evidence.map(chipOf))
    const take = el('button', {
      class: 'btn edit-suggestion-act',
      title: 'Take it: its step, made (Y)',
      attrs: { type: 'button', 'aria-label': `Take ${suggestion.words}` },
      on: { click: () => this.accept(suggestion) },
    })
    take.append(icon('check', { size: 13 }), el('span', { text: 'take' }), el('kbd', { class: 'kbd', text: 'Y' }))
    const down = el('button', {
      class: 'btn edit-suggestion-act',
      title: 'Turn it down: gone from the map, and learned from (N)',
      attrs: { type: 'button', 'aria-label': `Turn down ${suggestion.words}` },
      on: { click: () => this.reject(suggestion) },
    })
    down.append(icon('x', { size: 13 }), el('span', { text: 'turn down' }), el('kbd', { class: 'kbd', text: 'N' }))
    row.append(main, el('div', { class: 'edit-suggestion-foot' }, chips, el('div', { class: 'edit-suggestion-acts' }, take, down)))
    return row
  }
 
  private act(label: string, name: Parameters<typeof icon>[0], title: string, run: () => void, key?: string): HTMLButtonElement {
    const button = el('button', {
      class: 'btn edit-act',
      title: key === undefined ? title : `${title} (${key})`,
      attrs: { type: 'button' },
      on: { click: run },
    })
    button.append(icon(name, { size: 14 }), el('span', { text: label }))
    if (key !== undefined) button.append(el('kbd', { class: 'kbd', text: key }))
    return button
  }
 
  private paintSelection(): void {
    const card = this.selectionCard
    const head = el('h3', { class: 'edit-card-head', text: 'selection' })
    const selection = this.selection
    if (selection === null) {
      card.replaceChildren(
        head,
        el('p', {
          class: 'edit-empty',
          text: 'Press a piece, on the map or on a bar, and press it again for its whole sequence — or press the sequence’s name on a bar. Drag along the diagonal to select a stretch; drag off it to box two stretches, or press a corner for the stretch between its two ends.',
        }),
      )
      return
    }
    if (selection.kind === 'stretch') {
      const stretch = selection.stretch
      const pieces = this.props.store.assembly.piecesIn(stretch.sequence, stretch.from, stretch.to).length
      // One place earlier or later (§27.4): a sequence in the order, a piece among its sequence's.
      const whole = isWholeSequence(this.props.store.assembly, stretch)
      const earlier = this.act('earlier', 'chevron-up', whole ? 'One place earlier in the order — nothing is joined' : 'One place earlier among its sequence’s pieces', () => this.shiftSelection(-1), '↑')
      const later = this.act('later', 'chevron-down', whole ? 'One place later in the order — nothing is joined' : 'One place later among its sequence’s pieces', () => this.shiftSelection(1), '↓')
      earlier.disabled = shiftStep(this.props.store.assembly, stretch, -1) === null
      later.disabled = shiftStep(this.props.store.assembly, stretch, 1) === null
      card.replaceChildren(
        head,
        el('div', { class: 'edit-locus', text: formatLocus({ contig: stretch.sequence, start: stretch.from, end: stretch.to }) }),
        el('div', {
          class: 'edit-note',
          text: `${fmt.bp(stretch.to - stretch.from)} · ${pieces} ${pieces === 1 ? 'piece' : 'pieces'}`,
        }),
        el(
          'div',
          { class: 'edit-acts' },
          earlier,
          later,
          this.act('turn', 'flip-horizontal', 'Turn the stretch round', () => this.turn(stretch), 'I'),
          this.act('copy', 'copy', 'Copy the stretch in after itself', () => this.copy(stretch)),
          this.act('own sequence', 'split', 'Make the stretch a sequence of its own', () => this.splitOut(stretch), 'S'),
          this.act('set aside', 'trash-2', 'Take the stretch out of the assembly, with a reason', () => {
            const rect = card.getBoundingClientRect()
            this.asideMenu(stretch, rect.left + 16, rect.bottom - 8)
          }, 'delete'),
        ),
        el('p', {
          class: 'edit-hint',
          text: 'Drag its square, or its piece on a bar, to move it: let go between two sequences and it is a sequence of its own there, inside one and it goes in — ⇧ joins it to the end it is let go on, ⌥ copies it, I turns it on the way. Press it again for its whole sequence. A double click on a bar turns a piece.',
        }),
      )
      return
    }
    const { rows, cols } = selection
    const same = rows.sequence === cols.sequence && (rows.to <= cols.from || cols.to <= rows.from)
    const rowText = formatLocus({ contig: rows.sequence, start: rows.from, end: rows.to })
    const colText = formatLocus({ contig: cols.sequence, start: cols.from, end: cols.to })
    const swap = this.act('swap them', 'arrow-left-right', 'Each stretch takes the other’s place', () => this.swap(rows, cols))
    swap.disabled = !same
    if (!same) swap.title = 'Two stretches of one sequence that do not overlap swap places'
    card.replaceChildren(
      head,
      el('div', { class: 'edit-box-row' }, el('span', { class: 'edit-box-key', text: 'rows' }), el('span', { class: 'edit-locus', text: rowText })),
      el('div', { class: 'edit-box-row' }, el('span', { class: 'edit-box-key', text: 'columns' }), el('span', { class: 'edit-locus', text: colText })),
      el(
        'div',
        { class: 'edit-acts' },
        this.act('rows before columns', 'move', 'Move the rows’ stretch to just before the columns’', () => {
          this.step({ op: 'move', sequence: rows.sequence, from: rows.from, to: rows.to, into: cols.sequence, at: rows.sequence === cols.sequence && cols.from > rows.to ? cols.from - (rows.to - rows.from) : cols.from, strand: 1 })
        }),
        this.act('columns after rows', 'move', 'Move the columns’ stretch to just after the rows’', () => {
          this.step({ op: 'move', sequence: cols.sequence, from: cols.from, to: cols.to, into: rows.sequence, at: rows.sequence === cols.sequence && rows.to > cols.to ? rows.to - (cols.to - cols.from) : rows.to, strand: 1 })
        }),
        swap,
        this.act('turn rows', 'flip-vertical', 'Turn the rows’ stretch round', () => this.turn(rows)),
        this.act('turn columns', 'flip-horizontal', 'Turn the columns’ stretch round', () => this.turn(cols)),
      ),
    )
  }
 
  private paintHistory(): void {
    const store = this.props.store
    const { history, cursor } = store.edit
    const list = el('ol', { class: 'edit-history' })
    const row = (count: number, text: string): HTMLElement => {
      const item = el('li', {
        class: `edit-history-row${count === cursor ? ' is-current' : ''}${count > cursor ? ' is-undone' : ''}`,
      })
      const button = el('button', {
        class: 'edit-history-button',
        attrs: { type: 'button', 'aria-current': count === cursor ? 'step' : 'false' },
        title: count === cursor ? 'Where the edit stands' : count > cursor ? 'Redo up to here' : 'Go back to here',
        on: { click: () => store.goTo(count) },
      })
      button.append(el('span', { class: 'edit-history-n', text: count === 0 ? '·' : String(count) }), el('span', { text }))
      item.append(button)
      return item
    }
    list.append(row(0, 'the file as it is'))
    history.forEach((entry, i) => {
      const item = row(i + 1, stepText(entry.step))
      // A step a suggestion made says so, and what it rested on (§27.2).
      if (entry.by !== 'reader') {
        const by = el('span', { class: 'edit-history-by', text: entry.by === 'auto' ? 'auto' : 'suggested' })
        if (entry.suggestion !== undefined) by.title = entry.suggestion
        item.querySelector('.edit-history-button')?.append(by)
      }
      list.append(item)
    })
    const refusal = store.refusal === null ? null : el('p', { class: 'edit-note', text: store.refusal })
    this.historyCard.replaceChildren(
      el('h3', { class: 'edit-card-head', text: `history${history.length > 0 ? ` · ${cursor} of ${history.length}` : ''}` }),
      ...(refusal === null ? [] : [refusal]),
      list,
    )
  }
 
  /**
   * A stretch set aside, put back (§27.4): a sequence of its own, last, as the
   * file reads it — selected and framed, to be moved into place with ↑ ↓, its
   * grip or a drag.
   */
  private putBack(piece: Piece): void {
    this.step({ op: 'restore', sequence: piece.sequence, start: piece.start, end: piece.end })
    const units = this.grid === null || this.selection?.kind !== 'stretch' ? null : stretchUnits(this.grid, this.selection.stretch)
    if (units !== null) this.frameUnits(units[0], units[1])
  }
 
  /** A sequence selected whole, as a press on its row or on its name on a bar does. */
  private selectWhole(name: string): void {
    const length = this.props.store.assembly.lengthOf(name)
    if (length === null) return
    this.selection = { kind: 'stretch', stretch: { sequence: name, from: 0, to: length } }
  }
 
  /** The grip of a sequence's row, focused again once the card is painted anew. */
  private focusGrip(name: string): void {
    for (const grip of this.sequencesCard.querySelectorAll<HTMLElement>('.edit-sequence-grip')) {
      if (grip.dataset.sequence === name) grip.focus({ preventScroll: true })
    }
  }
 
  /**
   * A sequence's grip on the card (§27.4): dragged up or down the list, the
   * sequence goes where it is let go — before the row under the pointer, or
   * last — as one step, and nothing is joined. The card is not painted anew
   * while it is held: the rows it measures stay the rows on screen.
   */
  private wireGrip(grip: HTMLElement, name: string, list: HTMLElement): void {
    grip.addEventListener('pointerdown', (event) => {
      if (event.button !== 0) return
      event.preventDefault()
      grip.focus({ preventScroll: true })
      grip.setPointerCapture(event.pointerId)
      this.selectWhole(name)
      this.paintSelection()
      this.schedule()
      const rows = [...list.querySelectorAll<HTMLElement>('.edit-sequence-row')]
      const from = rows.findIndex((row) => row.contains(grip))
      rows.forEach((row, i) => {
        row.classList.toggle('is-lifted', i === from)
        row.querySelector('.edit-sequence')?.classList.toggle('is-selected', i === from)
      })
      let target = from
      const mark = (clientY: number): void => {
        target = rows.findIndex((row) => {
          const box = row.getBoundingClientRect()
          return clientY < box.top + box.height / 2
        })
        if (target < 0) target = rows.length
        const moves = target !== from && target !== from + 1
        rows.forEach((row, i) => {
          row.classList.toggle('is-drop-before', moves && i === target)
          row.classList.toggle('is-drop-after', moves && target === rows.length && i === rows.length - 1)
        })
      }
      const done = (commit: boolean): void => {
        grip.removeEventListener('pointermove', onMove)
        grip.removeEventListener('pointerup', onUp)
        grip.removeEventListener('pointercancel', onCancel)
        if (grip.hasPointerCapture(event.pointerId)) grip.releasePointerCapture(event.pointerId)
        rows.forEach((row) => row.classList.remove('is-drop-before', 'is-drop-after', 'is-lifted'))
        const assembly = this.props.store.assembly
        const length = assembly.lengthOf(name)
        if (!commit || length === null || target === from || target === from + 1) {
          this.paintSide()
          return
        }
        const before = assembly.sequences[target]?.name ?? null
        this.step({ op: 'place', sequence: name, from: 0, to: length, before, strand: 1, whole: true })
        this.focusGrip(name)
      }
      const onMove = (move: PointerEvent): void => mark(move.clientY)
      const onUp = (): void => done(true)
      const onCancel = (): void => done(false)
      grip.addEventListener('pointermove', onMove)
      grip.addEventListener('pointerup', onUp)
      grip.addEventListener('pointercancel', onCancel)
    })
  }
 
  private paintSequences(): void {
    const assembly = this.props.store.assembly
    const list = el('ul', { class: 'edit-sequences' })
    for (const sequence of assembly.sequences) {
      const length = assembly.lengthOf(sequence.name) ?? 0
      const pieces = sequence.parts.filter((part) => !('gap' in part)).length
      const selected =
        this.selection?.kind === 'stretch' &&
        this.selection.stretch.sequence === sequence.name &&
        this.selection.stretch.from === 0 &&
        this.selection.stretch.to === length
      const button = el('button', {
        class: `edit-sequence${selected ? ' is-selected' : ''}`,
        attrs: { type: 'button' },
        title: 'Select the whole sequence, and frame it',
        on: {
          click: () => {
            this.selection = { kind: 'stretch', stretch: { sequence: sequence.name, from: 0, to: length } }
            const grid = this.grid
            const units = grid === null ? null : stretchUnits(grid, this.selection.stretch)
            if (units !== null) this.frameUnits(units[0], units[1])
            this.paintSide()
            this.schedule()
          },
          // Its lines lit in the corner dot plot, as its name on a bar lights them (§27.3).
          pointerenter: () => this.dotplot?.focusOn({ sequence: sequence.name, from: 0, to: length }),
          pointerleave: () => this.dotplot?.focusOn(null),
        },
      })
      const units = this.grid?.sequence(sequence.name)
      if (units !== undefined && units !== null) button.dataset.cells = `${units.from} ${units.to}`
      const circle = this.circularOf(sequence.name)
      button.append(
        el('span', { class: 'edit-sequence-name', text: sequence.name, ...(circle ? { title: 'circular' } : {}) }),
        el('span', { class: 'edit-sequence-length', text: fmt.bp(length) }),
        el('span', { class: 'edit-sequence-pieces', text: `${circle ? '○ ' : ''}${pieces === 1 ? '' : `${pieces} pieces`}` }),
      )
      if (this.renaming === sequence.name) {
        list.append(el('li', { class: 'edit-sequence-row is-renaming' }, this.renameBox(sequence.name)))
        continue
      }
      // A name of its own (§27.3): the pencil, or a double click on the row.
      button.addEventListener('dblclick', (event) => {
        event.preventDefault()
        this.startRename(sequence.name)
      })
      const pencil = el('button', {
        class: 'btn-icon edit-sequence-rename',
        title: `Rename ${sequence.name}`,
        attrs: { type: 'button', 'aria-label': `Rename ${sequence.name}` },
        on: { click: () => this.startRename(sequence.name) },
      })
      pencil.append(icon('pencil', { size: 12 }))
      // Its place in the order (§27.4): dragged by its grip, or ↑ ↓ on it.
      const grip = el('button', {
        class: 'edit-sequence-grip',
        title: `Drag ${sequence.name} to another place in the order, or press ↑ ↓ — nothing is joined`,
        attrs: { type: 'button', 'aria-label': `Move ${sequence.name} in the order`, 'data-sequence': sequence.name },
      })
      grip.append(icon('grip-vertical', { size: 13 }))
      this.wireGrip(grip, sequence.name, list)
      list.append(el('li', { class: 'edit-sequence-row' }, grip, button, pencil))
    }
    const aside =
      assembly.aside.length === 0
        ? null
        : el(
            'div',
            { class: 'edit-aside' },
            el('h4', { class: 'edit-card-sub', text: `set aside · ${assembly.aside.length}` }),
            el(
              'ul',
              { class: 'edit-aside-list' },
              ...assembly.aside.map((item) => {
                const locus = formatLocus({ contig: item.piece.sequence, start: item.piece.start, end: item.piece.end })
                // Back into the assembly, as a sequence of its own (§27.4).
                const back = el('button', {
                  class: 'btn btn-quiet edit-aside-back',
                  title: 'Put it back: a sequence of its own, last, as the file reads it — one step, to undo like any other',
                  attrs: { type: 'button', 'aria-label': `Put back ${locus}` },
                  on: { click: () => this.putBack(item.piece) },
                })
                back.append(icon('undo-2', { size: 12 }), el('span', { text: 'put back' }))
                return el(
                  'li',
                  {},
                  el('span', { class: 'edit-aside-locus', text: locus }),
                  // Sent to another genome of the metagenome, which (§27.10).
                  el('span', {
                    class: 'edit-aside-why',
                    text: item.genome === undefined ? item.why : `→ ${item.genome === '__unbinned__' ? 'no genome' : item.genome}`,
                    title: item.genome === undefined ? '' : `A contig of ${item.genome === '__unbinned__' ? 'no genome' : item.genome} now, by its contacts`,
                  }),
                  back,
                )
              }),
            ),
          )
    // Longest first, the order an assembly is conventionally written in: one
    // step, undone as any is (§27.3).
    const byLength = [...assembly.sequences].sort((a, b) => (assembly.lengthOf(b.name) ?? 0) - (assembly.lengthOf(a.name) ?? 0)).map((sequence) => sequence.name)
    const sorted = byLength.every((name, i) => assembly.sequences[i].name === name)
    const sort = el('button', {
      class: 'btn btn-quiet edit-card-act',
      title: sorted ? 'They are longest first already' : 'Put the sequences longest first — one step, to undo like any other',
      attrs: { type: 'button' },
      on: { click: () => this.step({ op: 'reorder', names: byLength }) },
    })
    sort.append(el('span', { text: 'longest first' }))
    sort.disabled = sorted
    this.sequencesCard.replaceChildren(
      el('div', { class: 'edit-card-headrow' }, el('h3', { class: 'edit-card-head', text: `sequences · ${assembly.sequences.length}` }), sort),
      ...(this.sequencesNote === '' ? [] : [el('p', { class: 'edit-note edit-sequences-note', text: this.sequencesNote })]),
      list,
      ...(aside === null ? [] : [aside]),
    )
  }
 
  private startRename(name: string): void {
    this.renaming = name
    this.sequencesNote = ''
    this.paintSequences()
    // Focused as well as selected: `select` alone leaves the caret where the
    // last repaint put it — on a row's grip, after a step a Tab has just taken.
    const input = this.sequencesCard.querySelector<HTMLInputElement>('.edit-rename-input')
    input?.focus()
    input?.select()
  }
 
  /**
   * The box a sequence is renamed in: Enter makes it a step, Escape or a click
   * away leaves the name as it was. A name is one word, and one no other
   * sequence of the edit has — a FASTA header and an AGP line are split on
   * spaces, and two sequences of one name are one too many for either. And a
   * name of the file's own is the sequence's that is that original whole, and
   * nobody else's: the rename step's own rule, asked of it (`wholeOriginal`)
   * rather than said again here, where it had come out as *nobody's* — a
   * sequence renamed and wanting its own name back was refused it.
   */
  private renameBox(name: string): HTMLElement {
    const input = el('input', { class: 'input edit-rename-input', attrs: { type: 'text', value: name, 'aria-label': `New name for ${name}`, spellcheck: 'false', [TAB_WALKS]: '' } }) as HTMLInputElement
    /** `false` where the name typed was refused, the note saying why. */
    const done = (commit: boolean): boolean => {
      if (this.renaming !== name) return true
      this.renaming = null
      const wanted = input.value.trim()
      if (commit && wanted !== name) {
        const taken = this.props.store.assembly.sequences.some((sequence) => sequence.name === wanted)
        const original = this.props.store.edit.original
        const renamed = this.props.store.assembly.sequence(name)
        const theFiles = lengthsOf(original).has(wanted) && (renamed === null || wholeOriginal(renamed, original) !== wanted)
        if (wanted === '' || /\s/.test(wanted)) this.sequencesNote = 'A name is one word: a FASTA header and an AGP line are split on spaces.'
        else if (taken) this.sequencesNote = `${wanted} is the name of another sequence already.`
        else if (theFiles) this.sequencesNote = `${wanted} is a name of the file’s own, for that sequence whole and no other.`
        else {
          this.sequencesNote = ''
          this.step({ op: 'rename', sequence: name, name: wanted })
          return true
        }
        this.paintSequences()
        return false
      }
      this.paintSequences()
      return true
    }
    input.addEventListener('keydown', (event) => {
      const step = tabStep(event)
      if (step !== null) {
        // Enter that goes on to the next sequence's name, Shift+Tab to the one
        // before (§26.8): a rename keeps a sequence's place in the list, so the
        // next is found by where this one was. A refused name goes nowhere —
        // the note says why, as it does after Enter.
        event.preventDefault()
        event.stopPropagation()
        const names = this.props.store.assembly.sequences.map((sequence) => sequence.name)
        const at = names.indexOf(name)
        if (!done(true)) return
        const next = this.props.store.assembly.sequences[at + step]?.name
        if (at >= 0 && next !== undefined) this.startRename(next)
        return
      }
      if (event.key === 'Enter') {
        event.preventDefault()
        done(true)
      } else if (event.key === 'Escape') {
        event.preventDefault()
        event.stopPropagation()
        done(false)
      }
    })
    input.addEventListener('blur', () => done(false))
    return input
  }
 
  /**
   * On one genome of a metagenome (§27.10): what its contacts say about where
   * its contigs belong — how much of their contacts stay with the genome, the
   * contigs that meet another genome more, each with a way to send it there,
   * and the contigs of other genomes that meet this one most, each with a way
   * to bring it in.
   */
  private paintGenome(): void {
    const genome = this.props.store.edit.original.genome
    if (genome === undefined) return
    const links = this.links
    const head = el('h3', { class: 'edit-card-head', text: `genome · ${genome}` })
    if (this.linksRequest !== null) {
      this.genomeCard.replaceChildren(
        head,
        el(
          'p',
          { class: 'edit-note' },
          `Reading every contact for where the contigs belong… ${this.linksDone === null ? '' : `${Math.round(this.linksDone * 100)}%`} `,
          el('button', { class: 'btn-link', text: 'cancel', attrs: { type: 'button' }, on: { click: () => this.linksRequest?.cancel() } }),
        ),
      )
      return
    }
    if (links === null) {
      this.genomeCard.replaceChildren(
        head,
        el('p', { class: 'edit-note', text: 'Which of its contigs meet another genome more, and which of other genomes’ meet this one: one pass over every contact of the file.' }),
        ...(this.props.genomeLinks === undefined
          ? []
          : [el('button', { class: 'btn', text: 'read every contact', attrs: { type: 'button' }, on: { click: () => this.readLinks() } })]),
      )
      return
    }
    const assembly = this.props.store.assembly
    const placed = new Set(assembly.sequences.flatMap((sequence) => sequence.parts.flatMap((part) => (isGap(part) ? [] : [part.sequence]))))
    const inside = links.inside.filter((row) => placed.has(row.contig))
    const own = inside.reduce((sum, row) => sum + row.own, 0)
    const total = inside.reduce((sum, row) => sum + row.total, 0)
    const label = (name: string): string => (name === '__unbinned__' ? 'no genome' : name)
    const share = (part: number, whole: number): string => `${whole > 0 ? Math.round((100 * part) / whole) : 0}%`
    // A contig that meets another genome more than this one, with enough contacts to say.
    const strays = inside
      .flatMap((row) => {
        const other = row.partners.find((partner) => partner.genome !== genome)
        return other !== undefined && other.contacts > row.own && row.total >= LEAST_LINKS ? [{ row, other }] : []
      })
      .sort((a, b) => b.other.contacts / b.row.total - a.other.contacts / a.row.total)
      .slice(0, 8)
    const candidates = links.outside
      .filter((row) => !placed.has(row.contig) && row.contacts >= LEAST_LINKS && row.contacts / row.total >= BELONGS)
      .slice(0, 8)
    const stale = this.linksOf !== this.linksKey()
    this.genomeCard.replaceChildren(
      head,
      el('p', {
        class: 'edit-note',
        text: `${share(own, total)} of its contigs’ contacts with other contigs are with its own${stale ? ' — read before the last contig came in' : ''}.`,
      }),
      el('h4', { class: 'edit-genome-sub', text: strays.length === 0 ? 'No contig of it meets another genome more' : 'Meet another genome more' }),
      ...(strays.length === 0
        ? []
        : [
            el(
              'ul',
              { class: 'edit-genome-list' },
              ...strays.map(({ row, other }) =>
                el(
                  'li',
                  { class: 'edit-genome-row' },
                  el('span', { class: 'edit-genome-name', text: row.contig, title: row.contig }),
                  el('span', { class: 'edit-genome-share', text: `${share(row.own, row.total)} here · ${share(other.contacts, row.total)} ${label(other.genome)}` }),
                  el('button', {
                    class: 'btn edit-genome-act',
                    text: `send to ${label(other.genome)}`,
                    title: `Take ${row.contig} out of ${genome}, as a contig of ${label(other.genome)}: a step to undo like any other`,
                    attrs: { type: 'button' },
                    on: { click: () => this.send(row.contig, other.genome) },
                  }),
                ),
              ),
            ),
          ]),
      el('h4', { class: 'edit-genome-sub', text: candidates.length === 0 ? 'No contig elsewhere meets this genome most' : 'Meet this genome most' }),
      ...(candidates.length === 0
        ? []
        : [
            el(
              'ul',
              { class: 'edit-genome-list' },
              ...candidates.map((row) =>
                el(
                  'li',
                  { class: 'edit-genome-row' },
                  el('span', { class: 'edit-genome-name', text: row.contig, title: `${row.contig} · ${fmt.bp(row.length)} · of ${label(row.genome)}` }),
                  el('span', { class: 'edit-genome-share', text: `${label(row.genome)} · ${share(row.contacts, row.total)} of its contacts here` }),
                  el('button', {
                    class: 'btn edit-genome-act',
                    text: 'bring in',
                    title: `Bring ${row.contig} into ${genome}, whole, as a contig of its own: a step to undo like any other`,
                    attrs: { type: 'button' },
                    on: { click: () => this.props.store.bring({ name: row.contig, length: row.length, genome: row.genome }) },
                  }),
                ),
              ),
            ),
          ]),
      ...(stale && this.props.genomeLinks !== undefined
        ? [el('button', { class: 'btn-link', text: 'read again', attrs: { type: 'button' }, on: { click: () => this.readLinks() } })]
        : []),
    )
  }
 
  /** Send a contig of this genome to another (§27.10): every stretch of it the edit places, set aside as that genome's. */
  private send(contig: string, genome: string): void {
    const store = this.props.store
    for (const landing of [...store.assembly.landings(contig)].sort((a, b) => b.offset - a.offset)) {
      const length = landing.piece.end - landing.piece.start
      store.apply({ op: 'aside', sequence: landing.sequence, from: landing.offset, to: landing.offset + length, why: 'contaminant', genome })
    }
  }
 
  /** What the picture is of: the whole map, or one genome's contigs of a metagenome (§27.10). */
  private pictureOf(): string {
    const genome = this.props.store.edit.original.genome
    return genome === undefined ? 'The whole map' : `${genome}’s contigs alone, the rest of the metagenome left out,`
  }
 
  private paintPicture(): void {
    const picture = this.picture
    const evidence = this.evidence
    let sequence: string | null = null
    if (this.readingEvidence) sequence = 'Reading the sequence for its telomeres and gaps…'
    else if (evidence !== null) {
      const facts = [...evidence.facts.values()]
      const ends = facts.reduce((sum, fact) => sum + (fact.start === null ? 0 : 1) + (fact.end === null ? 0 : 1), 0)
      const gaps = facts.reduce((sum, fact) => sum + fact.gaps.length, 0)
      sequence =
        `From ${evidence.from}: telomeric repeats at ${ends.toLocaleString('en-US')} of ${(2 * facts.length).toLocaleString('en-US')} ends` +
        (evidence.gapsRead ? `, ${gaps.toLocaleString('en-US')} gap${gaps === 1 ? '' : 's'} of N` : '') +
        ' — a join that would bury a telomere counts against itself, and a break beside a gap is placed at it.'
    }
    this.pictureCard.replaceChildren(
      el('h3', { class: 'edit-card-head', text: 'picture' }),
      el('p', {
        class: 'edit-note',
        text:
          picture === null
            ? `${this.pictureOf()}, read once for the stage.`
            : `${this.pictureOf()} at ${fmt.bp(picture.binsize)} a cell, ${picture.n.toLocaleString('en-US')} cells a side, ${picture.balanced ? 'balanced' : 'raw counts'}; pieces move in whole cells, so a junction inside a cell is placed to the nearest edge.`,
      }),
      this.cellsChoice(),
      // Zoomed past a cell: the window read again, finer (§27.9).
      ...(this.windowRead === null || this.windowRead.key !== this.windowKey()
        ? []
        : [el('p', { class: 'edit-note edit-window-note', text: `Closer than a cell, the map on screen is read again at ${fmt.bp(this.windowRead.read.binsize)} a bin, through the edit.` })]),
      ...(sequence === null ? [] : [el('p', { class: 'edit-note edit-evidence-note', text: sequence })]),
    )
  }
 
  // -------------------------------------------------------------------------
  // Closing
  // -------------------------------------------------------------------------
 
  private teardown(): void {
    if (this.closed) return
    this.closed = true
    this.request?.cancel()
    this.request = null
    this.linksRequest?.cancel()
    this.linksRequest = null
    this.recountRequest?.cancel()
    this.recountRequest = null
    this.refineRequest?.cancel()
    this.refineRequest = null
    this.dotplot?.destroy()
    this.windowRequest?.cancel()
    this.windowRequest = null
    window.clearTimeout(this.windowTimer)
    window.clearTimeout(this.suggesting)
    if (this.frame !== 0) cancelAnimationFrame(this.frame)
    window.removeEventListener('keydown', this.onKey, true)
    window.removeEventListener('keyup', this.onKeyUp, true)
    window.removeEventListener('blur', this.onBlur)
    this.observer?.disconnect()
    this.stopStore()
    this.lanes?.destroy()
    closeMenu()
    // The picture is the stage's alone (§27.9): it goes with it.
    this.picture = null
    this.image = null
    this.props.onClose()
  }
}