aboutsummaryrefslogtreecommitdiffstats
path: root/src/api/dashboard/dashboard.html
blob: 153d7cb9476ff9480e89a791ad0c64597a96030a (plain)
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
<!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;
  }
  @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 { color: var(--warn); }
  #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. */
  main { flex: 1; min-height: 0; display: grid; gap: 16px; padding: 16px;
    grid-template-columns: minmax(0, 3fr) minmax(0, 2fr);
    grid-template-rows: auto minmax(0, 1fr) minmax(0, 1fr);
    grid-template-areas: "map peers" "map figures" "map document"; }
  @media (max-width: 900px) {
    body { height: auto; }
    main { grid-template-columns: minmax(0, 1fr); grid-template-rows: 70vh auto 70vh 70vh;
      grid-template-areas: "map" "peers" "figures" "document"; }
  }
  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); }
  section h2 .what .id { color: var(--muted); font-weight: normal; word-break: break-all; }
  #map { grid-area: map; }
  #peers-box { grid-area: peers; }
  #figures-box { grid-area: figures; }
  #document-box { grid-area: document; }
  svg { flex: 1; min-height: 0; width: 100%; display: block; cursor: default; }
  /* Dragged to pan or to move a node, also by touch. */
  #graph { touch-action: none; }
  #graph.dragging, #graph.dragging * { cursor: grabbing; }
  svg circle { cursor: pointer; }
  .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); }
  .legend .silent::before { border-top-style: dotted; --colour: var(--muted); }
  .legend .hint::before { display: none; }
  #legends { flex: none; }
  /* Hides the legend, and shows it again. */
  button.toggle { font: inherit; font-size: 12px; text-transform: none; letter-spacing: 0;
    float: right; 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.focus::before { width: 14px; height: 14px; background: var(--self);
    border: none; opacity: .35; }
  .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 button.add { font: inherit; line-height: 1; padding: 0 4px; margin-left: 4px;
    color: var(--muted); background: none; border: 1px solid var(--line); border-radius: 3px;
    cursor: pointer; }
  .tree button.add:hover { color: var(--fg); border-color: var(--muted); }
  .tree .nested { padding-left: 1.1em; }
  .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; }
  .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; }
  #peers tr.focused td { background: var(--line); }
  .id { font-family: ui-monospace, monospace; font-size: 12px; }
  /* A peer's status (not the legend's "dormant"). */
  #peers .active { color: var(--ok); } #peers .dormant { color: var(--bad); }
  #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); }
</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>
</header>
<main>
  <section id="map">
    <h2>Swarm <button id="legend-toggle" class="toggle">hide legend</button></h2>
    <div id="legends">
      <div class="legend">
        <span class="node self">this node</span>
        <span class="node">reports its links</span>
        <span class="node silent">reports none (no LINKS_REPLY)</span>
        <span class="node dormant-node">dormant (to this node)</span>
        <span class="node focus">in focus (click a node)</span>
      </div>
      <div class="legend" id="legend"></div>
      <div class="legend">
        <span class="hint">drag to pan, wheel or pinch to zoom, turn with two fingers,
          double-click to reset; drag a node to pin it, double-click it to let go</span>
      </div>
    </div>
    <svg id="graph"><g id="view"></g></svg>
  </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 id="figures-title">Figures</h2>
    <div class="scroll"><div id="stats" class="tree"></div></div>
  </section>
  <section id="document-box">
    <h2>Document</h2>
    <div class="scroll"><div id="document" class="tree"></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;

// 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;
}
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";
// 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 = (() => {
  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(" ");
function focus(id) {
  focused = id === null || id === state.node.id ? null : id;
  // 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();
}

// --- Peers ---
function renderPeers() {
  const table = document.getElementById("peers");
  const rows = [el("tr", {}, ...["peer", "status", "seen", "via", "rtt", "clock", "neighbour",
    "same epoch"]
    .map(h => el("th", {}, h)))];
  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 + ")" : "")
      : "";
    const row = el("tr", { "data-peer": id, class: id === focused ? "focused" : "" },
      el("td", { title: id }, peer.alias || el("span", { class: "id" }, short(id))),
      // How long dormant is about how long unseen ("seen"): in the tooltip only.
      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),
      el("td", {}, rtt),
      // 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) : ""),
      el("td", {}, peer.neighbour ? "yes" : ""),
      el("td", {}, peer.sameEpoch === null || peer.sameEpoch === undefined
        ? "" : peer.sameEpoch ? "yes" : "no"));
    // On press: the table may be drawn anew (ages) before a click would complete.
    row.addEventListener("pointerdown", () => focus(id === focused ? null : id));
    rows.push(row);
  }
  table.replaceChildren(...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" : "";
}

