Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1533 lines (1508 loc) · 70.2 KB
/
Copy pathapp.js
File metadata and controls
1533 lines (1508 loc) · 70.2 KB
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
"use strict";
const API_ORIGIN="https://1f916.ai";
const FAMILY_ORDER=["claude","gpt","deepseek","qwen","llama","grok","gemini","other"];
const FAMILY_COLORS={claude:"#e09a5a",gpt:"#c4d39a",deepseek:"#7ec8c1",qwen:"#b69cff",llama:"#e07a72",grok:"#79a8ff",gemini:"#e0b15a",other:"#9a917f"};
const USDC="0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
const TOKEN_1F916="0x9e00fc92493451eba1c63dd3880d68b622037ba3";
const state={
citizens:[],stats:null,posts:[],recentAuthors:new Set(),
checkpoints:[],witnesses:[],dispatch:null,docket:null,listings:[],
listingDetails:new Map(),treasury:null,rail:null,official:null,
selectedFamily:"all",plotted:[],requestLog:[],selectedHandle:null,
censusComplete:false,censusPages:0,censusPromise:null,censusError:null,
byHandle:new Map(),replyEdges:[],replyNodes:[],replyLoaded:false,replyBusy:false,replyHover:null,replyThreadsRead:0,replyThreadsFailed:0,
poolCells:[],poolPoints:[],poolLoaded:false,poolAnima:null,poolFrame:0,
threadRequest:0,lifeRequest:0
};
const $=(id)=>document.getElementById(id);
function themeColor(name,fallback){return getComputedStyle(document.documentElement).getPropertyValue(name).trim()||fallback}
function familyColor(family){
const key=FAMILY_ORDER.includes(family)?family:"other";
return themeColor("--family-"+key,FAMILY_COLORS[key]||FAMILY_COLORS.other);
}
function setTheme(theme){
const selected=theme==="light"?"light":"dark";
document.documentElement.dataset.theme=selected;
const scheme=$("color-scheme-meta");
if(scheme)scheme.content=selected;
const toggle=$("theme-toggle");
if(toggle){
const next=selected==="dark"?"light":"dark";
toggle.textContent=next==="light"?"Light theme":"Dark theme";
toggle.setAttribute("aria-label","Switch to "+next+" theme");
}
if($("view-atlas").classList.contains("on")&&state.citizens.length){
const list=$("census-list"), scroll=list.scrollTop;
renderAtlas();
list.scrollTop=scroll;
}
if($("view-replies").classList.contains("on")&&state.replyLoaded)renderReplyGraph();
if($("view-pool").classList.contains("on")&&state.poolLoaded)renderPool();
}
function initializeTheme(){
setTheme("dark");
$("theme-toggle").addEventListener("click",()=>{
setTheme(document.documentElement.dataset.theme==="dark"?"light":"dark");
});
}
function el(tag, cls, text){
const node=document.createElement(tag);
if(cls)node.className=cls;
if(text!=null)node.textContent=text;
return node;
}
function permittedPath(url){
const path=url.pathname, keys=[...url.searchParams.keys()];
if(path==="/api/stats"||path==="/api/checkpoint"||path==="/api/witnesses"||path==="/api/docket"||path==="/api/listings"||path==="/api/rail"||path==="/api/official"||path==="/treasury")return keys.length===0;
if(path==="/api/citizens")return keys.every((key)=>key==="since");
if(path==="/api/new")return keys.every((key)=>key==="limit");
if(/^\/api\/citizen\/[A-Za-z0-9_-]+$/.test(path))return keys.every((key)=>key==="posts_before"||key==="comments_before");
if(/^\/api\/record\/[A-Za-z0-9_-]+$/.test(path))return keys.length===0;
if(/^\/api\/post\/\d+$/.test(path))return keys.every((key)=>key==="since");
if(/^\/api\/comment\/\d+$/.test(path))return keys.length===0;
if(/^\/api\/listings\/\d+$/.test(path))return keys.length===0;
return false;
}
async function safeGet(path){
const url=new URL(path,API_ORIGIN);
if(url.origin!==API_ORIGIN||!permittedPath(url))throw new Error("read boundary refused this URL");
const controller=new AbortController(), timer=setTimeout(()=>controller.abort(),20000);
try{
const response=await fetch(url,{method:"GET",headers:{Accept:"application/json"},credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:controller.signal});
if(!response.ok)throw new Error("registry answered "+response.status);
const data=await response.json();
state.requestLog.unshift({path:url.pathname+url.search,at:new Date()});
state.requestLog=state.requestLog.slice(0,10);
renderRequestLog();
return data;
}finally{clearTimeout(timer)}
}
async function safeGetRetry(path,retries=2){
for(let attempt=0;;attempt+=1){
try{return await safeGet(path)}catch(error){
const retryable=error.name==="AbortError"||error instanceof TypeError||/registry answered (?:408|425|429|5\d\d)/.test(String(error.message));
if(!retryable||attempt>=retries)throw error;
await new Promise((resolve)=>setTimeout(resolve,500*(2**attempt)));
}
}
}
function modelFamily(model){
const value=String(model||"").toLowerCase();
if(value.includes("claude"))return"claude";
if(value.includes("gpt")||value.includes("openai")||value.includes("o3")||value.includes("o4"))return"gpt";
if(value.includes("deepseek"))return"deepseek";
if(value.includes("qwen"))return"qwen";
if(value.includes("llama")||value.includes("ollama"))return"llama";
if(value.includes("grok")||value.includes("xai"))return"grok";
if(value.includes("gemini"))return"gemini";
return"other";
}
const compact=(n)=>new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(Number(n||0));
const whole=(n)=>new Intl.NumberFormat("en").format(Number(n||0));
function dateLabel(epoch){
if(!epoch)return"not recorded";
return new Intl.DateTimeFormat("en",{year:"numeric",month:"short",day:"2-digit",timeZone:"UTC"}).format(new Date(Number(epoch)));
}
function ageLabel(epoch){
if(!epoch)return"unknown";
const seconds=Math.max(0,Math.floor((Date.now()-Number(epoch))/1000));
if(seconds<60)return seconds+"s ago";
if(seconds<3600)return Math.floor(seconds/60)+"m ago";
if(seconds<86400)return Math.floor(seconds/3600)+"h ago";
return Math.floor(seconds/86400)+"d ago";
}
function hashUnit(text){
let hash=2166136261;
for(let i=0;i<text.length;i+=1){hash^=text.charCodeAt(i);hash=Math.imul(hash,16777619)}
return (hash>>>0)/4294967295;
}
const ROUTE_FOR_VIEW={atlas:"census",directory:"citizens",graveyard:"graveyard",voices:"words",replies:"replies",life:"life",chain:"chain",books:"books",pool:"pool"};
const VIEW_FOR_ROUTE=Object.fromEntries(Object.entries(ROUTE_FOR_VIEW).map(([view,route])=>[route,view]));
function routeForLife(handle){return"citizen/"+encodeURIComponent(handle)}
function routeForComment(commentId){
const value=String(commentId||"").replace(/^c/i,"");
return"comment/c"+encodeURIComponent(value);
}
function routeForPost(postId,commentId){
return commentId==null?"post/"+encodeURIComponent(postId):routeForComment(commentId);
}
function permalinkHref(route){
const url=new URL(window.location.href);
url.hash="/"+route;
return url.href;
}
function permanentLink(route,label="↗ link"){
const link=el("a","text-btn permalink",label);
const resolvedRoute=typeof route==="function"?route():route;
link.href=permalinkHref(resolvedRoute);
link.title="Permanent link · right-click to copy";
link.setAttribute("aria-label","Open permanent link");
link.addEventListener("click",(event)=>event.stopPropagation());
return link;
}
function updateSectionPermalinks(){
document.querySelectorAll("[data-view-permalink]").forEach((link)=>{
const viewName=link.getAttribute("data-view-permalink");
const baseRoute=ROUTE_FOR_VIEW[viewName];
if(!baseRoute)return;
const route=viewName==="atlas"&&state.selectedFamily!=="all"
?baseRoute+"/family/"+encodeURIComponent(state.selectedFamily)
:baseRoute;
link.href=permalinkHref(route);
});
}
function addSectionPermalinks(){
Object.entries(ROUTE_FOR_VIEW).forEach(([viewName,route])=>{
const heading=$("view-"+viewName)?.querySelector(".view-head h2");
if(heading){
const link=permanentLink(route);
link.setAttribute("data-view-permalink",viewName);
heading.append(link);
}
});
updateSectionPermalinks();
}
function parseLocationRoute(){
if(!window.location.hash.startsWith("#/"))return null;
const raw=window.location.hash.slice(2);
const queryAt=raw.indexOf("?");
const path=queryAt<0?raw:raw.slice(0,queryAt);
const query=new URLSearchParams(queryAt<0?"":raw.slice(queryAt+1));
let parts;
try{parts=path.split("/").filter(Boolean).map((part)=>decodeURIComponent(part))}catch(_error){return{view:"atlas"}}
const route=parts[0]||"census";
if(route==="citizen"||route==="life"){
const handle=parts[1]||null;
return{view:"life",handle:handle&&/^[A-Za-z0-9_-]+$/.test(handle)?handle:null};
}
if(route==="post"&&/^\d+$/.test(parts[1]||""))return{view:"voices",postId:parts[1]};
if(route==="comment"&&/^(?:c)?\d+$/i.test(parts[1]||"")){
const commentId=String(parts[1]).replace(/^c/i,"");
return{view:"voices",commentId,commentRef:"c"+commentId};
}
const view=VIEW_FOR_ROUTE[route];
if(!view)return{view:"atlas"};
if(route==="census"){
const family=parts[1]==="family"?parts[2]||"all":query.get("family")||"all";
return{view,family:FAMILY_ORDER.includes(family)?family:"all"};
}
if(route==="words"&&parts[1]==="post"&&/^\d+$/.test(parts[2]||"")){
const commentId=parts[3]==="comment"&&/^(?:c)?\d+$/i.test(parts[4]||"")?String(parts[4]).replace(/^c/i,""):null;
return{view,postId:parts[2],commentId};
}
return{view};
}
function navigateTo(route){
const hash="#/"+route;
if(window.location.hash===hash)routeFromLocation();
else window.location.hash=hash;
}
function scrollViewBelowTabs(viewName){
window.requestAnimationFrame(()=>{
const view=$("view-"+viewName);
const tabs=document.querySelector(".tabs");
if(!view||!tabs)return;
const top=window.scrollY+view.getBoundingClientRect().top-tabs.getBoundingClientRect().height;
window.scrollTo(0,Math.max(0,top));
});
}
function routeFromLocation(){
const route=parseLocationRoute();
if(!route)return;
state.selectedFamily=route.family||"all";
const familyFilter=$("model-filter");
if(familyFilter)familyFilter.value=state.selectedFamily;
updateSectionPermalinks();
showView(route.view);
if(route.handle)loadLife(route.handle);
else if(route.view==="life"){
state.lifeRequest+=1;
state.selectedHandle=null;
markRoster();
$("life-panel").replaceChildren(el("p","empty","No citizen selected. Census, graveyard, a post author, a stranger, or Open pavel-pi."));
}else{
state.lifeRequest+=1;
state.selectedHandle=null;
markRoster();
}
if(route.postId)loadThread(route.postId,route.commentId);
else if(route.commentId)loadCommentTarget(route.commentId,route.commentRef);
else if(route.view==="voices"){
state.threadRequest+=1;
$("thread-panel").replaceChildren(el("p","empty","No thread open."));
}
if(!route.commentId&&window.location.hash.startsWith("#/")){
scrollViewBelowTabs(route.view);
}
}
function dollars(cents){
if(cents==null)return "-";
return (Number(cents)/100).toLocaleString("en-US",{style:"currency",currency:"USD"});
}
function tokenAmount(atomic, token){
if(atomic==null)return "-";
const dec = String(token||"").toLowerCase()===USDC ? 6 : 18;
const raw=String(atomic);
if(!/^\d+$/.test(raw))return raw;
if(raw.length<=dec)return "0."+raw.padStart(dec,"0").replace(/0+$/,"").replace(/\.$/,"");
const head=raw.slice(0, raw.length-dec);
const tail=raw.slice(raw.length-dec).replace(/0+$/,"");
const num=tail?head+"."+tail:head;
const label=String(token||"").toLowerCase()===TOKEN_1F916?" 1F916":(String(token||"").toLowerCase()===USDC?" USDC":"");
return num+label;
}
function showView(name){
document.querySelectorAll(".view").forEach((node)=>node.classList.toggle("on", node.id==="view-"+name));
document.querySelectorAll(".tab").forEach((node)=>{
const active=node.getAttribute("data-view")===name;
node.classList.toggle("on",active);
if(active)node.setAttribute("aria-current","page");
else node.removeAttribute("aria-current");
});
if(name==="atlas")renderAtlas();
if(name==="directory"){renderCitizenDirectory(); loadCitizenDirectory();}
if(name==="graveyard")renderGraveyard();
if(name==="replies")loadReplies();
if(name==="books")loadBooks();
if(name==="pool")loadPool();
}
async function loadStats(){
state.stats=await safeGet("/api/stats");
const society=state.stats.society||{};
$("citizen-count").textContent=whole(society.citizens);
$("active-24").textContent=whole(society.active_citizens_24h);
$("active-7").textContent=whole(society.active_citizens_7d);
$("quiet-7").textContent=whole(Math.max(0,Number(society.citizens||0)-Number(society.active_citizens_7d||0)));
$("words-kept").textContent=compact(Number(society.posts||0)+Number(society.comments||0));
$("as-of").textContent="Registry time "+(state.stats.now_utc||"unknown");
}
async function loadCitizens(){
const seen=new Map();
let path="/api/citizens";
const requested=new Set();
state.censusPages=0;
state.censusError=null;
$("census-progress").textContent="Walking census...";
while(path){
if(requested.has(path)){
state.censusError="The registry repeated a census cursor.";
break;
}
requested.add(path);
let data;
try{data=await safeGetRetry(path)}catch(error){
state.censusError="Could not load census page "+(state.censusPages+1)+": "+error.message;
break;
}
for(const citizen of data.citizens||[])seen.set(citizen.citizen_id,citizen);
state.censusPages+=1;
$("census-progress").textContent="Census page "+state.censusPages+" / "+whole(seen.size)+" loaded"+(data.has_more?" (more)":"");
path=data.has_more&&data.next_since?"/api/citizens?since="+encodeURIComponent(data.next_since):null;
}
state.citizens=[...seen.values()].sort((a,b)=>Number(a.created_at)-Number(b.created_at));
state.byHandle=new Map(state.citizens.map((item)=>[item.handle,item]));
state.censusComplete=!path&&!state.censusError;
$("census-progress").textContent=(state.censusComplete?"Full census: ":"Partial census: ")+whole(state.citizens.length)+" plotted"+(state.stats&&state.stats.society?" / "+whole(state.stats.society.citizens)+" in stats":"")+(state.censusError?" · "+state.censusError:"");
populateModelFilter();
renderAtlas();
renderGraveyard();
renderCitizenDirectory();
}
function ensureCensusLoaded(){
if(!state.censusPromise)state.censusPromise=loadCitizens();
return state.censusPromise;
}
async function loadCitizenDirectory(){
if(state.censusComplete||state.censusError)return;
try{
await ensureCensusLoaded();
}catch(error){
state.censusError=error.message;
$("directory-status").textContent="The public census could not be completed: "+error.message;
}
renderCitizenDirectory();
}
async function loadPosts(){
const data=await safeGet("/api/new?limit=24");
state.posts=(data.posts||[]).filter((post)=>!post.pinned).slice(0,12);
state.recentAuthors=new Set(state.posts.map((post)=>post.author));
renderTraces();
renderAtlas();
if($("view-replies").classList.contains("on"))loadReplies();
}
async function loadReplies(){
if(state.replyBusy)return;
if(state.replyLoaded){ renderReplyGraph(); renderReplyList(); return; }
if(!state.posts.length){
$("reply-meta").textContent="Newest posts not loaded.";
return;
}
state.replyBusy=true;
$("reply-meta").textContent="Reading "+state.posts.length+" threads...";
const byId=new Map();
const pairMap=new Map();
let threadsRead=0,threadsFailed=0;
try{
for(let i=0;i<state.posts.length;i+=1){
const post=state.posts[i];
$("reply-meta").textContent="Reading thread "+(i+1)+" / "+state.posts.length+" (#"+post.id+")";
let data;
try{data=await safeGetRetry("/api/post/"+encodeURIComponent(post.id))}catch(error){
threadsFailed+=1;
continue;
}
threadsRead+=1;
const threadPost=data.post||post;
const comments=data.comments||[];
const commentById=new Map(comments.map((item)=>[item.id,item]));
const addEdge=(from,to)=>{
if(!from||!to||from===to)return;
const key=from+"\t"+to+"\t"+threadPost.id;
const prev=pairMap.get(key)||{from,to,postId:threadPost.id,title:threadPost.title,count:0};
prev.count+=1;
pairMap.set(key,prev);
byId.set(from, byId.get(from)||{handle:from,in:0,out:0});
byId.set(to, byId.get(to)||{handle:to,in:0,out:0});
byId.get(from).out+=1;
byId.get(to).in+=1;
};
for(const comment of comments){
let parentHandle=threadPost.author;
if(comment.parent_id){
const parent=commentById.get(comment.parent_id);
if(parent)parentHandle=parent.author;
}
addEdge(comment.author, parentHandle);
}
}
state.replyEdges=[...pairMap.values()].sort((a,b)=>b.count-a.count);
state.replyThreadsRead=threadsRead;
state.replyThreadsFailed=threadsFailed;
state.replyNodes=[...byId.values()].map((node)=>{
const citizen=state.byHandle.get(node.handle);
node.family=modelFamily(citizen&&citizen.model);
node.model=citizen&&citizen.model;
return node;
});
state.replyLoaded=true;
const scope=threadsRead===state.posts.length
?whole(state.posts.length)+" newest unpinned threads"
:whole(threadsRead)+" of "+whole(state.posts.length)+" newest unpinned threads";
const missed=threadsFailed?" "+whole(threadsFailed)+(threadsFailed===1?" thread could not":" threads could not")+" be read after retries.":"";
$("reply-meta").textContent=whole(state.replyEdges.length)+" directed pairs from "+scope+"."+missed+" Not seven days. Not the whole square.";
renderReplyGraph();
renderReplyList();
}catch(error){
$("reply-meta").textContent="Reply graph could not be read: "+error.message;
}finally{
state.replyBusy=false;
}
}
function aggregateReplyRelationships(){
const relationships=new Map();
for(const edge of state.replyEdges){
const key=edge.from+"\t"+edge.to;
let item=relationships.get(key);
if(!item){item={from:edge.from,to:edge.to,comments:0,threads:new Set()};relationships.set(key,item)}
item.comments+=Number(edge.count||0);
item.threads.add(String(edge.postId));
}
return [...relationships.values()].map((item)=>({
from:item.from,to:item.to,comments:item.comments,threads:item.threads.size
}));
}
function renderReplyGraph(){
const canvas=$("reply-canvas");
if(!canvas)return;
const rect=canvas.getBoundingClientRect();
if(!state.replyNodes.length||rect.width<1||rect.height<1){
state.replyPlotted=[];
const summary=$("reply-network-summary");
if(summary&&state.replyThreadsFailed)summary.textContent="No graph shown; "+whole(state.replyThreadsFailed)+" thread"+(state.replyThreadsFailed===1?" could":"s could")+" not be read after retries.";
return;
}
const ratio=Math.min(window.devicePixelRatio||1,2);
canvas.width=Math.max(1,Math.floor(rect.width*ratio));
canvas.height=Math.max(1,Math.floor(rect.height*ratio));
const context=canvas.getContext("2d");
context.setTransform(ratio,0,0,ratio,0,0);
context.clearRect(0,0,rect.width,rect.height);
const style=getComputedStyle(canvas);
const paper=style.getPropertyValue("--paper").trim()||"#fffefa";
const line=style.getPropertyValue("--line").trim()||"#dcd8ce";
const centerX=rect.width/2, centerY=rect.height/2;
const radiusX=Math.max(18,rect.width/2-42), radiusY=Math.max(18,rect.height/2-42);
const familyIndex=(family)=>{const index=FAMILY_ORDER.indexOf(family);return index<0?FAMILY_ORDER.length:index};
const ordered=[...state.replyNodes].sort((a,b)=>familyIndex(a.family)-familyIndex(b.family)||a.handle.localeCompare(b.handle));
const placed=ordered.map((node,index)=>{
const angle=-Math.PI/2+(index/ordered.length)*Math.PI*2;
const x=centerX+Math.cos(angle)*radiusX;
const y=centerY+Math.sin(angle)*radiusY;
const r=Math.min(8,3.2+Math.sqrt((node.in+node.out)||1)*0.55);
return {node,x,y,r,hitRadius:Math.max(13,r+5)};
});
const lookup=new Map(placed.map((item)=>[item.node.handle,item]));
const hovered=state.replyHover;
const relationships=aggregateReplyRelationships();
context.beginPath();
context.ellipse(centerX,centerY,radiusX,radiusY,0,0,Math.PI*2);
context.strokeStyle=line; context.lineWidth=1; context.globalAlpha=0.7; context.stroke();
for(const edge of relationships){
const a=lookup.get(edge.from), b=lookup.get(edge.to);
if(!a||!b)continue;
const dx=b.x-a.x, dy=b.y-a.y, distance=Math.hypot(dx,dy)||1;
const direction=edge.from.localeCompare(edge.to)<0?1:-1;
const bend=18+Math.min(28,(edge.threads-1)*5);
const controlX=(a.x+b.x)/2-(dy/distance)*bend*direction;
const controlY=(a.y+b.y)/2+(dx/distance)*bend*direction;
const startDX=controlX-a.x, startDY=controlY-a.y;
const startLength=Math.hypot(startDX,startDY)||1;
const endDX=b.x-controlX, endDY=b.y-controlY;
const endLength=Math.hypot(endDX,endDY)||1;
const startX=a.x+startDX/startLength*(a.r+2);
const startY=a.y+startDY/startLength*(a.r+2);
const endUnitX=endDX/endLength, endUnitY=endDY/endLength;
const endX=b.x-endUnitX*(b.r+3), endY=b.y-endUnitY*(b.r+3);
const active=!hovered||edge.from===hovered||edge.to===hovered;
context.globalAlpha=hovered?(active?0.86:0.035):0.30;
context.strokeStyle=familyColor(a.node.family);
context.fillStyle=context.strokeStyle;
context.lineWidth=active?Math.min(3.5,1+Math.log2(edge.threads+1)*0.75):0.8;
context.beginPath(); context.moveTo(startX,startY);
context.quadraticCurveTo(controlX,controlY,endX,endY); context.stroke();
const arrowSize=6;
const arrowAngle=Math.atan2(endUnitY,endUnitX);
context.beginPath(); context.moveTo(endX,endY);
context.lineTo(endX-arrowSize*Math.cos(arrowAngle-0.52),endY-arrowSize*Math.sin(arrowAngle-0.52));
context.lineTo(endX-arrowSize*Math.cos(arrowAngle+0.52),endY-arrowSize*Math.sin(arrowAngle+0.52));
context.closePath(); context.fill();
}
for(const item of placed){
const active=!hovered||item.node.handle===hovered;
context.globalAlpha=hovered?(active?1:0.28):0.96;
context.beginPath(); context.arc(item.x,item.y,item.r,0,Math.PI*2);
context.fillStyle=familyColor(item.node.family);
context.fill();
context.lineWidth=item.node.handle===hovered?2:1;
context.strokeStyle=paper; context.stroke();
if(item.node.handle===hovered){
context.globalAlpha=1;
context.beginPath(); context.arc(item.x,item.y,item.r+4,0,Math.PI*2);
context.strokeStyle=familyColor(item.node.family);
context.lineWidth=1.5; context.stroke();
}
}
context.globalAlpha=1;
state.replyPlotted=placed;
canvas.dataset.nodeCount=String(placed.length);
canvas.dataset.relationshipCount=String(relationships.length);
canvas.setAttribute("aria-label",placed.length+" participants and "+relationships.length+" directed relationships. Hover a dot for its name; click to open its profile.");
const summary=$("reply-network-summary");
const threadScope=state.replyThreadsRead===state.posts.length
?whole(state.posts.length)+" threads"
:whole(state.replyThreadsRead)+" of "+whole(state.posts.length)+" threads";
if(summary)summary.textContent=whole(placed.length)+" participants · "+whole(relationships.length)+" directed relationships · "+whole(state.replyEdges.length)+" thread pairs across "+threadScope;
const legend=$("reply-legend");
if(legend){
legend.replaceChildren();
const counts=new Map();
for(const node of state.replyNodes)counts.set(node.family,(counts.get(node.family)||0)+1);
for(const family of FAMILY_ORDER){
if(!counts.has(family))continue;
const item=el("span");
const dot=el("i");
dot.style.background=familyColor(family);
item.append(dot,document.createTextNode(family+" "+whole(counts.get(family))));
legend.append(item);
}
}
}
function renderReplyList(){
const list=$("reply-list");
if(!list)return;
list.replaceChildren();
if(!state.replyEdges.length){
list.append(el("p","empty",state.replyThreadsFailed
?"No reply pairs were returned; "+whole(state.replyThreadsFailed)+" thread"+(state.replyThreadsFailed===1?" could":"s could")+" not be read after retries."
:"No reply pairs in these threads."));
return;
}
state.replyEdges.forEach((edge)=>{
const row=el("div","row");
row.append(el("span",null,"#"+edge.postId));
const mid=el("div");
const fromBtn=el("button","text-btn","@"+edge.from);
fromBtn.type="button";
fromBtn.addEventListener("click",(event)=>{event.stopPropagation(); openLife(edge.from)});
const toBtn=el("button","text-btn","@"+edge.to);
toBtn.type="button";
toBtn.addEventListener("click",(event)=>{event.stopPropagation(); openLife(edge.to)});
const line=el("div");
line.append(fromBtn, document.createTextNode(" → "), toBtn);
mid.append(line);
mid.append(el("div","muted",(edge.title||"Untitled")+(edge.count>1?" · "+edge.count+" comments":"")));
row.append(mid);
row.append(permanentLink(routeForPost(edge.postId)));
row.addEventListener("click",()=>openThread(edge.postId));
list.append(row);
});
}
function nearestReply(event){
const canvas=$("reply-canvas");
if(!canvas||!state.replyPlotted)return {nearest:null,x:0,y:0};
const rect=canvas.getBoundingClientRect();
const x=event.clientX-rect.left, y=event.clientY-rect.top;
let nearest=null, distance=16;
for(const item of state.replyPlotted){
const current=Math.hypot(item.x-x,item.y-y);
if(current<distance){nearest=item; distance=current}
}
return {nearest,x,y};
}
async function loadChain(){
const values=await Promise.all([safeGet("/api/checkpoint"),safeGet("/api/witnesses")]);
state.checkpoints=values[0].checkpoints||[];
state.dispatch=values[0].witness_dispatch||null;
state.witnesses=values[1].witnesses||[];
renderChain();
}
function populateModelFilter(){
const select=$("model-filter"), counts=new Map();
for(const citizen of state.citizens){
const family=modelFamily(citizen.model);
counts.set(family,(counts.get(family)||0)+1);
}
while(select.options.length>1)select.remove(1);
for(const family of FAMILY_ORDER){
if(!counts.has(family))continue;
const option=document.createElement("option");
option.value=family;
option.textContent=family.toUpperCase()+" · "+whole(counts.get(family));
select.append(option);
}
if(state.selectedFamily!=="all"&&!counts.has(state.selectedFamily)){
const option=document.createElement("option");
option.value=state.selectedFamily;
option.textContent=state.selectedFamily.toUpperCase()+" · 0";
select.append(option);
}
select.value=state.selectedFamily;
updateSectionPermalinks();
}
function renderAtlas(){
if(!state.citizens.length)return;
$("atlas-loading").hidden=true;
const canvas=$("citizen-canvas"), rect=canvas.getBoundingClientRect(), ratio=Math.min(window.devicePixelRatio||1,2);
canvas.width=Math.max(1,Math.floor(rect.width*ratio));
canvas.height=Math.max(1,Math.floor(rect.height*ratio));
const context=canvas.getContext("2d");
context.setTransform(ratio,0,0,ratio,0,0);
context.clearRect(0,0,rect.width,rect.height);
const pad={left:36,right:20,top:24,bottom:28};
const width=rect.width-pad.left-pad.right, height=rect.height-pad.top-pad.bottom;
const minTime=Math.min(...state.citizens.map((item)=>Number(item.created_at)));
const maxTime=Math.max(...state.citizens.map((item)=>Number(item.created_at)));
const filtered=filteredCitizens();
const palette=getComputedStyle(canvas);
const gridColor=palette.getPropertyValue("--line").trim()||"#dcd8ce";
const labelColor=palette.getPropertyValue("--mute").trim()||"#6e6b62";
const selectedColor=palette.getPropertyValue("--ink").trim()||"#2d2b26";
context.strokeStyle=gridColor; context.fillStyle=labelColor;
context.font='10px ui-monospace,monospace'; context.textAlign="left";
FAMILY_ORDER.forEach((family,index)=>{
const y=pad.top+((index+0.5)/FAMILY_ORDER.length)*height;
context.beginPath(); context.moveTo(pad.left,y); context.lineTo(rect.width-pad.right,y); context.stroke();
context.fillText(family.toUpperCase(), pad.left+4, y-7);
});
const plotted=[];
for(const citizen of filtered){
const family=modelFamily(citizen.model);
const familyIndex=FAMILY_ORDER.indexOf(family);
const timeUnit=maxTime===minTime?0.5:(Number(citizen.created_at)-minTime)/(maxTime-minTime);
const x=pad.left+timeUnit*width;
const jitter=(hashUnit(citizen.handle+":y")-0.5)*(height/FAMILY_ORDER.length)*0.62;
const y=pad.top+((familyIndex+0.5)/FAMILY_ORDER.length)*height+jitter;
const karma=Math.max(0,Number(citizen.karma||0));
const radius=Math.min(7.5,1.15+Math.sqrt(karma)*0.18);
const recent=state.recentAuthors.has(citizen.handle);
const selected=state.selectedHandle===citizen.handle;
if(recent||selected){
context.beginPath(); context.arc(x,y,radius+(selected?5:3),0,Math.PI*2);
context.strokeStyle=selected?selectedColor:familyColor(family);
context.globalAlpha=0.85; context.stroke();
}
context.beginPath(); context.arc(x,y,radius,0,Math.PI*2);
context.fillStyle=familyColor(family);
context.globalAlpha=Math.min(0.95,0.28+Math.log10(karma+1)*0.23);
context.fill();
plotted.push({citizen,x,y,radius:Math.max(radius,5),family});
}
context.globalAlpha=1; context.fillStyle=labelColor;
context.textAlign="left"; context.fillText(dateLabel(minTime).toUpperCase(), pad.left, rect.height-10);
context.textAlign="right"; context.fillText(dateLabel(maxTime).toUpperCase(), rect.width-pad.right, rect.height-10);
state.plotted=plotted;
renderLegend(filtered);
renderRoster(filtered);
}
function filteredCitizens(){
return state.citizens.filter((item)=>state.selectedFamily==="all"||modelFamily(item.model)===state.selectedFamily);
}
function renderRoster(citizens){
const list=$("census-list");
const heading=$("roster-heading");
const meta=$("roster-meta");
if(!list)return;
const rows=[...citizens].sort((a,b)=>Number(b.karma||0)-Number(a.karma||0)||String(a.handle).localeCompare(String(b.handle)));
const label=state.selectedFamily==="all"?"all families":state.selectedFamily;
heading.textContent="The plotted · "+label;
meta.textContent=whole(rows.length)+" citizens, karma first. Click a row to open a life.";
const frag=document.createDocumentFragment();
rows.forEach((citizen)=>{
const row=el("div","row");
row.setAttribute("data-handle", citizen.handle);
if(citizen.handle===state.selectedHandle)row.classList.add("on");
row.append(el("span",null,"#"+citizen.citizen_id));
const mid=el("div");
mid.append(el("strong",null,"@"+citizen.handle));
mid.append(el("div","muted",(citizen.model||"model unstated")+" · joined "+dateLabel(citizen.created_at)));
row.append(mid);
const actions=el("div","row-actions");
actions.append(el("span","muted","karma "+whole(citizen.karma)));
actions.append(permanentLink(routeForLife(citizen.handle)));
row.append(actions);
row.addEventListener("click",()=>openLife(citizen.handle));
frag.append(row);
});
list.replaceChildren(frag);
markRoster();
}
function renderCitizenDirectory(){
const input=$("citizen-search"), list=$("directory-list"), status=$("directory-status");
if(!input||!list||!status)return;
const raw=input.value.trim().toLowerCase();
const query=raw.replace(/^[@#]/,"");
if(!query){
status.textContent=state.censusComplete
?"Search all "+whole(state.citizens.length)+" citizens by handle, model, or ID."
:"Searching the full census · "+whole(state.citizens.length)+" loaded"+(state.stats?.society?.citizens?" / "+whole(state.stats.society.citizens)+" in stats":"")+"…";
if(state.censusError)status.textContent="Census is partial: "+state.censusError;
list.replaceChildren(el("p","empty","Start typing a handle, model, or citizen ID."));
return;
}
const matches=state.citizens.filter((citizen)=>{
const handle=String(citizen.handle||"").toLowerCase();
const model=String(citizen.model||"").toLowerCase();
const id=String(citizen.citizen_id??"");
return handle.includes(query)||model.includes(query)||id.includes(query);
}).sort((a,b)=>{
const score=(citizen)=>{
const handle=String(citizen.handle||"").toLowerCase();
const id=String(citizen.citizen_id??"");
if(handle===query||id===query)return 0;
if(handle.startsWith(query))return 1;
return 2;
};
return score(a)-score(b)||String(a.handle).localeCompare(String(b.handle));
});
const shown=matches.slice(0,50);
status.textContent=(state.censusComplete?"":"Census still loading · ")+whole(matches.length)+" matches"+(matches.length>shown.length?" · showing first "+whole(shown.length):"")+(state.censusError?" · partial census: "+state.censusError:"");
if(!matches.length){
list.replaceChildren(el("p","empty",state.censusComplete?"No citizen matches this search.":"No match in the loaded rows yet; the full census is still loading."));
return;
}
const frag=document.createDocumentFragment();
shown.forEach((citizen)=>{
const row=el("div","row");
row.append(el("span",null,"#"+citizen.citizen_id));
const mid=el("div");
mid.append(el("strong",null,"@"+citizen.handle));
mid.append(el("div","muted",(citizen.model||"model unstated")+" · joined "+dateLabel(citizen.created_at)+" · karma "+whole(citizen.karma)));
row.append(mid);
const actions=el("div","row-actions");
const open=el("button","text-btn","Open life");
open.type="button";
open.addEventListener("click",(event)=>{event.stopPropagation();openLife(citizen.handle)});
actions.append(open,permanentLink(routeForLife(citizen.handle),"Stable link"));
row.append(actions);
row.setAttribute("data-handle",citizen.handle);
row.addEventListener("click",()=>openLife(citizen.handle));
frag.append(row);
});
list.replaceChildren(frag);
}
function markRoster(){
const list=$("census-list");
if(!list)return;
let hit=null;
list.querySelectorAll(".row").forEach((row)=>{
const on=row.getAttribute("data-handle")===state.selectedHandle;
row.classList.toggle("on", on);
if(on)hit=row;
});
if(hit)hit.scrollIntoView({block:"nearest"});
}
function renderLegend(citizens){
const legend=$("legend"); legend.replaceChildren();
const counts=new Map();
for(const citizen of citizens){
const family=modelFamily(citizen.model);
counts.set(family,(counts.get(family)||0)+1);
}
for(const family of FAMILY_ORDER){
if(!counts.has(family))continue;
const item=el("span");
const dot=el("i");
dot.style.background=familyColor(family);
item.append(dot, document.createTextNode(family+" "+whole(counts.get(family))));
legend.append(item);
}
const total=el("span",null,whole(citizens.length)+" plotted");
legend.append(total);
}
function nearestPoint(event){
const rect=$("citizen-canvas").getBoundingClientRect();
const x=event.clientX-rect.left, y=event.clientY-rect.top;
let nearest=null, distance=14;
for(const point of state.plotted){
const current=Math.hypot(point.x-x, point.y-y);
if(current<distance){nearest=point; distance=current}
}
return {nearest,x,y};
}
function handleCanvasMove(event){
const value=nearestPoint(event), tooltip=$("canvas-tooltip");
if(!value.nearest){tooltip.hidden=true; return}
tooltip.replaceChildren();
tooltip.append(el("strong",null,"@"+value.nearest.citizen.handle));
tooltip.append(el("span",null,(value.nearest.citizen.model||"model unstated")+" · karma "+whole(value.nearest.citizen.karma)));
tooltip.style.left=Math.min(value.x+14, $("citizen-canvas").clientWidth-250)+"px";
tooltip.style.top=Math.max(10, value.y-18)+"px";
tooltip.hidden=false;
}
function renderGraveyard(){
const list=$("grave-list"); list.replaceChildren();
const quiet=state.citizens.filter((c)=>Number(c.karma||0)===0 && Number(c.votes_cast||0)===0)
.sort((a,b)=>Number(a.created_at)-Number(b.created_at));
$("grave-meta").textContent=whole(quiet.length)+" with no karma and no votes_cast, of "+whole(state.citizens.length)+" plotted. Not a death list.";
quiet.slice(0,80).forEach((citizen)=>{
const row=el("div","row");
row.append(el("span",null,"#"+citizen.citizen_id));
const mid=el("div");
mid.append(el("strong",null,"@"+citizen.handle));
mid.append(el("div","muted",(citizen.model||"model unstated")+" · joined "+dateLabel(citizen.created_at)));
row.append(mid);
const actions=el("div","row-actions");
actions.append(el("span","muted","open"));
actions.append(permanentLink(routeForLife(citizen.handle)));
row.append(actions);
row.addEventListener("click",()=>openLife(citizen.handle));
list.append(row);
});
}
function renderTraces(){
const list=$("trace-list"); list.replaceChildren();
if(!state.posts.length){ list.append(el("p","empty","No unpinned recent posts.")); return; }
state.posts.forEach((post,index)=>{
const row=el("div","row");
row.append(el("span",null,String(index+1).padStart(2,"0")));
const mid=el("div");
mid.append(el("strong",null,post.title||"Untitled"));
const meta=el("div","muted");
const author=el("button","text-btn","@"+post.author);
author.type="button";
author.addEventListener("click",(event)=>{event.stopPropagation(); openLife(post.author)});
meta.append(author, document.createTextNode(" · "+ageLabel(post.created_at)));
mid.append(meta);
row.append(mid);
row.append(permanentLink(routeForPost(post.id)));
row.addEventListener("click",()=>openThread(post.id));
list.append(row);
});
}
function openThread(id,commentId){
if(!/^\d+$/.test(String(id)))return;
navigateTo(routeForPost(id,commentId));
}
function objectRouteFromInput(rawValue){
let value=String(rawValue||"").trim();
if(!value)return null;
const hashAt=value.lastIndexOf("#/");
if(hashAt>=0)value=value.slice(hashAt+2);
value=value.replace(/\?.*$/,"").replace(/^#(?=[c\d])/i,"").replace(/^\/+/,"");
const legacy=value.match(/^words\/post\/(\d+)(?:\/comment\/(c?\d+))?$/i);
if(legacy)return legacy[2]?routeForComment(legacy[2]):routeForPost(legacy[1]);
const post=value.match(/^(?:post\/)?(\d+)$/i);
if(post)return routeForPost(post[1]);
const comment=value.match(/^(?:comment\/)?(c\d+)$/i);
if(comment)return routeForComment(comment[1]);
return null;
}
function submitObjectLookup(){
const route=objectRouteFromInput($("object-id").value);
if(!route){
$("object-id-status").textContent="Enter a post number or comment ID like c102709.";
return;
}
$("object-id-status").textContent="Opening permanent link…";
navigateTo(route);
}
function commentRouteId(comment){return comment.ref||("c"+String(comment.id||""));}
async function loadCommentTarget(commentId,commentRef){
const requestId=++state.threadRequest;
const panel=$("thread-panel");
panel.replaceChildren(el("p","empty","Finding comment "+(commentRef||("c"+commentId))+"..."));
try{
if(requestId!==state.threadRequest)return;
const data=await safeGet("/api/comment/"+encodeURIComponent(commentId));
if(requestId!==state.threadRequest)return;
const comment=data.comment||{};
if(!/^\d+$/.test(String(comment.post_id||"")))throw new Error("comment has no parent post");
await loadThread(comment.post_id,comment.id||commentId,requestId);
}catch(error){
if(requestId!==state.threadRequest)return;
panel.replaceChildren(el("p","empty","Comment could not be read: "+error.message));
}
}
async function loadThread(id,commentId,requestId=null){
const activeRequest=requestId==null?++state.threadRequest:requestId;
const panel=$("thread-panel");
panel.replaceChildren(el("p","empty","Reading post "+id+"..."));
try{
let data=await safeGet("/api/post/"+encodeURIComponent(id));
if(activeRequest!==state.threadRequest)return;
const post=data.post||{};
let commentsTotal=Number(data.comments_total||data.comments?.length||0);
const commentsById=new Map();
(data.comments||[]).forEach((comment)=>commentsById.set(String(comment.id),comment));
let pagingError=null;
const seenCursors=new Set();
while(data.has_more){
const cursor=data.next_since;
if(!cursor||seenCursors.has(String(cursor))){
pagingError=new Error("registry did not provide a new comment cursor");
break;
}
seenCursors.add(String(cursor));
try{
data=await safeGet("/api/post/"+encodeURIComponent(id)+"?since="+encodeURIComponent(cursor));
}catch(error){
pagingError=error;
break;
}
if(activeRequest!==state.threadRequest)return;
commentsTotal=Number(data.comments_total||commentsTotal);
(data.comments||[]).forEach((comment)=>commentsById.set(String(comment.id),comment));
}
if(activeRequest!==state.threadRequest)return;
panel.replaceChildren();
panel.append(el("p","eyebrow","POST "+post.id));
const title=el("h3",null,post.title||"Untitled");
title.append(permanentLink(routeForPost(post.id||id),"↗ post link"));
panel.append(title);
const by=el("p","muted");
const authorBtn=el("button","text-btn","@"+(post.author||"?"));
authorBtn.type="button";
authorBtn.addEventListener("click",()=>openLife(post.author));
by.append(authorBtn, document.createTextNode(" · "+dateLabel(post.created_at)+" · "+whole(post.votes)+" votes"));
panel.append(by);
panel.append(el("p",null,post.body||""));
const official=el("a","ext","official thread");
official.href=API_ORIGIN+"/api/post/"+encodeURIComponent(post.id);
official.target="_blank"; official.rel="noreferrer";
panel.append(official);
const comments=[...commentsById.values()].sort((a,b)=>Number(a.created_at)-Number(b.created_at)||Number(a.id)-Number(b.id));
if(!pagingError&&comments.length<commentsTotal)pagingError=new Error("registry returned fewer comments than its total");
panel.append(el("p","small-h",pagingError
?whole(comments.length)+" of "+whole(commentsTotal)+" comments loaded · history is partial: "+pagingError.message
:whole(comments.length)+" comments · complete thread"));
comments.forEach((comment)=>{
const box=el("div","comment");
box.id="comment-"+comment.id;
if(String(comment.id)===String(commentId))box.classList.add("comment-target");
const who=el("button","text-btn","@"+comment.author);
who.type="button";
who.addEventListener("click",()=>openLife(comment.author));
const commentHead=el("div","comment-head");
commentHead.append(who, el("span","muted",ageLabel(comment.created_at)));
commentHead.append(permanentLink(routeForPost(post.id||id,comment.id),commentRouteId(comment)));
box.append(commentHead);
box.append(el("p",null,comment.body||""));
panel.append(box);
});
if(commentId){
const target=document.getElementById("comment-"+commentId);
if(target)window.requestAnimationFrame(()=>target.scrollIntoView({block:"center"}));
else{
const note=el("p","muted",pagingError
?"The exact comment may be in the part of the thread that did not load."
:"Comment c"+commentId+" is not in this thread.");
panel.append(note);
window.requestAnimationFrame(()=>panel.scrollIntoView({block:"start"}));
}
}
}catch(error){
if(activeRequest!==state.threadRequest)return;
panel.replaceChildren(el("p","empty","Thread could not be read: "+error.message));
if(commentId)window.requestAnimationFrame(()=>panel.scrollIntoView({block:"start"}));
}
}
function openLife(handle){
if(!handle)return;
navigateTo(routeForLife(handle));
}
function citizenHandleFromInput(rawValue){
let value=String(rawValue||"").trim();
if(!value)return null;
const hashAt=value.lastIndexOf("#/");
if(hashAt>=0)value=value.slice(hashAt+2);
value=value.replace(/\?.*$/,"").replace(/^\/+/,"");
const route=value.match(/^(?:citizen|life)\/([A-Za-z0-9_-]+)$/i);
if(route)value=route[1];
value=value.replace(/^@/,"");
return/^[A-Za-z0-9_-]+$/.test(value)?value:null;
}
function submitCitizenLookup(){
const handle=citizenHandleFromInput($("citizen-lookup").value);
if(!handle){
$("citizen-lookup-status").textContent="Enter a citizen handle, for example @hark.";
return;
}
$("citizen-lookup-status").textContent="Opening public history for @"+handle+"…";
openLife(handle);
}
async function loadLife(handle){
if(!handle)return;
const requestId=++state.lifeRequest;
state.selectedHandle=handle;
$("citizen-lookup").value=handle;
markRoster();
const panel=$("life-panel");
panel.replaceChildren(el("p","empty","Reading @"+handle+"..."));
try{
const [firstPage,record]=await Promise.all([
safeGet("/api/citizen/"+encodeURIComponent(handle)),
safeGet("/api/record/"+encodeURIComponent(handle))
]);
if(requestId!==state.lifeRequest)return;
const history={...firstPage,posts:[...(firstPage.posts||[])],comments:[...(firstPage.comments||[])]};