-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.html
More file actions
952 lines (849 loc) · 30 KB
/
Copy pathreader.html
File metadata and controls
952 lines (849 loc) · 30 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vidlib</title>
<!-- Inline SVG favicon: vidlib document mark (magenta + cyan lines). No file, no 404. -->
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'><rect width='32' height='32' rx='7' fill='%230d0f0e'/><rect x='8' y='9' width='16' height='2.5' rx='1.2' fill='%23ff3fa4'/><rect x='8' y='15' width='16' height='2.5' rx='1.2' fill='%2336e0e0'/><rect x='8' y='21' width='11' height='2.5' rx='1.2' fill='%2336e0e0'/></svg>">
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Source+Serif+4:ital,opsz,wght@0,8..60,300;0,8..60,400;0,8..60,600;1,8..60,400&display=swap');
* { margin: 0; padding: 0; box-sizing: border-box; }
:root {
/* vidlib kit: dark token ladder (surfaces darkest -> raised) */
--bg: #0a0e14;
--bg2: #0d1320;
--surface: #0f1726;
--surface-2: #121d30;
--border: #1c2740;
--border-2: #26344f;
/* text: body kept comfortable (kit --nc-ink), never crushed to dim for prose */
--text: #c7d2e1;
--text-dim: #5d6b86;
--text-bright: #e6edf6;
/* structure / interactive accent = kit cyan (rings, links, active, progress) */
--accent: #36e0e0;
--accent-dim: #1d9c9c;
--accent-glow: rgba(54, 224, 224, 0.08);
/* brand wordmark = kit magenta (signature only, used sparingly) */
--mag: #ff3fa4;
--mag-glow: rgba(255, 63, 164, 0.55);
--r: 8px;
--mono: 'IBM Plex Mono', ui-monospace, "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, monospace;
--serif: 'Source Serif 4', Georgia, serif;
}
body {
font-family: var(--serif);
background:
radial-gradient(1200px 600px at 15% -10%, rgba(255, 63, 164, 0.06), transparent 60%),
radial-gradient(1000px 700px at 95% 0%, rgba(54, 224, 224, 0.05), transparent 55%),
var(--bg);
background-attachment: fixed;
color: var(--text);
line-height: 1.7;
min-height: 100vh;
-webkit-font-smoothing: antialiased;
}
/* Visible keyboard focus everywhere (never remove the ring) */
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
/* Screen-reader-only + skip link */
.sr-only {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
}
.skip-link {
position: fixed; top: 8px; left: 8px; z-index: 300;
background: var(--surface-2); color: var(--accent);
font-family: var(--mono); font-size: 12px;
padding: 8px 12px; border: 1px solid var(--accent-dim); border-radius: var(--r);
transform: translateY(-160%); transition: transform 0.2s;
}
.skip-link:focus { transform: translateY(0); }
/* ─── Layout ─── */
.app { display: flex; min-height: 100vh; }
.sidebar {
width: 320px;
min-width: 320px;
background: var(--surface);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
height: 100vh;
position: sticky;
top: 0;
}
.sidebar-header {
padding: 24px 20px 16px;
border-bottom: 1px solid var(--border);
}
/* vidlib wordmark: the signature. Magenta, wide tracking, soft glow. */
.sidebar-header h1 {
font-family: var(--mono);
font-size: 16px;
font-weight: 800;
color: var(--mag);
letter-spacing: 0.22em;
text-shadow: 0 0 18px var(--mag-glow), 0 0 2px rgba(255, 63, 164, 0.9);
}
.sidebar-header .count {
font-family: var(--mono);
font-size: 11px;
color: var(--text-dim);
margin-top: 4px;
}
.sidebar-search {
padding: 12px 20px 8px;
border-bottom: 1px solid var(--border);
}
.sidebar-search input {
width: 100%;
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--r);
padding: 8px 12px;
color: var(--text);
font-family: var(--mono);
font-size: 12px;
caret-color: var(--mag);
transition: border-color 0.2s, box-shadow 0.2s;
}
.sidebar-search input:focus { border-color: var(--accent-dim); box-shadow: 0 0 0 1px rgba(54, 224, 224, 0.25); }
.sidebar-search input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.sidebar-search input::placeholder { color: var(--text-dim); }
.sidebar-sort {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 20px 12px;
border-bottom: 1px solid var(--border);
}
.sidebar-sort .sort-label {
font-family: var(--mono);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--text-dim);
}
.sort-select {
flex: 1;
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--r);
padding: 6px 10px;
color: var(--text);
font-family: var(--mono);
font-size: 11px;
cursor: pointer;
}
.sidebar-list {
flex: 1;
overflow-y: auto;
padding: 8px 0;
}
.sidebar-list::-webkit-scrollbar { width: 4px; }
.sidebar-list::-webkit-scrollbar-track { background: transparent; }
.sidebar-list::-webkit-scrollbar-thumb { background: var(--border-2); border-radius: 2px; }
.channel-group { margin-bottom: 4px; }
/* Channel header doubles as a collapse toggle (native button) */
.channel-header {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
background: none;
border: 0;
cursor: pointer;
padding: 12px 20px 6px;
font-family: var(--mono);
text-align: left;
color: var(--text-dim);
transition: color 0.15s;
}
.channel-header:hover { color: var(--text); }
.channel-header .caret {
font-size: 9px;
width: 10px;
flex: 0 0 10px;
color: var(--accent-dim);
}
.channel-header .channel-name {
flex: 1;
font-size: 10px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.1em;
}
.channel-header .channel-count {
font-size: 10px;
color: var(--text-dim);
opacity: 0.7;
}
/* Sidebar item is now a real <button>, focusable + keyboard-operable for free */
.sidebar-item {
display: block;
width: 100%;
text-align: left;
background: none;
border: 0;
border-left: 2px solid transparent;
font-family: var(--serif);
color: inherit;
padding: 10px 20px;
cursor: pointer;
transition: background 0.15s;
}
.sidebar-item:hover { background: var(--surface-2); }
.sidebar-item.active {
background: var(--accent-glow);
border-left-color: var(--accent);
}
.sidebar-item .title {
font-size: 14px;
color: var(--text-bright);
line-height: 1.4;
}
.sidebar-item .meta {
font-family: var(--mono);
font-size: 10px;
color: var(--text-dim);
margin-top: 3px;
}
.list-empty {
font-family: var(--mono);
font-size: 11px;
color: var(--text-dim);
padding: 20px;
line-height: 1.6;
}
/* ─── Reader ─── */
.reader {
flex: 1;
display: flex;
justify-content: center;
padding: 60px 40px;
overflow-y: auto;
height: 100vh;
}
.reader-content {
max-width: 680px;
width: 100%;
}
.reader-empty,
.reader-loading {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: var(--text-dim);
font-family: var(--mono);
font-size: 13px;
text-align: center;
line-height: 1.8;
}
.reader-loading { flex-direction: column; gap: 4px; }
.empty-panel { max-width: 440px; text-align: left; }
.empty-panel p { margin-bottom: 14px; }
.empty-panel .lead { color: var(--text); font-size: 14px; margin-bottom: 18px; }
.empty-panel .hint { color: var(--text-dim); margin-top: 18px; margin-bottom: 6px; }
.empty-panel code { color: var(--text); }
.empty-panel strong { color: var(--text-bright); font-weight: 500; }
.cmd {
display: block;
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--r);
padding: 10px 12px;
color: var(--accent);
font-family: var(--mono);
font-size: 12px;
line-height: 1.6;
white-space: pre-wrap;
margin-bottom: 4px;
}
.spinner {
width: 22px; height: 22px;
border: 2px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin-bottom: 14px;
}
@keyframes spin { to { transform: rotate(360deg); } }
.reader-title {
font-size: 32px;
font-weight: 600;
color: var(--text-bright);
line-height: 1.25;
margin-bottom: 16px;
}
.reader-meta {
font-family: var(--mono);
font-size: 12px;
color: var(--text-dim);
margin-bottom: 8px;
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.reader-meta a {
color: var(--accent);
text-decoration: none;
transition: opacity 0.2s;
}
.reader-meta a:hover { opacity: 0.7; }
.reader-divider {
width: 40px;
height: 1px;
background: var(--accent-dim);
opacity: 0.6;
margin: 32px 0;
}
.reader-body p {
margin-bottom: 20px;
font-size: 17px;
color: var(--text);
}
.reader-body p:last-child { margin-bottom: 0; }
/* ─── Drop zone ─── */
.drop-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(10, 14, 20, 0.92);
z-index: 400;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 16px;
}
.drop-overlay.active { display: flex; }
.drop-overlay .drop-icon {
width: 64px;
height: 64px;
border: 2px dashed var(--accent);
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 28px;
}
.drop-overlay .drop-text {
font-family: var(--mono);
font-size: 14px;
color: var(--accent);
}
/* ─── File input ─── */
.load-btn {
margin: 12px 20px;
padding: 10px;
background: var(--bg);
border: 1px dashed var(--border);
border-radius: var(--r);
color: var(--text-dim);
font-family: var(--mono);
font-size: 11px;
cursor: pointer;
text-align: center;
transition: border-color 0.2s, color 0.2s;
}
.load-btn:hover { border-color: var(--accent-dim); color: var(--text); }
.load-btn:focus-within { border-color: var(--accent); color: var(--text); }
.load-btn input { display: none; }
/* ─── Reading progress ─── */
.progress-bar {
position: fixed;
top: 0;
left: 320px;
right: 0;
height: 2px;
background: transparent;
z-index: 50;
}
.progress-bar .fill {
height: 100%;
background: var(--accent);
width: 0%;
transition: width 0.1s;
box-shadow: 0 0 8px rgba(54, 224, 224, 0.5);
}
/* ─── Mobile sidebar toggle + scrim ─── */
.sidebar-toggle {
display: none;
position: fixed;
top: 12px;
left: 12px;
z-index: 250;
width: 40px;
height: 40px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--accent);
font-size: 18px;
line-height: 1;
cursor: pointer;
align-items: center;
justify-content: center;
}
.scrim {
display: none;
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.55);
z-index: 180;
}
.scrim.active { display: block; }
/* ─── Responsive ─── */
@media (max-width: 768px) {
.sidebar-toggle { display: flex; }
.sidebar {
position: fixed;
left: 0;
top: 0;
height: 100vh;
width: min(320px, 85vw);
min-width: 0;
z-index: 200;
transform: translateX(-100%);
transition: transform 0.25s ease;
box-shadow: 0 0 40px rgba(0, 0, 0, 0.5);
}
.sidebar.open { transform: translateX(0); }
.reader { padding: 64px 20px 32px; height: 100vh; }
.progress-bar { left: 0; }
}
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
.spinner { border-top-color: var(--accent); }
}
</style>
</head>
<body>
<a class="skip-link" href="#reader">Skip to reading pane</a>
<button class="sidebar-toggle" id="sidebarToggle" aria-controls="sidebar" aria-expanded="false" aria-label="Show library">☰</button>
<div class="scrim" id="scrim" hidden></div>
<div class="app">
<aside class="sidebar" id="sidebar" aria-label="Library">
<div class="sidebar-header">
<h1>vidlib</h1>
<div class="count" id="count" role="status" aria-live="polite">Loading…</div>
</div>
<div class="sidebar-search">
<input type="text" id="search" placeholder="Search library…" aria-label="Search library" autocomplete="off" />
</div>
<div class="sidebar-sort">
<span class="sort-label" aria-hidden="true">Sort</span>
<label class="sr-only" for="sort">Sort transcripts</label>
<select id="sort" class="sort-select">
<option value="channel">Channel</option>
<option value="title">Title A–Z</option>
<option value="length">Length</option>
</select>
</div>
<div class="sidebar-list" id="list"></div>
<label class="load-btn">
Load markdown files
<input type="file" id="fileInput" multiple accept=".md" />
</label>
</aside>
<div class="progress-bar" aria-hidden="true"><div class="fill" id="progress"></div></div>
<main class="reader" id="reader" tabindex="0" aria-label="Reading pane">
<div class="reader-loading" id="loading">
<div class="spinner" aria-hidden="true"></div>
<div>Loading library…</div>
</div>
<div class="reader-empty" id="empty" style="display:none">
<div class="empty-panel">
<p class="lead">No library loaded.</p>
<p>For the whole library with zero-click reading, serve this folder over HTTP and open the reader there:</p>
<code class="cmd">python3 -m http.server
# then open http://localhost:8000/reader.html</code>
<p>Over HTTP the reader loads every transcript automatically, no picking files.</p>
<p>Or load by hand: <strong>drop</strong> your <code>.md</code> files anywhere on this window, or click <strong>Load markdown files</strong> in the sidebar.</p>
<p class="hint">Add a new video to the library:</p>
<code class="cmd">python3 vidlib.py add <youtube-url></code>
</div>
</div>
<article class="reader-content" id="content" style="display:none"></article>
</main>
</div>
<div class="drop-overlay" id="dropOverlay">
<div class="drop-icon">📄</div>
<div class="drop-text">Drop .md files to add to library</div>
</div>
<script>
"use strict";
// ─── State ───
const state = {
library: [], // array of entries, in insertion order
byId: new Map(), // id -> entry
activeId: null, // id of the open transcript
renderOrder: [], // ids in the exact order the sidebar currently shows (filtered + expanded)
filter: '',
sort: 'channel',
collapsed: new Set(), // channel names that are collapsed
};
// ─── DOM refs ───
const $ = (id) => document.getElementById(id);
const listEl = $('list'), countEl = $('count'), searchEl = $('search'), sortEl = $('sort');
const readerEl = $('reader'), loadingEl = $('loading'), emptyEl = $('empty'), contentEl = $('content');
const progressEl = $('progress'), sidebarEl = $('sidebar'), scrimEl = $('scrim'), toggleEl = $('sidebarToggle');
const dropOverlay = $('dropOverlay'), fileInput = $('fileInput');
// ─── Escaping (closes the innerHTML injection foot-gun) ───
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
function escapeHtml(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, c => ESC[c]); }
const escapeAttr = escapeHtml;
function slugify(s) {
return String(s || '').toLowerCase().trim()
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80).replace(/-+$/g, '');
}
// ─── Markdown parsing (minimal, no deps) ───
function parseFrontmatter(text) {
const meta = {};
if (!text.startsWith('---')) return { meta, body: text };
const end = text.indexOf('---', 3);
if (end < 0) return { meta, body: text };
const fm = text.slice(3, end).trim();
fm.split('\n').forEach(line => {
const idx = line.indexOf(':');
if (idx > 0) {
const key = line.slice(0, idx).trim();
let val = line.slice(idx + 1).trim();
if (val.startsWith('"') && val.endsWith('"')) val = val.slice(1, -1);
meta[key] = val;
}
});
return { meta, body: text.slice(end + 3).trim() };
}
function mdToHtml(md) {
// Drop the H1 title, the bold meta line, the Watch link and the rule (rendered separately).
const lines = md.split('\n');
const body = [];
let skipHeader = true;
for (const line of lines) {
if (skipHeader) {
if (line.startsWith('# ') || line.startsWith('**') || line.startsWith('[Watch') ||
line.trim() === '---' || line.trim() === '') continue;
skipHeader = false;
}
body.push(line);
}
const text = body.join('\n').trim();
return text.split(/\n\n+/)
.filter(p => p.trim())
// escape() BEFORE insertion, so a transcript with "<" or "&" renders literally.
.map(p => `<p>${escapeHtml(p.replace(/\n/g, ' ').trim())}</p>`)
.join('\n');
}
function parseLen(rt) {
const mm = String(rt).match(/(\d+)\s*min/);
const wm = String(rt).match(/([\d,]+)\s*words?/);
return {
minutes: mm ? parseInt(mm[1], 10) : 0,
words: wm ? parseInt(wm[1].replace(/,/g, ''), 10) : 0,
};
}
function formatDate(dateStr) {
if (!dateStr || dateStr === 'unknown') return '';
try {
const y = dateStr.slice(0, 4);
const m = parseInt(dateStr.slice(4, 6), 10) - 1;
const d = dateStr.slice(6, 8);
return new Date(y, m, d).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
} catch { return dateStr; }
}
// ─── index.md parsing ───
// Headings `## Channel` set the current channel; list items
// `- [Title](channel-dir/slug.md) · reading` are the transcripts.
function parseIndex(text) {
const items = [];
let channel = '';
const linkRe = /^\s*[-*]\s*\[(.+?)\]\(([^)]+?\.md)\)\s*(?:·\s*(.*?))?\s*$/;
for (const raw of text.split('\n')) {
const line = raw.replace(/\r$/, '');
const h = line.match(/^##\s+(.*\S)\s*$/);
if (h) { channel = h[1].trim(); continue; }
const m = line.match(linkRe);
if (!m) continue;
let path = m[2].trim().replace(/^\.\//, '');
if (/^https?:/i.test(path) || path === 'index.md') continue;
items.push({ channel, path, title: m[1].trim(), hint: (m[3] || '').trim() });
}
return items;
}
// ─── Library building ───
function storeEntry(id, path, meta, body, fb) {
fb = fb || {};
const rt = meta.reading_time || fb.hint || '';
const { minutes, words } = parseLen(rt);
const entry = {
id, path,
channel: meta.channel || fb.channel || 'Unknown',
title: meta.title || fb.title || id.split('/').pop(),
date: meta.date || '', url: meta.url || '', duration: meta.duration || '',
reading_time: rt, pulled: meta.pulled || '',
minutes, words,
body,
html: mdToHtml(body),
};
const existing = state.byId.get(id);
if (existing) state.library[state.library.indexOf(existing)] = entry;
else state.library.push(entry);
state.byId.set(id, entry);
return entry;
}
// ─── Auto-load (the primary path when served over http/https) ───
async function autoLoad() {
let idxText;
try {
const r = await fetch('index.md', { cache: 'no-store' });
if (!r.ok) throw new Error('index.md ' + r.status);
idxText = await r.text();
} catch {
return false; // file:// or 404 -> manual fallback
}
const items = parseIndex(idxText);
if (!items.length) return false;
countEl.textContent = `Loading ${items.length}…`;
const results = await Promise.allSettled(items.map(async (it) => {
const r = await fetch(it.path, { cache: 'no-store' });
if (!r.ok) throw new Error(it.path + ' ' + r.status);
return { it, txt: await r.text() };
}));
for (const res of results) {
if (res.status !== 'fulfilled') continue;
const { it, txt } = res.value;
const { meta, body } = parseFrontmatter(txt);
const id = it.path.replace(/\.md$/, '');
storeEntry(id, it.path, meta, body, { channel: it.channel, title: it.title, hint: it.hint });
}
return state.library.length > 0;
}
// ─── Manual load (drag-drop + file picker fallback) ───
function handleFiles(fileList) {
const files = Array.from(fileList).filter(f => f.name.endsWith('.md') && f.name !== 'index.md');
if (!files.length) return;
let remaining = files.length;
const done = () => { if (--remaining === 0) { renderSidebar(); openInitial(); } };
files.forEach(file => {
const fr = new FileReader();
fr.onload = (ev) => {
const { meta, body } = parseFrontmatter(ev.target.result);
const base = file.name.replace(/\.md$/, '');
let dir = slugify(meta.channel || 'unknown');
const rel = file.webkitRelativePath || '';
if (rel.includes('/')) { const parts = rel.split('/'); dir = parts[parts.length - 2] || dir; }
storeEntry(`${dir}/${base}`, `${dir}/${file.name}`, meta, body, {});
done();
};
fr.onerror = done;
fr.readAsText(file);
});
}
// ─── Rendering: sidebar ───
function showState(which) {
loadingEl.style.display = which === 'loading' ? 'flex' : 'none';
emptyEl.style.display = which === 'empty' ? 'flex' : 'none';
contentEl.style.display = which === 'content' ? 'block' : 'none';
}
function renderSidebar() {
const q = state.filter.toLowerCase();
const filtered = state.library.filter(e =>
!q || e.title.toLowerCase().includes(q) || e.channel.toLowerCase().includes(q) || e.body.toLowerCase().includes(q)
);
const groups = new Map();
for (const e of filtered) {
if (!groups.has(e.channel)) groups.set(e.channel, []);
groups.get(e.channel).push(e);
}
const channels = [...groups.keys()].sort((a, b) => a.localeCompare(b));
const order = [];
let html = '';
for (const ch of channels) {
let items = groups.get(ch);
if (state.sort === 'title') items = [...items].sort((a, b) => a.title.localeCompare(b.title));
else if (state.sort === 'length') items = [...items].sort((a, b) => (b.minutes - a.minutes) || (b.words - a.words));
const collapsed = state.collapsed.has(ch);
html += `<div class="channel-group">`;
html += `<button type="button" class="channel-header" data-ch="${escapeAttr(ch)}" aria-expanded="${!collapsed}">`;
html += `<span class="caret" aria-hidden="true">${collapsed ? '▸' : '▾'}</span>`;
html += `<span class="channel-name">${escapeHtml(ch)}</span>`;
html += `<span class="channel-count">${items.length}</span>`;
html += `</button>`;
if (!collapsed) {
html += `<div class="channel-items" role="group" aria-label="${escapeAttr(ch)}">`;
for (const e of items) {
order.push(e.id);
const active = e.id === state.activeId;
const meta = [e.duration, e.reading_time].filter(Boolean).join(' → ');
html += `<button type="button" class="sidebar-item${active ? ' active' : ''}" data-id="${escapeAttr(e.id)}"${active ? ' aria-current="true"' : ''}>`;
html += `<span class="title">${escapeHtml(e.title)}</span>`;
if (meta) html += `<span class="meta">${escapeHtml(meta)}</span>`;
html += `</button>`;
}
html += `</div>`;
}
html += `</div>`;
}
listEl.innerHTML = html ||
`<div class="list-empty">No transcripts match “${escapeHtml(state.filter)}”.<br>Try fewer letters.</div>`;
state.renderOrder = order;
const n = state.library.length;
countEl.textContent = `${n} transcript${n !== 1 ? 's' : ''}`;
listEl.querySelectorAll('.sidebar-item').forEach(el => {
el.addEventListener('click', () => { openTranscript(el.dataset.id); closeSidebarMobile(); });
});
listEl.querySelectorAll('.channel-header').forEach(el => {
el.addEventListener('click', () => toggleCollapse(el.dataset.ch));
});
const activeEl = listEl.querySelector('.sidebar-item.active');
if (activeEl) activeEl.scrollIntoView({ block: 'nearest' });
}
// ─── Rendering: reader ───
function renderReader() {
const e = state.byId.get(state.activeId);
if (!e) { showState(state.library.length ? 'empty' : 'empty'); return; }
const metaParts = [e.channel, formatDate(e.date), e.duration ? `${e.duration} video` : '', e.reading_time].filter(Boolean);
const safeUrl = /^https?:\/\//i.test(e.url) ? e.url : '';
const urlHtml = safeUrl ? ` · <a href="${escapeAttr(safeUrl)}" target="_blank" rel="noopener noreferrer">Watch ↗</a>` : '';
contentEl.innerHTML =
`<h1 class="reader-title">${escapeHtml(e.title)}</h1>` +
`<div class="reader-meta">${escapeHtml(metaParts.join(' · '))}${urlHtml}</div>` +
`<div class="reader-divider"></div>` +
`<div class="reader-body">${e.html}</div>`;
showState('content');
document.title = e.title ? `${e.title} · vidlib` : 'vidlib';
restoreScroll(e.id);
}
// ─── Open / navigate ───
function setHash(id, replace) {
const h = '#' + id;
if (location.hash === h) return;
if (replace && history.replaceState) history.replaceState(null, '', h);
else location.hash = h;
}
function openTranscript(id, opts) {
opts = opts || {};
if (!state.byId.has(id)) return;
state.activeId = id;
try { localStorage.setItem('vidlib:lastOpen', id); } catch {}
renderReader();
renderSidebar();
if (opts.push !== false) setHash(id, opts.replace);
}
function moveSelection(delta) {
const order = state.renderOrder;
if (!order.length) return;
let i = order.indexOf(state.activeId);
if (i === -1) i = delta > 0 ? -1 : 0;
const ni = Math.max(0, Math.min(order.length - 1, i + delta));
const id = order[ni];
if (id && id !== state.activeId) openTranscript(id, { replace: true });
const el = listEl.querySelector('.sidebar-item.active');
if (el) el.focus();
}
function openInitial() {
const hashId = decodeURIComponent((location.hash || '').replace(/^#/, ''));
let lastId = null;
try { lastId = localStorage.getItem('vidlib:lastOpen'); } catch {}
let openId = null;
if (hashId && state.byId.has(hashId)) openId = hashId; // hash wins
else if (lastId && state.byId.has(lastId)) openId = lastId; // then resume
else if (state.renderOrder.length) openId = state.renderOrder[0]; // else first
if (openId) openTranscript(openId, { push: true });
else showState('empty');
}
// ─── Collapse groups ───
function toggleCollapse(ch) {
if (state.collapsed.has(ch)) state.collapsed.delete(ch);
else state.collapsed.add(ch);
renderSidebar();
}
// ─── Scroll persistence (per-transcript place-keeping) ───
function updateProgress() {
const max = readerEl.scrollHeight - readerEl.clientHeight;
const pct = max > 0 ? (readerEl.scrollTop / max) * 100 : 0;
progressEl.style.width = Math.max(0, Math.min(100, pct)) + '%';
}
function restoreScroll(id) {
let y = 0;
try { y = parseInt(localStorage.getItem('vidlib:scroll:' + id) || '0', 10) || 0; } catch {}
requestAnimationFrame(() => { readerEl.scrollTop = y; updateProgress(); });
}
let scrollSaveT;
function persistScrollNow() {
if (!state.activeId) return;
try { localStorage.setItem('vidlib:scroll:' + state.activeId, String(Math.round(readerEl.scrollTop))); } catch {}
}
readerEl.addEventListener('scroll', () => {
updateProgress();
clearTimeout(scrollSaveT);
scrollSaveT = setTimeout(persistScrollNow, 200);
});
window.addEventListener('beforeunload', persistScrollNow);
// ─── Mobile sidebar ───
function openSidebarMobile() {
sidebarEl.classList.add('open');
scrimEl.classList.add('active'); scrimEl.hidden = false;
toggleEl.setAttribute('aria-expanded', 'true');
}
function closeSidebarMobile() {
sidebarEl.classList.remove('open');
scrimEl.classList.remove('active'); scrimEl.hidden = true;
toggleEl.setAttribute('aria-expanded', 'false');
}
toggleEl.addEventListener('click', () => {
sidebarEl.classList.contains('open') ? closeSidebarMobile() : openSidebarMobile();
});
scrimEl.addEventListener('click', closeSidebarMobile);
// ─── Search + sort ───
searchEl.addEventListener('input', (e) => { state.filter = e.target.value; renderSidebar(); });
sortEl.addEventListener('change', (e) => { state.sort = e.target.value; renderSidebar(); });
// ─── File input + drag & drop ───
fileInput.addEventListener('change', (e) => handleFiles(e.target.files));
let dragCounter = 0;
document.addEventListener('dragenter', (e) => { e.preventDefault(); dragCounter++; dropOverlay.classList.add('active'); });
document.addEventListener('dragleave', (e) => {
e.preventDefault(); dragCounter--;
if (dragCounter <= 0) { dropOverlay.classList.remove('active'); dragCounter = 0; }
});
document.addEventListener('dragover', (e) => e.preventDefault());
document.addEventListener('drop', (e) => {
e.preventDefault();
dropOverlay.classList.remove('active'); dragCounter = 0;
handleFiles(e.dataTransfer.files);
});
// ─── Deep-link: react to hash changes (back button, shared link) ───
window.addEventListener('hashchange', () => {
const id = decodeURIComponent(location.hash.replace(/^#/, ''));
if (id && state.byId.has(id) && id !== state.activeId) openTranscript(id, { push: false });
});
// ─── Keyboard ───
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && sidebarEl.classList.contains('open')) { closeSidebarMobile(); return; }
const tag = e.target.tagName;
if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return;
if (e.key === 'ArrowDown') { e.preventDefault(); moveSelection(1); }
else if (e.key === 'ArrowUp') { e.preventDefault(); moveSelection(-1); }
else if (e.key === '/' || (e.key === 'f' && (e.metaKey || e.ctrlKey))) {
e.preventDefault(); searchEl.focus(); if (searchEl.select) searchEl.select();
}
});
// ─── Boot ───
async function init() {
showState('loading');
const ok = await autoLoad();
if (ok) {
renderSidebar();
openInitial();
} else {
countEl.textContent = 'No files loaded';
renderSidebar(); // empty list is fine
showState('empty'); // corrected file:// instructions
}
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
</script>
</body>
</html>