// --- Figures: a tree, its open branches kept across renders ---
const open = new Set(["stats", "peer", "links", "from", "to"]);
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);
    details.append(el("summary", {}, el("span", { class: "key" }, key),
      Array.isArray(value) ? " [" + value.length + "]" : ""));
    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 + ": "),
    JSON.stringify(aged(key, value)));
}
function renderStats() {
  const title = document.getElementById("figures-title");
  const what = el("span", { class: "what" });
  let shown;
  if (isPair(focused)) {
    const [a, b] = focused.split(" ");
    what.textContent = name(a) + " – " + name(b);
    what.title = 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.")));
      }
    }
    title.replaceChildren("Link: ", what);
    document.getElementById("stats").replaceChildren(...shown);
    return;
  }
  if (focused === null) {
    what.textContent = name(state.node.id) + " (this node)";
    shown = [tree("stats", state.stats, "stats")];
  } else {
    // 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];
    shown = [];
    if (peer) shown.push(tree("peer", peer, "peer"));
    else shown.push(el("div", { class: "key leaf" }, "Not a peer of this node."));
    if (report) shown.push(tree("links", report, "links"));
  }
  title.replaceChildren(focused === null ? "Figures: " : "Peer: ", what);
  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();
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"),
    el("span", { class: "silent" }, "an end reports no links"));
  document.getElementById("legend").replaceChildren(...items);
}

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) });
      } else if (link.dormant) {
        known.dormant = true;
      }
    }
  }
  // Dormant if either end holds the other so, whichever report is drawn.
  for (const edge of measured.values()) {
    if (edge.dormant && !edge.link.dormant) edge.link = { ...edge.link, dormant: true };
  }
  return { intended, measured };
}

function layout(nodes, pairs, width, height) {
  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 });
    }
  }
  const ideal = Math.min(width, height) / Math.max(2, Math.sqrt(nodes.length) * 1.5);
  for (let round = 0; round < 120; round++) {
    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] 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 pull = (d - ideal) / 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;
    }
    for (const id of nodes) {
      if (pinned.has(id)) continue;
    const p = positions.get(id), f = force.get(id);
      p.x = Math.min(width - 40, Math.max(40, p.x + Math.max(-10, Math.min(10, f.x))));
      p.y = Math.min(height - 20, Math.max(20, p.y + Math.max(-10, Math.min(10, f.y))));
    }
  }
}

