1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>continuum</title>
<style>
:root {
--bg: #fafaf9; --fg: #1c1917; --muted: #78716c; --line: #e7e5e4; --panel: #ffffff;
--ok: #15803d; --warn: #c2410c; --bad: #b91c1c; --intended: #a8a29e; --self: #1d4ed8;
/* How strong the grey under a console message is, pointed at or shown, and under
its nodes and link on the map. */
--pointed: .12; --shown: .22;
/* How strong the halo of a node or link is, pointed at or in focus, and the tint of
the console messages exchanged with it. */
--halo-hovered: .15; --halo-focused: .35;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #1c1917; --fg: #f5f5f4; --muted: #a8a29e; --line: #44403c; --panel: #292524;
--ok: #4ade80; --warn: #fb923c; --bad: #f87171; --intended: #57534e; --self: #60a5fa;
}
}
* { box-sizing: border-box; }
html { background: var(--bg); }
/* The window's height, unless it is way too small: then the page scrolls. */
body { margin: 0; background: var(--bg); color: var(--fg);
font: 14px/1.4 system-ui, sans-serif;
height: 100vh; min-height: 480px; display: flex; flex-direction: column; }
header { display: flex; gap: 1em; align-items: baseline; padding: 12px 16px;
border-bottom: 1px solid var(--line); flex-wrap: wrap; }
header h1 { font-size: 16px; margin: 0; }
#connection { margin-left: auto; color: var(--muted); }
#clock-warning, #peers .clock-off, #peers .epoch-off { color: var(--warn); }
/* A minute's bar each, the last 15: a link's trend at a glance. */
#peers .spark { font-family: ui-monospace, monospace; letter-spacing: 0; opacity: 0.7; }
#connection.live { color: var(--ok); }
#connection.down { color: var(--bad); }
/* A dot in the status's colour that breathes once with every event. */
#dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%;
background: currentColor; margin-right: 6px; vertical-align: 1px; opacity: .45; }
#dot.pulse { animation: breath .9s ease-in-out; }
@keyframes breath {
0% { opacity: .45; transform: scale(1); }
30% { opacity: 1; transform: scale(1.35); box-shadow: 0 0 6px currentColor; }
100% { opacity: .45; transform: scale(1); }
}
@media (prefers-reduced-motion: reduce) { #dot.pulse { animation-duration: .01s; } }
body.stale main { opacity: .55; }
/* Swarm on the left, the full height; peers (as tall as their rows, up to 8) above
the figures (the rest) on the right. */
/* The columns and rows as dragged (`--columns`, `--rows`, set by `sizes`). */
main { flex: 1; min-height: 0; display: grid; gap: 16px; padding: 16px;
grid-template-columns: var(--columns, minmax(0, 3fr) minmax(0, 2fr));
grid-template-rows: var(--rows, auto minmax(0, .4fr) minmax(0, .4fr) minmax(0, .2fr));
grid-template-areas: "map peers" "map figures" "map document" "map console"; }
@media (max-width: 900px) {
body { height: auto; }
/* Stacked: each box as tall as set here, a collapsed one as its title. */
main { grid-template-columns: minmax(0, 1fr); grid-template-rows: none;
grid-auto-rows: auto; grid-template-areas: "map" "peers" "figures" "document" "console"; }
#map, #figures-box, #document-box { height: 70vh; }
#console-box { height: 40vh; }
main > section.collapsed { height: auto; }
}
section { background: var(--panel); border: 1px solid var(--line); border-radius: 6px;
padding: 12px; min-width: 0; min-height: 0; display: flex; flex-direction: column; }
section h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .04em;
color: var(--muted); margin: 0 0 8px; flex: none; }
section h2 .what { text-transform: none; letter-spacing: 0; color: var(--fg); }
/* Collapsed: the title only, and nothing drawn in it (`busy`). */
button.collapse { font: inherit; padding: 0 4px 0 0; color: var(--muted); background: none;
border: none; cursor: pointer; }
button.collapse:hover { color: var(--fg); }
section.collapsed > :not(h2) { display: none; }
section.collapsed { align-self: start; }
section.collapsed h2 { margin: 0; }
section.collapsed h2 .toggle { display: none; }
/* A choice beside a box's title (the console's filter). */
section h2 label.choice { font-size: 12px; text-transform: none; letter-spacing: 0;
margin-left: 1em; cursor: pointer; }
section h2 label.choice input { vertical-align: -2px; margin: 0 3px 0 0; }
section.collapsed h2 label.choice { display: none; }
/* The console's rates, at the right of its title: messages and bytes per second, a
row each, small enough for both to fit the title's line, centred on it. Columns as
wide as their widest content will be, so the numbers stay put as they change. */
section h2 .rates { float: right; display: grid;
grid-template-columns: repeat(3, minmax(5ch, auto)) minmax(5.5ch, auto);
column-gap: 5px; height: 18px; align-content: center;
font-size: 9px; line-height: 9px; text-transform: none; letter-spacing: 0;
margin-left: 1em; font-variant-numeric: tabular-nums; }
section h2 .rates span { text-align: right; }
section h2 .rates span.unit { text-align: left; }
section.collapsed h2 .rates { display: none; }
/* After the console's filter: that it follows new messages (scrolled to the bottom). */
section h2 .following { font-size: 12px; text-transform: none; letter-spacing: 0;
margin-left: 1em; font-style: italic; }
section.collapsed h2 .following { display: none; }
/* A button within a title's line, where it comes (not at its end, as toggles are). */
section h2 button.inline { float: none; margin-left: 1em; line-height: 1em; }
/* The right column dragged off to the side: the map takes the width. */
@media (min-width: 901px) {
main.right-hidden > section:not(#map) { display: none; }
/* The right column all collapsed: its titles at the top, a hint below them. */
main.right-shut { grid-template-rows: auto auto auto auto minmax(0, 1fr);
grid-template-areas: "map peers" "map figures" "map document" "map console" "map hint"; }
main.right-shut #column-hint { display: block; }
}
#column-hint { grid-area: hint; display: none; font-size: 12px; }
section h2 .what .id { color: var(--muted); font-weight: normal; word-break: break-all; }
/* The space between boxes, where they are resized. */
main.resize-columns, main.resize-columns * { cursor: col-resize; }
main.resize-rows, main.resize-rows * { cursor: row-resize; }
/* The peers dragged to a height: the table fills it, and scrolls. */
main.peers-sized #peers-scroll { flex: 1; max-height: none !important; }
#map { grid-area: map; }
#peers-box { grid-area: peers; }
#figures-box { grid-area: figures; }
/* Its title on one line: what doesn't fit ends in an ellipsis (the whole of it its
tooltip). */
#figures-box h2 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#document-box { grid-area: document; position: relative; }
/* The remake's options, below the document's title, over the document. */
.popdown { position: absolute; top: 34px; right: 12px; z-index: 5; width: min(28em, 90%);
background: var(--panel); border: 1px solid var(--line); border-radius: 6px;
padding: 10px; box-shadow: 0 4px 16px rgb(0 0 0 / .15); font-size: 12px;
display: flex; flex-direction: column; gap: 8px; }
.popdown[hidden] { display: none; }
.popdown textarea { width: 100%; box-sizing: border-box; font-family: ui-monospace, monospace;
font-size: 12px; background: var(--bg); color: var(--fg); border: 1px solid var(--line); }
.popdown input, .popdown select { font: inherit; background: var(--bg); color: var(--fg);
border: 1px solid var(--line); }
.popdown label.file { display: block; margin-top: 4px; }
.popdown .note { margin: 0; }
.popdown .actions { display: flex; gap: 6px; }
.popdown .actions button.toggle { float: none; margin-left: 0; }
#remake-result.bad { color: var(--bad); }
.popdown .rule { display: flex; gap: 4px; align-items: center; margin-bottom: 4px; }
.popdown .rule input[type=text] { flex: 1; min-width: 0; font-family: ui-monospace, monospace; }
.popdown .rules-head .note { font-style: italic; }
.popdown button.toggle { float: none; margin-left: 0; }
#console-box { grid-area: console; }
#console-box .scroll { flex: 1; }
.console { font-family: ui-monospace, monospace; font-size: 12px; white-space: pre-wrap; }
.console .when { color: var(--muted); }
/* Room on the left for the bar of a related message, so it covers no text. */
.console > div { cursor: pointer; border-left: 3px solid transparent; padding-left: 4px; }
/* Of one exchange with the message pointed at or shown (`related`): a lighter grey, and
the bar. */
/* Exchanged with the node or over the link pointed at on the map, or in focus: the
colour of its halo; in focus wins. */
.console > div.peer-hovered {
background: color-mix(in srgb, var(--self) calc(var(--halo-hovered) * 100%), transparent); }
.console > div.peer-focused {
background: color-mix(in srgb, var(--self) calc(var(--halo-focused) * 100%), transparent); }
/* Filtered (`filter selected`): only the messages with what is in focus. */
.console.filtering > div:not(.peer-focused) { display: none; }
.console > div.related { background: rgba(127, 127, 127, .08); border-left-color: var(--self); }
.console > div:hover { background: rgb(127 127 127 / var(--pointed)); }
.console > div.focused { background: rgb(127 127 127 / var(--shown)); }
/* The message takes the box's width and scrolls with it, not in a box of its own. */
#stats pre.message { margin: 4px 0 0; font-size: 12px; white-space: pre-wrap;
max-height: none; overflow: visible; }
svg { flex: 1; min-height: 0; width: 100%; display: block; cursor: default; }
/* Dragged to pan or to move a node, also by touch. */
/* Dragged, not selected: neither its labels' text nor the picture itself. */
#graph { touch-action: none; user-select: none; -webkit-user-select: none; }
#graph.dragging, #graph.dragging * { cursor: grabbing; }
svg circle { cursor: pointer; }
/* Labels on an underlay of their own shape, so they read where they lie on a line. */
#graph text { paint-order: stroke; stroke: var(--panel); stroke-width: 4px;
stroke-linejoin: round; }
.legend { color: var(--muted); font-size: 12px; display: flex; gap: 1em; flex-wrap: wrap;
flex: none; }
.legend span::before { content: ""; display: inline-block; width: 18px; height: 0;
vertical-align: middle; margin-right: 4px; border-top: 2px solid var(--colour, currentColor); }
.legend .intended::before { border-top-style: dashed; --colour: var(--intended); }
.legend .used::before { border-top-width: 3px; --colour: var(--muted); }
.legend .other::before { border-top-width: 1px; --colour: var(--muted); }
.legend .direct::before { --colour: var(--muted); }
.legend .relayed::before { border-top-style: dashed; --colour: var(--muted); }
.legend .dormant::before { border-top-width: 1.5px; --colour: var(--muted);
box-shadow: 0 0 0 2.5px color-mix(in srgb, var(--bad) 50%, transparent); }
/* A chevron on a link, as on the map: a writer's tree, the way its changes go. */
.legend .writer-tree::before { content: "\203A"; width: auto; height: auto; border: none;
font-weight: bold; font-size: 15px; line-height: 0; color: var(--muted); }
.legend .hint::before { display: none; }
/* A kind of message: a dot in its colour, as on the map. */
.legend .message::before { width: 8px; height: 8px; border: none; border-radius: 50%;
background: var(--colour); }
/* The dots' size and speed, right after their legend, no taller than its text. */
.legend .slider { display: inline-flex; align-items: center; gap: 4px; }
.legend .slider::before { display: none; }
.legend .slider input { width: 6em; height: 1em; margin: 0; }
/* After the sliders, as tall; the kinds and the sliders greyed while the dots are off. */
.legend button.toggle { float: none; margin-left: 0; line-height: 1em; }
.legend.off .message, .legend.off .slider { opacity: .45; }
/* The map and, over its top, its controls (links, layout, legend) and the legend:
they take no room from the map, which stays as it is, the legend shown or hidden.
What is under them shows through; their contents are on an underlay of their own
shape (as the map's labels), and only buttons and sliders take the pointer: the map
under the rest is dragged as anywhere else. */
.map-area { position: relative; flex: 1; min-height: 0; display: flex; }
.map-overlay { position: absolute; top: 0; left: 0; right: 0; pointer-events: none; }
/* The controls at the top right, on the legend's first row, which leaves them room
(`--controls-width`, as wide as they are); the rows below take the whole width.
As tall as a row of the legend. */
.map-controls { position: absolute; top: 0; right: 0; display: flex; gap: 6px; }
#legends .legend:first-child { padding-right: calc(var(--controls-width, 0px) + 1em); }
.map-controls button.toggle { float: none; margin-left: 0; box-sizing: border-box;
height: 1.4em; line-height: calc(1.4em - 2px); padding-block: 0; }
.map-overlay .legend > *, .map-controls > * { filter: drop-shadow(2px 0 0 var(--panel))
drop-shadow(-2px 0 0 var(--panel)) drop-shadow(0 2px 0 var(--panel))
drop-shadow(0 -2px 0 var(--panel)); }
.map-overlay button, .map-overlay input, .map-overlay label { pointer-events: auto; }
/* How far behind the messages run: pointed at for its tooltip, which says why. */
.map-overlay #replay-delay { pointer-events: auto; cursor: help; }
/* Hides the legend, and shows it again. */
button.toggle { font: inherit; font-size: 12px; text-transform: none; letter-spacing: 0;
float: right; margin-left: 6px; padding: 0 6px; color: var(--muted); background: none;
border: 1px solid var(--line); border-radius: 3px; cursor: pointer; }
button.toggle:hover { color: var(--fg); border-color: var(--muted); }
/* Nodes: circles, as on the map. */
.legend .node::before { width: 10px; height: 10px; border: 1.5px solid var(--fg);
border-radius: 50%; background: var(--fg); }
.legend .node.silent::before { background: var(--panel); }
.legend .node.self::before { border-color: var(--self); background: var(--self); }
.legend .node.dormant-node::before { border: 2.5px solid var(--bad); }
.legend .node.clock-off::before { width: 14px; height: 14px; background: none;
border: 1.5px dashed var(--warn); }
.legend .node.focus::before { width: 14px; height: 14px; background: var(--self);
border: none; opacity: .35; }
.legend .node.subscribed::before { width: 6px; height: 6px; background: #000;
border: 4px solid var(--self); }
.legend .node.unreachable::before { width: 6px; height: 6px; background: #000;
border: 4px solid var(--muted); }
/* A node's menu (right-click): subscribe, its dashboard. */
#node-menu, #user-menu, #entry-menu { position: fixed; z-index: 10; background: var(--panel);
border: 1px solid var(--line); border-radius: 6px; padding: 4px 0;
box-shadow: 0 4px 16px rgb(0 0 0 / .15); font-size: 12px; }
#node-menu[hidden], #user-menu[hidden], #entry-menu[hidden] { display: none; }
/* A finger held on an entry opens its menu (`withMenu`), not the browser's callout. */
#document-box summary, #document-box .leaf { -webkit-touch-callout: none; }
#node-menu button, #user-menu button, #entry-menu button { display: block; width: 100%; text-align: left;
font: inherit; padding: 4px 12px; background: none; border: none; color: var(--fg);
cursor: pointer; }
#node-menu button:hover:not(:disabled), #user-menu button:hover,
#entry-menu button:hover { background: var(--bg); }
#node-menu button:disabled, #user-menu button[aria-disabled="true"] { color: var(--muted); }
#node-menu button:disabled { cursor: default; }
#who { font: inherit; background: none; border: none; color: var(--muted); cursor: pointer; }
#who:hover { color: var(--fg); }
#dialog { background: var(--panel); color: var(--fg); border: 1px solid var(--line);
border-radius: 6px; max-width: 36em; font-size: 13px; }
#dialog::backdrop { background: rgb(0 0 0 / .3); }
#dialog h2 { font-size: 14px; margin: 0 0 8px; }
#dialog h3 { font-size: 13px; margin: 12px 0 4px; }
#dialog table { border-collapse: collapse; width: 100%; }
#dialog td { padding: 2px 6px 2px 0; vertical-align: top; }
#dialog td.key { font-family: var(--mono, monospace); word-break: break-all; color: var(--muted); }
/* The keys as wide as the dialog lets them, never wider: the name and the actions
their widths, the key the rest, cut in the middle (`keyLine`) as much as it must. */
#dialog table.keys { table-layout: fixed; }
#dialog table.keys col.name { width: 7em; }
#dialog table.keys col.actions { width: 4em; }
#dialog table.keys td.name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#dialog table.keys td.actions { text-align: right; padding-right: 0; }
/* Being edited: its fields and buttons across the row. */
#dialog .key-edit { display: flex; gap: 6px; align-items: baseline; margin: 2px 0; }
#dialog .key-edit .key-name { width: 7em; flex: none; }
#dialog .key-edit .key-value { flex: 1; min-width: 0; }
#dialog table.keys td.key { word-break: normal; overflow: hidden; }
.key-line { display: flex; min-width: 0; }
.key-line .start { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
min-width: 0; }
.key-line .end { flex: none; white-space: pre; }
#dialog form { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; }
#dialog input { font: inherit; }
#dialog input[name="line"] { flex: 1; min-width: 16em; }
#dialog .close { margin-top: 12px; }
.scroll { overflow: auto; min-height: 0; }
#figures-box .scroll, #document-box .scroll { flex: 1; }
.tree pre { margin: 2px 0 4px 1.1em; white-space: pre-wrap; word-break: break-all;
max-height: 20em; overflow: auto; }
.note { color: var(--muted); font-style: italic; }
.error { color: var(--bad); }
.tree .nested { padding-left: 1.1em; }
/* The store's root is the box: its keys listed at the top level, its size in the
title (`#document-head`), whose menu is the root's. */
#document > details.root { padding-left: 0; }
#document > details.root > summary { display: none; }
section h2 .count { text-transform: none; letter-spacing: 0; font-weight: normal;
margin-left: .5em; }
.editor input.extra[type=text] { width: 12em; margin-bottom: 2px; display: block; }
.editor { margin: 2px 0 4px; }
.tree details > .editor { margin-left: 1.1em; }
.editor input[type=text], .editor textarea { width: 100%; font: inherit; color: var(--fg);
background: var(--bg); border: 1px solid var(--line); border-radius: 4px; padding: 2px 4px; }
.editor button { font: inherit; }
.editor button.delete, #dialog button.delete { color: #fff; background: var(--bad);
border: 1px solid var(--bad); border-radius: 3px; }
#dialog button.delete:disabled { opacity: .5; }
.tree details.editing > :not(summary):not(.editor) { display: none; }
.tree .leaf[title] { cursor: text; }
table { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
th, td { text-align: left; padding: 3px 8px 3px 0; border-bottom: 1px solid var(--line);
white-space: nowrap; }
th { color: var(--muted); font-weight: 500; position: sticky; top: 0;
background: var(--panel); }
#peers tr[data-peer] { cursor: pointer; }
/* Not neighbours: only answered. */
#peers tr.answered td { opacity: .5; }
#peers tr.focused td { background: var(--line); }
.id { font-family: ui-monospace, monospace; font-size: 12px; }
/* Where messages go: the start of the address, the rest in its tooltip. */
#peers td.via { max-width: 0; min-width: 8em; width: 100%; overflow: hidden; text-overflow: ellipsis; }
/* A peer's status (not the legend's "dormant"). */
#peers .active { color: var(--ok); } #peers .dormant { color: var(--bad); }
#peers .refused { color: var(--bad); font-weight: 600; }
#peers .unknown { color: var(--muted); }
.tree { font-family: ui-monospace, monospace; font-size: 12px; }
/* Every entry indented alike: a branch's triangle sits in the indentation, left of
where the text of every entry begins. */
.tree details, .tree .leaf { position: relative; padding-left: 1.1em; }
.tree summary { cursor: pointer; list-style: none; }
.tree summary::-webkit-details-marker { display: none; }
.tree summary::before { content: "▸"; position: absolute; left: .1em; color: var(--muted); }
.tree details[open] > summary::before { content: "▾"; }
.tree details > .note { padding-left: 1.1em; }
.key { color: var(--muted); }
/* What a value or key means, after it (`gloss`): an alias, a time, a size. */
.gloss { color: var(--muted); }
</style>
</head>
<body>
<header>
<h1>continuum</h1>
<span id="node" class="id"></span>
<span id="clock-warning"></span>
<span id="connection"><span id="dot"></span><span id="connection-text">connecting…</span></span>
<button id="who" type="button" hidden aria-haspopup="menu"></button>
</header>
<div id="user-menu" role="menu" hidden></div>
<div id="entry-menu" role="menu" hidden></div>
<dialog id="dialog"></dialog>
<main>
<section id="map">
<div class="map-area">
<div class="map-overlay">
<div class="map-controls">
<button id="rtt-toggle" class="toggle">layout: static</button>
<button id="tree-toggle" class="toggle">tree: off</button>
<button id="legend-toggle" class="toggle">hide legend</button>
</div>
<div id="legends">
<div class="legend">
<span class="node self">this node</span>
<span class="node">its links known</span>
<span class="node silent">its links unknown (not subscribed)</span>
<span class="node dormant-node">dormant (to this node)</span>
<span class="node clock-off">clock off the swarm's</span>
<span class="node focus">in focus (click a node)</span>
<span class="node subscribed">subscribed (its links read from it)</span>
<span class="node unreachable">subscribed, not reached from here</span>
</div>
<div class="legend" id="legend"></div>
<div class="legend" id="messages-legend"><button id="flows-toggle"
class="toggle">messages: dots</button></div>
<div class="legend">
<span class="hint">drag to pan, wheel or pinch to zoom, turn with two fingers;
drag a node to move it, middle-click it to pin it there or let it go,
double-click it to subscribe to its links (or not), right-click it for its
menu (subscribing, its dashboard)</span>
</div>
</div>
</div>
<div id="node-menu" hidden></div>
<svg id="graph"><g id="view"><g id="flow-streaks" pointer-events="none"></g><g id="flows" pointer-events="none"><g id="flow-dots"></g></g><g id="flashes" pointer-events="none"></g></g></svg>
</div>
</section>
<section id="peers-box">
<h2>Peers</h2>
<div class="scroll" id="peers-scroll"><table id="peers"></table></div>
</section>
<section id="figures-box">
<h2><span id="figures-title">Figures</span></h2>
<div class="scroll"><div id="stats" class="tree"></div></div>
</section>
<section id="document-box">
<h2>Document<span id="document-head" class="count"></span><button id="remake-toggle" class="toggle" aria-expanded="false"
title="Propose a remake of the document: compacted, replaced by JSON, or imported from an Automerge document (docs/remakes.md)">remake…</button></h2>
<form id="remake" class="popdown" hidden>
<label>kind <select id="remake-kind">
<option value="compact">compact</option>
<option value="replace">replace</option>
<option value="import">import</option>
</select></label>
<p class="note" data-kind="compact">The same content, without its history.</p>
<div data-kind="replace" hidden>
<textarea id="remake-json" rows="8" spellcheck="false"
placeholder='The new store root, as JSON: {"accounts": {}}'></textarea>
<label class="file">or from a file <input type="file" id="remake-json-file"
accept="application/json,.json"></label>
</div>
<div data-kind="import" hidden>
<label class="file">Automerge document (a backup) <input type="file"
id="remake-import-file"></label>
</div>
<div data-kind="replace import" hidden>
<div class="rules-head">rules <span class="note">where writes made after the base
go: a path prefix moved, or dropped</span></div>
<div id="remake-rules"></div>
<button type="button" id="remake-add-rule" class="toggle">add rule</button>
</div>
<label>settle <input id="remake-settle" size="6" placeholder="default"
title="How long votes are collected: seconds, or e.g. 500ms, 8m; empty: twice the dormancy threshold"></label>
<label>switch delay <input id="remake-switch-delay" size="6" placeholder="default"
title="How long nodes wait after the vote succeeded before switching, so the commit reaches every node first: seconds, or e.g. 500ms, 1m; empty: one keepalive interval"></label>
<label title="Accept a switch delay below a keepalive interval (?force=switchDelay): slow nodes may miss the commit before the others switch, and have to rejoin"><input
type="checkbox" id="remake-force-switch-delay"> even below a keepalive interval</label>
<label title="How far behind a returning node may be and still have its writes carried over automatically: at most this many remakes behind, or the first it missed proposed at most this long ago (seconds, or e.g. 12h, 7d). Both empty: 1 epoch or 7 days; one given: that limit alone">replay window
<input id="remake-replay-epochs" size="3" inputmode="numeric" placeholder="1"> epochs or
<input id="remake-replay-age" size="5" placeholder="7d"></label>
<label title="How long nodes keep the old document: this many epochs, or this long (seconds, or e.g. 12h, 30d). Both empty: 2 epochs or 30 days; one given: that limit alone">archive retention
<input id="remake-archive-epochs" size="3" inputmode="numeric" placeholder="2"> epochs or
<input id="remake-archive-age" size="5" placeholder="30d"></label>
<p class="note">Writes made meanwhile that no rule covers are quarantined on the node
that made them.</p>
<div class="actions"><button type="submit" class="toggle">propose</button>
<button type="button" id="remake-cancel" class="toggle">cancel</button></div>
<p id="remake-result" class="note" hidden></p>
</form>
<div class="scroll"><div id="document" class="tree"></div></div>
</section>
<div id="column-hint" class="note">Drag the space left of these boxes to the right to
hide the column.</div>
<section id="console-box">
<h2>Console <label class="choice" title="Only the messages with the node or over the link in focus (clicked on the map or in the peers); all while nothing is"><input type="checkbox" id="console-filter">filter selected</label><span id="console-following" class="following" title="Scrolled to the bottom: new messages are scrolled to as they come; scroll up to stop">following…</span><button id="console-clear" class="toggle inline" title="Empty this page's console: what comes from now on fills it again">clear</button><span id="console-rates" class="rates" title="Messages and bytes per second sent and received, as load averages are: over the last 1, 5 and 15 minutes (exponentially weighted), since the page was opened; with the filter, those with the node or over the link in focus"></span></h2>
<div class="scroll" id="console-scroll"><div id="console" class="console"></div>
<div id="console-none" class="note" hidden>No information available</div></div>
</section>
</main>
<script>
"use strict";
// Which page this is (the node fills it in); a snapshot naming another came from
// another build: reloaded then, to get its page.
const PAGE_VERSION = "__PAGE_VERSION__";
// The state as the node published it, and when it did (the last event).
let state = null;
let stateAt = 0;
// --- Hand-off: a double click on a node opens its dashboard, on another host, as this
// page was left (`handOff`): the map where it was, the view, the pins, the focus and the
// settings this browser keeps for the page (another host's are its own). It comes in
// the URL's fragment, which no request carries: taken here, before anything reads the
// settings, and gone from the URL at once. ---
const HAND_OFF = "#continuum=";
const handOver = (() => {
if (!location.hash.startsWith(HAND_OFF)) return null;
try {
const handed = JSON.parse(decodeURIComponent(location.hash.slice(HAND_OFF.length)));
for (const [key, value] of Object.entries(handed.settings || {})) {
if (key.startsWith("continuum-") && typeof value === "string") {
try { localStorage.setItem(key, value); } catch (_) {}
}
}
return handed;
} catch (_) {
return null;
} finally {
try {
history.replaceState(null, "", location.pathname + location.search);
} catch (_) { /* not where history works */ }
}
})();
// The nodes whose own links this page reads from them (`follow`), kept in the browser,
// and how each goes: declared before anything draws.
const SUBSCRIPTIONS = "continuum-subscriptions";
// Opened from another node's page (`handOver`), that node is subscribed to too: its
// links and messages were that page's own, and are another's here.
const subscriptions = (() => {
let kept = new Set();
try {
const listed = JSON.parse(localStorage.getItem(SUBSCRIPTIONS) || "[]");
kept = new Set(Array.isArray(listed) ? listed.filter(id => typeof id === "string") : []);
} catch (_) { /* none kept */ }
if (handOver && typeof handOver.from === "string" && !kept.has(handOver.from)) {
kept.add(handOver.from);
try { localStorage.setItem(SUBSCRIPTIONS, JSON.stringify([...kept])); } catch (_) {}
}
return kept;
})();
// Each subscription followed: `status` (`connecting`, `live`, `unreachable`), `why`
// not, its latest `report` and when it came (`at`), and how to stop it (`stop`).
const subscribed = new Map();
// Fields that grow by themselves: the node's list (`GROWING` and `is_age` in its
// dashboard), filled in when it serves the page.
const GROWING = new Set(__GROWING__);
const isAge = key => key === "secsAgo" || key.endsWith("SecsAgo") || GROWING.has(key);
const elapsed = () => Math.floor((Date.now() - stateAt) / 1000);
const aged = (key, value) =>
isAge(key) && typeof value === "number" ? value + elapsed() : value;
// RFC 7386.
function mergePatch(target, patch) {
if (patch === null || typeof patch !== "object" || Array.isArray(patch)) return patch;
const result = target !== null && typeof target === "object" && !Array.isArray(target)
? target : {};
for (const [key, value] of Object.entries(patch)) {
if (value === null) delete result[key];
else result[key] = mergePatch(result[key], value);
}
return result;
}
function el(tag, attrs, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(attrs || {})) node.setAttribute(key, value);
for (const child of children) {
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
// Sets `node`'s tooltip (its `title`; none if null), unless the pointer is on it: then
// once the pointer leaves, so an open tooltip doesn't close and open again with every
// update (as `tooltip` does on the map).
const titlesDue = new Map();
function retitle(node, title) {
if (node.getAttribute("title") === title) { titlesDue.delete(node); return; }
const set = value => value === null ? node.removeAttribute("title") : node.setAttribute("title", value);
if (!node.matches(":hover")) { titlesDue.delete(node); set(title); return; }
if (!titlesDue.has(node)) {
node.addEventListener("mouseleave", () => {
if (!titlesDue.has(node)) return;
const due = titlesDue.get(node);
titlesDue.delete(node);
set(due);
}, { once: true });
}
titlesDue.set(node, title);
}
// Makes `old` (an element) like `fresh`, one of the same tag, keeping its nodes where
// they are alike, changing only what differs, and tooltips as `retitle` does: drawn
// anew with every update, a table would close the tooltip the pointer is on, and open
// it again. Listeners on `fresh` are not kept: put them on what stays.
function morph(old, fresh) {
for (const attr of old.getAttributeNames()) {
if (!fresh.hasAttribute(attr)) {
if (attr === "title") retitle(old, null); else old.removeAttribute(attr);
}
}
for (const attr of fresh.getAttributeNames()) {
const value = fresh.getAttribute(attr);
if (attr === "title") retitle(old, value);
else if (old.getAttribute(attr) !== value) old.setAttribute(attr, value);
}
morphChildren(old, [...fresh.childNodes]);
}
// `parent`'s children made like `fresh` (`morph`).
function morphChildren(parent, fresh) {
const old = [...parent.childNodes];
fresh.forEach((node, i) => {
const was = old[i];
if (was && was.nodeType === Node.TEXT_NODE && node.nodeType === Node.TEXT_NODE) {
if (was.nodeValue !== node.nodeValue) was.nodeValue = node.nodeValue;
} else if (was && was.nodeType === Node.ELEMENT_NODE && was.nodeName === node.nodeName) {
morph(was, node);
} else if (was) {
parent.replaceChild(node, was);
} else {
parent.append(node);
}
});
for (const extra of old.slice(fresh.length)) extra.remove();
}
const SVG = "http://www.w3.org/2000/svg";
function svg(tag, attrs) {
const node = document.createElementNS(SVG, tag);
for (const [key, value] of Object.entries(attrs || {})) node.setAttribute(key, value);
return node;
}
const short = id => id.length > 14 ? id.slice(0, 6) + "…" + id.slice(-6) : id;
function name(id) {
const member = state.graph.members[id];
return (member && member.alias) || (state.peers.peers[id] || {}).alias || short(id);
}
// Milliseconds as signed seconds: "+5.0 s".
const seconds = ms => (ms < 0 ? "−" : "+") + (Math.abs(ms) / 1000).toFixed(1) + " s";
// Every member's clock against the swarm's, for the map: from the clocks the reports
// carry of their peers (`clock` on each link: this node's own and subscribed nodes'),
// chained from this node along the narrowest bounds, then taken against their median.
// A member is off when it differs from the median beyond its chained bound and the
// limit (`--clock-skew-warn`); with fewer than three members compared, none is (two
// can't tell whose clock is off). An estimate for the eye: each node judges its own
// clock by its peers' (`clock-warning`). By member: { offsetMs, withinMs, off }.
function swarmClocks() {
// Each way between two members: how far the far end's clock is ahead, give or take.
const edges = new Map();
const edge = (from, to, offset, within) => {
if (!edges.has(from)) edges.set(from, []);
edges.get(from).push([to, offset, within]);
};
for (const [reporter, report] of Object.entries(state.graph.measured)) {
for (const link of report.links || []) {
if (!link.clock) continue;
edge(reporter, link.peer, link.clock.offsetMs, link.clock.withinMs);
edge(link.peer, reporter, -link.clock.offsetMs, link.clock.withinMs);
}
}
// Ahead of this node's, along the narrowest chained bounds (Dijkstra; the maps are small).
const reached = new Map(), queue = [[0, state.node.id, 0]];
while (queue.length) {
let next = 0;
for (let i = 1; i < queue.length; i++) if (queue[i][0] < queue[next][0]) next = i;
const [within, member, offset] = queue.splice(next, 1)[0];
if (reached.has(member)) continue;
reached.set(member, { offset, within });
for (const [to, step, stepWithin] of edges.get(member) || []) {
if (!reached.has(to)) queue.push([within + stepWithin, to, offset + step]);
}
}
const offsets = [...reached.values()].map(r => r.offset).sort((a, b) => a - b);
const median = offsets[Math.floor(offsets.length / 2)] || 0;
const limit = (state.stats.clock || {}).limitMs || 0;
const judged = reached.size >= 3 && limit > 0;
const clocks = {};
for (const [member, { offset, within }] of reached) {
const offsetMs = offset - median;
clocks[member] = { offsetMs, withinMs: within,
off: judged && Math.abs(offsetMs) > within + limit };
}
return clocks;
}
// Whether `clock` (a peer's, `/peers`) differs from this node's beyond the limit for sure.
function clockOff(clock) {
const limit = (state.stats.clock || {}).limitMs || 0;
return !!clock && limit > 0 && Math.abs(clock.offsetMs) > clock.withinMs + limit;
}
function age(secs) {
if (secs === null || secs === undefined) return "";
if (secs < 120) return secs + " s";
if (secs < 7200) return Math.floor(secs / 60) + " min";
if (secs < 172800) return Math.floor(secs / 3600) + " h";
return Math.floor(secs / 86400) + " d";
}
// What is in focus, its figures shown: a node's ID, or a link's pair key (`pairKey`,
// two IDs). null: this node's (`/admin/stats`).
let focused = handOver ? handOver.focused || null : (() => {
try { return decodeURIComponent(location.hash.slice(1)) || null; } catch { return null; }
})();
const pairKey = (a, b) => a < b ? a + " " + b : b + " " + a;
const isPair = key => key !== null && key.includes(" ");
// What subscribed nodes in focus say of themselves (`renderStats`): a node's figures
// (`/admin/stats`) and peers (`/peers`), or a link's ends' peers, read from each every
// 2 s while in focus, with the page's narrow token (`readFigures`). By node ID:
// `stats`, `peers`, and `why` where they weren't read.
const figuresOf = new Map();
// The latest reading's number: an earlier one still on its way neither draws nor reads
// again.
let figuresTimer = null, figuresRound = 0;
function focus(id) {
focused = id === null || id === state.node.id ? null : id;
if (shownMessage !== null) {
shownMessage = null;
document.querySelectorAll("#console > div.focused").forEach(line => line.classList.remove("focused"));
markRelated(null);
}
// In the URL too, so a reload (a new version) keeps it.
try {
history.replaceState(null, "", focused === null ? location.pathname
: "#" + encodeURIComponent(focused));
} catch { /* not where history works */ }
render();
markPeerMessages();
loadTree();
readFigures();
}
// --- Peers ---
// On press (the table may be drawn anew, with ages, before a click would complete): the
// row's peer in focus, or none if it was. On the table, as its rows are kept and
// changed (`morph`), whoever they show.
document.getElementById("peers").addEventListener("pointerdown", event => {
const row = event.target.closest("tr[data-peer]");
if (!row) return;
const id = row.getAttribute("data-peer");
focus(id === focused ? null : id);
});
function renderPeers() {
const table = document.getElementById("peers");
const headers = { reaches: "How many members besides this node it reaches (an active " +
"session with each), as it said; +: those of them this node doesn't reach itself (it " +
"is a way to them)", hop: "How long its sync and blob messages take to come, by its clock and " +
"this node's (its offset taken off): this minute's mean, and the last 15 minutes' as " +
"a line; good to half the round trip, but the trend exactly" };
const rows = [el("tr", {}, ...["peer", "status", "seen", "via", "rtt", "hop", "clock",
"reaches", "epoch"]
.map(h => el("th", { title: headers[h] || "" }, h)))];
// Whom this node reaches, to tell those a peer reaches and it doesn't.
const ours = new Set(state.peers.localReaches || []);
for (const [id, peer] of Object.entries(state.peers.peers)) {
const destination = peer.destination;
const path = destination && destination.paths && destination.paths[0];
const rtt = path && typeof path.rttMs === "number" ? path.rttMs.toFixed(1) + " ms" : "";
const via = destination
? destination.address + (destination.connection ? " (" + destination.connection + ")" : "")
: "";
// Not a neighbour: this node only answers it (muted).
const row = el("tr", { "data-peer": id,
class: (id === focused ? "focused" : "") + (peer.neighbour ? "" : " answered") },
el("td", { title: id + (peer.neighbour ? ""
: "\nnot a neighbour: this node only answers it, and syncs with it on its own only as a neighbour") },
peer.alias || el("span", { class: "id" }, short(id))),
// How long dormant is about how long unseen ("seen"): in the tooltip only. Refused
// as a whole (its own change broke the swarm's rules) above all.
peer.refused
? el("td", { class: "refused", title: "refused as a whole for " +
age(aged("secsAgo", peer.refused.secsAgo)) + ": its change " +
short(peer.refused.change) + " broke the swarm's rules (" + peer.refused.why +
"), so this node sends it nothing" }, "refused")
: el("td", { class: peer.status, title: peer.status === "dormant"
? "dormant for " + age(aged("dormantForSecs", peer.dormantForSecs)) : "" }, peer.status),
el("td", {}, age(aged("lastSeenSecsAgo", peer.lastSeenSecsAgo))),
el("td", { class: "id via", title: via }, via),
el("td", {}, rtt),
hopCell(peer.hopDelay),
// Its clock against this node's, flagged beyond the limit (`--clock-skew-warn`).
el("td", { class: clockOff(peer.clock) ? "clock-off" : "", title: peer.clock
? "ahead of this node's by " + peer.clock.offsetMs + " ms, give or take " +
peer.clock.withinMs + " ms" : "" }, peer.clock ? seconds(peer.clock.offsetMs) : ""),
reachesCell(peer.reaches, ours, id),
epochCell(peer.epoch, peer.sameEpoch));
rows.push(row);
}
morphChildren(table, rows);
// As tall as the rows, up to 8 of them (and the header); then it scrolls.
const scroll = document.getElementById("peers-scroll");
scroll.style.maxHeight = rows.length > 9
? (rows[8].offsetTop + rows[8].offsetHeight) + "px" : "";
}
// The epoch a peer last said it is on: its generation, flagged where it isn't this
// node's (they don't sync then); its ID in the tooltip.
function epochCell(epoch, same) {
if (!epoch) return el("td", { title: "it hasn't said yet" }, "");
return el("td", { class: same === false ? "epoch-off" : "",
title: "epoch " + epoch.id + (same === false ? ": not this node's, so they don't sync" : "") },
String(epoch.generation));
}
// How long a peer's sync messages take to come (`hopDelay`): the latest minute's mean,
// and the last 15 minutes' as a line of bars (a minute without messages blank), each
// figure in the tooltip.
function hopCell(hop) {
if (!hop) return el("td", { title: "no sync message from it yet while its clock was known" }, "");
const minutes = hop.byMinuteMs || [];
const known = minutes.filter(ms => typeof ms === "number");
const latest = known.length ? known[known.length - 1] : null;
const low = Math.min(...known), high = Math.max(...known);
const bars = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
const line = minutes.map(ms => typeof ms !== "number" ? " "
: bars[high > low ? Math.round((ms - low) / (high - low) * (bars.length - 1)) : 0]).join("");
const within = ms => ms === null || ms === undefined ? "beyond the last bucket" : "within " + ms + " ms";
const title = [
hop.count + " messages since this node started, mean " + hop.meanMs + " ms",
"half " + within(hop.halfWithinMs) + ", 99% " + within(hop.p99WithinMs),
hop.halfRttMs !== null && hop.halfRttMs !== undefined
? "half the round trip: " + hop.halfRttMs + " ms (beyond it: waiting in queues, or the clock offset's error)"
: "no recent round trip",
hop.belowZero ? hop.belowZero + " took less than nothing by the clocks (the offset's error)" : "",
"the last 15 minutes' means, oldest first: " +
minutes.map(ms => typeof ms === "number" ? ms : "–").join(", "),
].filter(Boolean).join("\n");
return el("td", { title },
latest === null ? "" : latest + " ms ", el("span", { class: "spark" }, line));
}
// Whom a peer reaches (`reaches`, as it said; null: it hasn't said in this session), as
// a count, and those of them this node doesn't reach (`ours`), marked: the peer is a way
// to them. Each by name in the tooltip.
function reachesCell(reaches, ours, id) {
if (!Array.isArray(reaches)) {
return el("td", { title: "hasn't said whom it reaches in this session" }, "");
}
const others = reaches.filter(member => member !== state.node.id);
const only = others.filter(member => !ours.has(member) && member !== id);
const named = member => name(member) + (only.includes(member) ? " +" : "");
return el("td", { title: others.length ? others.map(named).sort().join("\n")
: "reaches no other member" },
String(others.length) + (only.length ? " (+" + only.length + ")" : ""));
}
// --- Figures: a tree, its open branches kept across renders ---
const open = new Set(["links", "from", "to", "paths", "paths.destination"]);
// As the page it was opened from had them (`handOver`).
if (handOver && Array.isArray(handOver.figures)) {
open.clear();
for (const path of handOver.figures) if (typeof path === "string") open.add(path);
}
// What a value means, shown muted in parentheses after it (`glossed`): a node ID's
// alias, a Unix-milliseconds time in RFC 3339 (a key that names a time: …At, …Until,
// …Since, at, since, alive), bytes in KiB, MiB, GiB (a key ending in …Bytes, or
// bytes), and bytes per second likewise (…BytesPerSec, bytesPerSec). Null if nothing to add.
const DATE_MS = [946684800000, 4102444800000];
function aliasOf(id) {
if (!state || typeof id !== "string") return null;
const member = state.graph.members[id], peer = state.peers.peers[id];
return (member && member.alias) || (peer && peer.alias) || null;
}
function bytesReadable(bytes) {
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
let unit = 0;
while (Math.abs(bytes) >= 1024 && unit < units.length - 1) { bytes /= 1024; unit++; }
return (unit === 0 ? String(bytes) : bytes.toFixed(1)) + " " + units[unit];
}
function gloss(key, value) {
if (typeof value === "string") return aliasOf(value);
if (typeof value !== "number" || !Number.isFinite(value)) return null;
const name = String(key);
// By how the key ends: `savedBytesSecsAgo` is no size.
if (/(^b|B)ytesPerSec$/.test(name)) return value >= 1024 ? bytesReadable(value) + "/s" : null;
if (/(^b|B)ytes$/.test(name)) return value >= 1024 ? bytesReadable(value) : null;
if ((/(At|Until|Since)$/.test(name) || /^(at|until|since|alive)$/.test(name)) &&
value >= DATE_MS[0] && value < DATE_MS[1]) {
return new Date(value).toISOString().replace(".000Z", "Z");
}
return null;
}
// `gloss`'s, as an element to put after the value (or the key: an alias), if any.
function glossed(text) {
return text === null ? [] : [" ", el("span", { class: "gloss" }, "(" + text + ")")];
}
function tree(key, value, path) {
// Empty: nothing to open.
if (value !== null && typeof value === "object" && Object.keys(value).length === 0) {
return el("div", { class: "leaf" }, el("span", { class: "key" }, key + ": "),
Array.isArray(value) ? "[]" : "{}");
}
if (value !== null && typeof value === "object") {
const details = el("details", {});
if (open.has(path)) details.open = true;
details.addEventListener("toggle", () => {
if (details.open) open.add(path); else open.delete(path);
});
const entries = Array.isArray(value) ? value.map((v, i) => [String(i), v]) : Object.entries(value);
const summary = el("summary", {}, el("span", { class: "key" }, key), ...glossed(aliasOf(key)),
Array.isArray(value) ? " [" + value.length + "]" : "");
// Opened or closed on press, as the peers' rows are focused: the tree is drawn anew
// every second (ages), and a click whose press and release land on two drawings is
// lost. Keys (Enter, space) still click.
summary.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
event.preventDefault();
details.open = !details.open;
});
summary.addEventListener("click", event => {
if (event.detail !== 0) event.preventDefault();
});
details.append(summary);
for (const [k, v] of entries) details.append(tree(k, v, path + "." + k));
return details;
}
return el("div", { class: "leaf" }, el("span", { class: "key" }, key,
...glossed(aliasOf(key)), ": "), JSON.stringify(aged(key, value)),
...glossed(gloss(key, value)));
}
// Read every 2 s while in focus (`figuresOf`, `figuresTimer` with `focused`).
async function readFigures() {
clearTimeout(figuresTimer);
figuresTimer = null;
const round = ++figuresRound;
if (focused === null || !state) return;
const reading = focused;
const ids = (isPair(reading) ? reading.split(" ") : [reading])
.filter(id => id !== state.node.id && subscriptions.has(id));
await Promise.all(ids.map(async id => {
const get = async path => {
const response = await fetch(endpointOf(id, path), { cache: "no-store",
headers: { Authorization: "Bearer " + narrowToken.token, Accept: "application/json" } });
const answer = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(response.status + " " + (answer.error || response.statusText));
return answer;
};
try {
if (!narrowToken) throw new Error(tokenWhy);
const [stats, peers] = await Promise.all([isPair(reading) ? null : get("stats"), get("../peers")]);
const known = figuresOf.get(id) || {};
figuresOf.set(id, { stats: stats || known.stats || null, peers: peers.peers || peers });
} catch (error) {
figuresOf.set(id, { ...(figuresOf.get(id) || {}), why: error.message || String(error) });
}
}));
if (round !== figuresRound || focused !== reading) return;
if (ids.length > 0) render();
figuresTimer = setTimeout(readFigures, 2000);
}
function renderStats() {
const title = document.getElementById("figures-title");
const what = el("span", { class: "what" });
let shown;
const stats = document.getElementById("stats");
if (shownMessage !== null) {
const message = shownMessage;
// Drawn once: a message doesn't change, and drawing it anew would scroll it back up.
if (stats.dataset.message === String(message.seq)) return;
stats.dataset.message = String(message.seq);
what.textContent = message.node
? message.type + " " + name(message.to) + " ← " + name(message.from)
: message.type + " " + WAYS[message.way] + " " + name(message.peer);
const field = (key, value) => el("div", { class: "leaf" },
el("span", { class: "key" }, key + ": "), value);
title.replaceChildren("Message: ", what);
retitle(title, title.textContent);
// A subscribed node's: logged there, written out as read from it.
if (message.node) {
const text = el("pre", { class: "message" }, "reading it from " + name(message.node) + "…");
document.getElementById("stats").replaceChildren(
field("at", clockTime(new Date(message.at))),
field("from", message.from),
field("to", message.to),
field("logged by", message.node),
...(message.address ? [field("address", message.address)] : []),
field("type", message.type),
field("bytes", String(message.bytes)),
text);
writtenOut(message).then(written => { text.textContent = written; },
error => {
text.replaceWith(el("div", { class: "note" }, "Not read from " + name(message.node) +
": " + (error.message || String(error))));
});
return;
}
document.getElementById("stats").replaceChildren(
field("at", clockTime(new Date(message.at))),
field(message.way === "received" ? "from" : "to", message.peer),
...(message.address ? [field("address", message.address)] : []),
field("way", message.way),
field("type", message.type),
field("bytes", String(message.bytes)),
el("pre", { class: "message" }, message.text));
return;
}
delete stats.dataset.message;
if (isPair(focused)) {
const [a, b] = focused.split(" ");
what.textContent = name(a) + " – " + name(b);
retitle(what, focused);
const listed = (x, y) => (state.graph.intended[x] || []).includes(y);
shown = [el("div", { class: "leaf" }, el("span", { class: "key" }, "intended: "),
listed(a, b) || listed(b, a) ? "yes (member list)" : "no")];
// Each end's view of it, as it reported it.
for (const [x, y, path] of [[a, b, "from"], [b, a, "to"]]) {
const report = state.graph.measured[x];
const link = report && report.links.find(link => link.peer === y);
if (link) {
shown.push(tree(name(x) + " reports", { secsAgo: report.secsAgo, ...link }, path));
} else {
shown.push(el("div", { class: "key leaf" }, name(x) + (report
? " reports no link to " + name(y) + "." : " reports no links.")));
}
}
// Where this node is an end: the link itself, as `/peers` has the other end (where
// messages go, the paths, the addresses). The whole entry is the node's focus.
// Each end's paths to the other: this node's, and a subscribed node's as it says
// (`figuresOf`).
const self = state.node.id;
for (const [x, y] of [[a, b], [b, a]]) {
const peers = x === self ? state.peers.peers : (figuresOf.get(x) || {}).peers;
const peer = peers && peers[y];
if (peer) {
shown.push(tree(x === self ? "this node's paths" : name(x) + "'s paths", {
destination: peer.destination, addresses: peer.addresses }, "paths." + (x === self ? "self" : x)));
}
}
title.replaceChildren("Link: ", what);
retitle(title, title.textContent);
document.getElementById("stats").replaceChildren(...shown);
return;
}
if (focused === null) {
what.textContent = name(state.node.id) + " (this node)";
// Its stats are the box: their keys at the top level, how many in the title.
const entries = Object.entries(state.stats || {});
shown = entries.map(([k, v]) => tree(k, v, "stats." + k));
title.replaceChildren("Figures: ", what,
el("span", { class: "count" }, describe({ type: "map", size: entries.length })));
retitle(title, title.textContent);
document.getElementById("stats").replaceChildren(...shown);
return;
}
// Its alias (if it has one) and its node ID, in full.
const alias = (state.graph.members[focused] || {}).alias ||
(state.peers.peers[focused] || {}).alias;
what.replaceChildren(...(alias ? [alias, " "] : []), el("span", { class: "id" }, focused));
const peer = state.peers.peers[focused];
const report = state.graph.measured[focused];
// A subscribed node: its own figures at the top level, as this node's are, then this
// node's `/peers` entry for it and the links it reports, each a branch.
if (subscriptions.has(focused)) {
const known = figuresOf.get(focused) || {};
const figures = Object.entries(known.stats || {});
shown = figures.map(([k, v]) => tree(k, v, "stats." + k));
if (known.why) {
shown.push(el("div", { class: "note" }, "Its figures not read: " + known.why));
} else if (!known.stats) {
shown.push(el("div", { class: "note" }, "Reading its figures…"));
}
shown.push(peer ? tree("as this node sees it", peer, "seen")
: el("div", { class: "key leaf" }, "Not a peer of this node."));
if (report) shown.push(tree("links", report, "links"));
title.replaceChildren("Node: ", what, el("span", { class: "count" },
describe({ type: "map", size: figures.length + 1 + (report ? 1 : 0) })));
retitle(title, title.textContent);
document.getElementById("stats").replaceChildren(...shown);
return;
}
// Its `/peers` entry is the box, as this node's stats are: its keys at the top level,
// and after them the links the member reports.
const entries = Object.entries(peer || {});
shown = entries.map(([k, v]) => tree(k, v, "peer." + k));
if (!peer) shown.push(el("div", { class: "key leaf" }, "Not a peer of this node."));
if (report) shown.push(tree("links", report, "links"));
title.replaceChildren("Peer: ", what, ...(peer ? [el("span", { class: "count" },
describe({ type: "map", size: entries.length + (report ? 1 : 0) }))] : []));
retitle(title, title.textContent);
document.getElementById("stats").replaceChildren(...shown);
}
// --- Swarm map: a small force layout, positions kept across renders ---
const positions = new Map();
// Nodes put somewhere by hand (dragged): the layout leaves them there.
const pinned = new Set();
// The lines of the measured links as drawn (`renderGraph`), by pair key: the end whose
// report is drawn (`a`, the way its bows go) and how far each transport's line bows out
// at the middle (`sides`; the one in use 0, straight).
const routes = new Map();
const transportColour = new Map([["mycelium", "#2563eb"], ["libp2p", "#9333ea"],
["tor", "#0891b2"]]);
const SPARE = ["#ca8a04", "#db2777", "#65a30d"];
function colourOf(transport) {
if (!transport) return "var(--muted)";
if (!transportColour.has(transport)) {
transportColour.set(transport, SPARE[(transportColour.size - 3) % SPARE.length]);
}
return transportColour.get(transport);
}
function renderLegend(measured) {
const transports = new Set();
for (const { link } of measured.values()) {
transports.add(link.transport || "");
for (const other of link.others || []) transports.add(other.transport);
}
const items = [el("span", { class: "intended" }, "intended (member list)")];
for (const transport of [...transports].sort()) {
const item = el("span", {}, transport || "unknown transport");
item.style.setProperty("--colour", colourOf(transport || null));
items.push(item);
}
items.push(el("span", { class: "used" }, "in use"),
el("span", { class: "other" }, "other transport"),
el("span", { class: "direct" }, "direct"),
el("span", { class: "relayed" }, "relayed"),
el("span", { class: "dormant" }, "dormant or down"));
if (treeShown) {
items.push(el("span", { class: "writer-tree" }, name(treeWriter()) +
"'s tree: the way its changes go (of the node in focus)"));
}
// Drawn anew only when it changed: the pull slider at its end is dragged meanwhile.
const legend = document.getElementById("legend");
const signature = items.map(item => item.className + ":" + item.textContent).join("|");
if (legend.dataset.signature !== signature) {
legend.dataset.signature = signature;
legend.replaceChildren(...items, pullControl());
}
}
// How hard the links pull their ends together, against the nodes pushing each other
// apart, as the `pull` slider at the end of the links' legend says: 3 to its value
// (a third to 3 times as hard; once, the middle, at first), kept in this browser. Harder,
// the links are shorter: their length is what the map's size and members make of it
// (`idealLength`) divided by how hard. Moved, the map moves to the new balance
// smoothly (`settle`), static or dynamic.
const PULL_MOST = 3;
let pullStrength = 1;
try { pullStrength = PULL_MOST ** (Number(localStorage.getItem("continuum-pull")) || 0); } catch (_) {}
pullStrength = Math.min(PULL_MOST, Math.max(1 / PULL_MOST, pullStrength));
let pullSlider = null;
function pullControl() {
if (pullSlider === null) {
const slider = el("input", { type: "range", min: "-1", max: "1", step: ".05",
title: "How hard the links pull their ends together: to the right harder, the links" +
" shorter (the middle: as the map's size and members make them)" });
slider.value = String(Math.log(pullStrength) / Math.log(PULL_MOST));
slider.addEventListener("input", () => {
pullStrength = PULL_MOST ** Number(slider.value);
try { localStorage.setItem("continuum-pull", slider.value); } catch (_) {}
if (!state) return;
settleAnyway = true;
renderGraph();
settle();
});
pullSlider = el("label", { class: "slider" }, "pull", slider);
}
return pullSlider;
}
function edges() {
const intended = new Map();
for (const [a, neighbours] of Object.entries(state.graph.intended)) {
for (const b of neighbours) {
intended.set(pairKey(a, b), [a, b]);
}
}
// One measured edge per pair: a report with an RTT, then the fresher.
const measured = new Map();
for (const [a, report] of Object.entries(state.graph.measured)) {
for (const link of report.links) {
const key = pairKey(a, link.peer);
const known = measured.get(key);
const timed = typeof link.rttMs === "number";
const knownTimed = known && typeof known.link.rttMs === "number";
if (!known || (timed && !knownTimed) ||
(timed === knownTimed && report.secsAgo < known.secsAgo)) {
measured.set(key, { a, b: link.peer, link, secsAgo: report.secsAgo,
dormant: link.dormant || (known && known.dormant),
down: link.down || (known && known.down) });
} else {
if (link.dormant) known.dormant = true;
if (link.down) known.down = true;
}
}
}
// Dormant, or down, if either end says so, whichever report is drawn.
for (const edge of measured.values()) {
if ((edge.dormant && !edge.link.dormant) || (edge.down && !edge.link.down)) {
edge.link = { ...edge.link, dormant: !!edge.dormant, down: !!edge.down };
}
}
return { intended, measured };
}
// How long a link is, ideally, for `count` nodes on a map of that size.
function idealLength(count, width, height) {
return Math.min(width, height) / Math.max(2, Math.sqrt(count) * 1.5) / pullStrength;
}
// `pairs`: [a, b, length, loose], the length the link pulls towards (else
// `idealLength`), and whether it is loose (`lengths`).
// How hard a loose link pulls, against a measured one.
const LOOSE = .1;
// `only`, if given: the nodes laid out; the others stay where they are.
function layout(nodes, pairs, width, height, only) {
for (const id of nodes) {
if (!positions.has(id)) {
positions.set(id, { x: width / 2 + (Math.random() - .5) * width / 2,
y: height / 2 + (Math.random() - .5) * height / 2 });
}
}
// Each round is as long as there are pairs of nodes: with many members, fewer rounds
// than 120 rather than a page that stops for seconds (`LAYOUT_FOR_MS`).
const until = performance.now() + LAYOUT_FOR_MS;
for (let round = 0; round < 120 && performance.now() < until; round++) {
relax(nodes, pairs, width, height, 1, 10, only);
}
}
// How long a layout may hold the page up at once, in ms; what it leaves, the map
// settles into while shown (`settle`).
const LAYOUT_FOR_MS = 150;
// One round of the layout: every node moved by `gain` of the forces on it, at most
// `most` px. Returns how far the furthest moved. A gain of 1 overshoots where a node
// has several links (the pulls add up): it gets close fast, then swings about its
// place; well below 1, it comes to rest. `only`, if given: the nodes that move.
// `placing`: a layout (`layout`), which places the nodes no live link holds too; else
// they stay where they are, sticky, unless none is held.
function relax(nodes, pairs, width, height, gain, most, only, placing) {
const ideal = idealLength(nodes.length, width, height);
{
const force = new Map(nodes.map(id => [id, { x: 0, y: 0 }]));
for (let i = 0; i < nodes.length; i++) {
for (let j = i + 1; j < nodes.length; j++) {
const p = positions.get(nodes[i]), q = positions.get(nodes[j]);
const dx = p.x - q.x, dy = p.y - q.y, d2 = Math.max(dx * dx + dy * dy, 1);
const push = ideal * ideal / d2;
force.get(nodes[i]).x += dx * push / 10; force.get(nodes[i]).y += dy * push / 10;
force.get(nodes[j]).x -= dx * push / 10; force.get(nodes[j]).y -= dy * push / 10;
}
}
for (const [a, b, length, loose] of pairs) {
const p = positions.get(a), q = positions.get(b);
if (!p || !q) continue;
const dx = q.x - p.x, dy = q.y - p.y, d = Math.max(Math.hypot(dx, dy), 1);
const stretch = d - (length || ideal);
// A loose link pulls a little, and never pushes.
const pull = loose ? Math.max(0, stretch) / d / 4 * LOOSE : stretch / d / 4;
force.get(a).x += dx * pull; force.get(a).y += dy * pull;
force.get(b).x -= dx * pull; force.get(b).y -= dy * pull;
}
let moved = 0;
const sticky = id => held.size > 0 && !held.has(id) && !placing;
for (const id of nodes) {
if (pinned.has(id) || id === grabbed || (only && !only.has(id))) continue;
const p = positions.get(id), f = force.get(id);
const fx = f.x * gain, fy = f.y * gain;
const x = Math.min(width - 40, Math.max(40, p.x + Math.max(-most, Math.min(most, fx))));
const y = Math.min(height - 20, Math.max(20, p.y + Math.max(-most, Math.min(most, fy))));
moved = Math.max(moved, Math.abs(x - p.x), Math.abs(y - p.y));
p.x = x; p.y = y;
}
return moved;
}
}
// The layout (`rtt-toggle`, kept in this browser): static by default, nodes moving only
// when laid out anew (members or links come or go); or dynamic, resized by round trip:
// each measured link's length grows with the square root of its round trip against
// the median one's, within bounds. Then, when the lengths change, the map moves to
// them a little every frame (`settle`), not at once.
let byRtt = false;
// A writer's tree on the map (`swarm::tree`, `GET /admin/dashboard/tree`): of the node in
// focus, else of this node; asked for anew when the writer changes and every 10 s.
let treeShown = false;
try { treeShown = localStorage.getItem("continuum-tree") === "1"; } catch (_) {}
let writerTree = null;
const treeWriter = () => focused !== null && !isPair(focused) ? focused
: state ? state.node.id : null;
function loadTree() {
const writer = treeWriter();
if (!treeShown || writer === null) { writerTree = null; return; }
fetch("dashboard/tree?writer=" + encodeURIComponent(writer))
.then(response => response.ok ? response.json() : null)
.then(loaded => {
if (loaded && loaded.writer === treeWriter()) {
writerTree = loaded;
if (state) renderGraph();
}
})
.catch(() => {});
}
setInterval(() => { if (treeShown) loadTree(); }, 10000);
try { byRtt = localStorage.getItem("continuum-by-rtt") === "1"; } catch (_) {}
// One spring per pair of nodes, intended or measured or both: [a, b, length, loose].
// Measured links shape the map; a link only intended (nothing measured backs it) is
// `loose`: it gives way to them, pulling only a little where stretched and never pushing
// where they hold its ends closer (`LOOSE`).
function lengths(intended, measured, count, width, height) {
const ideal = idealLength(count, width, height);
const rtts = [...measured.values()].map(edge => edge.link.rttMs)
.filter(rtt => typeof rtt === "number" && rtt > 0).sort((x, y) => x - y);
const median = rtts[Math.floor(rtts.length / 2)];
const pairs = new Map([...intended].map(([key, [a, b]]) => [key, [a, b, ideal, true]]));
for (const [key, { a, b, link }] of measured) {
const rtt = link.rttMs;
const length = byRtt && median && typeof rtt === "number" && rtt > 0
? ideal * Math.min(2.5, Math.max(.4, Math.sqrt(rtt / median))) : ideal;
pairs.set(key, [a, b, Math.round(length), false]);
}
return [...pairs.values()];
}
// What `settle` moves the map towards: the latest render's nodes and lengths.
let settling = false, settleTo = null, lastLengths = "";
// A static map moved to new lengths once (the `pull` slider), as a dynamic one is.
let settleAnyway = false;
function settle() {
if (settling) return;
settling = true;
let frames = 0;
const step = () => {
// Static again: where they are now.
if (!byRtt && !settleAnyway) { settling = false; return; }
const { nodes, pairs, width, height } = settleTo;
// Damped: the swings of the layout's rounds die down instead of going on.
const moved = relax(nodes, pairs, width, height, .15, 2);
renderGraph();
if (moved > .1 && ++frames < 600 && !document.hidden) requestAnimationFrame(step);
else {
settling = false;
settleAnyway = false;
// Hidden: on again with the next render.
if (document.hidden) lastLengths = "";
}
};
requestAnimationFrame(step);
}
// The node or link (its pair key) under the pointer, if any. Kept here rather than
// left to :hover: its halo is an element of its own, drawn behind it.
let hovered = null;
function hover(id) {
if (hovered === id) return;
hovered = id;
if (state) renderGraph();
markPeerMessages();
}
function hoverable(element, id) {
element.addEventListener("mouseenter", () => hover(id));
element.addEventListener("mouseleave", () => hover(null));
}
// The map's elements by what they show (a key), kept across renders and updated in
// place: the one under the pointer stays itself.
const drawn = new Map();
// The element `key` names, with exactly `attrs`; `made` sets up a new one (its
// listeners).
function drawing(key, tag, attrs, made) {
let node = drawn.get(key);
if (!node) {
node = svg(tag);
if (made) made(node);
drawn.set(key, node);
}
for (const attr of node.getAttributeNames()) if (!(attr in attrs)) node.removeAttribute(attr);
for (const [attr, value] of Object.entries(attrs)) {
if (node.getAttribute(attr) !== String(value)) node.setAttribute(attr, value);
}
return node;
}
// A label's `attrs`, turned back where the map is turned (`view`): upright, about where
// it is anchored.
function upright(attrs) {
if (!view.turn) return attrs;
return { ...attrs, transform: "rotate(" + -degrees(view.turn) + " " + attrs.x + " " +
attrs.y + ")" };
}
function text(node, content) {
if (node.textContent !== content) node.textContent = content;
}
// A label on the map: its text, breathing once when it changed (not when new), as the
// connection's dot does: its underlay, in the shape of the new text, glows and fades.
// An animation of its own, not a class: every render sets the label's attributes.
const calm = matchMedia("(prefers-reduced-motion: reduce)");
function label(node, content) {
if (node.textContent === content) return;
const before = node.textContent;
node.textContent = content;
if (!before || calm.matches || !node.animate) return;
const colours = getComputedStyle(document.documentElement);
const panel = colours.getPropertyValue("--panel").trim();
const glow = "color-mix(in srgb, " + colours.getPropertyValue("--self").trim() + " 45%, " +
panel + ")";
node.animate([
{ stroke: panel, strokeWidth: "4px" },
{ stroke: glow, strokeWidth: "7px", offset: .3 },
{ stroke: panel, strokeWidth: "4px" },
], { duration: 900, easing: "ease-in-out" });
}
// A tooltip whose text changes under the pointer goes and comes back (the ages in it
// change on every render): its new text waits until the pointer leaves.
const tooltipsDue = new WeakMap();
function tooltip(node, content) {
let title = node.firstElementChild;
if (!title) node.append(title = svg("title"));
if (title.textContent === content || !title.textContent || !node.matches(":hover")) {
tooltipsDue.delete(node);
text(title, content);
return;
}
if (!tooltipsDue.has(node)) {
node.addEventListener("mouseleave", () => {
const due = tooltipsDue.get(node);
tooltipsDue.delete(node);
if (due !== undefined) text(title, due);
}, { once: true });
}
tooltipsDue.set(node, content);
}
// `root` showing `children`, in order: the others go, and only what is out of place
// moves.
function show(root, children) {
const shown = new Set(children);
for (const [key, node] of drawn) {
if (!shown.has(node)) { node.remove(); drawn.delete(key); }
}
let at = root.firstChild;
for (const node of children) {
if (node === at) at = at.nextSibling; else root.insertBefore(node, at);
}
}
let lastShape = "";
// The whole map laid out with the next render, not only nodes new to it: at first.
let relayout = true;
// The map's size at the last render.
let lastSize = null;
function renderGraph() {
if (document.getElementById("map").classList.contains("collapsed")) return;
const root = document.getElementById("graph");
const width = root.clientWidth || 800, height = root.clientHeight || 560;
root.setAttribute("viewBox", "0 0 " + width + " " + height);
// Resized (the window, a box): the map as it was, about its middle, scaled by as much
// as the box's area (so resized back, it is as before), not laid out anew; within the
// box.
if (lastSize && (lastSize.width !== width || lastSize.height !== height)) {
const k = Math.sqrt(width / lastSize.width * height / lastSize.height);
for (const p of positions.values()) {
p.x = Math.min(width - 40, Math.max(40, width / 2 + (p.x - lastSize.width / 2) * k));
p.y = Math.min(height - 20, Math.max(20, height / 2 + (p.y - lastSize.height / 2) * k));
}
}
lastSize = { width, height };
const nodes = Object.keys(state.graph.members).sort();
const { intended, measured } = edges();
renderLegend(measured);
const pairs = lengths(intended, measured, nodes.length, width, height);
// Laid out when who's there or who links to whom changed: only the nodes new to the
// map, the others staying where they are (links that came, after the first reports,
// don't move them); all of them at first.
const shape = nodes.join(",") + "|" + [...intended.keys(), ...measured.keys()].sort().join(",");
if (shape !== lastShape) {
for (const id of [...positions.keys()]) {
if (!nodes.includes(id)) { positions.delete(id); pinned.delete(id); }
}
const fresh = new Set(nodes.filter(id => !positions.has(id)));
if (relayout) {
layout(nodes, pairs, width, height);
// Dynamic: settled at once, not moving into place before one's eyes; as far as
// `LAYOUT_FOR_MS` allows (with many members), the rest frame by frame (`settle`).
if (byRtt) {
const until = performance.now() + LAYOUT_FOR_MS;
let settled = false;
for (let round = 0; round < 3000 && performance.now() < until; round++) {
if (relax(nodes, pairs, width, height, .15, 2) <= .1) { settled = true; break; }
}
if (settled) lastLengths = pairs.map(pair => pair.join(" ")).join(",");
}
} else if (fresh.size > 0) {
layout(nodes, pairs, width, height, fresh);
}
relayout = false;
lastShape = shape;
}
settleTo = { nodes, pairs, width, height };
const wanted = pairs.map(pair => pair.join(" ")).join(",");
if (byRtt && wanted !== lastLengths) {
lastLengths = wanted;
settle();
}
const children = [];
// Under everything: the nodes and the link of the message shown in the console, and
// of the one pointed at, each in the grey its line has there (the shown one's where
// both mark the same), in its own shape (the lines of a link as they bow, a node's
// circle). A group per grey, so where its shapes overlap it is no darker.
const marking = new Map();
for (const [message, how] of [[pointedMessage, "pointed"], [shownMessage, "shown"]]) {
if (message === null) continue;
const [a, b] = message.node ? [message.from, message.to] : [state.node.id, message.peer];
for (const key of [a, b, pairKey(a, b)]) {
marking.set(key, how);
}
}
const marks = Object.fromEntries(["pointed", "shown"].map(how => [how,
drawing("marks " + how, "g", { "pointer-events": "none",
style: "opacity: var(--" + how + ")" })]));
const marked = { pointed: [], shown: [] };
// A shape under `key` (a node's ID, a link's pair key), if it is marked.
const mark = (key, tag, attrs) => {
const how = marking.get(key);
if (how) marked[how].push(svg(tag, attrs));
};
const markLine = (key, d, width) => mark(key, "path", { d, fill: "none",
stroke: "rgb(127 127 127)", "stroke-width": width + 8, "stroke-linecap": "round" });
children.push(marks.pointed, marks.shown);
// Behind a link: a halo while it's hovered or in focus (`width`: of its lines).
const halo = (key, p, q, width) => {
if (key !== hovered && key !== focused) return;
children.push(drawing("halo " + key, "line", { x1: p.x, y1: p.y, x2: q.x, y2: q.y,
stroke: "var(--self)",
style: "stroke-opacity: var(" + (key === focused ? "--halo-focused" : "--halo-hovered") + ")",
"stroke-width": width + 8, "stroke-linecap": "round" }));
};
// Over a link: an invisible, wider line to point at and click.
const hits = [];
// The links' round trips.
const labels = [];
const hit = (key, p, q, width) => {
const line = drawing("hit " + key, "line", { x1: p.x, y1: p.y, x2: q.x, y2: q.y,
stroke: "transparent", "stroke-width": width + 8, cursor: "pointer" }, line => {
// Dragged, it pans, as beside the nodes; a click, it is in focus.
line.addEventListener("pointerdown", event => { event.stopPropagation(); pan(event, () => focus(key)); });
hoverable(line, key);
});
hits.push(line);
return line;
};
for (const [key, [a, b]] of intended) {
if (measured.has(key)) continue;
const p = positions.get(a), q = positions.get(b);
halo(key, p, q, 1);
markLine(key, "M " + p.x + " " + p.y + " L " + q.x + " " + q.y, 1);
children.push(drawing("intended " + key, "line", { x1: p.x, y1: p.y, x2: q.x, y2: q.y,
stroke: "var(--intended)", "stroke-dasharray": "4 4", "stroke-width": 1 }));
tooltip(hit(key, p, q, 1), name(a) + " – " + name(b) + ": intended (member list), not measured");
}
const ms = rtt => rtt < 10 ? rtt.toFixed(1) : String(Math.round(rtt));
routes.clear();
for (const [key, { a, b, link, secsAgo }] of measured) {
const p = positions.get(a), q = positions.get(b);
if (!p || !q) continue;
// The transport in use thick, in the middle; the others thin, beside it.
const lines = [{ transport: link.transport, rttMs: link.rttMs, used: true }];
for (const other of link.others || []) lines.push({ ...other, used: false });
// As wide as the lines side by side.
const width = 3 + 12 * Math.ceil((lines.length - 1) / 2);
halo(key, p, q, width);
// It covers the lines: their descriptions are its tooltip.
const covering = hit(key, p, q, width);
const descriptions = [];
const length = Math.max(Math.hypot(q.x - p.x, q.y - p.y), 1);
const nx = -(q.y - p.y) / length, ny = (q.x - p.x) / length;
// As one end alone reports it (the other's links not read: not subscribed), in its
// tooltip.
const alone = !(b in state.graph.measured);
// Dormant, or down (no path answers, whatever its connection was): a red underlay
// as wide as the lines, as a dormant node's red outline.
const broken = link.dormant || link.down;
if (broken) {
children.push(drawing("underlay " + key, "line", { x1: p.x, y1: p.y, x2: q.x, y2: q.y,
stroke: "var(--bad)", "stroke-opacity": .5, "stroke-width": width + 4,
"stroke-linecap": "round" }));
}
// The one in use drawn last: on top of the others where they meet, at the nodes.
const drawnLines = [];
lines.forEach((line, i) => {
// 0, then +1, -1, +2, -2 … steps of 6 px to the side, at the middle: from node to
// node, each bowing out that far (a quadratic curve, its control point twice as
// far out); `aside(t)`, how far out at `t` along.
const side = i === 0 ? 0 : (i % 2 ? 1 : -1) * Math.ceil(i / 2) * 6;
const aside = t => 4 * t * (1 - t) * side;
// Where it bows, for the messages that go over it (`route`).
const route = routes.get(key) || { a, sides: new Map() };
if (line.transport && !route.sides.has(line.transport)) route.sides.set(line.transport, side);
routes.set(key, route);
const cx = (p.x + q.x) / 2 + nx * side * 2, cy = (p.y + q.y) / 2 + ny * side * 2;
const attrs = { d: "M " + p.x + " " + p.y + " Q " + cx + " " + cy + " " + q.x + " " + q.y,
fill: "none", stroke: colourOf(line.transport),
// Narrow where dormant or down (over its underlay).
"stroke-width": broken ? (line.used ? 1.5 : 0.8) : line.used ? 3 : 1.2 };
// Dashed where relayed, solid where direct.
if (line.used ? link.relayed : line.relayed) {
attrs["stroke-dasharray"] = "7 4";
}
markLine(key, attrs.d, attrs["stroke-width"]);
const drawnLine = drawing("path " + key + " " + i, "path", attrs);
const description = name(a) + " – " + name(b) +
(line.transport ? " via " + line.transport : "") + (line.used ? " (in use)" : "") +
((line.used ? link.relayed : line.relayed) ? ", relayed" : "") + (link.dormant ? ", dormant" : "") +
(line.used && link.down ? ", down" : "") +
(alone ? ", as " + name(a) + " alone reports it" : "") +
(typeof line.rttMs === "number" ? ", " + line.rttMs.toFixed(1) + " ms" : "") +
", measured " + age(secsAgo + elapsed()) + " ago";
tooltip(drawnLine, description);
descriptions.push(description);
drawnLines.push(drawnLine);
if (typeof line.rttMs === "number") {
// Near the end that measured it (`a`, whose report is drawn), clear of its
// node and name, and short of the middle: the one in use larger, the others
// closer still, beside theirs.
const along = Math.min(length / 2, Math.max(36, length * .3));
const t = (line.used ? along : Math.max(24, along * .6)) / length;
const out = line.used ? -4 : Math.sign(side) * 9;
const rtt = drawing("rtt " + key + " " + i, "text", upright({
x: p.x + (q.x - p.x) * t + nx * (aside(t) + out),
y: p.y + (q.y - p.y) * t + ny * (aside(t) + out) + (line.used ? 0 : 3),
"text-anchor": "middle", "font-size": line.used ? 11 : 9,
fill: line.used ? "var(--fg)" : "var(--muted)" }));
label(rtt, ms(line.rttMs));
labels.push(rtt);
}
});
children.push(...drawnLines.reverse());
tooltip(covering, descriptions.join("\n"));
}
// Above every line, so none crosses them.
// The tree of the writer in focus (`treeShown`): a chevron on each link from parent to
// child, at its middle, pointing the way changes go, in the colour of the link.
if (treeShown && writerTree && writerTree.writer === treeWriter()) {
for (const [child, parent] of Object.entries(writerTree.parents)) {
const p = parent && positions.get(parent), q = positions.get(child);
if (!p || !q) continue;
const length = Math.max(Math.hypot(q.x - p.x, q.y - p.y), 1);
const ux = (q.x - p.x) / length, uy = (q.y - p.y) / length;
const mx = (p.x + q.x) / 2, my = (p.y + q.y) / 2;
const d = "M " + (mx - ux * 5 - uy * 5) + " " + (my - uy * 5 + ux * 5) + " L " +
(mx + ux * 5) + " " + (my + uy * 5) + " L " + (mx - ux * 5 + uy * 5) + " " +
(my - uy * 5 - ux * 5);
const shape = { d, fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round" };
// The colour of the link's line in use (its transport's), as the line it is on.
const edge = measured.get(pairKey(parent, child));
const colour = edge ? colourOf(edge.link.transport) : "var(--intended)";
labels.push(drawing("tree under " + child, "path",
{ ...shape, stroke: "var(--panel)", "stroke-width": 6 }));
const chevron = drawing("tree " + child, "path",
{ ...shape, stroke: colour, "stroke-width": 2.5 });
tooltip(chevron, "in " + name(writerTree.writer) + "'s tree: " + name(parent) + " → " + name(child));
labels.push(chevron);
}
}
// Flashes (`drawFlows`) over the lines, below their labels and the nodes.
children.push(document.getElementById("flow-streaks"));
children.push(...labels);
// Above the lines and their labels, below the nodes.
children.push(...hits);
const { amber, coordinating } = inRemakes();
const clocks = swarmClocks();
for (const id of nodes) {
const p = positions.get(id), member = state.graph.members[id];
const reported = id in state.graph.measured;
const shown = focused === null ? member.self : id === focused;
// A link in focus: both ends ringed.
// A halo as links have: light under the pointer, stronger in focus.
if (shown || id === hovered) {
children.push(drawing("ring " + id, "circle", { cx: p.x, cy: p.y, r: 13,
fill: "var(--self)", stroke: "none",
style: "fill-opacity: var(" + (shown ? "--halo-focused" : "--halo-hovered") + ")" }));
}
const pressed = element => {
// The right button opens its menu: no drag, whose holding the pointer on the map
// would take the right-click from the node.
element.addEventListener("pointerdown", event => {
event.stopPropagation();
if (event.button !== 2) drag(event, id);
});
element.addEventListener("contextmenu", event => {
event.preventDefault();
nodeMenu(id, event.clientX, event.clientY);
});
hoverable(element, id);
};
// A clock off the swarm's: a dashed orange ring.
if ((clocks[id] || {}).off) {
children.push(drawing("clock " + id, "circle", { cx: p.x, cy: p.y, r: 11, fill: "none",
stroke: "var(--warn)", "stroke-width": 1.5, "stroke-dasharray": "3 2" }));
}
// Dormant as this node sees it (`/peers`): a red outline.
const dormant = (state.peers.peers[id] || {}).status === "dormant";
const radius = member.self ? 8 : 6;
mark(id, "circle", { cx: p.x, cy: p.y, r: radius + 6, fill: "rgb(127 127 127)" });
// In a remake (`inRemakes`): amber; its coordinator also with a halo, or deciding.
const voting = amber.has(id);
// Its remake's wait (`countdowns`), and whether it is over: settled but not decided
// yet (a question mark on it, below), or committed with this node's wait to
// switch over (nothing: it switches any moment).
const countdown = coordinating.has(id) ? countdowns.get(id) : undefined;
const over = countdown !== undefined && countdown.until <= performance.now();
const deciding = over && countdown.kind === "settle";
if (coordinating.has(id) && !over) {
// While it settles, and once committed until this node switches: a golden halo,
// smaller than the one in focus and over it, waning counterclockwise from the top
// of the screen, however the map is turned; whole while no wait is known yet
// (just proposed, or committed before this node saw it). A circle half the halo's
// radius, its stroke as wide as the radius: a disc, its dashes a slice of it.
const dash = countdownDash(id, COUNTDOWN_R / 2);
children.push(drawing("countdown " + id, "circle", { cx: p.x, cy: p.y,
r: COUNTDOWN_R / 2, fill: "none", stroke: AMBER, "stroke-width": COUNTDOWN_R,
"stroke-opacity": .55, "pointer-events": "none",
...(dash ? { "stroke-dasharray": dash, transform: countdownTurn(p) } : {}) }));
if (dash && countdownFrame === null) countdownFrame = requestAnimationFrame(tickCountdowns);
}
// Deciding: hollow, so its question mark shows.
// Subscribed (`subscriptions`): a black centre, and a ring of this node's colour a
// third of its diameter wide; grey while not reached from here.
const following = !member.self && subscriptions.has(id) ? subscribed.get(id) : undefined;
const ring = following && !dormant && !voting && !deciding;
const circle = drawing("node " + id, "circle", { cx: p.x, cy: p.y,
r: ring ? radius - radius / 3 : radius,
fill: deciding ? "var(--panel)" : voting ? AMBER : ring ? "#000" : member.self ? "var(--self)" : reported ? "var(--fg)" : "var(--panel)",
stroke: dormant ? "var(--bad)" : voting ? AMBER : ring ? (following.status === "live" ? "var(--self)" : "var(--muted)") : member.self ? "var(--self)" : "var(--fg)",
"stroke-width": dormant ? 2.5 : ring ? radius * 2 / 3 : 1.5 }, pressed);
// Its clock against the swarm's, as the members' reports chain it (the node's).
const clock = clocks[id];
tooltip(circle, id + (reported ? "" : " (no links reported)") +
(following ? (following.status === "live" ? " (subscribed)" :
" (subscribed, not reached from here: " + following.why + ")") : "") +
(dormant ? " (dormant)" : "") +
(coordinating.has(id) ? " (coordinates a remake)" : voting ? " (voted for a remake)" : "") +
(clock && clock.off ? " (clock " + seconds(clock.offsetMs) + " off the swarm's, ±" +
clock.withinMs + " ms)" : ""));
// Pinned (middle-clicked): a dot in the middle.
const pin = pinned.has(id) ? [drawing("pin " + id, "circle", { cx: p.x, cy: p.y, r: 2,
fill: member.self || reported ? "var(--panel)" : "var(--fg)",
"pointer-events": "none" })] : [];
const nameLabel = drawing("name " + id, "text", upright({ x: p.x + 10, y: p.y + 4,
"font-size": 12, fill: "var(--fg)", cursor: "pointer" }), pressed);
label(nameLabel, name(id));
// Deciding: a golden question mark in it. Without the map's labels' edge in the
// background colour (`#graph text`, 4 px wide: a style, which only a style
// overrides), which would cover the node's rim.
const asking = deciding ? [drawing("deciding " + id, "text", upright({ x: p.x, y: p.y,
"font-size": radius * 1.7, "font-weight": "bold", fill: AMBER, style: "stroke: none",
"text-anchor": "middle", "dominant-baseline": "central", "pointer-events": "none" }))] : [];
for (const question of asking) text(question, "?");
children.push(circle, ...pin, ...asking, nameLabel);
}
marks.pointed.replaceChildren(...marked.pointed);
marks.shown.replaceChildren(...marked.shown);
show(document.getElementById("view"), children);
}
// --- Document: read a level at a time (`/store?shallow=true`) as it is opened, and
// read again where the node says it changed (`document` events) ---
// What is open, by path (as JSON): the first level to begin with.
const documentOpen = new Set([JSON.stringify([])]);
// As the page it was opened from had them (`handOver`): the same document, so the same
// paths, opened as the tree is drawn.
if (handOver && Array.isArray(handOver.document)) {
for (const path of handOver.document) if (typeof path === "string") documentOpen.add(path);
}
// The open branches read, by path (as JSON): to read again on a change.
const documentBranches = new Map();
function storeUrl(path, shallow) {
const where = path.length ? "../store/" + path.map(encodeURIComponent).join("/") : "../store";
return where + (shallow ? "?shallow=true" : "");
}
// Store paths split at "/": a key with one (or an empty key) can't be read on its own.
const addressable = path => path.every(segment => segment !== "" && !segment.includes("/"));
// Either is within the other.
const related = (a, b) => a.length <= b.length
? a.every((segment, i) => segment === b[i]) : related(b, a);
function describe(summary) {
switch (summary.type) {
case "map": return "{" + summary.size + (summary.size === 1 ? " key}" : " keys}");
case "list": return "[" + summary.size + (summary.size === 1 ? " item]" : " items]");
case "text": return "text, " + summary.size + " characters";
default: return summary.type + ("size" in summary ? ", " + summary.size + " bytes" : "");
}
}
async function readStore(path, shallow) {
const response = await fetch(storeUrl(path, shallow), { headers: { Accept: "application/json" } });
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
}
// An empty map, list or text: shown as it is, nothing to open.
const EMPTY = { map: "{}", list: "[]", text: "\"\"" };
const EMPTY_VALUE = { map: () => ({}), list: () => [], text: () => "" };
// A red `Delete` that acts on a second click, from half a second to 3 s after the first
// (`Delete: sure?`): a double-click doesn't delete. `act()`: whether it did; if not, the
// button is `Delete` again.
function deleteButton(act) {
const button = el("button", { type: "button", class: "delete" }, "Delete");
let sure = null, askedAt = 0;
button.addEventListener("click", async () => {
if (sure === null) {
button.textContent = "Delete: sure?";
askedAt = performance.now();
sure = setTimeout(() => { sure = null; button.textContent = "Delete"; }, 3000);
return;
}
if (performance.now() - askedAt < 500) return;
clearTimeout(sure);
button.disabled = true;
if (!(await act())) {
sure = null;
button.textContent = "Delete";
button.disabled = false;
}
});
return button;
}
// --- Editing: `Edit value` in an entry's menu turns it into a field holding its contents;
// saved with PUT /store/<path> (the whole value, objects too) ---
// A string is edited as text (sent as text/plain), anything else as JSON; "JSON"
// switches. `done(saved, response)` when saved or cancelled.
// `options` for adding rather than replacing: `extra`, a short field before the value
// (`{ label, initial, hint }`: the key, or the index); `check(extra)`, an error text if
// it won't do; `send(body, type, extra)`, the request (PUT to `path` without).
function editor(path, value, done, options = {}) {
const message = el("span", { class: "note" });
const fail = text => { message.className = "error"; message.textContent = text; };
const asText = typeof value === "string";
const text = asText ? value : JSON.stringify(value, null, 2);
const field = el("textarea", { spellcheck: "false",
rows: String(Math.max(2, Math.min(20, text.split("\n").length + 1))) });
field.value = text;
const json = el("input", { type: "checkbox" });
json.checked = !asText;
json.addEventListener("change", () => {
if (json.checked) { field.value = JSON.stringify(field.value); return; }
try {
const parsed = JSON.parse(field.value);
if (typeof parsed !== "string") throw new Error("not a string");
field.value = parsed;
} catch {
json.checked = true;
fail("Only a JSON string can be edited as text.");
}
});
const extra = options.extra
? el("input", { type: "text", spellcheck: "false", class: "extra",
placeholder: options.extra.label, title: options.extra.hint || options.extra.label })
: null;
if (extra) extra.value = options.extra.initial || "";
const send = options.send || ((body, type) => fetch(storeUrl(path, false),
withToken({ method: "PUT", body, headers: { "Content-Type": type } })));
const save = el("button", { type: "button" }, options.extra ? "Add" : "Save");
const cancel = el("button", { type: "button" }, "Cancel");
const submit = async () => {
const body = field.value;
const problem = extra && options.check ? options.check(extra.value) : null;
if (problem) { fail(problem); return; }
if (json.checked) {
try { JSON.parse(body); } catch (error) {
fail("Not JSON: " + error.message); return;
}
}
save.disabled = true;
message.className = "note";
message.textContent = "Saving…";
try {
const response = await send(body, json.checked ? "application/json" : "text/plain",
extra ? extra.value : null);
if (!response.ok) {
// The node says why (`{"error": …}`), where it does.
let why = response.status === 403 ? "not allowed" : "";
try { why = (await response.json()).error || why; } catch { /* no body */ }
throw new Error("HTTP " + response.status + (why ? ": " + why : ""));
}
done(true, response);
} catch (error) {
save.disabled = false;
fail("Not saved: " + error.message);
}
};
save.addEventListener("click", submit);
cancel.addEventListener("click", () => done(false));
// Editing what's there: it can be deleted too (DELETE /store/<path>, `deleteButton`).
const remove = options.extra ? null : deleteButton(async () => {
save.disabled = true;
message.className = "note";
message.textContent = "Deleting…";
try {
const response = await fetch(storeUrl(path, false), withToken({ method: "DELETE" }));
if (!response.ok) {
let why = response.status === 403 ? "not allowed" : "";
try { why = (await response.json()).error || why; } catch { /* no body */ }
throw new Error("HTTP " + response.status + (why ? ": " + why : ""));
}
done("deleted", response);
return true;
} catch (error) {
save.disabled = false;
fail("Not deleted: " + error.message);
return false;
}
});
// Enter in the short field saves; in the area, Ctrl or ⌘ and Enter does.
const keys = (input, line) => input.addEventListener("keydown", event => {
if (event.key === "Escape") { event.preventDefault(); done(false); }
else if (event.key === "Enter" && (line || event.ctrlKey || event.metaKey)) {
event.preventDefault(); submit();
}
});
keys(field, false);
if (extra) keys(extra, true);
setTimeout(() => (extra && !extra.value ? extra : field).focus());
return el("div", { class: "editor" }, ...(extra ? [extra] : []), field,
el("div", {}, save, " ", cancel, " ", ...(remove ? [remove, " "] : []),
el("label", {}, json, " JSON"), " ",
el("span", { class: "note" }, "Ctrl+Enter saves, Esc cancels"), " ", message));
}
// Store paths name keys below the root; the root itself isn't written whole.
const editable = path => path.length > 0 && addressable(path);
// Branches whose reading again waited for an edit in them to end, by path (as JSON).
const documentDeferred = new Set();
// After an edit: what changed is read again (the node's `document` event follows),
// and what was waiting for the edit; `opened`, what it made, shown open. `saved`:
// true, false (cancelled), or "deleted" (then its parent is read again).
function edited(path, saved, opened = path) {
if (saved === "deleted") path = path.slice(0, -1);
else if (saved) documentOpen.add(JSON.stringify(opened));
release();
const waiting = [...documentDeferred].map(id => JSON.parse(id));
documentDeferred.clear();
if (saved || waiting.length) documentChanged({ paths: saved ? [path, ...waiting] : waiting });
}
// Whether `element` holds a field being edited: left as it is until it's done.
const editing = element => element.querySelector(".editor") !== null;
// Adding to a map (a key and its value, PUT /store/<path>/<key>) or a list (an index
// and the value, POST /store/<path>/<index>: the items from there on move up; -1 is the
// end), without writing it whole. `known()`: a map's keys as last read, so an existing
// one isn't overwritten.
// The field for adding to `path` (from its menu, `entryItems`), below its row: a list's
// index as `index` has it at first ("-1": at the end; "": asked for).
function adding(kind, path, known, place, index) {
const map = kind === "map";
{
const area = place();
if (editing(area)) return;
const form = editor(path, "", async (saved, response) => {
form.remove();
let added = path;
if (saved) {
if (map) added = [...path, form.dataset.extra];
else {
try { added = [...path, String((await response.json()).index)]; } catch { /* path */ }
}
}
edited(path, saved, added);
}, {
extra: map
? { label: "key", initial: "" }
: { label: "index", initial: index, hint: "where: 0 is the first; -1 the end" },
check: extra => {
form.dataset.extra = extra;
return map
? (extra === "" ? "A key, please."
: extra.includes("/") ? "A key with \"/\" can't be named in a path."
: known().includes(extra) ? "\"" + extra + "\" exists already: edit it instead."
: null)
: (/^(-1|\d+)$/.test(extra.trim()) ? null : "The index: 0 or more, or -1 for the end.");
},
send: (body, type, extra) => fetch(storeUrl([...path, map ? extra : extra.trim()], false),
withToken({ method: map ? "PUT" : "POST", body, headers: { "Content-Type": type } })),
});
area.prepend(form);
}
}
// --- An entry's menu (right-click, or a finger held on it): edit its value, rename its
// key (a map's), add to it (a map: a key; a list: an item at the end, or at an index).
// Each in a field below its row. ---
// By touch (`touch`), its top right corner at the finger, so the hand holding it, a
// right hand mostly, doesn't cover it; else its top left at the pointer.
function entryMenu(x, y, items, touch = false) {
const menu = document.getElementById("entry-menu");
menu.replaceChildren(...items.map(([label, act]) => {
const button = el("button", { type: "button", role: "menuitem" }, label);
button.addEventListener("click", () => { menu.hidden = true; act(); });
return button;
}));
if (items.length === 0) return;
menu.hidden = false;
const left = touch ? x - menu.offsetWidth : x;
menu.style.left = Math.max(8, Math.min(left, innerWidth - menu.offsetWidth - 8)) + "px";
menu.style.top = Math.max(8, Math.min(y, innerHeight - menu.offsetHeight - 8)) + "px";
}
// `row` opens a menu of `items()` on a right-click, or a finger held on it half a second
// (the click that ends the touch then neither opens nor closes the row).
const HOLD_MS = 500;
// What the last press on an entry was made with (`pointerType`).
let lastPointer = "mouse";
function withMenu(row, items) {
row.addEventListener("contextmenu", event => {
if (event.target.closest(".editor, .renamer")) return;
// Nothing to offer: the browser's own menu.
const offered = items();
if (offered.length === 0) return;
event.preventDefault();
event.stopPropagation();
// Opened by a finger held (some browsers say so with this, after the hold below).
entryMenu(event.clientX, event.clientY, offered,
event.pointerType === "touch" || lastPointer === "touch");
});
let held = null, swallow = false;
row.addEventListener("pointerdown", event => {
lastPointer = event.pointerType;
if (event.pointerType !== "touch" || event.target.closest(".editor, .renamer")) return;
const { clientX: x, clientY: y } = event;
held = setTimeout(() => {
held = null;
const offered = items();
if (offered.length === 0) return;
swallow = true;
entryMenu(x, y, offered, true);
}, HOLD_MS);
const cancel = moved => {
if (moved && Math.hypot(moved.clientX - x, moved.clientY - y) < 10) return;
clearTimeout(held);
held = null;
row.removeEventListener("pointermove", cancel);
};
row.addEventListener("pointermove", cancel);
row.addEventListener("pointerup", () => cancel(), { once: true });
row.addEventListener("pointercancel", () => cancel(), { once: true });
});
row.addEventListener("click", event => {
if (!swallow) return;
swallow = false;
event.preventDefault();
event.stopPropagation();
}, true);
}
// Renaming a map's key: a field below its row, the key in it. Its value is read, written
// under the new key (PUT), and the old key deleted (DELETE): two writes, the value as
// JSON. `siblings()`: the map's keys as last read, so none is overwritten.
function renaming(path, siblings, row) {
if (row.parentNode.querySelector(":scope > .renamer")) return;
const old = path[path.length - 1], parent = path.slice(0, -1);
const field = el("input", { type: "text", spellcheck: "false", class: "extra" });
field.value = old;
const message = el("span", { class: "note" });
const fail = text => { message.className = "error"; message.textContent = text; };
const go = el("button", { type: "button" }, "Rename");
const cancel = el("button", { type: "button" }, "Cancel");
const form = el("div", { class: "editor renamer" }, field,
el("div", {}, go, " ", cancel, " ",
el("span", { class: "note" }, "Enter renames, Esc cancels"), " ", message));
const close = renamed => {
form.remove();
edited(parent, renamed, renamed ? [...parent, field.value] : parent);
};
const submit = async () => {
const to = field.value;
const problem = to === "" ? "A key, please."
: to.includes("/") ? "A key with \"/\" can't be named in a path."
: to === old ? "The same key."
: siblings().includes(to) ? "\"" + to + "\" exists already."
: null;
if (problem) { fail(problem); return; }
go.disabled = true;
message.className = "note";
message.textContent = "Renaming…";
const why = async response => {
let why = response.status === 403 ? "not allowed" : "";
try { why = (await response.json()).error || why; } catch { /* no body */ }
return "HTTP " + response.status + (why ? ": " + why : "");
};
try {
const value = await readStore(path, false);
const put = await fetch(storeUrl([...parent, to], false), withToken({ method: "PUT",
body: JSON.stringify(value), headers: { "Content-Type": "application/json" } }));
if (!put.ok) throw new Error("Not renamed: " + await why(put));
const removed = await fetch(storeUrl(path, false), withToken({ method: "DELETE" }));
if (!removed.ok) {
throw new Error("Written under \"" + to + "\", but \"" + old + "\" not deleted: " +
await why(removed));
}
close(true);
} catch (error) {
go.disabled = false;
fail(error.message);
}
};
go.addEventListener("click", submit);
cancel.addEventListener("click", () => close(false));
field.addEventListener("keydown", event => {
if (event.key === "Escape") { event.preventDefault(); close(false); }
else if (event.key === "Enter") { event.preventDefault(); submit(); }
});
row.after(form);
setTimeout(() => { field.focus(); field.select(); });
}
// The items of an entry's menu: `edit`, if it can be edited; renaming, if it is a map's
// key (`parentKind`); adding to it, if it is a map or list (`kind`) that can be written
// in (`place`: where the field goes; `known`: its keys).
function entryItems({ path, kind, parentKind, siblings, row, edit, known, place }) {
const items = [];
if (edit) items.push(["Edit value", edit]);
if (parentKind === "map" && editable(path)) {
items.push(["Rename key", () => renaming(path, siblings, row)]);
}
if (place && kind === "map") items.push(["Add a key", () => adding("map", path, known, place, "")]);
if (place && kind === "list") {
items.push(["Append an item", () => adding("list", path, known, place, "-1")],
["Insert an item at…", () => adding("list", path, known, place, "")]);
}
return items;
}
// In the protocol's data (`_continuum`): node IDs, times and sizes glossed (`gloss`).
const glossedPath = path => path[0] === "_continuum";
function editableLeaf(key, shown, value, path) {
const glosses = glossedPath(path);
// The key one element (kept while editing), its alias in it.
const leaf = el("div", { class: "leaf" }, el("span", { class: "key" }, key,
...(glosses ? glossed(aliasOf(key)) : []), ": "), shown,
...(glosses ? glossed(gloss(key, value)) : []));
if (!editable(path)) return leaf;
leaf.title = "Right-click (or hold a finger on it) for its menu";
leaf.edit = () => {
if (editing(leaf)) return;
window.getSelection().removeAllRanges();
const before = [...leaf.childNodes];
leaf.replaceChildren(before[0], editor(path, value, saved => {
leaf.replaceChildren(...before);
edited(path, saved);
}));
};
return leaf;
}
// An entry that changed in the document breathes once, as the map's labels do: its
// row glows and fades.
function glow(entry) {
if (calm.matches || !entry.animate) return;
const row = entry.tagName === "DETAILS" ? entry.querySelector(":scope > summary")
: entry.classList.contains("leaf") ? entry : entry.firstElementChild || entry;
const colour = getComputedStyle(document.documentElement).getPropertyValue("--self").trim();
row.animate([
{ backgroundColor: "transparent" },
{ backgroundColor: "color-mix(in srgb, " + colour + " 30%, transparent)", offset: .3 },
{ backgroundColor: "transparent" },
], { duration: 900, easing: "ease-in-out" });
}
// One entry: a short scalar as it is; anything else a branch read when opened. A
// branch's entries are kept across reads, so what's open inside stays open.
// `parentKind`: what it is in (`map`, `list`); `siblings()`: the keys there.
function documentEntry(key, summary, path, parentKind = null, siblings = () => []) {
if (summary.size === 0 && summary.type in EMPTY) {
const leaf = editableLeaf(key, EMPTY[summary.type], EMPTY_VALUE[summary.type](), path);
// An empty map or list takes its first entry here: from its menu, the field below.
if ((summary.type === "map" || summary.type === "list") && editable(path)) {
const below = el("div", { class: "nested" });
withMenu(leaf, () => entryItems({ path, kind: summary.type, parentKind, siblings,
row: leaf, edit: leaf.edit, known: () => [], place: () => below }));
return el("div", {}, leaf, below);
}
if (leaf.edit) {
withMenu(leaf, () => entryItems({ path, parentKind, siblings, row: leaf, edit: leaf.edit }));
}
return leaf;
}
if ("value" in summary) {
const leaf = editableLeaf(key, JSON.stringify(summary.value), summary.value, path);
if (leaf.edit) {
withMenu(leaf, () => entryItems({ path, parentKind, siblings, row: leaf, edit: leaf.edit }));
}
return leaf;
}
const details = el("details", {});
const described = document.createTextNode(describe(summary));
const head = el("summary", {}, el("span", { class: "key" }, key),
...(glossedPath(path) ? glossed(aliasOf(key)) : []), " ", described);
details.append(head);
// Edited as a whole (from its menu): read, then shown in a field.
let edit = null;
if (editable(path)) {
head.title = "Right-click (or hold a finger on it) for its menu";
edit = async () => {
if (details.querySelector(":scope > .editor:not(.renamer)")) return;
let value;
try { value = await readStore(path, false); } catch (error) {
described.textContent = describe(summary) + " (not read: " + error.message + ")";
return;
}
details.open = true;
details.classList.add("editing");
head.after(editor(path, value, saved => {
details.querySelector(":scope > .editor:not(.renamer)").remove();
details.classList.remove("editing");
edited(path, saved);
}));
};
}
// A newer summary from the parent: a branch of the same kind stays as it is.
details.updated = newer => {
summary = newer;
described.textContent = describe(newer);
};
details.sameKind = newer => !("value" in newer) && newer.type === summary.type;
if (!addressable(path)) {
details.append(el("div", { class: "note" }, "Its path can't be read on its own (a key with \"/\")."));
return details;
}
const id = JSON.stringify(path);
const children = new Map();
const browsed = summary.type === "map" || summary.type === "list";
// Adding: on the row, the field just below it (the branch opened for it).
const writable = browsed && (editable(path) || path.length === 0);
const place = () => {
details.open = true;
return { prepend: form => head.after(form), querySelector: q => details.querySelector(":scope > " + q) };
};
details.menuItems = () => entryItems({ path, kind: summary.type, parentKind, siblings,
row: head, edit, known: () => [...children.keys()], place: writable ? place : null });
withMenu(head, details.menuItems);
let read = false;
// Read once at least: what's new or changed from then on breathes (`glow`).
let filled = false;
const fill = async () => {
// Being edited as a whole: read again once that's done.
if (details.classList.contains("editing")) { documentDeferred.add(id); return; }
try {
if (browsed) {
const shallow = await readStore(path, true);
details.updated(shallow);
const entries = shallow.entries || {};
// A list's items by index (the node sends them sorted as text).
const keys = Object.keys(entries);
if (summary.type === "list") keys.sort((a, b) => Number(a) - Number(b));
for (const [k, child] of children) {
if (k in entries) continue;
// Being edited: kept until that's done.
if (editing(child.element)) { documentDeferred.add(id); continue; }
child.element.remove();
children.delete(k);
}
for (const k of keys) {
const newer = entries[k];
const known = children.get(k);
if (known && JSON.stringify(known.summary) === JSON.stringify(newer)) continue;
if (known && editing(known.element)) { documentDeferred.add(id); continue; }
if (known && known.element.sameKind && known.element.sameKind(newer)) {
known.element.updated(newer);
known.summary = newer;
glow(known.element);
continue;
}
const element = documentEntry(k, newer, [...path, k], summary.type,
() => [...children.keys()]);
if (known) known.element.replaceWith(element);
children.set(k, { element, summary: newer });
if (filled) glow(element);
}
// In order; moving keeps their state.
details.querySelectorAll(":scope > .note").forEach(note => note.remove());
if (!children.size) details.append(el("div", { class: "note" }, "empty"));
for (const k of keys) if (children.has(k)) details.append(children.get(k).element);
} else {
const value = await readStore(path, false);
const shown = el("pre", {}, typeof value === "string" ? value : JSON.stringify(value, null, 2));
const before = details.querySelector(":scope > pre");
if (before) before.replaceWith(shown); else details.append(shown);
if (before && before.textContent !== shown.textContent) glow(shown);
}
filled = true;
} catch (error) {
details.querySelectorAll(":scope > .note").forEach(note => note.remove());
details.append(el("div", { class: "note error" }, "Not read: " + error.message));
}
};
const open = () => {
documentOpen.add(id);
documentBranches.set(id, { path, element: details, refresh: fill });
if (!read) { read = true; fill(); }
};
details.addEventListener("toggle", () => {
if (details.open) open();
else { documentOpen.delete(id); documentBranches.delete(id); }
});
if (documentOpen.has(id)) { details.open = true; open(); }
return details;
}
// The node says what changed (paths), or that anything may have (`all`).
// Changes waiting while text in the document box is selected (`busy`): merged, applied
// after. A field being edited holds only what it is in (`editing`, `documentDeferred`).
let documentPending = null;
function documentChanged(change) {
if (busy(document.getElementById("document-box"))) {
documentPending = documentPending === null ? change
: documentPending.all || change.all ? { all: true }
: { paths: [...documentPending.paths, ...change.paths] };
return;
}
for (const [id, branch] of documentBranches) {
if (!branch.element.isConnected) { documentBranches.delete(id); continue; }
if (change.all || change.paths.some(path => related(path, branch.path))) branch.refresh();
}
}
// The store's root, always open: its keys are the box's top level, and its size
// (everything its row has but its key) goes into the title.
const documentRoot = documentEntry("store", { type: "map", size: "…" }, []);
documentRoot.classList.add("root");
documentRoot.open = true;
document.getElementById("document-head").append(
...[...documentRoot.querySelector(":scope > summary").childNodes].slice(1));
// The title stands for the root: its menu adds a key at the top level.
withMenu(document.querySelector("#document-box > h2"), documentRoot.menuItems);
document.getElementById("document").replaceChildren(documentRoot);
// A box is busy while text in it is selected: drawing it anew would lose the selection,
// so it waits (`held`) until it's gone.
// Collapsed, or not shown at all (the right column dragged off): drawn when opened
// (`release`).
function hidden(box) {
return box.classList.contains("collapsed") || box.getClientRects().length === 0;
}
function busy(box) {
if (hidden(box)) return true;
const selection = window.getSelection();
if (!selection || selection.isCollapsed || !selection.rangeCount) return false;
return box.contains(selection.getRangeAt(0).commonAncestorContainer);
}
let held = false;
function render(ages = false) {
if (!state) return;
applySubscriptions();
document.getElementById("node").textContent =
(state.node.alias ? state.node.alias + " · " : "") + state.node.id;
const skew = state.stats.clock;
document.getElementById("clock-warning").textContent = skew && skew.off
? "clock " + seconds(skew.offsetMs) + " off its peers'" : "";
held = false;
const boxes = [["peers-box", renderPeers], ["figures-box", renderStats]];
// Its ages are in tooltips only: drawn on events, not every second.
if (!ages) boxes.push(["map", renderGraph]);
for (const [box, draw] of boxes) {
if (busy(document.getElementById(box))) held = true; else draw();
}
}
// What waited for a box to be free: drawn, or applied, now.
function release() {
if (held) render();
if (documentPending !== null && !busy(document.getElementById("document-box"))) {
const change = documentPending;
documentPending = null;
documentChanged(change);
}
}
document.addEventListener("selectionchange", release);
// The legend's first row leaves the controls room, however wide they are (their texts
// change).
{
const controls = document.querySelector(".map-controls");
const overlay = document.querySelector(".map-overlay");
const room = () => overlay.style.setProperty("--controls-width", controls.offsetWidth + "px");
room();
if (window.ResizeObserver) new ResizeObserver(room).observe(controls);
}
// The legend, hidden and shown again, over the map: the map stays as it is.
const legendToggle = document.getElementById("legend-toggle");
function showLegend(shown) {
const legends = document.getElementById("legends");
legends.hidden = !shown;
legendToggle.textContent = shown ? "hide legend" : "show legend";
}
legendToggle.addEventListener("click", () => {
showLegend(document.getElementById("legends").hidden);
});
// Hidden as on the page it was opened from (`handOver`).
if (handOver && handOver.legend === false) showLegend(false);
// A writer's tree, shown and hidden (`treeShown`).
const treeToggle = document.getElementById("tree-toggle");
function showTreeToggle() {
treeToggle.textContent = treeShown ? "tree: on" : "tree: off";
treeToggle.title = treeShown
? "The tree of the node in focus (or this node) as a writer: the way its changes go. Click to hide it"
: "Click to show the tree of the node in focus (or this node) as a writer: the way its changes go";
}
showTreeToggle();
treeToggle.addEventListener("click", () => {
treeShown = !treeShown;
try { localStorage.setItem("continuum-tree", treeShown ? "1" : "0"); } catch (_) {}
showTreeToggle();
writerTree = null;
loadTree();
if (state) renderGraph();
});
// Links as long as their round trips, and back.
const rttToggle = document.getElementById("rtt-toggle");
function showRttToggle() {
rttToggle.textContent = byRtt ? "layout: dynamic" : "layout: static";
rttToggle.title = "Click for " + (byRtt ? "a static layout"
: "a dynamic one: links as long as their round trips");
}
showRttToggle();
rttToggle.addEventListener("click", () => {
byRtt = !byRtt;
try { localStorage.setItem("continuum-by-rtt", byRtt ? "1" : "0"); } catch (_) {}
showRttToggle();
// To the lengths afresh, when resized again.
lastLengths = "";
if (state) renderGraph();
});
// --- Pan, zoom and turn: the map's group moved, scaled and turned (`turn`, in
// radians). Lines, labels and nodes scale with it, as on a map; labels stay upright
// (`upright`). ---
const graph = document.getElementById("graph");
const view = { x: 0, y: 0, k: 1, turn: 0 };
const degrees = radians => radians * 180 / Math.PI;
function moveView() {
document.getElementById("view").setAttribute("transform",
"translate(" + view.x + " " + view.y + ") rotate(" + degrees(view.turn) + ") scale(" +
view.k + ")");
}
// The map as the page it was opened from left it (`handOver`): its nodes where they
// were (new ones are placed among them; on a dynamic map all then move to their places
// smoothly, `settle`), the view and the pins.
if (handOver) {
for (const [id, at] of Object.entries(handOver.positions || {})) {
const [x, y] = Array.isArray(at) ? at : [];
if (Number.isFinite(x) && Number.isFinite(y)) positions.set(id, { x, y });
}
for (const id of handOver.pinned || []) if (positions.has(id)) pinned.add(id);
if (positions.size > 0) relayout = false;
const handed = handOver.view || {};
for (const key of ["x", "y", "k", "turn"]) {
if (Number.isFinite(handed[key])) view[key] = handed[key];
}
moveView();
}
// The fragment that opens another node's dashboard (`id`'s) as this page is now
// (`handOver`). What is in focus stays, but `id` itself: its page is its own. Also this
// node's own page, reloaded for a new version (`id` null).
function handOff(id, handed) {
const settings = {};
try {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith("continuum-")) settings[key] = localStorage.getItem(key);
}
} catch (_) {}
const round = value => Math.round(value * 10) / 10;
return HAND_OFF + encodeURIComponent(JSON.stringify({
positions: Object.fromEntries([...positions].map(([node, p]) => [node, [round(p.x), round(p.y)]])),
pinned: [...pinned],
view: { ...view },
focused: focused === id ? null : focused,
// The node this page is of: the next page subscribes to it.
from: state ? state.node.id : undefined,
settings,
legend: !document.getElementById("legends").hidden,
figures: [...open],
document: [...documentOpen],
// A token reading the member list only, for five minutes, enough for the map: the
// other node's login page begins a session with it (`login.html`), where the
// browser has none there. Whoever publishes the dashboard gets it: no more.
token: handed || undefined,
}));
}
// `[x, y]` turned by `angle`.
function turned(x, y, angle) {
const c = Math.cos(angle), s = Math.sin(angle);
return [x * c - y * s, x * s + y * c];
}
// Where the pointer is, in the map's own units (its `viewBox` is its size).
function pointer(event) {
const box = graph.getBoundingClientRect();
return { x: event.clientX - box.left, y: event.clientY - box.top };
}
// How far it zooms: from a quarter to eight times.
const zoomed = k => Math.min(8, Math.max(.25, k));
// The wheel zooms around the pointer.
graph.addEventListener("wheel", event => {
event.preventDefault();
const at = pointer(event);
const k = zoomed(view.k * Math.exp(-event.deltaY * .002));
view.x = at.x - (at.x - view.x) * k / view.k;
view.y = at.y - (at.y - view.y) * k / view.k;
view.k = k;
moveView();
}, { passive: false });
// A press on the map: dragged (more than a few pixels), it `move`s by as much as the
// pointer did; let go where pressed, it's a `click`.
let press = null;
function pressing(event, move, click) {
press = { from: pointer(event), moved: false, move, click };
graph.setPointerCapture(event.pointerId);
}
// Fingers on the map, by pointer. Two pinch: the map zooms around the point between
// them, moves with it, and turns as they do. A press (`pressing`) is given up when the
// second comes.
const touching = new Map();
let pinch = null;
const between = (a, b) => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
// From the first two fingers as they are now.
function pinchFrom() {
const [one, two] = touching.values();
pinch = { view: { ...view }, at: between(one, two),
distance: Math.max(Math.hypot(two.x - one.x, two.y - one.y), 1),
angle: Math.atan2(two.y - one.y, two.x - one.x) };
}
function pinched() {
const [one, two] = touching.values();
const at = between(one, two);
const k = zoomed(pinch.view.k * Math.hypot(two.x - one.x, two.y - one.y) / pinch.distance);
const turn = pinch.view.turn + Math.atan2(two.y - one.y, two.x - one.x) - pinch.angle;
// What was between the fingers (on the map, unturned and unscaled) stays between them.
const [x, y] = turned(pinch.at.x - pinch.view.x, pinch.at.y - pinch.view.y, -pinch.view.turn);
const [dx, dy] = turned(x * k / pinch.view.k, y * k / pinch.view.k, turn);
Object.assign(view, { x: at.x - dx, y: at.y - dy, k, turn });
moveView();
// Its labels upright again.
if (state) renderGraph();
}
// Before the map's own handlers (a node's included): a second finger takes over.
graph.addEventListener("pointerdown", event => {
if (event.pointerType !== "touch") return;
touching.set(event.pointerId, pointer(event));
graph.setPointerCapture(event.pointerId);
if (touching.size < 2) return;
press = null;
graph.classList.remove("dragging");
pinchFrom();
event.stopImmediatePropagation();
}, true);
// A finger lifted: the others pinch on from where they are, or (one left) do nothing
// until lifted too.
function untouched(event) {
if (!touching.delete(event.pointerId)) return;
if (touching.size >= 2) pinchFrom(); else pinch = null;
}
graph.addEventListener("pointermove", event => {
if (touching.has(event.pointerId)) touching.set(event.pointerId, pointer(event));
if (pinch) { pinched(); return; }
if (!press) return;
const at = pointer(event);
const dx = at.x - press.from.x, dy = at.y - press.from.y;
if (!press.moved && Math.hypot(dx, dy) < 4) return;
press.moved = true;
graph.classList.add("dragging");
press.move(dx, dy);
});
graph.addEventListener("pointerup", event => {
untouched(event);
const click = press && !press.moved ? press.click : null;
press = null;
graph.classList.remove("dragging");
dropped();
if (click) click();
});
graph.addEventListener("pointercancel", event => {
untouched(event);
press = null;
graph.classList.remove("dragging");
dropped();
});
// The map dragged: it pans; a click, `click`.
function pan(event, click) {
const from = { ...view };
pressing(event, (dx, dy) => {
view.x = from.x + dx;
view.y = from.y + dy;
moveView();
}, click);
}
// Beside the nodes: dragged, it pans; a click, back to this node.
graph.addEventListener("pointerdown", event => {
if (event.target !== graph) return;
pan(event, () => focus(null));
});
// Not the browser's drag and drop of the picture.
graph.addEventListener("dragstart", event => event.preventDefault());
// A node: dragged, it moves, held where the pointer is (`grabbed`) until let go; a click,
// it is in focus; a second one soon after subscribes to it, or no longer
// (`toggleSubscription`); a right click shows its menu (`nodeMenu`). A
// middle click pins it where it is (`pinned`: the layout leaves it
// there), or lets it go if pinned (`unpin`); dragged with the middle button, it is
// pinned where it's dropped. Told apart here: the map holds the pointer while pressed
// (`pressing`), so the browser's clicks go to the map, not the node.
let lastNodeClick = { id: null, at: 0 };
const DOUBLE_CLICK_MS = 400;
let grabbed = null;
// Of the press under way on a node: whether it's the middle button's, and whether it
// moved the node.
let middlePress = false, dragMoved = false;
function drag(event, id) {
const p = positions.get(id), from = { x: p.x, y: p.y };
grabbed = id;
middlePress = event.button === 1;
// Not the browser's scrolling by the middle button.
if (middlePress) event.preventDefault();
dragMoved = false;
pressing(event, (dx, dy) => {
dragMoved = true;
// The pointer's move, on the map (unturned and unscaled).
const [x, y] = turned(dx, dy, -view.turn);
p.x = from.x + x / view.k;
p.y = from.y + y / view.k;
renderGraph();
// Dynamic: the others follow it at once.
if (byRtt) settle();
}, () => {
if (middlePress) {
if (pinned.has(id)) unpin(id); else pin(id);
return;
}
const now = performance.now();
if (lastNodeClick.id === id && now - lastNodeClick.at < DOUBLE_CLICK_MS) {
lastNodeClick = { id: null, at: 0 };
toggleSubscription(id);
} else {
lastNodeClick = { id, at: now };
focus(id);
}
});
}
// --- Subscriptions: other nodes' own links, read from them by this page directly
// (their `dashboard/links/own/events`, with a token: `access.md`, Tokens), for the map.
// Kept in the browser (handed over with the rest), each followed while the page is
// open; a node the browser can't reach shows grey, with why in its tooltip. ---
function keepSubscriptions() {
try { localStorage.setItem(SUBSCRIPTIONS, JSON.stringify([...subscriptions])); } catch (_) {}
}
function toggleSubscription(id) {
if (!state || id === state.node.id) return;
if (subscriptions.has(id)) {
subscriptions.delete(id);
const entry = subscribed.get(id);
if (entry) entry.stop();
subscribed.delete(id);
// Its report as this node has it, if any.
unapplySubscriptions();
} else {
subscriptions.add(id);
follow(id);
}
keepSubscriptions();
render();
readFigures();
}
// The subscriptions' reports on the map, over what this node has of them: fresher.
// What they cover of the node's state is kept aside (`overlaid`: by node, the node's
// report, or undefined) and put back before a patch from the node applies
// (`unapplySubscriptions`): a patch is onto the node's state, and one onto a report
// the page put there, or took away, would leave half of one.
const overlaid = new Map();
function applySubscriptions() {
for (const [id, entry] of subscribed) {
if (!entry.report || !state.graph.members[id]) continue;
if (!overlaid.has(id)) overlaid.set(id, state.graph.measured[id]);
state.graph.measured[id] = {
secsAgo: Math.max(0, Math.floor((stateAt - entry.at) / 1000)),
links: entry.report.links || [],
epoch: entry.report.epoch,
subscribed: true,
};
}
}
function unapplySubscriptions() {
for (const [id, report] of overlaid) {
if (report === undefined) delete state.graph.measured[id];
else state.graph.measured[id] = report;
}
overlaid.clear();
}
// Tokens: this page's, from logging in on this node (the browser's password for it, the
// proxy's, or the session the login page began), and a narrower one, reading the member
// list only, to send to others.
// Each refreshed half way through its life (`tokenAt`: when the page got it).
let token = null, narrowToken = null, tokenWhy = "not logged in yet", tokenTimer = null;
let tokenAt = 0, obtaining = false;
const READ_MEMBERS = [{ path: ["_continuum", "members"], rights: ["read"] }];
// A request that changes something, with this page's token: the session's cookie lets
// in only those that read (`login::bearer`).
function withToken(init) {
if (token) init.headers = Object.assign({}, init.headers, { Authorization: "Bearer " + token.token });
return init;
}
async function tokenCall(url, bearer, body) {
const headers = { "Content-Type": "application/json" };
if (bearer) headers.Authorization = "Bearer " + bearer;
const response = await fetch(url, { method: "POST", headers,
body: JSON.stringify(body || {}) });
const answer = await response.json().catch(() => ({}));
if (!response.ok) throw refused(response.status, answer.error || response.statusText);
return answer;
}
// An error with the status it came with (`status`): 400, 401 and 403 are the login's
// end, others pass.
function refused(status, why) {
const error = new Error(status + " " + why);
error.status = status;
return error;
}
// How the page got in: by its session ("session"), which logging out ends, or through
// the proxy, which names the user ("header"), which it can't end. Never by a password
// the browser keeps (basic authentication): the login page takes passwords.
let loggedIn = null;
const CANT_LOG_OUT = {
header: "This page got in by your proxy, which names you to the node: log out of the " +
"proxy (its own logout, or closing the browser).",
};
// Through the proxy, if it names the user (`POST /auth/login`); refused otherwise, a
// password the browser keeps included.
async function throughProxy() {
const answer = await tokenCall("../auth/login");
if (answer.login !== "header") throw refused(401, "log in on the login page");
return answer;
}
function showWho() {
const who = document.getElementById("who");
who.hidden = !token;
who.textContent = token ? token.user + " ▾" : "";
}
// A message in the page's dialog, with a close button.
function say(title, ...body) {
const dialog = document.getElementById("dialog");
const close = el("button", { type: "button", class: "close" }, "close");
close.addEventListener("click", () => dialog.close());
dialog.replaceChildren(el("h2", {}, title), ...body, close);
if (!dialog.open) dialog.showModal();
}
// The user's menu (its name, top right): its credentials; logging out.
document.getElementById("who").addEventListener("click", event => {
const menu = document.getElementById("user-menu");
if (!menu.hidden) {
menu.hidden = true;
return;
}
const item = (label, act) => {
const button = el("button", { type: "button", role: "menuitem" }, label);
button.addEventListener("click", () => { menu.hidden = true; act(); });
return button;
};
const cant = CANT_LOG_OUT[loggedIn];
const out = item("log out", () => cant ? say("Logging out", el("p", {}, cant)) : logOut());
if (cant) {
// Not `disabled`: a click on it says why.
out.setAttribute("aria-disabled", "true");
out.title = cant;
}
menu.replaceChildren(item("credentials…", credentials), out);
menu.hidden = false;
const box = event.currentTarget.getBoundingClientRect();
menu.style.top = box.bottom + 4 + "px";
menu.style.left = Math.max(8, box.right - menu.offsetWidth) + "px";
});
async function logOut() {
// This browser's session ends; other sessions of the user go on.
await fetch("../auth/session", { method: "DELETE", credentials: "same-origin" }).catch(() => {});
clearTimeout(tokenTimer);
token = narrowToken = null;
// In still, by what the page can't end: said so; else to the login page.
try {
token = await throughProxy();
tokenAt = Date.now();
loggedIn = token.login;
showWho();
say("Logged out of this session", el("p", {}, CANT_LOG_OUT[loggedIn] ||
"The page is let in still, by other means."));
obtainTokens();
} catch (_) {
location.assign("../login");
}
}
// The user's credentials: its keys (`/auth/keys`): each edited (its name, its line),
// removed (its last only where it has a password on this node, which it logs in by
// then), or one added; under a strict policy, how to sign them anew; where its password
// is. What fails says so where it was asked, which stays as it was, to be set right.
async function credentials() {
const password = el("p", {}, "Your password is in each node's password file " +
"(--htpasswd): its operator changes it there.");
let answer;
try {
const response = await fetch("../auth/keys", withToken({ cache: "no-store" }));
answer = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(answer.error || response.status + " " + response.statusText);
} catch (error) {
say("Credentials", password, el("p", { class: "error" }, "Your keys: " + error.message));
return;
}
const keys = Object.entries(answer.keys || {});
const signed = !!answer.signed;
// The columns' widths set once, whatever its rows (one edited spans them all).
const table = el("table", { class: "keys" }, el("colgroup", {},
el("col", { class: "name" }), el("col", {}), el("col", { class: "actions" })));
const row = (id, line) => {
const tr = el("tr", {});
// Its name, as much of the key as fits, and `edit`, at the right.
const shown = () => {
const edit = el("button", { type: "button" }, "edit");
if (signed) {
edit.disabled = true;
edit.title = "signed: see below";
}
edit.addEventListener("click", editing);
tr.replaceChildren(el("td", { class: "name", title: id }, id),
el("td", { class: "key", title: line }, keyLine(line)),
el("td", { class: "actions" }, edit));
};
// Its name and line in fields, across the row; saved under the name (a new name:
// written under it, then the old one removed), or deleted (`deleteButton`; its last
// only where the user has a password on this node).
const editing = () => {
const name = el("input", { size: 12, spellcheck: "false", class: "key-name" });
name.value = id;
const value = el("input", { spellcheck: "false", class: "key-value" });
value.value = line;
const save = el("button", { type: "button" }, "save");
const cancel = el("button", { type: "button" }, "cancel");
const failed = el("span", { class: "error" });
const remove = deleteButton(async () => {
save.disabled = true;
const why = await keyRequest(id, null);
if (why === null) { credentials(); return true; }
save.disabled = false;
failed.textContent = "Not deleted: " + why;
return false;
});
if (keys.length < 2 && !answer.password) {
remove.disabled = true;
remove.title = "your last key, and you have no password on this node: add another first";
}
const submit = async () => {
const to = name.value.trim(), text = value.value.trim();
if (to === "" || text === "") { failed.textContent = "A name and a key, please."; return; }
if (to !== id && keys.some(([other]) => other === to)) {
failed.textContent = "\"" + to + "\" is a key of yours already."; return;
}
save.disabled = true;
failed.textContent = "";
let why = await keyRequest(to, text);
if (why === null && to !== id) {
const old = await keyRequest(id, null);
if (old !== null) why = "saved as \"" + to + "\", but \"" + id + "\" not removed: " + old;
}
if (why === null) credentials();
else { save.disabled = false; failed.textContent = "Not saved: " + why; }
};
save.addEventListener("click", submit);
cancel.addEventListener("click", shown);
for (const field of [name, value]) {
field.addEventListener("keydown", event => {
if (event.key === "Enter") { event.preventDefault(); submit(); }
else if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); shown(); }
});
}
tr.replaceChildren(el("td", { colspan: "3" },
el("div", { class: "key-edit" }, name, value),
el("div", { class: "key-edit" }, save, cancel, remove, failed)));
value.focus();
};
shown();
return tr;
};
table.append(...keys.map(([id, line]) => row(id, line)));
const parts = [password, el("h3", {}, "Your keys"),
keys.length ? table : el("p", { class: "note" }, "none")];
if (signed) {
parts.push(el("p", {}, "This swarm has its users sign their entries: change your " +
"keys by signing yours anew, with a key you hold: continuum-signed key-add NAME " +
"FILE.pub, continuum-signed key-remove NAME."));
} else {
const failed = el("p", { class: "error" });
const form = el("form", {},
el("input", { name: "id", placeholder: "name (laptop)", required: "", size: 12 }),
el("input", { name: "line", placeholder: "ssh-ed25519 AAAA… (its .pub)", required: "",
spellcheck: "false" }),
el("button", {}, "add"));
form.addEventListener("submit", async event => {
event.preventDefault();
const id = form.elements.id.value.trim(), line = form.elements.line.value.trim();
if (keys.some(([other]) => other === id)) {
failed.textContent = "\"" + id + "\" is a key of yours already: edit it instead.";
return;
}
failed.textContent = "";
const why = await keyRequest(id, line);
if (why === null) credentials();
else failed.textContent = "Not added: " + why;
});
parts.push(form, failed);
}
say("Credentials", ...parts);
}
// A key as much of it as fits: its type and what tells it apart (an Ed25519 key's
// base64 after the part every one of them shares), cut in the middle where it doesn't
// fit, its last eight characters and its comment always shown.
const ED25519_COMMON = "AAAAC3NzaC1lZDI1NTE5AAAAI";
function keyLine(line) {
const [type = "", data = "", ...comment] = line.trim().split(/\s+/);
const own = data.startsWith(ED25519_COMMON) ? data.slice(ED25519_COMMON.length) : data;
const cut = Math.max(0, own.length - 8);
return el("span", { class: "key-line" },
el("span", { class: "start" }, type + " " + own.slice(0, cut)),
el("span", { class: "end" }, own.slice(cut) + (comment.length ? " " + comment.join(" ") : "")));
}
// Key `id` of the user's set to `line`, or removed (`line` null): null if done, else why
// not.
async function keyRequest(id, line) {
const init = line === null ? { method: "DELETE" }
: { method: "PUT", headers: { "Content-Type": "text/plain" }, body: line };
try {
const response = await fetch("../auth/keys/" + encodeURIComponent(id), withToken(init));
if (response.ok) return null;
const answer = await response.json().catch(() => ({}));
return answer.error || response.status + " " + response.statusText;
} catch (error) {
return error.message;
}
}
async function obtainTokens() {
if (obtaining) return;
obtaining = true;
clearTimeout(tokenTimer);
try {
// Refreshed as the session (`POST /auth/session`), whose cookie lets the page in;
// the first: by that cookie, else through the proxy.
if (token && token.expiresAt > Date.now() + 60000) {
token = await tokenCall("../auth/session", token.token);
} else {
try {
token = await tokenCall("../auth/session");
loggedIn = "session";
} catch (error) {
if (!(error.status >= 400 && error.status < 500)) throw error;
token = await throughProxy();
loggedIn = token.login;
}
}
tokenAt = Date.now();
showWho();
narrowToken = await tokenCall("../auth/refresh", token.token, { limit: READ_MEMBERS });
tokenWhy = null;
const life = Math.min(token.expiresAt, narrowToken.expiresAt) - Date.now();
tokenTimer = setTimeout(obtainTokens, Math.max(30000, life / 2));
// Those that waited for one.
for (const id of subscriptions) {
const entry = subscribed.get(id);
if (!entry || entry.status === "unreachable") follow(id);
}
} catch (error) {
token = narrowToken = null;
tokenWhy = "no token: " + error.message;
showWho();
// The login ended (or none): to the login page; else (the node away) again soon.
if ([400, 401, 403].includes(error.status)) {
location.assign("../login");
return;
}
tokenTimer = setTimeout(obtainTokens, 30000);
} finally {
obtaining = false;
}
}
// A timer fires late where the computer slept or the tab was in the background: whether
// the token is half way through its life is looked at again when the page shows, and
// every 30 s, refreshed while it still can be.
function refreshIfDue() {
if (token && Date.now() - tokenAt >= (token.expiresAt - tokenAt) / 2) obtainTokens();
}
document.addEventListener("visibilitychange", () => { if (!document.hidden) refreshIfDue(); });
setInterval(refreshIfDue, 30000);
// Follows `id`'s own links, again after a while if it fails (2 s, doubling to a minute).
// Not this node itself (a subscription handed over from another node's page, where it
// was another): its links and messages are the page's own already, and read twice
// they'd show twice.
function follow(id, delay = 2000) {
if (state && id === state.node.id) return;
const old = subscribed.get(id);
if (old) old.stop();
const controller = new AbortController();
let retry = null;
const entry = { status: "connecting", why: "connecting", report: old ? old.report : null,
at: old ? old.at : 0, stop: () => { clearTimeout(retry); controller.abort(); } };
subscribed.set(id, entry);
const fail = why => {
if (controller.signal.aborted || subscribed.get(id) !== entry) return;
entry.status = "unreachable";
entry.why = why;
render();
retry = setTimeout(() => {
if (subscriptions.has(id) && subscribed.get(id) === entry) follow(id, Math.min(60000, delay * 2));
}, delay);
};
const member = state && state.graph.members[id];
if (!member || !member.dashboard) return fail("it publishes no dashboard (--dashboard-url)");
if (!narrowToken) return fail(tokenWhy);
const at = path => endpointOf(id, path);
let url;
try {
url = at("dashboard/links/own/events");
} catch (_) {
return fail("its dashboard's address isn't one");
}
read(url, controller.signal, () => {
entry.status = "live";
entry.why = null;
delay = 2000;
render();
}, (kind, data) => {
if (kind === "links") {
entry.report = JSON.parse(data);
entry.at = Date.now();
render();
}
}).catch(error => fail(error.message || String(error)));
// Its messages, for the console and the map: while they come, quietly; a failure of
// their own leaves the links be.
const messagesUrl = at("dashboard/messages/own/events");
const followMessages = (wait = 2000) => {
if (controller.signal.aborted) return;
read(messagesUrl, controller.signal, () => { entry.messagesLive = true; wait = 2000; },
(kind, data) => {
if (kind !== "messages") return;
const batch = JSON.parse(data);
remoteMessagesArrived(id, entry, batch.messages, batch.sent);
})
.catch(() => {
entry.messagesLive = false;
if (!controller.signal.aborted) setTimeout(() => followMessages(Math.min(60000, wait * 2)), wait);
});
};
followMessages();
}
// A member's endpoint, beside the page it publishes (`…/admin/dashboard` →
// `…/admin/dashboard/<path>`); throws where its address isn't one.
function endpointOf(id, path) {
const member = state && state.graph.members[id];
const base = ((member && member.dashboard) || "").split("#")[0].replace(/\/+$/, "");
return new URL(path, base).href;
}
// A subscribed node's message written out, read from it (its console's
// `messages/own/{seq}`) with this page's narrow token, kept on the message once read.
async function writtenOut(message) {
if (typeof message.text === "string") return message.text;
if (!narrowToken) throw new Error(tokenWhy);
const response = await fetch(endpointOf(message.node, "dashboard/messages/own/" + message.ownSeq),
{ cache: "no-store", headers: { Authorization: "Bearer " + narrowToken.token } });
const answer = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(response.status + " " + (answer.error || response.statusText));
message.text = String(answer.text);
return message.text;
}
// Server-sent events from `url`, read with this page's narrow token (`EventSource`
// can't send one): `opened` once answered, `event(kind, data)` for each; rejects when it
// fails or ends (`offline`: the node stopped).
async function read(url, signal, opened, event) {
const response = await fetch(url, { signal, cache: "no-store",
headers: { Authorization: "Bearer " + narrowToken.token, Accept: "text/event-stream" } });
if (!response.ok) {
const answer = await response.json().catch(() => ({}));
throw new Error(response.status + " " + (answer.error || response.statusText));
}
opened();
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
for (;;) {
const { value, done } = await reader.read();
if (done) throw new Error("its stream ended");
buffer += value.replace(/\r/g, "");
let end;
while ((end = buffer.indexOf("\n\n")) >= 0) {
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
let kind = "message";
const data = [];
for (const line of block.split("\n")) {
if (line.startsWith("event:")) kind = line.slice(6).trim();
else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
}
if (kind === "offline") throw new Error("it stopped");
event(kind, data.join("\n"));
}
}
}
// A node's menu (right-click): subscribing to its links, or no longer; going to its
// dashboard, greyed where it publishes none (`--dashboard-url`), and on this node's own,
// which is here.
function nodeMenu(id, x, y) {
const menu = document.getElementById("node-menu");
const member = state.graph.members[id] || {};
const item = (label, enabled, act) => {
const button = el("button", { type: "button" }, label);
button.disabled = !enabled;
button.addEventListener("click", () => { menu.hidden = true; act(); });
return button;
};
menu.replaceChildren(
item(subscriptions.has(id) ? "unsubscribe" : "subscribe to its links", !member.self,
() => toggleSubscription(id)),
item("go to its dashboard", !member.self && !!member.dashboard, () => openDashboard(id)));
const goto = menu.lastElementChild;
goto.title = member.self ? "this node's: here" : member.dashboard ? member.dashboard.split("#")[0]
: "it publishes no dashboard (--dashboard-url)";
menu.hidden = false;
menu.style.left = Math.min(x, innerWidth - menu.offsetWidth - 8) + "px";
menu.style.top = Math.min(y, innerHeight - menu.offsetHeight - 8) + "px";
}
addEventListener("pointerdown", event => {
for (const id of ["node-menu", "user-menu", "entry-menu"]) {
const menu = document.getElementById(id);
if (!menu.hidden && !menu.contains(event.target) && event.target.id !== "who") {
menu.hidden = true;
}
}
}, true);
addEventListener("keydown", event => {
if (event.key !== "Escape") return;
document.getElementById("node-menu").hidden = true;
document.getElementById("user-menu").hidden = true;
document.getElementById("entry-menu").hidden = true;
});
// A node's dashboard, where it publishes one (`--dashboard-url`, in the member list),
// opened in this page; else its halo flashes red, larger than usual, and "no dashboard"
// rises from it in the same red, both fading out. This node's own: here already.
const FLASH_MS = 1200;
async function openDashboard(id) {
const member = state.graph.members[id];
if (!member || member.self) return;
if (member.dashboard) {
let handed = null;
if (token) {
try {
handed = (await tokenCall("../auth/refresh", token.token,
{ limit: READ_MEMBERS, lifetime: 300 })).token;
} catch (_) { /* the other dashboard asks for a login then */ }
}
location.assign(member.dashboard.split("#")[0] + handOff(id, handed));
return;
}
const layer = document.getElementById("flashes");
const halo = svg("circle", { r: 17, fill: "var(--bad)", "fill-opacity": .5 });
const words = svg("text", { "text-anchor": "middle", "font-size": 12, "font-weight": 600,
fill: "var(--bad)", "fill-opacity": .5 });
words.textContent = "no dashboard";
layer.append(halo, words);
const started = performance.now();
const step = now => {
const p = positions.get(id);
const t = Math.min(1, Math.max(0, (now - started) / FLASH_MS));
if (!p || t >= 1) {
halo.remove();
words.remove();
return;
}
const opacity = String(1 - t);
halo.setAttribute("cx", p.x);
halo.setAttribute("cy", p.y);
halo.setAttribute("opacity", opacity);
// Up on the screen, however the map is turned or zoomed: from above the node, slowly.
const [x, y] = turned(0, -(22 + (calm.matches ? 0 : 30 * t)), -view.turn);
const attrs = upright({ x: p.x + x / view.k, y: p.y + y / view.k });
words.setAttribute("x", attrs.x);
words.setAttribute("y", attrs.y);
if (attrs.transform) words.setAttribute("transform", attrs.transform);
else words.removeAttribute("transform");
words.setAttribute("opacity", opacity);
requestAnimationFrame(step);
};
requestAnimationFrame(step);
}
// Nodes that entered a new epoch (a remake: `remakes.md`) shine: a golden halo grows
// from the node and fades, as a breath, larger. Their epochs come from `/peers` (this
// node's, `localEpoch`, and each peer's) and from the links members report
// (`graph.measured`, each with the epoch its member said it is in), so for every member
// that reports. Only a later generation than the page knew shines, and only from a
// report of the last two minutes: a late or older report doesn't make it shine again.
const SHINE_MS = 1600, SHINE_FRESH_SECS = 120;
const knownEpochs = new Map();
function epochsArrived() {
if (!state) return;
const seen = [];
if (state.peers.localEpoch) seen.push([state.node.id, state.peers.localEpoch, 0]);
for (const [id, peer] of Object.entries(state.peers.peers)) {
if (peer.epoch) seen.push([id, peer.epoch, 0]);
}
for (const [id, report] of Object.entries(state.graph.measured)) {
if (report.epoch) seen.push([id, report.epoch, report.secsAgo || 0]);
}
for (const [id, epoch, secsAgo] of seen) {
const was = knownEpochs.get(id);
if (was !== undefined && epoch.generation <= was) continue;
if (was !== undefined && secsAgo <= SHINE_FRESH_SECS) shine(id);
knownEpochs.set(id, epoch.generation);
}
}
function shine(id) {
breathe(id, { fill: "#f59e0b", rim: "#fbbf24", to: 46, ms: SHINE_MS, opacity: .55 });
}
// A halo growing from node `id` from about its size `to` a radius, in and out as a
// breath over `ms`, at most `opacity` (the rim more); staying its size where motion is
// to be calm. Above the nodes (`flashes`).
function breathe(id, { fill, rim, to, ms, opacity }) {
if (document.hidden || !positions.has(id)) return;
const layer = document.getElementById("flashes");
const halo = svg("circle", { fill, stroke: rim, "stroke-width": 3 });
layer.append(halo);
const started = performance.now();
const step = now => {
const p = positions.get(id);
const t = Math.min(1, Math.max(0, (now - started) / ms));
if (!p || t >= 1) {
halo.remove();
return;
}
halo.setAttribute("cx", p.x);
halo.setAttribute("cy", p.y);
halo.setAttribute("r", calm.matches ? (10 + to) / 2 : 10 + (to - 10) * Math.sqrt(t));
halo.setAttribute("fill-opacity", (opacity * Math.sin(Math.PI * t)).toFixed(2));
halo.setAttribute("stroke-opacity", (Math.min(1, opacity * 1.6) * Math.sin(Math.PI * t)).toFixed(2));
requestAnimationFrame(step);
};
requestAnimationFrame(step);
}
// Remakes on the map (`remakes` in the snapshot: those of this node's epoch, with their
// coordinator, phase and voters). While one is open (proposed, or committed until they
// switch), its coordinator and voters are amber, the coordinator with a halo; a small
// amber breath as one is proposed (its coordinator) and as each vote comes. Decided, a
// pop over all of them: green if committed, red if aborted or expired, and they turn
// back. Only changes seen while the page is open: those of before show as they are.
const AMBER = "#f59e0b";
const knownRemakes = new Map();
let remakesKnown = false;
function remakesArrived() {
if (!state) return;
const remakes = state.remakes || [];
const seen = new Set();
const pop = (remake, fill) => {
for (const id of new Set([remake.coordinator, ...remake.voters])) {
breathe(id, { fill, rim: fill, to: 26, ms: 600, opacity: .6 });
}
};
countdowns.clear();
for (const remake of remakes) {
seen.add(remake.id);
// Settling: how long its votes are collected; committed: this node's wait to switch.
// Anchored when first seen, not with every update (each moved it by however old the
// update was: jumps, with short waits), and from there on whole: it starts and ends
// at the top, even where most of the wait was over before this page saw it.
const [kind, left] = remake.phase === "proposed" && typeof remake.settleInMs === "number"
? ["settle", remake.settleInMs]
: remake.phase === "committed" && typeof remake.switchInMs === "number" &&
remake.switchDelayMs > 0 ? ["switch", remake.switchInMs] : [null, 0];
const key = remake.id + " " + kind;
if (kind && !anchors.has(key)) {
anchors.set(key, { until: performance.now() + left, total: Math.max(1, left) });
}
// Committed and over (it switches any moment): an empty ring, not a whole one again.
const anchor = anchors.get(key) ||
(remake.phase === "committed" && anchors.get(remake.id + " switch"));
if (anchor) countdowns.set(remake.coordinator, { ...anchor, kind: kind || "switch" });
const was = knownRemakes.get(remake.id);
if (remakesKnown) {
const breath = id => breathe(id, { fill: AMBER, rim: AMBER, to: 20, ms: 900, opacity: .45 });
if (!was && remake.phase === "proposed") breath(remake.coordinator);
// The coordinator's own vote with its proposal: one breath.
const before = new Set(was ? was.voters : [remake.coordinator]);
if (remake.phase === "proposed" || (was && was.phase === "proposed")) {
for (const voter of remake.voters) if (!before.has(voter)) breath(voter);
}
if (was && was.phase === "proposed" && remake.phase !== "proposed") {
pop(remake, remake.phase === "committed" ? "#16a34a" : "#dc2626");
}
}
knownRemakes.set(remake.id, remake);
}
if (countdowns.size > 0 && countdownFrame === null) {
countdownFrame = requestAnimationFrame(tickCountdowns);
}
// Gone from the snapshot: this node switched to the next epoch (the records stay in
// the old one's document). Committed then, if it was still open.
for (const [id, remake] of knownRemakes) {
if (seen.has(id)) continue;
if (remake.phase === "proposed" &&
(knownEpochs.get(state.node.id) || 0) > remake.fromGeneration) {
pop(remake, "#16a34a");
}
knownRemakes.delete(id);
}
for (const key of anchors.keys()) if (!seen.has(key.split(" ")[0])) anchors.delete(key);
remakesKnown = true;
}
// Open remakes' coordinators, by node ID: when the wait ends (by `performance.now()`),
// the whole wait (ms), and which: `settle` (votes collected) or `switch` (committed,
// this node's wait to switch). Each is a golden halo, whole at first, waning
// counterclockwise to the top as the wait runs out: the votes', then, once committed,
// whole again, the switch's, gone as the epoch switches.
const countdowns = new Map();
// The halo's radius: within the one of a node in focus (13), drawn over it.
const COUNTDOWN_R = 11;
// When each wait was first seen (`remakesArrived`), by remake ID and kind.
const anchors = new Map();
let countdownFrame = null;
// The ring's dashes for `id` (radius `r`), if it counts: the part filled, or left.
function countdownDash(id, r) {
const countdown = countdowns.get(id);
if (!countdown) return null;
const left = Math.min(1, Math.max(0, (countdown.until - performance.now()) / countdown.total));
const around = 2 * Math.PI * r;
return (around * left).toFixed(1) + " " + around.toFixed(1);
}
// Where a halo at `p` starts: a circle's stroke starts at its right and goes clockwise;
// turned a quarter back (and back from the map's own turn, `view`), it starts at the
// top of the screen, so what is left ends further back counterclockwise as it wanes.
function countdownTurn(p) {
return "rotate(" + (-90 - degrees(view.turn)) + " " + p.x + " " + p.y + ")";
}
// Every frame while a halo counts: its dashes and where they start, nothing else drawn
// anew. Both: a key's element may have been drawn before it counted, and then it
// starts at its right, going clockwise, until the next render turns it.
function tickCountdowns() {
countdownFrame = null;
const now = performance.now();
if (document.hidden || ![...countdowns.values()].some(c => c.until > now - 100)) return;
// A wait just over: drawn anew, for what shows then (`render`: a question mark, or
// nothing).
const ended = [...countdowns.values()].filter(c => c.until <= now && !c.ended);
for (const countdown of ended) countdown.ended = true;
if (ended.length) renderGraph();
for (const id of countdowns.keys()) {
const ring = drawn.get("countdown " + id);
if (ring && ring.isConnected) {
const dash = countdownDash(id, Number(ring.getAttribute("r")));
if (dash) {
ring.setAttribute("stroke-dasharray", dash);
ring.setAttribute("transform", countdownTurn(
{ x: Number(ring.getAttribute("cx")), y: Number(ring.getAttribute("cy")) }));
}
}
}
countdownFrame = requestAnimationFrame(tickCountdowns);
}
// Who is amber now (`remakesArrived`), and who of them coordinates: of the open
// remakes, those not past the epoch yet (`knownEpochs`).
function inRemakes() {
const amber = new Set(), coordinating = new Set();
for (const remake of (state && state.remakes) || []) {
if (remake.phase !== "proposed" && remake.phase !== "committed") continue;
const still = id => (knownEpochs.get(id) || 0) <= remake.fromGeneration;
for (const id of [remake.coordinator, ...remake.voters]) if (still(id)) amber.add(id);
if (still(remake.coordinator)) coordinating.add(remake.coordinator);
}
return { amber, coordinating };
}
// A dragged node let go of: dynamic, it moves to its place among the others again;
// dragged with the middle button, it is pinned there.
function dropped() {
if (grabbed === null) return;
const id = grabbed;
grabbed = null;
if (dragMoved && middlePress) {
pin(id);
return;
}
if (byRtt) settle();
}
// A node pinned where it is: the layout leaves it there.
function pin(id) {
pinned.add(id);
renderGraph();
}
// A node let go: on a dynamic map, it moves to its place among the others, smoothly
// (`settle`); on a static one, it stays where it is, as every node there does.
function unpin(id) {
if (!pinned.delete(id)) return;
renderGraph();
if (byRtt) settle();
}
// Beside the nodes, or off the map: nothing hovered (the element left may be gone).
graph.addEventListener("mousemove", event => { if (event.target === graph) hover(null); });
graph.addEventListener("mouseleave", () => hover(null));
// --- Messages on the map: this node's messages with its peers (`ownMessagesArrived`)
// and each subscribed node's (`remoteMessagesArrived`), as their streams bring them,
// soon after they went, drawn as dots running along the link the way the messages
// went, as far apart as they were sent, a few at most per link and way of a batch: a
// picture of the traffic, not a record of it. As dots, all at one speed (`flowSpeed`), so over a longer link they
// arrive later; as flashes, each crosses its link as fast as the message did (half the
// link's round trip) and leaves an afterglow that draws back into where it went
// (`FLASH_GLOW_MS`). Dots are kept above everything else on the map (`flows`, after
// what `show` places), flashes over the lines but below their labels and the nodes. ---
const FLOWS_AT_MOST = 6;
// The timeline the messages run on (`runMessages`, below).
const REPLAY_WINDOW_MS = 30000, REPLAY_MARGIN_MS = 100, REPLAY_LEAST_MS = 150,
REPLAY_MOST_MS = 10000;
// By node whose stream it is: [when, lag] of its recent batches, the oldest first.
const lags = new Map();
let replayDelay = 500;
let clocksKnown = null, clocksAt = -Infinity;
// The line from `from` to `to` a message went over, as drawn: over `transport`'s
// line, else (none known, or none drawn for it) the one in use. `at(t)`: the point `t`
// along (0 at `from`, 1 at `to`) and the direction there (a unit vector); `length`,
// about how long it is. Null while an end isn't on the map.
function route(from, to, transport) {
const p = positions.get(from), q = positions.get(to);
if (!p || !q) return null;
const drawnRoute = routes.get(pairKey(from, to));
const known = drawnRoute && transport && drawnRoute.sides.get(transport);
// Bowing out to the left of the way from `a`: to the right of the other way.
const side = (known || 0) * (drawnRoute && drawnRoute.a !== from ? -1 : 1);
const chord = Math.max(Math.hypot(q.x - p.x, q.y - p.y), 1);
const nx = -(q.y - p.y) / chord, ny = (q.x - p.x) / chord;
// The quadratic curve the line is: its control point twice as far out as it bows.
const c = { x: (p.x + q.x) / 2 + nx * side * 2, y: (p.y + q.y) / 2 + ny * side * 2 };
const length = (chord + Math.hypot(c.x - p.x, c.y - p.y) + Math.hypot(q.x - c.x, q.y - c.y)) / 2;
const at = t => {
const u = 1 - t;
const dx = 2 * u * (c.x - p.x) + 2 * t * (q.x - c.x);
const dy = 2 * u * (c.y - p.y) + 2 * t * (q.y - c.y);
const d = Math.max(Math.hypot(dx, dy), 1e-6);
return { x: u * u * p.x + 2 * u * t * c.x + t * t * q.x,
y: u * u * p.y + 2 * u * t * c.y + t * t * q.y, ux: dx / d, uy: dy / d };
};
return { length, at };
}
// The transport an address is of (`mycelium://…` is Mycelium's), as the links name it.
const schemeOf = address => address ? address.split(":")[0] : null;
// A flash's afterglow, after it arrived; and how long it takes over a link whose round
// trip isn't known.
const FLASH_GLOW_MS = 700, FLASH_UNKNOWN_MS = 50;
// How they are shown (`flows-toggle`, kept in this browser; dots at first): `dots`,
// `flash` or `off`.
const FLOW_MODES = ["dots", "flash", "off"];
let flowsMode = "dots";
try {
const kept = localStorage.getItem("continuum-flows");
flowsMode = FLOW_MODES.includes(kept) ? kept : kept === "0" ? "off" : "dots";
} catch (_) {}
let flowsShown = flowsMode !== "off";
const flowsToggle = document.getElementById("flows-toggle");
function showFlowsToggle() {
const next = FLOW_MODES[(FLOW_MODES.indexOf(flowsMode) + 1) % FLOW_MODES.length];
flowsToggle.textContent = "messages: " + flowsMode;
flowsToggle.title = "Click for " + (next === "off" ? "none"
: next === "dots" ? "dots running along the links"
: "flashes: each as fast as the message, with an afterglow toward where it went");
}
showFlowsToggle();
flowsToggle.addEventListener("click", () => {
flowsMode = FLOW_MODES[(FLOW_MODES.indexOf(flowsMode) + 1) % FLOW_MODES.length];
flowsShown = flowsMode !== "off";
try { localStorage.setItem("continuum-flows", flowsMode); } catch (_) {}
showFlowsToggle();
showMessagesLegend();
if (!flowsShown) {
flows.length = 0;
document.getElementById("flow-dots").replaceChildren();
document.getElementById("flow-streaks").replaceChildren();
}
});
// How long a message takes from `from` to `to`: half the round trip either end
// measured, as the map has it (`FLASH_UNKNOWN_MS` if neither did).
function oneWayMs(from, to) {
for (const [a, b] of [[from, to], [to, from]]) {
const report = state && state.graph.measured[a];
const link = report && (report.links || []).find(link => link.peer === b);
if (link && typeof link.rttMs === "number") return link.rttMs / 2;
}
return FLASH_UNKNOWN_MS;
}
let lastTraffic = null;
const flows = [];
let flowFrame = null;
// Messages and bytes by kind, of a peer's `traffic.sent` or `.received`.
function messages(byKind) {
return Object.fromEntries(Object.entries(byKind || {})
.map(([kind, counter]) => [kind, { messages: counter.messages, bytes: counter.bytes }]));
}
// The colour of a kind of message (`traffic`'s kinds, each of them), on the map and in
// the console, and what the legend calls it; the replies as their requests.
const KIND_COLOURS = [["sync", "#ea580c"], ["blob", "#a16207"], ["hello", "#16a34a"],
["status", "#e11d48"], ["identity", "#0d9488"], ["paths", "var(--muted)"],
["probe", "#6366f1"], ["plumtree", "#c026d3"], ["hyparview", "#0369a1"],
["refusals", "#b91c1c"]];
const KIND_NAMES = { identity: "identity (who/me)", paths: "paths (pings)",
plumtree: "plumtree (prune/graft)", hyparview: "hyparview (neighbour)" };
const kindColour = kind => (KIND_COLOURS.find(([name]) => kind === name ||
kind === name + "Reply") || [null, "var(--fg)"])[1];
// How large the dots are drawn, times `dotRadius` (the slider after their legend, kept
// in this browser).
let dotScale = 2;
try { dotScale = Number(localStorage.getItem("continuum-dot-scale")) || 2; } catch (_) {}
dotScale = Math.min(4, Math.max(1.25, dotScale));
// How fast the dots run, in map units per ms (the slider after the size's, kept in this
// browser): .3 crosses a link of 200 in about 0.7 s.
let flowSpeed = .3;
try { flowSpeed = Number(localStorage.getItem("continuum-dot-speed")) || .3; } catch (_) {}
flowSpeed = Math.min(.9, Math.max(.1, flowSpeed));
let dotSlider = null, speedSlider = null;
function showMessagesLegend() {
const legend = document.getElementById("messages-legend");
legend.classList.toggle("off", !flowsShown);
if (dotSlider === null) {
const slider = dotSlider = el("input", { type: "range", min: "1.25", max: "4", step: ".25",
title: "How large the dots are" });
slider.value = String(dotScale);
slider.addEventListener("input", () => {
dotScale = Number(slider.value);
try { localStorage.setItem("continuum-dot-scale", String(dotScale)); } catch (_) {}
});
const speed = speedSlider = el("input", { type: "range", min: ".1", max: ".9", step: ".1",
title: "How fast the dots run (flashes run as fast as the messages did)" });
speed.value = String(flowSpeed);
speed.addEventListener("input", () => {
flowSpeed = Number(speed.value);
try { localStorage.setItem("continuum-dot-speed", String(flowSpeed)); } catch (_) {}
});
// Before the toggle, which ends the line.
legend.prepend(...KIND_COLOURS.map(([kind, colour]) =>
el("span", { class: "message", style: "--colour: " + colour },
KIND_NAMES[kind] || kind)),
el("label", { class: "slider" }, "size", slider),
el("label", { class: "slider" }, "speed", speed),
el("span", { id: "replay-delay", class: "hint" }));
document.getElementById("replay-delay").addEventListener("pointerenter", explainReplay);
showReplay();
}
dotSlider.disabled = !flowsShown;
speedSlider.disabled = flowsMode !== "dots";
}
showMessagesLegend();
// A dot's radius for a message of `bytes`: grows with the size's logarithm, from 1.5
// (a ping) to 8.
const dotRadius = bytes => Math.min(8, Math.max(1.5, 1.5 + 1.1 * Math.log10(1 + bytes / 32)));
// The dots for messages that grew by `kinds` (kind: messages, bytes): `FLOWS_AT_MOST`
// at most, shared out by kind (one each at least, the busiest first), each as large as
// its kind's messages on average; interleaved.
function dotsFor(kinds, total) {
const byKind = Object.entries(kinds).sort(([, a], [, b]) => b.messages - a.messages)
.map(([kind, grown]) => ({ kind, bytes: grown.bytes / grown.messages,
count: Math.min(grown.messages, Math.max(1, Math.round(FLOWS_AT_MOST * grown.messages / total))) }));
const dots = [];
for (let round = 0; dots.length < FLOWS_AT_MOST && byKind.some(k => k.count > round); round++) {
for (const kind of byKind) {
if (kind.count > round && dots.length < FLOWS_AT_MOST) dots.push(kind);
}
}
return dots;
}
// This node's traffic with each peer, as the update brings it: its rates, and what its
// peers should have received (`deliveredHere`). The map runs messages from the message
// logs instead, as they come (`runMessages`).
function trafficArrived() {
if (!state) return;
const self = state.node.id;
const current = new Map();
for (const [id, peer] of Object.entries(state.peers.peers)) {
if (peer.traffic) {
current.set(id, { sent: messages(peer.traffic.sent),
received: messages(peer.traffic.received) });
}
}
if (lastTraffic) deliveredHere(self, current, lastTraffic);
measureRates(current);
lastTraffic = current;
}
// Whether messages run on the map now: shown, and seen.
function flowsNow() {
return flowsShown && !calm.matches && !document.hidden &&
!document.getElementById("map").classList.contains("collapsed");
}
// --- One timeline for the map's messages: each stream (this node's, each subscribed
// node's) comes over its own way, the slower ones later, so messages run not as they
// arrive but when they were logged, on this node's clock (each node's `at` taken back by
// how far its clock is ahead of this node's, as the map chains them: `aheadOf`), a
// while behind (`replayDelay`): as long as the slowest stream lagged within the last
// `REPLAY_WINDOW_MS`, and a margin. So messages of different nodes run as far apart
// as they went, give or take how well their clocks are known. The browser's own clock
// is against all of them alike, so it drops out. ---
// How far `node`'s clock is ahead of this node's, as the map chains them (`swarmClocks`,
// worked out again at most every second); 0 where not known.
function aheadOf(node) {
if (!state || node === state.node.id) return 0;
const now = performance.now();
if (now - clocksAt > 1000) {
clocksKnown = swarmClocks();
clocksAt = now;
}
const self = clocksKnown[state.node.id], it = clocksKnown[node];
return self && it ? it.offsetMs - self.offsetMs : 0;
}
// A batch of `node`'s stream came, sent by it at `sent` (its clock): how long its
// messages lagged, the most of them (by the browser's clock against this node's,
// `aheadOf`), which the delay must cover; and of that, how long they waited in the node
// (`sent` against when it logged them: its own clock, exact) and how long the batch took
// on the way (from `sent`, by the clocks as known). A batch of a gap (lagging more than
// `REPLAY_MOST_MS`) counts for nothing: it would hold the map that far behind for a while.
function noteStream(node, list, sent) {
if (!state || list.length === 0) return;
const ahead = aheadOf(node), wall = Date.now(), now = performance.now();
const earliest = Math.min(...list.map(message => message.at));
const lag = wall - (earliest - ahead);
if (lag > REPLAY_MOST_MS) return;
const inNode = typeof sent === "number" ? sent - earliest : null;
const way = typeof sent === "number" ? wall - (sent - ahead) : null;
const kept = (lags.get(node) || []).filter(([at]) => now - at <= REPLAY_WINDOW_MS);
kept.push([now, lag, inNode, way]);
lags.set(node, kept);
for (const [other, samples] of lags) {
if (!samples.some(([at]) => now - at <= REPLAY_WINDOW_MS)) lags.delete(other);
}
const slowest = Math.max(...[...lags.values()].flat().map(([, lag]) => lag));
replayDelay = Math.min(REPLAY_MOST_MS, Math.max(REPLAY_LEAST_MS, slowest + REPLAY_MARGIN_MS));
showReplay();
}
// `behind: …` in the messages' legend: how far behind they run, and in its tooltip how
// that came about: the stream that lagged the most within the window, plus the margin
// (or the bounds, where they held it), and the three slowest streams, each with the
// most and least it lagged. Lags are as the page measures them, by the browser's
// clock against this node's: one that is off adds to all of them alike. The tooltip is
// written as the pointer comes onto it, and stays as it is while it's there (a tooltip
// changing under the pointer goes away).
function showReplay() {
const shown = document.getElementById("replay-delay");
if (!shown) return;
// Its text node kept, its text changed: the element under the pointer stays itself.
const words = "behind: " + (replayDelay / 1000).toFixed(2) + " s";
if (shown.firstChild) shown.firstChild.data = words;
else shown.textContent = words;
}
function explainReplay() {
const shown = document.getElementById("replay-delay");
if (!shown || !state) return;
const s = ms => (ms / 1000).toFixed(2) + " s";
const range = values => values.length === 0 ? "?"
: Math.min(...values) === Math.max(...values) ? s(values[0])
: s(Math.min(...values)) + "–" + s(Math.max(...values));
const self = state.node.id;
const each = [...lags].map(([node, samples]) => {
const of = i => samples.map(sample => sample[i]).filter(value => typeof value === "number");
return { node, least: Math.min(...of(1)), most: Math.max(...of(1)),
inNode: of(2), way: of(3) };
}).sort((x, y) => y.most - x.most);
if (each.length === 0) {
shown.title = "Messages run when they went, this far behind real time; no stream yet.";
return;
}
const slowest = each[0];
const bound = slowest.most + REPLAY_MARGIN_MS < REPLAY_LEAST_MS ? ", raised to the least, " + s(REPLAY_LEAST_MS)
: slowest.most + REPLAY_MARGIN_MS > REPLAY_MOST_MS ? ", cut to the most, " + s(REPLAY_MOST_MS) : "";
const line = ({ node, least, most, inNode, way }) =>
(node === self ? "this node (" + name(node) + ")" : name(node)) + ": " + s(most) +
" (least " + s(least) + "); in the node " + range(inNode) + ", on the way " + range(way);
// The three slowest, and this node's own stream always.
const listed = each.slice(0, 3);
const own = each.find(stream => stream.node === self);
if (own && !listed.includes(own)) listed.push(own);
shown.title = "Messages run when they went, this far behind real time, so the slowest" +
" stream's are in too:\n" + s(replayDelay) + " = " + name(slowest.node) + "'s lag, the most" +
" of any stream in the last 30 s (" + s(slowest.most) + "), + " + s(REPLAY_MARGIN_MS) +
bound + "\n\nThe slowest streams, and this node's (the most and the least each lagged," +
" last 30 s; of that, how long a batch waited in its node, from logging its first" +
" message to sending it, and took on the way, from sending to arriving):\n" +
listed.map((stream, i) => (each.indexOf(stream) + 1) + ". " + line(stream)).join("\n") +
(each.length > listed.length ? "\n(" + (each.length - listed.length) + " more)" : "");
}
// Messages as `node`'s stream brought them (each named by both ends, `from` and `to`;
// `arrived`: logged by its receiver, the sender's not read, so it went its link's
// crossing before), run along their links at their places on the timeline.
// `FLOWS_AT_MOST` at most per link and way of a batch, shared out by kind (`dotsFor`)
// over the moment where more came. Those lagging more than `REPLAY_MOST_MS` (after a
// gap: the computer slept, the stream stalled) don't run.
function runMessages(list, node) {
if (list.length === 0 || !state) return;
const ahead = aheadOf(node), wall = Date.now(), now = performance.now();
// On the timeline: when the message was logged, as `performance.now()` has it, now
// and behind.
const placed = list.map(message => ({ ...message, lag: wall - (message.at - ahead) }));
if (!flowsNow()) return;
const links = new Map();
for (const message of placed) {
if (message.lag > REPLAY_MOST_MS) continue;
const transport = schemeOf(message.address);
const key = message.from + " " + message.to + " " + (transport || "") +
(message.arrived ? " arrived" : "");
const link = links.get(key) ||
{ from: message.from, to: message.to, transport, arrived: !!message.arrived, messages: [] };
link.messages.push(message);
links.set(key, link);
}
const at = message => now + replayDelay - message.lag;
for (const { from, to, transport, arrived, messages: sent } of links.values()) {
if (sent.length <= FLOWS_AT_MOST) {
for (const message of sent) {
flows.push({ from, to, transport, arrived, at: at(message), kind: message.counted,
r: dotRadius(message.bytes) });
}
continue;
}
const kinds = {};
for (const message of sent) {
const kind = kinds[message.counted] || (kinds[message.counted] = { messages: 0, bytes: 0 });
kind.messages += 1;
kind.bytes += message.bytes;
}
const times = sent.map(at), first = Math.min(...times), span = Math.max(...times) - first;
const shown = dotsFor(kinds, sent.length);
shown.forEach((dot, i) => {
flows.push({ from, to, transport, arrived, at: first + i * span / shown.length,
kind: dot.kind, r: dotRadius(dot.bytes) });
});
}
if (flows.length > 0 && flowFrame === null) flowFrame = requestAnimationFrame(drawFlows);
}
// This node's messages, as its stream brings them (`messages` events): listed in the
// console, and run along its links, those it sent, and those it received from a node
// whose messages the page doesn't read (a subscribed node's run from it, as they left).
function ownMessagesArrived(list, sent) {
messagesArrived(list);
if (!state) return;
noteStream(state.node.id, list, sent);
const self = state.node.id;
runMessages(list.filter(message => message.way === "sent" ||
(message.way === "received" && !logging(message.peer)))
.map(message => ({ ...message, arrived: message.way === "received",
from: message.way === "sent" ? self : message.peer,
to: message.way === "sent" ? message.peer : self })), self);
}
// A subscribed node's messages (`follow`), as they come: listed in the console and
// run along its links, as this node's own. Its messages with this node are this node's
// to show, and what it received from another subscribed node that one's (as what it
// sent): each message once. Each named by both ends (`from`, `to`) and the node that
// logged it (`node`), its number and exchange made its own (`node:seq`).
function remoteMessagesArrived(id, entry, list, sent) {
if (!state || id === state.node.id) return;
noteStream(id, list, sent);
const self = state.node.id;
// Its messages come whole, those since the last event, up to the latest 500: one
// missing between (a busy moment) leaves what was delivered unknown for now.
if (list.length > 0) {
if (entry.lastSeq !== undefined && list[0].seq !== entry.lastSeq + 1) forgetDeliveries(id);
entry.lastSeq = list[list.length - 1].seq;
}
// For the console: its messages with others than this node (this node's own log has
// those), each message once. For the map: each message as it left, from its sender
// where the page reads the sender's messages (this node's own counts, or a
// subscribed node's), so it runs the way it went; else as it arrived.
const kept = [], running = [];
for (const message of list) {
if (message.way === "refused") continue;
const [from, to] = message.way === "sent" ? [id, message.peer] : [message.peer, id];
const made = { ...message, seq: id + ":" + message.seq, ownSeq: message.seq, node: id, from, to,
related: message.related ? id + ":" + message.related : null };
if (message.way === "sent") noteDelivery(from, to, message.counted, "sent");
else noteDelivery(from, to, message.counted, "got");
if (message.peer !== self && !(message.way === "received" && message.peer !== id &&
logging(message.peer))) kept.push(made);
if (message.way === "sent" || !(message.peer === self || logging(message.peer))) {
running.push({ ...made, arrived: message.way === "received" });
}
}
checkDeliveries();
runMessages(running, id);
if (kept.length > 0) messagesArrived(kept);
}
// Whether the page reads `id`'s messages one by one: a subscribed node's, while they
// come.
const logging = id => subscriptions.has(id) && (subscribed.get(id) || {}).messagesLive === true;
// --- Messages that didn't arrive: where the page reads both ends of a link (this node's
// counts, or a subscribed node's messages), what one sent the other should count
// received. Sent but not received within `DELIVERY_GRACE_MS` (both come every 2 s, each
// on its own tick), the link breathes red (`breatheLink`). By message, of every kind but
// those the paths and identity layers count under the address rather than the node
// (this node's counts leave them out). Kept from when both ends are read; forgotten
// when either isn't any more, or a tick of either came short. ---
const DELIVERY_GRACE_MS = 5000, UNCOUNTED = new Set(["paths", "identity"]);
// By `from to`: `sent` and `got`, each a queue of [when, how many], the oldest first.
const deliveries = new Map();
const readHere = id => state !== null && (id === state.node.id || logging(id));
function noteDelivery(from, to, kind, which, count = 1) {
if (UNCOUNTED.has(kind) || count <= 0) return;
const key = from + " " + to;
if (!flowsShown || !readHere(from) || !readHere(to)) { deliveries.delete(key); return; }
const record = deliveries.get(key) || { from, to, sent: [], got: [] };
record[which].push([performance.now(), count]);
deliveries.set(key, record);
}
function forgetDeliveries(id) {
for (const [key, record] of deliveries) {
if (record.from === id || record.to === id) deliveries.delete(key);
}
}
// This node's counts, as they grew since the last update: by peer, what it sent and
// received, each kind counted.
function deliveredHere(self, current, before) {
for (const [id, counts] of current) {
const was = before.get(id);
if (!was) continue;
for (const [way, from, to, which] of [["sent", self, id, "sent"], ["received", id, self, "got"]]) {
for (const [kind, count] of Object.entries(counts[way])) {
const earlier = was[way][kind] || { messages: 0 };
noteDelivery(from, to, kind, which, count.messages - earlier.messages);
}
}
}
checkDeliveries();
}
// Received messages settle the oldest sent first; what was sent longer ago than the
// grace and is still unsettled didn't arrive. Received with nothing sent to settle (the
// sender's tick not in yet) waits as long again, then goes.
function checkDeliveries() {
const now = performance.now();
for (const [key, record] of deliveries) {
const { sent, got } = record;
while (sent.length > 0 && got.length > 0) {
const settled = Math.min(sent[0][1], got[0][1]);
sent[0][1] -= settled;
got[0][1] -= settled;
if (sent[0][1] === 0) sent.shift();
if (got[0][1] === 0) got.shift();
}
let lost = 0;
while (sent.length > 0 && sent[0][0] <= now - DELIVERY_GRACE_MS) lost += sent.shift()[1];
while (got.length > 0 && got[0][0] <= now - 2 * DELIVERY_GRACE_MS) got.shift();
if (lost > 0) breatheLink(record.from, record.to, lost);
if (sent.length === 0 && got.length === 0) deliveries.delete(key);
}
}
// A red halo along the link `from`–`to` (its line in use), in and out once: `lost`
// messages sent over it didn't arrive. Below the flashes' layer's other breaths.
const LOST_MS = 1200;
function breatheLink(from, to, lost) {
if (document.hidden || !flowsShown) return;
const layer = document.getElementById("flashes");
const halo = svg("path", { fill: "none", stroke: "var(--bad)", "stroke-width": 10,
"stroke-linecap": "round", "pointer-events": "none" });
const title = svg("title");
title.textContent = lost + (lost === 1 ? " message " : " messages ") + name(from) +
" sent " + name(to) + " didn't arrive";
halo.append(title);
layer.prepend(halo);
const started = performance.now();
const step = now => {
const line = route(from, to, null);
const t = Math.min(1, Math.max(0, (now - started) / LOST_MS));
if (!line || t >= 1) {
halo.remove();
return;
}
const points = [];
for (let k = 0; k <= 12; k++) {
const point = line.at(k / 12);
points.push(point.x.toFixed(1) + " " + point.y.toFixed(1));
}
halo.setAttribute("d", "M" + points.join("L"));
halo.setAttribute("stroke-opacity", (.5 * Math.sin(Math.PI * t)).toFixed(2));
requestAnimationFrame(step);
};
requestAnimationFrame(step);
}
// --- The console's rates: messages and bytes per second sent and received, per peer
// and in all, averaged as load averages are, over 1, 5 and 15 minutes (each sample
// weighs in by how long ago it was, `e^(-age/window)`), from the counts each update
// brings. The first sample is taken as it is, so they needn't climb from 0 first. ---
const RATE_WINDOWS_S = [60, 300, 900];
// By peer, and in all (`null`): the averages (`messages`, `bytes`: per window); and when
// the counts were last taken.
const rates = new Map();
let ratesAt = null;
function measureRates(current) {
const now = performance.now();
if (lastTraffic !== null && ratesAt !== null && now > ratesAt) {
const secs = (now - ratesAt) / 1000;
// Of `what` (`messages`, `bytes`), sent and received, by how much each grew.
const grown = (counts, before, what) => ["sent", "received"].reduce((sum, way) => {
const total = of => Object.values(of[way]).reduce((sum, count) => sum + count[what], 0);
return sum + Math.max(0, total(counts) - total(before));
}, 0);
const average = (known, rate) => known ? known.map((average, i) =>
rate + (average - rate) * Math.exp(-secs / RATE_WINDOWS_S[i])) : RATE_WINDOWS_S.map(() => rate);
const sample = (key, messages, bytes) => {
const was = rates.get(key);
rates.set(key, { messages: average(was && was.messages, messages / secs),
bytes: average(was && was.bytes, bytes / secs) });
};
let messagesInAll = 0, bytesInAll = 0;
for (const [id, counts] of current) {
const before = lastTraffic.get(id);
if (!before) continue;
const messages = grown(counts, before, "messages");
const bytes = grown(counts, before, "bytes");
sample(id, messages, bytes);
messagesInAll += messages;
bytesInAll += bytes;
}
sample(null, messagesInAll, bytesInAll);
// Peers gone from the list: their averages too.
for (const key of [...rates.keys()]) if (key !== null && !current.has(key)) rates.delete(key);
}
ratesAt = now;
showRates();
}
// The averages shown: in all, or with the filter, of the peer in focus; none (–) for a
// link between other nodes, a node that is no peer, or before two updates came.
function showRates() {
const filtering = consoleFiltered && focused !== null;
const peer = filtering ? peerOf(focused) : null;
const shown = filtering && peer === null ? undefined : rates.get(peer);
const format = rate => rate < 100 ? rate.toFixed(2) : String(Math.round(rate));
// Bytes in the unit the largest of the three needs, all three alike.
const largest = shown ? Math.max(...shown.bytes) : 0;
const [unit, per] = largest < 1024 ? ["B/s", 1] : largest < 1048576 ? ["KiB/s", 1024]
: ["MiB/s", 1048576];
const row = (values, unit) => [...(values ? values.map(format) : ["–", "", ""]), unit];
const cells = [...row(shown && shown.messages, "msg/s"),
...row(shown && shown.bytes.map(bytes => bytes / per), unit)];
const box = document.getElementById("console-rates");
if (box.childElementCount !== cells.length) {
box.replaceChildren(...cells.map((_, i) => el("span", { class: i % 4 === 3 ? "unit" : "" })));
}
cells.forEach((cell, i) => text(box.children[i], cell));
}
// --- Console: the messages this node exchanged with its peers, one by one, as the
// node logs them (`messages` events, `traffic::MessageLog`), the latest at the bottom,
// `CONSOLE_LINES` at most. Scrolled along while at the bottom. A click on one shows it
// in the figures box (`shownMessage`). ---
const CONSOLE_LINES = 500;
// A time of day on the 24-hour clock, whatever the browser's locale: 18:04:05.123.
const clockTime = date => [date.getHours(), date.getMinutes(), date.getSeconds()]
.map(part => String(part).padStart(2, "0")).join(":") + "." +
String(date.getMilliseconds()).padStart(3, "0");
const size = bytes => bytes < 1024 ? bytes + " B" : bytes < 1048576
? (bytes / 1024).toFixed(1) + " KiB" : (bytes / 1048576).toFixed(1) + " MiB";
// The messages, kept while the box is collapsed and drawn when it's opened
// (`showConsole`).
const consoleMessages = [];
// The message shown in the figures box instead of what is in focus; null: none.
let shownMessage = null;
const WAYS = { sent: "→", received: "←", refused: "↛" };
// The exchange marked in the console (a message's `related`): the one of the message
// pointed at, else of the one shown; null: none.
let relatedMarked = null;
// The message pointed at in the console, if any: its nodes and link are marked on the
// map (`renderGraph`), else the shown one's.
let pointedMessage = null;
function pointAt(message) {
pointedMessage = message;
markRelated(message ? message.related : shownRelated());
if (state) renderGraph();
}
function markRelated(key) {
relatedMarked = key || null;
for (const line of document.getElementById("console").children) {
line.classList.toggle("related", relatedMarked !== null && line.dataset.related === relatedMarked);
}
}
const shownRelated = () => shownMessage && shownMessage.related;
// The peer whose messages `key` (a node, or a link's pair key) stands for: the node,
// or the other end of one of this node's links; null: none (this node itself, whose
// every message it would be, or a link between others).
function peerOf(key) {
if (key === null || !state) return null;
const self = state.node.id;
if (!isPair(key)) return key === self ? null : key;
const [a, b] = key.split(" ");
return a === self ? b : b === self ? a : null;
}
// A console line's tint for the node or link pointed at on the map, or in focus.
// Whether a message (its line's `data-…`: `peer` for this node's, `from` and `to` for a
// subscribed node's) is one with the node or over the link `key` stands for.
function about(data, key) {
if (key === null || !state) return false;
if (!data.peer) {
if (!data.from) return false;
return isPair(key) ? key === pairKey(data.from, data.to)
: key !== state.node.id && (data.from === key || data.to === key);
}
const peer = peerOf(key);
return peer !== null && data.peer === peer;
}
function peerClasses(message) {
const data = { peer: message.node ? "" : message.peer, from: message.from, to: message.to };
return (about(data, focused) ? " peer-focused" : "") +
(about(data, hovered) ? " peer-hovered" : "");
}
function markPeerMessages() {
for (const line of document.getElementById("console").children) {
line.classList.toggle("peer-focused", about(line.dataset, focused));
line.classList.toggle("peer-hovered", about(line.dataset, hovered));
}
filterConsole();
}
// `filter selected`: only the messages with the node or over the link in focus (those
// tinted for it, `peer-focused`), all while nothing is; where there are none (a link
// between other nodes, a node this one exchanges nothing with), a note. Pointing at
// one doesn't count. Kept in this browser.
let consoleFiltered = false;
try { consoleFiltered = localStorage.getItem("continuum-console-filter") === "1"; } catch (_) {}
const consoleFilter = document.getElementById("console-filter");
consoleFilter.checked = consoleFiltered;
consoleFilter.addEventListener("change", () => {
consoleFiltered = consoleFilter.checked;
try { localStorage.setItem("continuum-console-filter", consoleFiltered ? "1" : "0"); } catch (_) {}
filterConsole();
});
// What the console is filtered by (what is in focus), null: nothing. When it changes
// (filtered or not any more, or another focus), the console goes to the bottom, and
// follows from there.
let consoleView = null;
function filterConsole() {
showRates();
const log = document.getElementById("console");
const filtering = consoleFiltered && focused !== null;
log.classList.toggle("filtering", filtering);
document.getElementById("console-none").hidden =
!filtering || log.querySelector(":scope > div.peer-focused") !== null;
const view = filtering ? focused : null;
if (view !== consoleView) {
consoleView = view;
const scroll = document.getElementById("console-scroll");
scroll.scrollTop = scroll.scrollHeight;
}
}
// A line: when, which way, with whom, the type (in its kind's colour), the size, and the
// transport it went by (in its colour, the address in its tooltip), where known.
function consoleLine(message) {
// A subscribed node's (`remoteMessagesArrived`): its receiver, and whom from.
const between = message.node ? name(message.to) + " ← " + name(message.from) + " "
: WAYS[message.way] + " " + name(message.peer) + " ";
const line = el("div", { "data-seq": String(message.seq), "data-t": String(message.t || 0),
"data-related": message.related || "",
"data-peer": message.node ? "" : message.peer,
"data-from": message.from || "", "data-to": message.to || "",
class: (shownMessage && shownMessage.seq === message.seq ? "focused" : "") +
(relatedMarked !== null && message.related === relatedMarked ? " related" : "") +
peerClasses(message),
title: message.way === "refused" ? "refused: the transport wouldn't send it"
: message.node ? "logged by " + name(message.node) + ", subscribed to" : "" },
// On this node's clock, as they are ordered; by its node's own in the tooltip.
el("span", { class: "when", title: message.node && Math.round(message.t || message.at) !==
message.at ? "by " + name(message.node) + "'s clock " + clockTime(new Date(message.at)) : "" },
clockTime(new Date(Math.round(message.t || message.at))) + " "),
between,
el("span", { style: "color: " + kindColour(message.counted) }, message.type),
" " + size(message.bytes),
...(message.address ? [" ", el("span", { style: "color: " + colourOf(schemeOf(message.address)),
title: message.address }, schemeOf(message.address))] : []));
// On press, as the peers' rows: lines come and go under the pointer.
line.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
showMessage(shownMessage && shownMessage.seq === message.seq ? null : message);
});
// The messages of its exchange marked while pointed at; then the shown one's again.
line.addEventListener("pointerenter", () => pointAt(message));
line.addEventListener("pointerleave", () => pointAt(null));
return line;
}
function showMessage(message) {
shownMessage = message;
const log = document.getElementById("console");
for (const line of log.children) {
line.classList.toggle("focused", message !== null && line.dataset.seq === String(message.seq));
}
markRelated(message !== null ? message.related : null);
render();
}
// In the order they went, as the map runs them (`aheadOf`): each placed by when its node
// logged it, on this node's clock (`t`), among those that came before it, however late
// its node's stream brought it.
function messagesArrived(messages) {
for (const message of messages) {
message.t = message.at - (state ? aheadOf(message.node || state.node.id) : 0);
let i = consoleMessages.length;
while (i > 0 && consoleMessages[i - 1].t > message.t) i--;
consoleMessages.splice(i, 0, message);
}
consoleMessages.splice(0, Math.max(0, consoleMessages.length - CONSOLE_LINES));
if (hidden(document.getElementById("console-box"))) return;
const log = document.getElementById("console");
const scroll = document.getElementById("console-scroll");
const following = scroll.scrollTop + scroll.clientHeight >= scroll.scrollHeight - 4;
for (const message of messages.slice(-CONSOLE_LINES)) {
let before = null;
for (let line = log.lastElementChild; line && Number(line.dataset.t) > message.t;
line = line.previousElementSibling) before = line;
log.insertBefore(consoleLine(message), before);
}
while (log.childElementCount > CONSOLE_LINES) log.firstElementChild.remove();
filterConsole();
if (following) scroll.scrollTop = scroll.scrollHeight;
showFollowing();
}
// `following…` while the console is at its bottom: it scrolls to new messages then
// (`messagesArrived`); scrolled up, it stays where it is.
const consoleScroll = document.getElementById("console-scroll");
function showFollowing() {
const scroll = consoleScroll;
document.getElementById("console-following").hidden =
scroll.scrollTop + scroll.clientHeight < scroll.scrollHeight - 4;
}
consoleScroll.addEventListener("scroll", showFollowing, { passive: true });
// `clear`: the console emptied; it fills again with what comes from now on.
document.getElementById("console-clear").addEventListener("click", () => {
consoleMessages.length = 0;
pointedMessage = null;
if (shownMessage !== null) showMessage(null);
markRelated(null);
document.getElementById("console").replaceChildren();
filterConsole();
showFollowing();
});
function showConsole() {
document.getElementById("console").replaceChildren(...consoleMessages.map(consoleLine));
filterConsole();
const scroll = document.getElementById("console-scroll");
scroll.scrollTop = scroll.scrollHeight;
showFollowing();
}
function drawFlows() {
flowFrame = null;
const now = performance.now();
// Where each is, along the line it went over (`route`): as a dot, how far along (0
// to 1) as long as the line is now; as a flash, its head and its afterglow's tail
// (each 0 to 1) and how bright. Arrived (a flash: its afterglow gone), or its link
// gone, it goes.
// Each starts when it was logged (`at`), or, logged as it arrived, its crossing
// before: as a flash, half the link's round trip; as a dot, as long as it runs.
const where = flow => {
const line = route(flow.from, flow.to, flow.transport);
if (!line) return null;
if (flowsMode === "flash") {
const travel = flow.travel || (flow.travel = Math.max(1, oneWayMs(flow.from, flow.to)));
flow.start = flow.arrived ? flow.at - travel : flow.at;
const age = now - flow.start, glow = Math.max(0, (age - travel) / FLASH_GLOW_MS);
return { line, done: glow >= 1, head: Math.min(1, age / travel),
tail: 1 - (1 - Math.min(1, glow)) ** 2, opacity: 1 - Math.min(1, glow) };
}
flow.start = flow.arrived ? flow.at - line.length / flowSpeed : flow.at;
const t = (now - flow.start) * flowSpeed / line.length;
return { line, done: t >= 1, t };
};
for (let i = flows.length - 1; i >= 0; i--) {
const at = where(flows[i]);
if (at === null || at.done) flows.splice(i, 1);
}
const dots = [], streaks = [];
const f = n => n.toFixed(1);
for (const flow of flows) {
const at = where(flow);
if (now < flow.start) continue;
const r = flow.r * dotScale, colour = kindColour(flow.kind);
if (flowsMode === "flash") {
// From the tail, a point, widening to the head, rounded, along the line: brightest
// where the message is, drawing back toward it as it fades.
const head = at.head, tail = Math.min(at.tail, head), w = r * .8, steps = 8;
const left = [], right = [];
for (let k = 0; k <= steps; k++) {
const s = tail + (head - tail) * k / steps, point = at.line.at(s);
const width = w * k / steps;
left.push(f(point.x - point.uy * width) + " " + f(point.y + point.ux * width));
right.push(f(point.x + point.uy * width) + " " + f(point.y - point.ux * width));
}
streaks.push({ colour, opacity: at.opacity, d: "M" + left.join("L") +
"A" + f(w) + " " + f(w) + " 0 0 0 " + right[steps] + "L" +
right.slice(0, steps).reverse().join("L") + "Z" });
} else {
const point = at.line.at(at.t);
dots.push({ x: point.x, y: point.y, r, colour, opacity: Math.sin(Math.PI * at.t) });
}
}
const layer = (id, count, tag) => {
const group = document.getElementById(id);
while (group.children.length < count) group.append(svg(tag));
while (group.children.length > count) group.lastChild.remove();
return group;
};
const dotLayer = layer("flow-dots", dots.length, "circle");
dots.forEach((dot, i) => {
const circle = dotLayer.children[i];
circle.setAttribute("cx", dot.x);
circle.setAttribute("cy", dot.y);
circle.setAttribute("r", dot.r.toFixed(1));
circle.setAttribute("fill", dot.colour);
circle.setAttribute("opacity", dot.opacity.toFixed(2));
});
const streakLayer = layer("flow-streaks", streaks.length, "path");
streaks.forEach((streak, i) => {
const path = streakLayer.children[i];
path.setAttribute("d", streak.d);
path.setAttribute("fill", streak.colour);
path.setAttribute("opacity", streak.opacity.toFixed(2));
});
if (flows.length > 0) flowFrame = requestAnimationFrame(drawFlows);
}
// --- Events ---
const connection = document.getElementById("connection");
const dot = document.getElementById("dot");
// One breath per event from the node.
function pulse() {
dot.classList.remove("pulse");
void dot.offsetWidth; // restarts the animation
dot.classList.add("pulse");
}
function status(text, live) {
document.getElementById("connection-text").textContent = text;
connection.className = live ? "live" : "down";
document.body.classList.toggle("stale", !live && state !== null);
}
// While not live, what is shown stays as it was last (ages don't count on).
let live = false;
let events = null;
// The next attempt, while one is waited for: a connect now replaces it.
let retry = null;
function connect() {
clearTimeout(retry);
retry = null;
events = new EventSource("dashboard/events");
events.addEventListener("snapshot", event => {
const snapshot = JSON.parse(event.data);
if (snapshot.page !== PAGE_VERSION) {
events.close();
status("new version; reloading…", false);
// As this page is now (`handOff`): the map, what's open, the focus; reloaded with
// the URL's fragment, which the new page takes (`handOver`).
try {
history.replaceState(null, "", location.pathname + location.search + handOff(null));
} catch (_) { /* not where history works: reloaded as it is */ }
location.reload();
return;
}
// Changes while not connected went unseen: what is open is read again.
if (state !== null) documentChanged({ all: true });
const first = state === null;
state = snapshot; stateAt = Date.now(); live = true; overlaid.clear();
status("live", true); pulse(); render(); trafficArrived(); epochsArrived();
remakesArrived();
if (first) readFigures();
if (treeShown && writerTree === null) loadTree();
if (token === null && tokenTimer === null) obtainTokens();
// Followed before the page knew which node it is: not any more.
const own = subscribed.get(state.node.id);
if (own) { own.stop(); subscribed.delete(state.node.id); }
for (const id of subscriptions) if (!subscribed.has(id)) follow(id);
});
events.addEventListener("patch", event => {
if (!state) return;
unapplySubscriptions();
state = mergePatch(state, JSON.parse(event.data)); stateAt = Date.now(); pulse(); render();
trafficArrived();
epochsArrived();
remakesArrived();
});
events.addEventListener("document", event => { pulse(); documentChanged(JSON.parse(event.data)); });
events.addEventListener("messages", event => {
const batch = JSON.parse(event.data);
ownMessagesArrived(batch.messages, batch.sent);
});
// The node stops: it says so, and ends the stream. Back once it is.
events.addEventListener("offline", () => {
events.close(); live = false;
status("node stopped; reconnecting…", false);
retry = setTimeout(connect, 3000);
});
events.addEventListener("error", () => {
// Each attempt that failed: a breath too, so it shows it keeps trying.
pulse();
live = false;
if (events.readyState === EventSource.CLOSED) {
// Given up (an HTTP error, e.g. the node is up but not serving the page yet).
status("disconnected; retrying…", false);
retry = setTimeout(connect, 5000);
} else {
// EventSource reconnects by itself; the node sends a snapshot first again.
status("reconnecting…", false);
}
});
}
// --- Remakes: proposed from here (`POST /admin/remakes`, `docs/remakes.md`): compact,
// replace by JSON (typed, or from a file), import an Automerge document (uploaded as
// it is). This node coordinates it and votes for it; the map shows it as it goes. ---
const remakeForm = document.getElementById("remake");
const remakeToggle = document.getElementById("remake-toggle");
function showRemake(shown) {
remakeForm.hidden = !shown;
remakeToggle.setAttribute("aria-expanded", String(shown));
if (shown) remakeKindChanged();
}
function remakeKindChanged() {
const kind = document.getElementById("remake-kind").value;
for (const part of remakeForm.querySelectorAll("[data-kind]")) {
part.hidden = !part.dataset.kind.split(" ").includes(kind);
}
}
// A rule (`Rule` in the API): writes under `from` (a path, `/` between keys; empty: all)
// go under `to`, the rest of their path after it, or are dropped; the longest `from`
// that matches wins.
function addRemakeRule() {
const from = el("input", { type: "text", placeholder: "from (e.g. users)",
title: "A path prefix, keys separated by /; empty: every path" });
const to = el("input", { type: "text", placeholder: "to (e.g. accounts)",
title: "Where those writes go instead (the rest of their path after it); empty: the root, so from and to both empty keeps every write where it is" });
const drop = el("input", { type: "checkbox", title: "Drop those writes" });
const remove = el("button", { type: "button", class: "toggle", title: "Remove this rule" }, "×");
drop.addEventListener("change", () => { to.disabled = drop.checked; });
const row = el("div", { class: "rule" }, from, "→", to,
el("label", {}, drop, "drop"), remove);
remove.addEventListener("click", () => row.remove());
document.getElementById("remake-rules").append(row);
}
document.getElementById("remake-add-rule").addEventListener("click", addRemakeRule);
// The rules as the API takes them; a path as its keys (`/` between them).
function remakeRules() {
const keys = path => path.split("/").map(key => key.trim()).filter(key => key !== "");
return [...document.querySelectorAll("#remake-rules .rule")].map(row => {
const [from, to] = row.querySelectorAll("input[type=text]");
const drop = row.querySelector("input[type=checkbox]").checked;
return drop ? { from: keys(from.value), drop: true }
: { from: keys(from.value), to: keys(to.value) };
});
}
function remakeResult(text, bad) {
const result = document.getElementById("remake-result");
result.hidden = false;
result.textContent = text;
result.classList.toggle("bad", bad);
}
remakeToggle.addEventListener("click", () => showRemake(remakeForm.hidden));
document.getElementById("remake-cancel").addEventListener("click", () => showRemake(false));
document.getElementById("remake-kind").addEventListener("change", remakeKindChanged);
document.addEventListener("keydown", event => {
if (event.key === "Escape" && !remakeForm.hidden) showRemake(false);
});
// A JSON file fills the text area, to be looked at (and edited) before proposing.
document.getElementById("remake-json-file").addEventListener("change", event => {
const file = event.target.files[0];
if (!file) return;
file.text().then(text => { document.getElementById("remake-json").value = text; })
.catch(error => remakeResult("Reading " + file.name + ": " + error, true));
});
// A retention from its two fields (`epochs` and `age`), or null for the node's default
// (both empty); throws where the epochs aren't a whole number.
function remakeRetention(name, label) {
const epochs = document.getElementById("remake-" + name + "-epochs").value.trim();
const age = document.getElementById("remake-" + name + "-age").value.trim();
if (!epochs && !age) return null;
const retention = {};
if (epochs) {
if (!/^\d+$/.test(epochs)) throw new Error("The " + label + "'s epochs aren't a whole number.");
retention.epochs = Number(epochs);
}
if (age) retention.age = age;
return retention;
}
remakeForm.addEventListener("submit", event => {
event.preventDefault();
const kind = document.getElementById("remake-kind").value;
const settle = document.getElementById("remake-settle").value.trim();
const switchDelay = document.getElementById("remake-switch-delay").value.trim();
const force = document.getElementById("remake-force-switch-delay").checked
? "force=switchDelay" : "";
let replayWindow, archiveRetention;
try {
replayWindow = remakeRetention("replay", "replay window");
archiveRetention = remakeRetention("archive", "archive retention");
} catch (error) {
remakeResult(error.message, true);
return;
}
let request;
if (kind === "import") {
// The document as it is (octet-stream): its options in the query.
const file = document.getElementById("remake-import-file").files[0];
if (!file) { remakeResult("Choose the Automerge document to import.", true); return; }
const options = new URLSearchParams(force);
if (settle) options.set("settle", settle);
if (switchDelay) options.set("switchDelay", switchDelay);
if (replayWindow) options.set("replayWindow", JSON.stringify(replayWindow));
if (archiveRetention) options.set("archiveRetention", JSON.stringify(archiveRetention));
const rules = remakeRules();
if (rules.length) options.set("rules", JSON.stringify(rules));
const query = options.size ? "?" + options : "";
request = fetch("remakes" + query, withToken({ method: "POST", body: file,
headers: { "Content-Type": "application/octet-stream" } }));
} else {
const body = { kind };
if (settle) body.settle = settle;
if (switchDelay) body.switchDelay = switchDelay;
if (replayWindow) body.replayWindow = replayWindow;
if (archiveRetention) body.archiveRetention = archiveRetention;
if (kind === "replace") {
let parsed;
try {
parsed = JSON.parse(document.getElementById("remake-json").value);
} catch (error) {
remakeResult("The new document isn't JSON: " + error.message, true);
return;
}
body.spec = { document: parsed };
const rules = remakeRules();
if (rules.length) body.spec.rules = rules;
}
request = fetch("remakes" + (force ? "?" + force : ""), withToken({ method: "POST",
body: JSON.stringify(body), headers: { "Content-Type": "application/json" } }));
}
remakeResult("Proposing…", false);
request
.then(response => response.json().catch(() => ({})).then(report => ({ response, report })))
.then(({ response, report }) => {
if (response.ok) {
remakeResult("Proposed" + (report.id ? ": " + report.id : "") +
". The map shows the votes as they come.", false);
} else {
remakeResult(response.status + ": " + (report.error || response.statusText) +
(report.force === "switchDelay" ? " (tick \u201ceven below a keepalive interval\u201d)"
: report.force ? " (the API takes ?force=" + report.force + ")" : ""), true);
}
})
.catch(error => remakeResult("Proposing failed: " + error, true));
});
// Opened from another member's page (`handOver`) with a token: it begins this browser's
// session here before anything is read, with no login page in between. Without a
// session, `obtainTokens` goes to the login page.
(async () => {
if (handOver && typeof handOver.token === "string") {
try {
await tokenCall("../auth/session", handOver.token);
} catch (_) { /* a session of this browser's own may let it in still */ }
delete handOver.token;
}
connect();
obtainTokens();
})();
// A page not shown (another tab, a minimised window) is paused: hidden for a while, it
// closes its stream, so the node stops building updates and asking members for their
// links for it; shown again, it reconnects. Briefly hidden, nothing changes.
const PAUSE_AFTER = 30000;
let paused = false;
let pausing = null;
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
pausing = setTimeout(() => {
pausing = null;
paused = true;
clearTimeout(retry);
retry = null;
if (events) events.close();
live = false;
status("paused while hidden", false);
}, PAUSE_AFTER);
} else {
clearTimeout(pausing);
pausing = null;
if (paused) {
paused = false;
status("reconnecting…", false);
connect();
}
}
});
// A click on the status: live, everything now (a tick on the node, what's open of the
// document read again); otherwise, reconnecting now.
connection.title = "Click to refresh now";
connection.style.cursor = "pointer";
connection.addEventListener("click", () => {
pulse();
if (live) {
fetch("dashboard/refresh", withToken({ method: "POST" })).catch(() => {});
documentChanged({ all: true });
} else {
if (events) events.close();
status("reconnecting…", false);
connect();
}
});
// Ages count on between events; nothing else changes without one.
setInterval(() => { if (live) render(true); }, 1000);
window.addEventListener("resize", () => render());
// --- Sizes: the space between boxes dragged to resize them, double-clicked to reset;
// kept in this browser ---
const main = document.querySelector("main");
// The map's share of the width (1: the right column dragged off to the side, hidden);
// the peers' height in px; the console's share of what the peers leave, and the
// figures' share of the rest. Null: as laid out by default.
let sizes = { columns: null, peers: null, split: null, console: null };
try { sizes = { ...sizes, ...JSON.parse(localStorage.getItem("continuum-sizes") || "{}") }; }
catch (_) {}
function applySizes() {
const style = main.style;
const shut = id => document.getElementById(id).classList.contains("collapsed");
const right = ["peers-box", "figures-box", "document-box", "console-box"];
const wasHidden = main.classList.contains("right-hidden");
main.classList.toggle("right-hidden", sizes.columns === 1);
main.classList.toggle("right-shut", sizes.columns !== 1 && right.every(shut));
// The right column all collapsed keeps its width, resized as ever (dragged to the
// side, it goes); the map is never collapsed.
if (sizes.columns === 1) style.setProperty("--columns", "minmax(0, 1fr) 0");
else if (sizes.columns === null) style.removeProperty("--columns");
else style.setProperty("--columns", "minmax(0, " + sizes.columns + "fr) minmax(0, " +
(1 - sizes.columns) + "fr)");
// Back: what waited is drawn.
if (wasHidden && sizes.columns !== 1) {
if (!hidden(document.getElementById("console-box"))) showConsole();
release();
}
// A collapsed box's row as tall as its title; the open ones share the rest, as they
// did, and the peers take it all when they're the only one open. Their fractions
// add up to 1: fewer would leave room unused (CSS grid gives fractions adding up to
// less than 1 only that part of the room).
const split = sizes.split === null ? .5 : sizes.split;
const consoleShare = sizes.console === null ? .2 : sizes.console;
const rest = 1 - consoleShare;
const fractions = { "figures-box": split * rest, "document-box": (1 - split) * rest,
"console-box": consoleShare };
const openShare = Object.keys(fractions).filter(id => !shut(id))
.reduce((sum, id) => sum + fractions[id], 0);
const share = id => shut(id) ? "auto" : "minmax(0, " + fractions[id] / openShare + "fr)";
const peersOnly = !shut("peers-box") && right.slice(1).every(shut);
const peers = shut("peers-box") ? "auto" : peersOnly ? "minmax(0, 1fr)"
: sizes.peers === null ? "auto" : sizes.peers + "px";
style.setProperty("--rows", peers + " " + share("figures-box") + " " +
share("document-box") + " " + share("console-box"));
main.classList.toggle("peers-sized", sizes.peers !== null || peersOnly);
try { localStorage.setItem("continuum-sizes", JSON.stringify(sizes)); } catch (_) {}
}
const box = id => document.getElementById(id).getBoundingClientRect();
// Which space between boxes `event` is over, if any: "columns", "peers" (below the
// peers), "split" (between figures and document) or "console" (above the console).
// Only side by side; with the right column hidden, right of the map: "columns".
function gapAt(event) {
if (event.target !== main) return null;
if (sizes.columns === 1 && main.classList.contains("right-hidden")) {
return event.clientX >= box("map").right ? "columns" : null;
}
const map = box("map"), peers = box("peers-box"), figures = box("figures-box"),
documentBox = box("document-box"), consoleBox = box("console-box");
if (map.right >= peers.left) return null;
if (event.clientX >= map.right && event.clientX <= peers.left) return "columns";
if (event.clientX < peers.left || event.clientX > peers.right) return null;
if (event.clientY >= peers.bottom && event.clientY <= figures.top) return "peers";
if (event.clientY >= figures.bottom && event.clientY <= documentBox.top) return "split";
if (event.clientY >= documentBox.bottom && event.clientY <= consoleBox.top) return "console";
return null;
}
function resizeTo(gap, event) {
const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
// The space between boxes (`main`'s gap), half of it each side.
const half = parseFloat(getComputedStyle(main).columnGap) / 2;
if (gap === "columns") {
// Across the whole width: the right column's right edge is `main`'s, inside.
const map = box("map");
const right = main.getBoundingClientRect().right -
parseFloat(getComputedStyle(main).paddingRight);
const share = (event.clientX - half - map.left) / (right - map.left - 2 * half);
// Dragged to the side: hidden.
sizes.columns = share > .9 ? 1 : clamp(share, .2, .8);
} else if (gap === "peers") {
const peers = box("peers-box"), consoleBox = box("console-box");
sizes.peers = Math.round(clamp(event.clientY - half - peers.top, 60,
consoleBox.bottom - peers.top - 6 * half - 200));
} else if (gap === "console") {
const figures = box("figures-box"), consoleBox = box("console-box");
sizes.console = clamp((consoleBox.bottom - event.clientY - half) /
(consoleBox.bottom - figures.top - 4 * half), .05, .8);
} else {
const figures = box("figures-box"), documentBox = box("document-box");
sizes.split = clamp((event.clientY - half - figures.top) /
(documentBox.bottom - figures.top - 2 * half), .1, .9);
}
applySizes();
}
let resizing = null;
let resizeFrame = null;
main.addEventListener("pointermove", event => {
if (resizing) {
resizeTo(resizing, event);
// The map's view box follows its size: drawn once a frame.
if (resizeFrame === null) resizeFrame = requestAnimationFrame(() => {
resizeFrame = null;
render();
});
return;
}
const gap = gapAt(event);
main.classList.toggle("resize-columns", gap === "columns");
main.classList.toggle("resize-rows", gap === "peers" || gap === "split" || gap === "console");
});
main.addEventListener("pointerdown", event => {
resizing = gapAt(event);
if (!resizing) return;
event.preventDefault();
main.setPointerCapture(event.pointerId);
});
const resized = () => {
if (!resizing) return;
resizing = null;
main.classList.remove("resize-columns", "resize-rows");
render();
};
main.addEventListener("pointerup", resized);
main.addEventListener("pointercancel", resized);
// --- Boxes collapsed to their titles, and opened again; kept in this browser. A
// collapsed box isn't drawn (`busy`), so it costs nothing while the node updates. ---
const collapsed = new Set();
try {
for (const id of JSON.parse(localStorage.getItem("continuum-collapsed") || "[]")) {
collapsed.add(id);
}
} catch (_) {}
// The map isn't collapsed: it is what the page is about (a choice kept from before isn't
// taken).
collapsed.delete("map");
for (const section of document.querySelectorAll("main > section:not(#map)")) {
const button = el("button", { class: "collapse" });
section.querySelector("h2").prepend(button);
const show = () => {
const shut = collapsed.has(section.id);
section.classList.toggle("collapsed", shut);
button.textContent = shut ? "▸" : "▾";
button.title = shut ? "Open" : "Collapse";
};
show();
button.addEventListener("click", () => {
if (collapsed.has(section.id)) collapsed.delete(section.id); else collapsed.add(section.id);
try { localStorage.setItem("continuum-collapsed", JSON.stringify([...collapsed])); }
catch (_) {}
show();
applySizes();
if (collapsed.has(section.id)) return;
if (section.id === "console-box") showConsole();
release();
render();
});
}
applySizes();
main.addEventListener("dblclick", event => {
const gap = gapAt(event);
if (!gap) return;
sizes[gap] = null;
applySizes();
render();
});
</script>
</body>
</html>
|