-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.html
More file actions
682 lines (630 loc) · 34.1 KB
/
Copy pathmonitor.html
File metadata and controls
682 lines (630 loc) · 34.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Monitor — WeScripture</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&family=EB+Garamond:wght@600;700&display=swap" rel="stylesheet">
<style>
:root{--bg:#f7f3eb;--card:#fffdf9;--line:rgba(0,0,0,.10);--text:#2f2a24;--muted:#7a6d5c;--accent:#9c7a4d;}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);font:14px/1.5 Inter,system-ui,sans-serif}
header{padding:18px 18px 8px;max-width:1100px;margin:0 auto}
.brand{display:flex;gap:10px;align-items:baseline}
.brand a{text-decoration:none;color:inherit}
h1{margin:0;font:700 34px/1.05 "EB Garamond",Georgia,serif}
.sub{margin:6px 0 0;color:var(--muted)}
main{max-width:1100px;margin:0 auto;padding:14px 18px 34px}
.row{display:flex;flex-wrap:wrap;gap:10px;align-items:stretch}
.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:14px 14px 12px;min-width:240px;flex:1}
.k{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}
.v{margin-top:6px;font-size:28px;font-weight:700;color:var(--accent)}
.meta{margin-top:4px;color:var(--muted);font-size:12px}
.controls{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:12px 0 2px}
button{border:1px solid rgba(156,122,77,.28);background:#fcfaf6;color:var(--accent);font-weight:700;padding:10px 12px;border-radius:12px;cursor:pointer}
button:hover{background:rgba(156,122,77,.08)}
button:disabled{opacity:.6;cursor:default}
.status{color:var(--muted);font-size:12px}
.charts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:10px}
@media(max-width:900px){.charts{grid-template-columns:1fr}}
canvas{width:100%;height:180px}
.chart-title{margin:0 0 8px;font:700 18px/1.15 "EB Garamond",Georgia,serif}
.small{font-size:12px;color:var(--muted)}
.tables{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:10px}
@media(max-width:900px){.tables{grid-template-columns:1fr}}
table{width:100%;border-collapse:collapse}
th,td{padding:8px 8px;border-top:1px solid rgba(0,0,0,.08);font-size:13px;vertical-align:top}
th{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);text-align:left}
td.n{white-space:nowrap;text-align:right;color:var(--accent);font-weight:700}
tr.clickable td:first-child{cursor:pointer}
tr.clickable td:first-child:hover{text-decoration:underline}
.detail{padding:10px 10px 8px;color:var(--text)}
.detail .small{color:var(--muted)}
.detail-list{margin:6px 0 0;padding-left:18px}
.detail-list li{margin:2px 0}
.mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace}
.mini-links{display:flex;gap:10px;flex-wrap:wrap;margin-top:8px}
.mini-links a{color:var(--accent);text-decoration:none;font-weight:700}
.mini-links a:hover{text-decoration:underline}
.monitor-fab{position:fixed;right:14px;bottom:14px;z-index:999;display:inline-flex;align-items:center;justify-content:center;padding:10px 12px;border-radius:999px;border:1px solid rgba(156,122,77,.28);background:rgba(254,252,248,.96);color:var(--accent);text-decoration:none;font-weight:700;font-size:13px;box-shadow:0 10px 28px rgba(0,0,0,.10);backdrop-filter:blur(10px)}
.monitor-fab:hover{background:rgba(156,122,77,.08)}
</style>
</head>
<body>
<header>
<div class="brand"><a href="./index.html">WeScripture</a></div>
<h1>Monitor</h1>
<p class="sub">Shared history via Supabase when configured. Otherwise, uses local history on this device. <a href="./gloss-monitor.html">Gloss build pipeline</a> (deep keyword index).</p>
</header>
<main>
<div class="controls">
<button id="runNow" type="button">Run now</button>
<button id="clearLocal" type="button">Clear local history</button>
<span id="status" class="status"></span>
</div>
<div class="row">
<div class="card"><div class="k">Links (total)</div><div class="v" id="mLinks">—</div><div class="meta" id="mLinksMeta"></div></div>
<div class="card"><div class="k">Paragraphs (total)</div><div class="v" id="mParas">—</div><div class="meta" id="mParasMeta"></div></div>
<div class="card"><div class="k">Sources (docs)</div><div class="v" id="mSources">—</div><div class="meta" id="mSourcesMeta"></div></div>
</div>
<div class="charts">
<div class="card"><h2 class="chart-title">Links over time</h2><canvas id="cLinks" width="900" height="360"></canvas><div class="small" id="cLinksHint"></div></div>
<div class="card"><h2 class="chart-title">Paragraphs over time</h2><canvas id="cParas" width="900" height="360"></canvas><div class="small" id="cParasHint"></div></div>
<div class="card"><h2 class="chart-title">Sources over time</h2><canvas id="cSources" width="900" height="360"></canvas><div class="small" id="cSourcesHint"></div></div>
</div>
<div class="charts">
<div class="card"><h2 class="chart-title">Docs linked (%)</h2><canvas id="cDocPct" width="900" height="360"></canvas><div class="small" id="cDocPctHint"></div></div>
<div class="card"><h2 class="chart-title">Paragraphs linked (%)</h2><canvas id="cParaPct" width="900" height="360"></canvas><div class="small" id="cParaPctHint"></div></div>
<div class="card"><h2 class="chart-title">Linked paragraphs (count)</h2><canvas id="cLinkedParas" width="900" height="360"></canvas><div class="small" id="cLinkedParasHint"></div></div>
</div>
<div class="tables">
<div class="card">
<h2 class="chart-title">Top verses by connections</h2>
<div class="small" id="thresh"></div>
<div class="mini-links">
<a href="/library/published/verse_connection_counts.tsv">Download all verses (TSV)</a>
</div>
<table aria-label="Top verses"><thead><tr><th>Verse</th><th class="n">Links</th></tr></thead><tbody id="topVerses"><tr><td colspan="2" class="small">Loading…</td></tr></tbody></table>
</div>
<div class="card">
<h2 class="chart-title">Top morsels by verses</h2>
<div class="small">Morsel = (doc_id, para_idx)</div>
<div class="mini-links">
<a href="/library/published/morsel_connection_counts.tsv">Download all morsels (TSV)</a>
</div>
<table aria-label="Top morsels"><thead><tr><th>Morsel</th><th class="n">Verses</th></tr></thead><tbody id="topMorsels"><tr><td colspan="2" class="small">Loading…</td></tr></tbody></table>
</div>
</div>
<div class="card" style="margin-top:10px">
<h2 class="chart-title">Browse full tables</h2>
<div class="small">Smart filtering: search + min connections + sort + pagination.</div>
<div class="controls" style="margin-top:8px">
<select id="browseKind" style="padding:10px 12px;border-radius:12px;border:1px solid rgba(0,0,0,.12);background:#fffdf9;color:var(--text);font-weight:700">
<option value="verses">Verses</option>
<option value="morsels">Morsels</option>
</select>
<input id="browseQ" type="search" placeholder="Filter (e.g. 'John 3' or 'history_of_church')" style="flex:1;min-width:220px;padding:10px 12px;border-radius:12px;border:1px solid rgba(0,0,0,.12);background:#fffdf9" />
<input id="browseMin" type="number" min="0" step="1" value="0" style="width:120px;padding:10px 12px;border-radius:12px;border:1px solid rgba(0,0,0,.12);background:#fffdf9" />
<select id="browseSort" style="padding:10px 12px;border-radius:12px;border:1px solid rgba(0,0,0,.12);background:#fffdf9;color:var(--text);font-weight:700">
<option value="desc">Most first</option>
<option value="asc">Least first</option>
</select>
</div>
<div class="controls" style="margin-top:6px">
<button id="browsePrev" type="button">Prev</button>
<button id="browseNext" type="button">Next</button>
<span class="status" id="browseMeta"></span>
</div>
<table aria-label="Browse results" style="margin-top:6px">
<thead><tr><th id="browseColA">Item</th><th class="n" id="browseColB">Count</th></tr></thead>
<tbody id="browseBody"><tr><td colspan="2" class="small">Loading…</td></tr></tbody>
</table>
<div class="mini-links">
<a href="/library/published/verse_connection_counts.tsv">Download verses TSV</a>
<a href="/library/published/morsel_connection_counts.tsv">Download morsels TSV</a>
<a href="/library/published/connection_thresholds.json">Thresholds JSON</a>
</div>
</div>
<div class="card" style="margin-top:10px">
<h2 class="chart-title">Corpus backlog</h2>
<div class="small">Add items that still need to be pulled in, encoded, correlated, etc. (shared via Supabase when configured).</div>
<div class="controls" style="margin-top:8px">
<input id="blTitle" type="text" placeholder="Title" style="flex:2;min-width:220px;padding:10px 12px;border-radius:12px;border:1px solid rgba(0,0,0,.12);background:#fffdf9" />
<input id="blUrl" type="url" placeholder="URL (optional)" style="flex:3;min-width:220px;padding:10px 12px;border-radius:12px;border:1px solid rgba(0,0,0,.12);background:#fffdf9" />
<button id="blAdd" type="button">Add</button>
<span id="blStatus" class="status"></span>
</div>
<div class="controls" style="margin-top:6px">
<label class="small"><input type="checkbox" id="blNeedPull" checked /> pull</label>
<label class="small"><input type="checkbox" id="blNeedEncode" checked /> encode</label>
<label class="small"><input type="checkbox" id="blNeedCorrelate" checked /> correlate</label>
</div>
<table aria-label="Corpus backlog" style="margin-top:6px">
<thead><tr><th>Item</th><th>Status</th><th class="n">Priority</th><th>Needs</th><th></th></tr></thead>
<tbody id="blBody"><tr><td colspan="5" class="small">Loading…</td></tr></tbody>
</table>
</div>
</main>
<script>
const KEY = 'wescripture_monitor_v1';
function fmt(n){ return Number(n||0).toLocaleString(); }
function setText(id, v){ const el=document.getElementById(id); if(el) el.textContent = v; }
function loadLocal(){ try{ const raw = localStorage.getItem(KEY); if(!raw) return []; const arr = JSON.parse(raw); return Array.isArray(arr) ? arr : []; }catch(e){ return []; } }
function saveLocal(arr){ try{ localStorage.setItem(KEY, JSON.stringify(arr.slice(-180))); }catch(e){} }
function summarizeDelta(arr, field){
if(arr.length < 2) return '';
const a = arr[arr.length-2][field] || 0, b = arr[arr.length-1][field] || 0;
const d = b - a;
if(!d) return 'no change since last run';
return (d>0?'+':'') + fmt(d) + ' since last run';
}
function renderLatest(arr){
const last = arr[arr.length-1];
if(!last){ setText('mLinks','—'); setText('mParas','—'); setText('mSources','—'); setText('mLinksMeta',''); setText('mParasMeta',''); setText('mSourcesMeta',''); return; }
setText('mLinks', fmt(last.links)); setText('mParas', fmt(last.paragraphs)); setText('mSources', fmt(last.sources));
setText('mLinksMeta', summarizeDelta(arr,'links')); setText('mParasMeta', summarizeDelta(arr,'paragraphs')); setText('mSourcesMeta', summarizeDelta(arr,'sources'));
}
function drawSeries(canvasId, hintId, arr, field){
const c=document.getElementById(canvasId), hint=document.getElementById(hintId);
if(!c) return;
const ctx=c.getContext('2d'), w=c.width, h=c.height;
ctx.clearRect(0,0,w,h);
ctx.fillStyle='#fffdf9'; ctx.fillRect(0,0,w,h);
ctx.strokeStyle='rgba(0,0,0,0.08)'; ctx.strokeRect(0.5,0.5,w-1,h-1);
const pts = arr.slice(-60).map(x => Number(x[field]||0));
if(pts.length < 2){ if(hint) hint.textContent = pts.length ? '1 point' : 'No history yet.'; return; }
let min=Math.min(...pts), max=Math.max(...pts); if(min===max){ min=min*0.98; max=max*1.02; }
const padX=18,padY=18;
const x=i=>padX+(i/(pts.length-1))*(w-2*padX);
const y=v=>(h-padY)-((v-min)/(max-min))*(h-2*padY);
ctx.strokeStyle='rgba(0,0,0,0.06)';
for(let i=0;i<=4;i++){ const yy=padY+(i/4)*(h-2*padY); ctx.beginPath(); ctx.moveTo(padX,yy); ctx.lineTo(w-padX,yy); ctx.stroke(); }
ctx.strokeStyle='#9c7a4d'; ctx.lineWidth=2;
ctx.beginPath(); ctx.moveTo(x(0),y(pts[0])); for(let i=1;i<pts.length;i++) ctx.lineTo(x(i),y(pts[i])); ctx.stroke();
ctx.fillStyle='#9c7a4d'; ctx.beginPath(); ctx.arc(x(pts.length-1),y(pts[pts.length-1]),4,0,Math.PI*2); ctx.fill();
if(hint) hint.textContent = `Last ${pts.length} points · min ${fmt(min)} · max ${fmt(max)} · last ${fmt(pts[pts.length-1])}`;
}
function docPct(x){
const a = Number(x && x.linked_docs) || 0;
const b = Number(x && x.sources) || 0;
return b ? (a / b * 100.0) : 0;
}
function paraPct(x){
const a = Number(x && x.linked_paragraphs) || 0;
const b = Number(x && x.paragraphs) || 0;
return b ? (a / b * 100.0) : 0;
}
function renderAll(arr){
renderLatest(arr);
drawSeries('cLinks','cLinksHint',arr,'links');
drawSeries('cParas','cParasHint',arr,'paragraphs');
drawSeries('cSources','cSourcesHint',arr,'sources');
// Coverage series (computed on the fly from fields)
drawSeries('cLinkedParas','cLinkedParasHint',arr,'linked_paragraphs');
(function(){
const docSeries = (arr||[]).map(x => Object.assign({}, x, { __doc_pct: docPct(x) }));
const paraSeries = (arr||[]).map(x => Object.assign({}, x, { __para_pct: paraPct(x) }));
drawSeries('cDocPct','cDocPctHint',docSeries,'__doc_pct');
drawSeries('cParaPct','cParaPctHint',paraSeries,'__para_pct');
})();
}
async function fetchText(url){
const r = await fetch(url, { cache:'no-store' });
if(!r.ok) throw new Error('HTTP ' + r.status);
return await r.text();
}
function parseTsvCounts(text){
const out = [];
String(text||'').split('\n').forEach(line => {
const s = (line||'').trim();
if(!s || s.startsWith('#')) return;
const parts = s.split('\t');
if(parts.length < 2) return;
// Verses TSV: verse_ref \t connections
// Morsels TSV: doc_id \t para_idx \t verses
let name = parts[0];
let n = 0;
if(parts.length >= 3){
name = parts[0] + '\t' + parts[1];
n = Number(parts[2]) || 0;
} else {
n = Number(parts[1]) || 0;
}
out.push([name, n]);
});
return out;
}
function renderTopTable(tbodyId, rows, labelFmt){
const tb = document.getElementById(tbodyId);
if(!tb) return;
const top = (rows||[]).slice(0, 25);
if(!top.length){ tb.innerHTML = `<tr><td colspan="2" class="small">No data.</td></tr>`; return; }
tb.innerHTML = top.map(([name, n]) => {
const safe = String(name||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
return `<tr><td>${labelFmt ? labelFmt(safe) : safe}</td><td class="n">${fmt(n)}</td></tr>`;
}).join('');
}
async function loadPublishedCounts(){
try{
const [thTxt, vTxt, mTxt] = await Promise.all([
fetch('/library/published/connection_thresholds.json', { cache:'no-store' }).then(r=>r.ok?r.json():null).catch(()=>null),
fetchText('/library/published/verse_connection_counts.tsv'),
fetchText('/library/published/morsel_connection_counts.tsv'),
]);
const tEl = document.getElementById('thresh');
if(tEl && thTxt && thTxt.graph_min_score_default != null){
tEl.textContent = `Linked if score ≥ ${thTxt.graph_min_score_default} (graph). Verse-discovery UI uses ≥ ${thTxt.verse_discovery_min_score_default}.`;
} else if (tEl) {
tEl.textContent = 'Linked if score ≥ 0.25 (graph). Verse-discovery UI uses ≥ 0.40.';
}
const vRows = parseTsvCounts(vTxt).sort((a,b)=>b[1]-a[1]);
const mRows = parseTsvCounts(mTxt).sort((a,b)=>b[1]-a[1]);
renderTopTable('topVerses', vRows);
renderTopTable('topMorsels', mRows, (safe)=>`<span style="font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace">${safe}</span>`);
// Cache for browser table
window.__PUBLISHED = {
verses: vRows,
morsels: mRows,
thresholds: thTxt || null,
};
initBrowseTable();
}catch(e){
const v = document.getElementById('topVerses');
const m = document.getElementById('topMorsels');
if(v) v.innerHTML = `<tr><td colspan="2" class="small">Error loading published tables.</td></tr>`;
if(m) m.innerHTML = `<tr><td colspan="2" class="small">Error loading published tables.</td></tr>`;
}
}
function initBrowseTable(){
const state = window.__BROWSE_STATE || { kind:'verses', q:'', min:0, sort:'desc', page:0, pageSize:200, rows:[] };
window.__BROWSE_STATE = state;
const elKind = document.getElementById('browseKind');
const elQ = document.getElementById('browseQ');
const elMin = document.getElementById('browseMin');
const elSort = document.getElementById('browseSort');
const elPrev = document.getElementById('browsePrev');
const elNext = document.getElementById('browseNext');
function applyFromInputs(resetPage){
state.kind = (elKind && elKind.value) || state.kind;
state.q = (elQ && elQ.value) ? String(elQ.value).trim().toLowerCase() : '';
state.min = Number(elMin && elMin.value) || 0;
state.sort = (elSort && elSort.value) || state.sort;
if(resetPage) state.page = 0;
renderBrowse();
}
if(elKind) elKind.addEventListener('change', ()=>applyFromInputs(true));
if(elQ) elQ.addEventListener('input', ()=>applyFromInputs(true));
if(elMin) elMin.addEventListener('input', ()=>applyFromInputs(true));
if(elSort) elSort.addEventListener('change', ()=>applyFromInputs(true));
if(elPrev) elPrev.addEventListener('click', ()=>{ state.page = Math.max(0, state.page-1); renderBrowse(); });
if(elNext) elNext.addEventListener('click', ()=>{ state.page = state.page+1; renderBrowse(); });
applyFromInputs(true);
}
function renderBrowse(){
const pub = window.__PUBLISHED || {};
const state = window.__BROWSE_STATE;
const rows = (state.kind === 'morsels') ? (pub.morsels || []) : (pub.verses || []);
const q = state.q || '';
const min = state.min || 0;
let filtered = rows;
if(min > 0) filtered = filtered.filter(r => (r && r[1] >= min));
if(q) filtered = filtered.filter(r => String(r[0]||'').toLowerCase().includes(q));
filtered = filtered.slice().sort((a,b)=> state.sort === 'asc' ? (a[1]-b[1]) : (b[1]-a[1]));
const total = filtered.length;
const pageSize = state.pageSize;
const page = Math.max(0, state.page || 0);
const start = page * pageSize;
const end = Math.min(total, start + pageSize);
if(start >= total && page > 0){ state.page = 0; return renderBrowse(); }
const tb = document.getElementById('browseBody');
const meta = document.getElementById('browseMeta');
const colA = document.getElementById('browseColA');
const colB = document.getElementById('browseColB');
if(colA) colA.textContent = state.kind === 'morsels' ? 'Morsel' : 'Verse';
if(colB) colB.textContent = state.kind === 'morsels' ? 'Verses' : 'Links';
if(meta) meta.textContent = `${fmt(total)} match${total===1?'':'es'} · showing ${fmt(start+1)}–${fmt(end)} (page ${page+1})`;
if(!tb) return;
const view = filtered.slice(start, end);
if(!view.length){ tb.innerHTML = `<tr><td colspan="2" class="small">No matches.</td></tr>`; return; }
const expanded = state.expandedKey || '';
tb.innerHTML = view.map(([name, n]) => {
const safe = String(name||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
const key = state.kind === 'morsels' ? safe : safe;
const a = state.kind === 'morsels'
? `<span class="mono">${safe}</span>`
: safe;
const isOpen = expanded && expanded === key;
const row = `<tr class="clickable" data-key="${safe}"><td>${a}</td><td class="n">${fmt(n)}</td></tr>`;
const det = isOpen ? `<tr class="detail-row"><td colspan="2"><div class="detail" data-detail-for="${safe}"><span class="small">Loading…</span></div></td></tr>` : '';
return row + det;
}).join('');
}
async function ensureSourceLinks(){
if(window.__SOURCE_LINKS) return window.__SOURCE_LINKS;
const r = await fetch('/library/source_links.json', { cache:'no-store' });
if(!r.ok) throw new Error('source_links_http_' + r.status);
const j = await r.json();
window.__SOURCE_LINKS = j || {};
return window.__SOURCE_LINKS;
}
function linkToJump(ref){
const u = '/library/index.html?jump=' + encodeURIComponent(String(ref||''));
const safe = String(ref||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
return `<a href="${u}">${safe}</a>`;
}
async function renderDetailsFor(state, key){
const tb = document.getElementById('browseBody');
if(!tb) return;
const host = tb.querySelector(`[data-detail-for="${CSS.escape(key)}"]`);
if(!host) return;
try{
const sl = await ensureSourceLinks();
if(state.kind === 'morsels'){
const parts = String(key).split('\\t');
// key in our table is full doc_id or verse_ref; for morsels TSV we stored doc_id in col 0 only,
// but browse table uses the TSV name string (doc_id) and count. Need para_idx as part of key? Not present.
// In browse view we show morsel key as "doc_id\tpara_idx" in the TSV name field (see published file).
const name = String(key);
const i = name.lastIndexOf('\\t');
const docId = i >= 0 ? name.slice(0, i) : name;
const paraIdx = i >= 0 ? name.slice(i+1) : '';
const refs = (sl && sl[docId] && sl[docId][String(paraIdx)]) ? sl[docId][String(paraIdx)] : [];
if(!refs || !refs.length){
host.innerHTML = `<div class="small">No verse refs found for this morsel.</div>`;
return;
}
const items = refs.slice(0, 20).map(r => {
const score = (r && r.score != null) ? Number(r.score) : null;
const s = (score != null && !Number.isNaN(score)) ? ` <span class="small">(score ${score.toFixed(3)})</span>` : '';
return `<li>${linkToJump(r.ref)}${s}</li>`;
}).join('');
host.innerHTML = `<div class="small">Connected verses (top ${Math.min(20, refs.length)}):</div><ol class="detail-list">${items}</ol>`;
return;
}
// kind === verses: invert source_links on demand for this verse
const target = String(key);
const hits = [];
for(const docId of Object.keys(sl||{})){
const paras = sl[docId];
if(!paras || typeof paras !== 'object') continue;
for(const paraIdx of Object.keys(paras)){
const refs = paras[paraIdx];
if(!Array.isArray(refs) || !refs.length) continue;
let best = null;
for(const rr of refs){
if(rr && rr.ref === target){
const sc = (rr.score != null) ? Number(rr.score) : 0;
if(best == null || sc > best) best = sc;
}
}
if(best != null){
hits.push({ docId, paraIdx, score: best });
}
}
}
hits.sort((a,b)=> (b.score - a.score));
const top = hits.slice(0, 20);
if(!top.length){
host.innerHTML = `<div class="small">No morsels found for this verse in source_links.</div>`;
return;
}
const items = top.map(h => {
const id = `${h.docId}\\t${h.paraIdx}`;
const safeId = id.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
const s = (h.score != null && !Number.isNaN(h.score)) ? ` <span class="small">(score ${Number(h.score).toFixed(3)})</span>` : '';
return `<li><span class="mono">${safeId}</span>${s}</li>`;
}).join('');
host.innerHTML = `<div class="small">Connected morsels (top ${top.length}):</div><ol class="detail-list">${items}</ol>`;
}catch(e){
host.innerHTML = `<div class="small">Error loading details.</div>`;
}
}
(function wireBrowseClicks(){
document.addEventListener('click', function(ev){
const tr = ev.target && ev.target.closest ? ev.target.closest('#browseBody tr.clickable') : null;
if(!tr) return;
const state = window.__BROWSE_STATE;
if(!state) return;
const key = tr.getAttribute('data-key') || '';
if(!key) return;
state.expandedKey = (state.expandedKey === key) ? '' : key;
renderBrowse();
if(state.expandedKey) renderDetailsFor(state, state.expandedKey);
});
})();
async function readFnJson(r){
const text = await r.text();
const t = (text || '').trim();
if(!t) throw new Error('Empty response from server.');
if(t[0] === '<'){
throw new Error('Server returned HTML instead of JSON (Netlify function missing or blocked). Use Netlify deploy / netlify dev, or remove SPA rewrites for /.netlify/functions/*.');
}
try { return JSON.parse(t); } catch (e) {
throw new Error('Invalid JSON from server: ' + (e && e.message ? e.message : String(e)));
}
}
async function fetchServerHistory(){
const r = await fetch('/.netlify/functions/monitor_history', { cache:'no-store' });
const j = await readFnJson(r);
if(!r.ok) throw new Error((j && j.error) || ('HTTP ' + r.status));
if(j && j.ok && j.configured && Array.isArray(j.items)) return { configured:true, items:j.items };
return { configured:false, items:[] };
}
async function fetchBacklog(){
const r = await fetch('/.netlify/functions/monitor_backlog', { cache:'no-store' });
const j = await readFnJson(r);
if(!r.ok) throw new Error((j && j.error) || ('HTTP ' + r.status));
if(j && j.ok && j.configured && Array.isArray(j.items)) return { configured:true, items:j.items };
return { configured:false, items:[] };
}
async function backlogMutate(method, payload){
const r = await fetch('/.netlify/functions/monitor_backlog', {
method,
cache:'no-store',
headers: { 'content-type':'application/json; charset=utf-8' },
body: JSON.stringify(payload || {}),
});
const j = await readFnJson(r);
if(!r.ok) throw new Error((j && j.error) || ('HTTP ' + r.status));
return j;
}
function needsLabel(needs){
const n = needs && typeof needs === 'object' ? needs : {};
const parts = [];
if(n.pull) parts.push('pull');
if(n.encode) parts.push('encode');
if(n.correlate) parts.push('correlate');
return parts.length ? parts.join(', ') : '—';
}
function renderBacklog(items){
const tb = document.getElementById('blBody');
if(!tb) return;
const rows = Array.isArray(items) ? items : [];
if(!rows.length){ tb.innerHTML = `<tr><td colspan="5" class="small">No backlog items.</td></tr>`; return; }
tb.innerHTML = rows.map(it => {
const title = String(it.title||'').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
const url = String(it.canonical_url||'').trim();
const safeUrl = url.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
const st = String(it.status||'todo');
const pri = Number(it.priority||0);
const needs = needsLabel(it.needs);
const itemCell = url ? `<a href="${safeUrl}" target="_blank" rel="noreferrer" style="color:var(--accent);font-weight:700;text-decoration:none">${title}</a>` : `<span style="font-weight:700">${title}</span>`;
return `<tr data-id="${String(it.id)}">
<td>${itemCell}<div class="small">${String(it.author||'')}</div></td>
<td>
<select class="blStatusSel" style="padding:8px 10px;border-radius:10px;border:1px solid rgba(0,0,0,.12);background:#fffdf9">
${['todo','doing','blocked','done'].map(x => `<option value="${x}" ${x===st?'selected':''}>${x}</option>`).join('')}
</select>
</td>
<td class="n"><input class="blPri" type="number" value="${pri}" step="1" style="width:90px;padding:8px 10px;border-radius:10px;border:1px solid rgba(0,0,0,.12);background:#fffdf9;text-align:right" /></td>
<td class="small">${needs}</td>
<td class="n"><button class="blDel" type="button">Del</button></td>
</tr>`;
}).join('');
}
async function runNow(){
const btn=document.getElementById('runNow');
const status=document.getElementById('status');
if(btn) btn.disabled = true;
if(status) status.textContent='Running…';
try{
const hist = await fetchServerHistory();
if(hist.configured){
const r = await fetch('/.netlify/functions/monitor_sample', { cache:'no-store' });
const j = await readFnJson(r);
if(!r.ok || !j.ok) throw new Error((j && j.error) || ('HTTP ' + r.status));
const hist2 = await fetchServerHistory();
renderAll(hist2.items || []);
if(status) status.textContent = 'Saved to shared history.';
} else {
const r = await fetch('/.netlify/functions/monitor_metrics', { cache:'no-store' });
const j = await readFnJson(r);
if(!r.ok) throw new Error((j && j.error) || ('HTTP ' + r.status));
const arr = loadLocal(); arr.push(j); saveLocal(arr); renderAll(arr);
if(status) status.textContent = `Saved locally (${arr.length} points).`;
}
}catch(e){
if(status) status.textContent = 'Error: ' + (e && (e.message || String(e)));
}finally{
if(btn) btn.disabled = false;
}
}
document.getElementById('runNow').addEventListener('click', runNow);
document.getElementById('clearLocal').addEventListener('click', () => { localStorage.removeItem(KEY); renderAll([]); const s=document.getElementById('status'); if(s) s.textContent='Local history cleared.'; });
(async function init(){
try{
const hist = await fetchServerHistory();
if(hist.configured){
renderAll(hist.items || []);
setText('status', 'Using shared history.');
return;
}
}catch(e){}
const local = loadLocal();
renderAll(local);
const last = local[local.length-1];
const lastDay = last && last.ts ? String(last.ts).slice(0,10) : '';
const today = new Date().toISOString().slice(0,10);
if(lastDay !== today) runNow();
})();
loadPublishedCounts();
(async function initBacklog(){
const s = document.getElementById('blStatus');
try{
const bl = await fetchBacklog();
if(!bl.configured){
if(s) s.textContent = 'Not configured on server.';
const tb = document.getElementById('blBody');
if(tb) tb.innerHTML = `<tr><td colspan="5" class="small">Backlog requires Supabase server env.</td></tr>`;
return;
}
window.__BACKLOG = bl.items || [];
renderBacklog(window.__BACKLOG);
if(s) s.textContent = `Loaded ${fmt(window.__BACKLOG.length)} items.`;
}catch(e){
if(s) s.textContent = 'Error: ' + (e && (e.message || String(e)));
}
})();
document.getElementById('blAdd').addEventListener('click', async () => {
const s = document.getElementById('blStatus');
const title = (document.getElementById('blTitle').value || '').trim();
const url = (document.getElementById('blUrl').value || '').trim();
const needs = {
pull: !!document.getElementById('blNeedPull').checked,
encode: !!document.getElementById('blNeedEncode').checked,
correlate: !!document.getElementById('blNeedCorrelate').checked,
};
if(!title){ if(s) s.textContent = 'Title required.'; return; }
try{
if(s) s.textContent = 'Adding…';
await backlogMutate('POST', { title, canonical_url: url, needs });
const bl = await fetchBacklog();
window.__BACKLOG = bl.items || [];
renderBacklog(window.__BACKLOG);
document.getElementById('blTitle').value = '';
document.getElementById('blUrl').value = '';
if(s) s.textContent = 'Added.';
}catch(e){
if(s) s.textContent = 'Error: ' + (e && (e.message || String(e)));
}
});
document.addEventListener('change', async (ev) => {
const tr = ev.target && ev.target.closest ? ev.target.closest('#blBody tr[data-id]') : null;
if(!tr) return;
const id = tr.getAttribute('data-id');
if(!id) return;
const s = document.getElementById('blStatus');
const sel = tr.querySelector('.blStatusSel');
const pri = tr.querySelector('.blPri');
try{
if(s) s.textContent = 'Saving…';
await backlogMutate('PATCH', { id, status: sel ? sel.value : undefined, priority: pri ? pri.value : undefined });
if(s) s.textContent = 'Saved.';
}catch(e){
if(s) s.textContent = 'Error: ' + (e && (e.message || String(e)));
}
});
document.addEventListener('click', async (ev) => {
const btn = ev.target && ev.target.closest ? ev.target.closest('.blDel') : null;
if(!btn) return;
const tr = btn.closest('#blBody tr[data-id]');
if(!tr) return;
const id = tr.getAttribute('data-id');
const s = document.getElementById('blStatus');
try{
if(s) s.textContent = 'Deleting…';
await backlogMutate('DELETE', { id });
const bl = await fetchBacklog();
window.__BACKLOG = bl.items || [];
renderBacklog(window.__BACKLOG);
if(s) s.textContent = 'Deleted.';
}catch(e){
if(s) s.textContent = 'Error: ' + (e && (e.message || String(e)));
}
});
</script>
<a class="monitor-fab" href="/monitor.html" aria-label="Open Monitor">Monitor</a>
</body>
</html>