// 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();
}
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;
}
function tooltip(node, content) {
  let title = node.firstElementChild;
  if (!title) node.append(title = svg("title"));
  text(title, 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 = "";
function renderGraph() {
  const root = document.getElementById("graph");
  const width = root.clientWidth || 800, height = root.clientHeight || 560;
  root.setAttribute("viewBox", "0 0 " + width + " " + height);
  const nodes = Object.keys(state.graph.members).sort();
  const { intended, measured } = edges();
  renderLegend(measured);
  const pairs = [...intended.values(), ...[...measured.values()].map(m => [m.a, m.b])];
  // Laid out anew only when who's there or who links to whom changed.
  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); }
    }
    layout(nodes, pairs, width, height);
    lastShape = shape;
  }
  const children = [];
  // 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)", "stroke-opacity": key === focused ? .35 : .15,
      "stroke-width": width + 8, "stroke-linecap": "round" }));
  };
  // Over a link: an invisible, wider line to point at and click.
  const hits = [];
  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 => {
      // On press: the map may be drawn anew before a click would complete.
      line.addEventListener("pointerdown", event => { event.stopPropagation(); 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);
    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));
  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;
    // An end that reports no links (any more): what's drawn may be out of date.
    const silent = !(a in state.graph.measured) || !(b in state.graph.measured);
    // Dormant: a red underlay as wide as the lines, as a dormant node's red outline.
    if (link.dormant) {
      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" }));
    }
    lines.forEach((line, i) => {
      // 0, then +1, -1, +2, -2 … steps of 6 px to the side.
      const side = i === 0 ? 0 : (i % 2 ? 1 : -1) * Math.ceil(i / 2) * 6;
      const ox = nx * side, oy = ny * side;
      const attrs = { x1: p.x + ox, y1: p.y + oy, x2: q.x + ox, y2: q.y + oy,
        stroke: colourOf(line.transport),
        // Narrow where dormant (over its underlay).
        "stroke-width": link.dormant ? (line.used ? 1.5 : 0.8) : line.used ? 3 : 1.2 };
      // Dotted where an end reports nothing, dashed where relayed, solid where direct.
      if (silent) {
        attrs["stroke-dasharray"] = line.used ? "1 5" : "1 3";
        attrs["stroke-linecap"] = "round";
      } else if (line.used ? link.relayed : line.relayed) {
        attrs["stroke-dasharray"] = "7 4";
      }
      const drawnLine = drawing("line " + key + " " + i, "line", 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" : "") +
        (silent ? ", one end reports no links" : "") +
        (typeof line.rttMs === "number" ? ", " + line.rttMs.toFixed(1) + " ms" : "") +
        ", measured " + age(secsAgo + elapsed()) + " ago";
      tooltip(drawnLine, description);
      descriptions.push(description);
      children.push(drawnLine);
      if (typeof line.rttMs === "number") {
        // The one in use at the middle, larger; the others further along, beside theirs.
        const t = line.used ? .5 : .3;
        const out = line.used ? -4 : Math.sign(side) * 9;
        const label = drawing("rtt " + key + " " + i, "text", upright({
          x: p.x + (q.x - p.x) * t + ox + nx * out,
          y: p.y + (q.y - p.y) * t + oy + ny * out + (line.used ? 0 : 3),
          "text-anchor": "middle", "font-size": line.used ? 11 : 9,
          fill: line.used ? "var(--fg)" : "var(--muted)" }));
        text(label, ms(line.rttMs));
        children.push(label);
      }
    });
    tooltip(covering, descriptions.join("\n"));
  }
  // Above the lines and their labels, below the nodes.
  children.push(...hits);
  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)", "fill-opacity": shown ? .35 : .15, stroke: "none" }));
    }
    const pressed = element => {
      element.addEventListener("pointerdown", event => { event.stopPropagation(); drag(event, id); });
      element.addEventListener("dblclick", () => unpin(id));
      hoverable(element, id);
    };
    // Dormant as this node sees it (`/peers`): a red outline.
    const dormant = (state.peers.peers[id] || {}).status === "dormant";
    const circle = drawing("node " + id, "circle", { cx: p.x, cy: p.y, r: member.self ? 8 : 6,
      fill: member.self ? "var(--self)" : reported ? "var(--fg)" : "var(--panel)",
      stroke: member.self ? "var(--self)" : dormant ? "var(--bad)" : "var(--fg)",
      "stroke-width": dormant ? 2.5 : 1.5 }, pressed);
    const clock = (state.peers.peers[id] || {}).clock;
    tooltip(circle, id + (reported ? "" : " (no links reported)") +
      (dormant ? " (dormant)" : "") +
      (clockOff(clock) ? " (clock " + seconds(clock.offsetMs) + " off this node's)" : ""));
    const label = drawing("name " + id, "text", upright({ x: p.x + 10, y: p.y + 4,
      "font-size": 12, fill: "var(--fg)", cursor: "pointer" }), pressed);
    text(label, name(id));
    children.push(circle, label);
  }
  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([])]);
// 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: () => "" };

// --- Editing: a double click on an entry 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),
    { 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));
  // 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, " ", 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.
function edited(path, saved, opened = path) {
  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: a "+" on the row, the field below it. `known()`: a
// map's keys as last read, so an existing one isn't overwritten.
function addButton(kind, path, known, place) {
  const map = kind === "map";
  const button = el("button", { type: "button", class: "add",
    title: map ? "Add a key" : "Insert an item" }, "+");
  button.addEventListener("click", event => {
    // Not a click on the row: it would open or close it.
    event.preventDefault();
    event.stopPropagation();
    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: "-1", 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),
        { method: map ? "PUT" : "POST", body, headers: { "Content-Type": type } }),
    });
    area.prepend(form);
  });
  return button;
}

function editableLeaf(key, shown, value, path) {
  const leaf = el("div", { class: "leaf" }, el("span", { class: "key" }, key + ": "), shown);
  if (!editable(path)) return leaf;
  leaf.title = "Double-click to edit";
  leaf.addEventListener("dblclick", event => {
    if (editing(leaf)) return;
    event.preventDefault();
    window.getSelection().removeAllRanges();
    const before = [...leaf.childNodes];
    leaf.replaceChildren(before[0], editor(path, value, saved => {
      leaf.replaceChildren(...before);
      edited(path, saved);
    }));
  });
  return leaf;
}

// 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.
function documentEntry(key, summary, path) {
  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: "+" on its row, the field below.
    if ((summary.type === "map" || summary.type === "list") && editable(path)) {
      const below = el("div", { class: "nested" });
      leaf.append(" ", addButton(summary.type, path, () => [], () => below));
      return el("div", {}, leaf, below);
    }
    return leaf;
  }
  if ("value" in summary) {
    return editableLeaf(key, JSON.stringify(summary.value), summary.value, path);
  }
  const details = el("details", {});
  const described = document.createTextNode(describe(summary));
  const head = el("summary", {}, el("span", { class: "key" }, key), " ", described);
  details.append(head);
  // A double click edits the whole of it: read, then shown in a field.
  if (editable(path)) {
    head.title = "Double-click to edit";
    head.addEventListener("mousedown", event => { if (event.detail > 1) event.preventDefault(); });
    head.addEventListener("dblclick", async event => {
      event.preventDefault();
      if (details.querySelector(":scope > .editor")) 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").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).
  if (browsed && (editable(path) || path.length === 0)) {
    head.append(" ", addButton(summary.type, path, () => [...children.keys()], () => {
      details.open = true;
      return { prepend: form => head.after(form), querySelector: q => details.querySelector(":scope > " + q) };
    }));
  }
  let read = 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;
            continue;
          }
          const element = documentEntry(k, newer, [...path, k]);
          if (known) known.element.replaceWith(element);
          children.set(k, { element, summary: newer });
        }
        // 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);
      }
    } 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();
  }
}
document.getElementById("document").replaceChildren(
  documentEntry("store", { type: "map", size: "…" }, []));

// 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.
function busy(box) {
  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;
  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, hidden and shown again; the map takes the room.
const legendToggle = document.getElementById("legend-toggle");
legendToggle.addEventListener("click", () => {
  const legends = document.getElementById("legends");
  legends.hidden = !legends.hidden;
  legendToggle.textContent = legends.hidden ? "show legend" : "hide legend";
  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 + ")");
}
// `[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");
  if (click) click();
});
graph.addEventListener("pointercancel", event => {
  untouched(event);
  press = null;
  graph.classList.remove("dragging");
});
// Beside the nodes: dragged, it pans; a click, back to this node.
graph.addEventListener("pointerdown", event => {
  if (event.target !== graph) return;
  const from = { ...view };
  pressing(event, (dx, dy) => {
    view.x = from.x + dx;
    view.y = from.y + dy;
    moveView();
  }, () => focus(null));
});
// A node: dragged, it stays where it is put (`pinned`), and the layout places the others
// around it; a click, it is in focus.
function drag(event, id) {
  const p = positions.get(id), from = { x: p.x, y: p.y };
  pressing(event, (dx, dy) => {
    // 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;
    pinned.add(id);
    renderGraph();
  }, () => focus(id));
}
// A node let go: the layout places it again.
function unpin(id) {
  if (!pinned.delete(id)) return;
  lastShape = "";
  renderGraph();
}
// A double-click beside the nodes: the whole map again.
graph.addEventListener("dblclick", event => {
  if (event.target !== graph) return;
  Object.assign(view, { x: 0, y: 0, k: 1, turn: 0 });
  moveView();
  if (state) renderGraph();
});
// 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));

// --- 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);
      location.reload();
      return;
    }
    // Changes while not connected went unseen: what is open is read again.
    if (state !== null) documentChanged({ all: true });
    state = snapshot; stateAt = Date.now(); live = true;
    status("live", true); pulse(); render();
  });
  events.addEventListener("patch", event => {
    if (!state) return;
    state = mergePatch(state, JSON.parse(event.data)); stateAt = Date.now(); pulse(); render();
  });
  events.addEventListener("document", event => { pulse(); documentChanged(JSON.parse(event.data)); });
  // 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);
    }
  });
}
connect();
// 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, the members asked
// again, 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", { 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", () => { lastShape = ""; render(); });
</script>
</body>
</html>