-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoDB-inspector.html
More file actions
884 lines (801 loc) · 35.5 KB
/
MoDB-inspector.html
File metadata and controls
884 lines (801 loc) · 35.5 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
<!DOCTYPE html>
<html lang="en" data-theme="gruvbox">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MoDB Inspector</title>
<link rel="stylesheet" href="mo-layout.css">
<style>
/* Inspector-specific tweaks */
.inspector-nav {
flex-grow: 1;
overflow-y: auto;
padding: 6px 10px 10px;
scroll-behavior: smooth;
}
.nav-item {
padding: 10px 14px;
border-radius: 10px;
cursor: pointer;
margin-bottom: 4px;
font-size: 14px;
font-weight: 500;
transition: all 0.2s;
border: 1px solid transparent;
display: flex;
align-items: center;
gap: 10px;
color: var(--text);
background: transparent;
width: 100%;
text-align: left;
font-family: inherit;
}
.nav-item:hover { background: var(--panel-hover); transform: translateX(3px); }
.nav-item.active { background: rgba(100,100,100,0.1); border-color: var(--highlight); color: var(--highlight); font-weight: bold; }
.actions-paired { display: flex; gap: 10px; }
.results-panel {
flex-grow: 1;
overflow-y: auto;
padding: 20px;
}
.search-box-inline {
display: flex;
gap: 10px;
align-items: center;
margin-bottom: 14px;
flex-wrap: wrap;
}
.search-box-inline input {
width: 320px;
max-width: 100%;
}
pre {
background: var(--panel-bg);
border: 1px solid var(--border);
padding: 12px;
overflow-x: auto;
font-size: 12px;
border-radius: var(--radius-md);
color: var(--text);
}
.page-nav {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 14px;
font-size: 13px;
color: var(--muted);
}
.page-nav button { padding: 4px 12px; font-size: 12px; margin: 0; }
/* Inspect stores view */
.store {
font-size: 1.05rem;
font-weight: 600;
margin-top: 28px;
margin-bottom: 10px;
letter-spacing: 0.01em;
color: var(--text);
}
.store:first-of-type { margin-top: 0; }
.store .count { font-weight: 400; color: var(--muted); font-size: 0.9em; }
.results-panel table { margin-bottom: 28px; font-size: 13px; }
.results-panel table td { padding: 6px 10px; }
.results-panel table th { padding: 6px 10px; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; }
.results-panel table td.type { color: var(--highlight); font-family: monospace; font-size: 12px; }
.results-panel table td.field { font-weight: 500; }
/* Search results & profile */
.results-panel > h2:first-child { margin-top: 0; }
.results-panel > h2 {
font-size: 1.15rem;
font-weight: 600;
margin: 28px 0 12px;
color: var(--text);
}
.results-panel > h2 .count { font-weight: 400; color: var(--muted); font-size: 0.9em; }
.profile { margin-top: 8px; margin-bottom: 20px; }
.profile-section { margin-bottom: 22px; }
.profile-section:last-child { margin-bottom: 0; }
.profile-section h3 {
font-size: 0.72rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--highlight);
margin: 0 0 10px;
padding-bottom: 6px;
border-bottom: 1px solid var(--border);
}
.profile-row {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 3px 0;
font-size: 13px;
line-height: 1.5;
}
.profile-row .label {
min-width: 110px;
color: var(--muted);
font-size: 12px;
flex-shrink: 0;
font-weight: 500;
}
.profile-row .value { color: var(--text); word-break: break-word; }
.profile-row .ok { color: var(--success); }
.profile-row .missing { color: var(--danger); }
.profile-row .warn { color: var(--warning); }
.sentence-block {
display: flex;
flex-direction: column;
gap: 6px;
margin-bottom: 14px;
padding: 10px 12px;
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
.sentence-block:last-child { margin-bottom: 0; }
.sentence-line {
display: flex;
align-items: flex-start;
gap: 10px;
font-size: 13px;
line-height: 1.5;
}
.sentence-line .label {
min-width: 110px;
color: var(--muted);
font-size: 12px;
flex-shrink: 0;
font-weight: 500;
}
.sentence-line .value { word-break: break-word; }
.blob-badge {
display: inline-block;
background: rgba(62, 207, 90, 0.12);
color: var(--success);
border: 1px solid rgba(62, 207, 90, 0.3);
padding: 1px 8px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.02em;
}
.empty { color: var(--muted); font-size: 13px; margin-bottom: 8px; }
/* Word grid (Browse / Partial matches) */
.word-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 10px;
margin-bottom: 28px;
}
.word-card {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 12px 14px;
transition: border-color 0.2s, transform 0.15s;
}
.word-card:hover { transform: translateY(-2px); border-color: var(--highlight); }
.word-card .hanzi { font-size: 1.3rem; font-weight: 600; margin-bottom: 2px; }
.word-card .pinyin { font-size: 13px; color: var(--highlight); margin-bottom: 2px; }
.word-card .meaning { font-size: 12px; color: var(--muted); margin-bottom: 6px; }
.word-card .meta { font-size: 11px; color: var(--muted); display: flex; gap: 8px; }
/* Filter bar */
.filter-bar {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
margin-bottom: 14px;
padding: 10px 12px;
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: var(--radius-md);
}
.filter-bar select {
background: var(--panel-bg);
color: var(--text);
border: 1px solid var(--border);
border-radius: 8px;
padding: 6px 10px;
font-size: 13px;
font-family: inherit;
cursor: pointer;
}
.filter-pills {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.pill {
background: transparent;
border: 1px solid var(--border);
color: var(--muted);
padding: 4px 10px;
border-radius: 20px;
font-size: 12px;
font-family: inherit;
cursor: pointer;
transition: all 0.15s;
}
.pill:hover { border-color: var(--highlight); color: var(--text); }
.pill.active { background: var(--highlight); color: var(--bg); border-color: var(--highlight); font-weight: 600; }
/* Word card clickable */
.word-card { cursor: pointer; }
/* Modal overlay */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
backdrop-filter: blur(4px);
z-index: 1000;
display: none;
align-items: center;
justify-content: center;
padding: 20px;
}
.modal-overlay.show { display: flex; }
.modal-panel {
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
width: 100%;
max-width: 680px;
max-height: 90vh;
overflow-y: auto;
padding: 24px;
position: relative;
box-shadow: 0 20px 60px rgba(0,0,0,0.4);
}
.modal-close {
position: absolute;
top: 14px;
right: 14px;
background: var(--panel-bg);
border: 1px solid var(--border);
color: var(--text);
width: 32px;
height: 32px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-size: 16px;
line-height: 1;
}
.modal-close:hover { background: var(--danger); color: #fff; border-color: var(--danger); }
.modal-back {
display: inline-flex;
align-items: center;
gap: 6px;
margin-bottom: 14px;
background: transparent;
border: 1px solid var(--border);
color: var(--muted);
padding: 6px 12px;
border-radius: 8px;
font-size: 13px;
font-family: inherit;
cursor: pointer;
}
.modal-back:hover { color: var(--text); border-color: var(--highlight); }
/* Dashboard cards (Inspect / Stats) */
.dash-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 12px;
margin-bottom: 24px;
}
.dash-card {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 16px;
text-align: center;
}
.dash-card .num {
font-size: 1.8rem;
font-weight: 700;
color: var(--highlight);
line-height: 1.2;
margin-bottom: 4px;
}
.dash-card .lbl {
font-size: 12px;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.06em;
}
.dash-card .sub {
font-size: 11px;
color: var(--muted);
margin-top: 4px;
}
@media (max-width: 700px) {
.search-box-inline input { width: 100%; }
.dash-grid { grid-template-columns: repeat(2, 1fr); }
}
</style>
</head>
<body>
<div class="app-layout">
<!-- LEFT SIDEBAR -->
<aside class="sidebar">
<header class="sidebar-header">
<div class="sidebar-header-top">
<h2>🔍 MoDB</h2>
</div>
<div class="sidebar-actions actions-paired">
<button class="btn-primary" onclick="exportDB()">💾 Export</button>
<button class="btn-secondary" onclick="document.getElementById('importFile').click()">📥 Import</button>
<input type="file" id="importFile" accept=".json" class="hidden-input" onchange="importDB(this)">
</div>
</header>
<nav class="inspector-nav" id="inspectorNav">
<button class="nav-item active" onclick="setActiveNav(this); browseWords()">📚 Browse Words</button>
<button class="nav-item" onclick="setActiveNav(this); searchUI()">🔎 Search Word</button>
<button class="nav-item" onclick="setActiveNav(this); inspect()">🔍 Inspect Stores</button>
<button class="nav-item" onclick="setActiveNav(this); liveStats()">📊 Live Stats</button>
<button class="nav-item" onclick="setActiveNav(this); showSchema()">📋 Show Schema</button>
<button class="nav-item" onclick="setActiveNav(this); clearDB()">⚠️ Clear MoDB</button>
<div style="margin-top: 14px; padding: 0 4px;">
<select id="themeSelect" style="width: 100%;" onchange="document.documentElement.setAttribute('data-theme', this.value)">
<option value="midnight">Midnight Slate</option>
<option value="oled">OLED Black</option>
<option value="nordic">Nordic Night</option>
<option value="gruvbox" selected>Gruvbox</option>
<option value="everforest">Everforest</option>
</select>
</div>
</nav>
</aside>
<!-- RIGHT MAIN -->
<main class="main-content">
<div id="searchBox" class="search-box-inline" style="display:none">
<input type="text" id="q" placeholder="Type hanzi or pinyin..." onkeydown="if(event.key==='Enter')doSearch()">
<button class="btn-primary" onclick="doSearch()">Search</button>
</div>
<div id="results" class="panel results-panel">
<div class="empty-state">
<span>Select an action from the sidebar to inspect your MoDB database.</span>
</div>
</div>
</main>
</div>
<script src="mo-common.js"></script>
<script>
function setActiveNav(el) {
document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
el.classList.add('active');
}
function escHtml(s) {
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
let _allWords = [];
let _page = 0;
const PAGE_SIZE = 20;
// Browse filter / sort state
let _browseSort = 'added-desc'; // added-desc | added-asc | alpha | srs-level | srs-reps | srs-due
let _browseFilterSource = 'all'; // all | reader | cards | migrated
let _browseFilterAudio = 'all'; // all | word | sentence | any
let _browseFilterEnriched = 'all'; // all | yes | no
let _browseAudioMap = new Map();
let _browseSrsMap = new Map();
let _browseSentencesMap = new Map();
async function inspect() {
const results = document.getElementById('results');
results.innerHTML = '<p class="empty-state">Loading...</p>';
await MoDB.open();
const [words, audio, sentences, srs, sessions, settings] = await Promise.all([
MoDB.getAll(MoDB.S.WORDS),
MoDB.getAll(MoDB.S.AUDIO),
MoDB.getAll(MoDB.S.SENTENCES),
MoDB.getAll(MoDB.S.SRS),
MoDB.getAll(MoDB.S.SESSIONS),
MoDB.getSettings(),
]);
const withWordAudio = audio.filter(a => a.wordAudio && a.wordAudio.byteLength > 0).length;
const withSentAudio = audio.filter(a => a.sentenceAudios && a.sentenceAudios.some(sa => sa.audio && sa.audio.byteLength > 0)).length;
const totalAudioBytes = audio.reduce((sum, a) => {
let s = (a.wordAudio && a.wordAudio.byteLength) || 0;
s += (a.sentenceAudios || []).reduce((t, sa) => t + ((sa.audio && sa.audio.byteLength) || 0), 0);
return sum + s;
}, 0);
let html = '<h2 style="margin-top:0">MoDB Overview</h2>';
html += `<div class="dash-grid">
<div class="dash-card"><div class="num">${words.length.toLocaleString()}</div><div class="lbl">Words</div></div>
<div class="dash-card"><div class="num">${audio.length.toLocaleString()}</div><div class="lbl">Audio Records</div><div class="sub">${withWordAudio} word · ${withSentAudio} sentence</div></div>
<div class="dash-card"><div class="num">${sentences.length.toLocaleString()}</div><div class="lbl">Sentences</div></div>
<div class="dash-card"><div class="num">${srs.length.toLocaleString()}</div><div class="lbl">SRS Items</div></div>
<div class="dash-card"><div class="num">${sessions.length.toLocaleString()}</div><div class="lbl">Sessions</div></div>
<div class="dash-card"><div class="num">${(totalAudioBytes / 1024 / 1024).toFixed(1)} MB</div><div class="lbl">Audio Storage</div></div>
</div>`;
html += '<h2 class="store" style="margin-top:8px">Stores</h2>';
html += '<table><tr><th>Store</th><th>Records</th><th>Status</th></tr>';
const rows = [
['Words', words.length, words.length ? '<span class="ok">Active</span>' : '<span class="missing">Empty</span>'],
['Audio', audio.length, audio.length ? '<span class="ok">Active</span>' : '<span class="missing">Empty</span>'],
['Sentences', sentences.length, sentences.length ? '<span class="ok">Active</span>' : '<span class="missing">Empty</span>'],
['SRS', srs.length, srs.length ? '<span class="ok">Active</span>' : '<span class="missing">Empty</span>'],
['Sessions', sessions.length, sessions.length ? '<span class="ok">Active</span>' : '<span class="missing">Empty</span>'],
['Settings', settings ? 1 : 0, settings ? '<span class="ok">Saved</span>' : '<span class="missing">Default</span>'],
];
for (const [name, count, status] of rows) {
html += `<tr><td class="field">${name}</td><td>${count.toLocaleString()}</td><td>${status}</td></tr>`;
}
html += '</table>';
html += `<div style="margin-top:14px"><button class="btn-primary" onclick="inspect()">🔄 Refresh</button></div>`;
results.innerHTML = html;
}
function showSchema() {
const schema = {
'words': { id:'PK hanzi', hanzi:'string', pinyin:'string', pinyinToneless:'string', meaning:'string', source:'string', createdAt:'number', updatedAt:'number', enriched:'boolean' },
'audio': { id:'PK hanzi', wordAudio:'ArrayBuffer', sentenceAudios:'array', source:'string', createdAt:'number', updatedAt:'number' },
'sentences': { id:'auto-increment', wordId:'FK', zh:'string', es:'string', createdAt:'number', updatedAt:'number' },
'srs': { id:'PK hanzi', interval:'number', ease:'number', due:'number', reps:'number', lapses:'number', hidden:'boolean' },
'sessions': { id:'PK "category/name"', category:'string', name:'string', readCount:'number', lastRead:'number', updatedAt:'number' },
'settings': { id:'global', theme:'string', cardScale:'number', sessionSize:'number', apiKeys:'object', readerTheme:'string', readerFont:'string', readerFontSize:'number', readerHighlight:'string', readerActiveStyle:'string', readerAnimStyle:'string', updatedAt:'number' }
};
document.getElementById('results').innerHTML = '<h2>Schema</h2><pre>' + JSON.stringify(schema, null, 2) + '</pre>';
}
function srsLevelRank(srs) {
if (!srs || srs.reps === 0) return 0; // New
if (srs.interval < 1) return 1; // Learning
if (srs.interval < 7) return 2; // Young
if (srs.interval < 30) return 3; // Mature
return 4; // Mastered
}
function srsLevelLabel(srs) {
const r = srsLevelRank(srs);
return ['New', 'Learning', 'Young', 'Mature', 'Mastered'][r];
}
function getFilteredWords() {
let list = _allWords.slice();
// Source filter
if (_browseFilterSource !== 'all') {
list = list.filter(w => w.source === _browseFilterSource);
}
// Audio filter
if (_browseFilterAudio !== 'all') {
list = list.filter(w => {
const a = _browseAudioMap.get(w.id);
if (!a) return false;
if (_browseFilterAudio === 'word') return a.wordAudio && a.wordAudio.byteLength > 0;
if (_browseFilterAudio === 'sentence') {
return (a.sentenceAudios || []).some(sa => sa.audio && sa.audio.byteLength > 0);
}
if (_browseFilterAudio === 'any') {
const hasWord = a.wordAudio && a.wordAudio.byteLength > 0;
const hasSent = (a.sentenceAudios || []).some(sa => sa.audio && sa.audio.byteLength > 0);
return hasWord || hasSent;
}
return true;
});
}
// Enriched filter
if (_browseFilterEnriched !== 'all') {
list = list.filter(w => (_browseFilterEnriched === 'yes') === !!w.enriched);
}
// Sort
switch (_browseSort) {
case 'added-desc': list.sort((a, b) => (b.createdAt || b.updatedAt || 0) - (a.createdAt || a.updatedAt || 0)); break;
case 'added-asc': list.sort((a, b) => (a.createdAt || a.updatedAt || 0) - (b.createdAt || b.updatedAt || 0)); break;
case 'alpha': list.sort((a, b) => (a.hanzi || '').localeCompare(b.hanzi || '')); break;
case 'srs-level': list.sort((a, b) => srsLevelRank(_browseSrsMap.get(b.id)) - srsLevelRank(_browseSrsMap.get(a.id))); break;
case 'srs-reps': list.sort((a, b) => ((_browseSrsMap.get(b.id)?.reps || 0) - (_browseSrsMap.get(a.id)?.reps || 0))); break;
case 'srs-due': list.sort((a, b) => ((_browseSrsMap.get(a.id)?.due || 0) - (_browseSrsMap.get(b.id)?.due || 0))); break;
}
return list;
}
async function browseWords() {
const results = document.getElementById('results');
results.innerHTML = '<p class="empty-state">Loading words...</p>';
await MoDB.open();
const [words, audio, sentences, srs] = await Promise.all([
MoDB.getAllWords(),
MoDB.getAll(MoDB.S.AUDIO),
MoDB.getAll(MoDB.S.SENTENCES),
MoDB.getAll(MoDB.S.SRS),
]);
_allWords = words;
_browseAudioMap = new Map(audio.map(a => [a.id, a]));
_browseSrsMap = new Map(srs.map(s => [s.id, s]));
_browseSentencesMap = new Map();
for (const s of sentences) {
const arr = _browseSentencesMap.get(s.wordId) || [];
arr.push(s);
_browseSentencesMap.set(s.wordId, arr);
}
_page = 0;
renderPage();
}
function renderPage() {
const results = document.getElementById('results');
const filtered = getFilteredWords();
const start = _page * PAGE_SIZE;
const slice = filtered.slice(start, start + PAGE_SIZE);
// Filter bar
let html = '<div class="filter-bar">';
html += `<select onchange="setBrowseSort(this.value)">
<option value="added-desc" ${_browseSort==='added-desc'?'selected':''}>Newest first</option>
<option value="added-asc" ${_browseSort==='added-asc'?'selected':''}>Oldest first</option>
<option value="alpha" ${_browseSort==='alpha'?'selected':''}>A → Z</option>
<option value="srs-level" ${_browseSort==='srs-level'?'selected':''}>SRS Level (high → low)</option>
<option value="srs-reps" ${_browseSort==='srs-reps'?'selected':''}>Most Reviewed</option>
<option value="srs-due" ${_browseSort==='srs-due'?'selected':''}>Due for Review</option>
</select>`;
html += `<div class="filter-pills">`;
const sources = [['all','All src'],['reader','Reader'],['cards','Cards'],['migrated','Migrated']];
for (const [v,l] of sources) html += `<button class="pill${_browseFilterSource===v?' active':''}" onclick="setBrowseFilter('source','${v}')">${l}</button>`;
html += `</div><div class="filter-pills">`;
const audios = [['all','Any audio'],['word','Word audio'],['sentence','Sentence audio'],['any','Has any audio']];
for (const [v,l] of audios) html += `<button class="pill${_browseFilterAudio===v?' active':''}" onclick="setBrowseFilter('audio','${v}')">${l}</button>`;
html += `</div><div class="filter-pills">`;
const enrich = [['all','All'],['yes','Enriched'],['no','Not enriched']];
for (const [v,l] of enrich) html += `<button class="pill${_browseFilterEnriched===v?' active':''}" onclick="setBrowseFilter('enriched','${v}')">${l}</button>`;
html += '</div></div>';
html += `<h2>📚 Words <span class="count">(${filtered.length} of ${_allWords.length})</span></h2>`;
html += `<div class="page-nav"><button class="btn-secondary" onclick="prevPage()" ${_page===0?'disabled':''}>← Prev</button>`;
html += `Page ${_page + 1} of ${Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))}`;
html += `<button class="btn-secondary" onclick="nextPage()" ${start+PAGE_SIZE>=filtered.length?'disabled':''}>Next →</button></div>`;
if (slice.length === 0) {
html += '<p class="empty-state">No words match the current filters.</p>';
} else {
html += '<div class="word-grid">';
for (const w of slice) {
const srs = _browseSrsMap.get(w.id);
const a = _browseAudioMap.get(w.id);
const hasWordAudio = a && a.wordAudio && a.wordAudio.byteLength > 0;
const hasSentAudio = a && (a.sentenceAudios || []).some(sa => sa.audio && sa.audio.byteLength > 0);
const sentCount = (_browseSentencesMap.get(w.id) || []).length;
html += `<div class="word-card" onclick="openWordModal('${escHtml(w.id)}')">
<div class="hanzi">${escHtml(w.hanzi)}</div>
<div class="pinyin">${escHtml(w.pinyin || '—')} <span style="color:#666">(${escHtml(w.pinyinToneless || '—')})</span></div>
<div class="meaning">${escHtml(w.meaning || '—')}</div>
<div class="meta">
<span>src: ${w.source}</span>
<span>enr: ${w.enriched ? '✓' : '—'}</span>
${hasWordAudio ? '<span style="color:var(--success)">🔊</span>' : ''}
${hasSentAudio ? '<span style="color:var(--success)">🗣️</span>' : ''}
${srs ? `<span title="${srsLevelLabel(srs)}">SRS:${srsLevelRank(srs)}</span>` : ''}
<span>${sentCount}snt</span>
</div>
</div>`;
}
html += '</div>';
}
results.innerHTML = html;
}
function setBrowseSort(val) { _browseSort = val; _page = 0; renderPage(); }
function setBrowseFilter(type, val) {
if (type === 'source') _browseFilterSource = val;
if (type === 'audio') _browseFilterAudio = val;
if (type === 'enriched') _browseFilterEnriched = val;
_page = 0;
renderPage();
}
function prevPage() { const f = getFilteredWords(); if (_page > 0) { _page--; renderPage(); } }
function nextPage() { const f = getFilteredWords(); if ((_page + 1) * PAGE_SIZE < f.length) { _page++; renderPage(); } }
async function openWordModal(wordId) {
const word = _allWords.find(w => w.id === wordId);
if (!word) return;
const content = document.getElementById('wordModalContent');
content.innerHTML = '<p class="empty-state">Loading profile...</p>';
document.getElementById('wordModal').classList.add('show');
content.innerHTML = await renderWordProfile(word);
}
function closeWordModal() {
document.getElementById('wordModal').classList.remove('show');
}
function searchUI() {
document.getElementById('searchBox').style.display = '';
document.getElementById('q').focus();
document.getElementById('results').innerHTML = '<p class="empty-state">Enter a hanzi above and press Enter.</p>';
}
async function doSearch() {
const q = document.getElementById('q').value.trim();
if (!q) return;
const results = document.getElementById('results');
results.innerHTML = '<p class="empty-state">Searching...</p>';
await MoDB.open();
let html = '';
try {
const exact = await MoDB.getWord(q);
if (exact) {
html += await renderWordProfile(exact);
} else {
html += '<h2>Exact Match</h2><p class="empty">Not found</p>';
}
const all = await MoDB.getAllWords();
const partials = all.filter(w => w.hanzi && w.hanzi.includes(q)).slice(0, 20);
html += `<h2>Partial Matches <span class="count">(${partials.length})</span></h2>`;
if (partials.length === 0) {
html += '<p class="empty">No partial matches</p>';
} else {
html += '<div class="word-grid">';
for (const w of partials) {
html += `<div class="word-card">
<div class="hanzi">${w.hanzi}</div>
<div class="pinyin">${w.pinyin || '—'}</div>
<div class="meaning">${w.meaning || '—'}</div>
<div class="meta"><span>src: ${w.source}</span><span>enr: ${w.enriched ? '✓' : '—'}</span></div>
</div>`;
}
html += '</div>';
}
const sessions = await MoDB.getAllSessions();
const relSessions = sessions.filter(s => s.id.includes(q));
html += `<h2>Sessions <span class="count">(${relSessions.length})</span></h2>`;
if (relSessions.length) {
html += '<pre>' + JSON.stringify(relSessions, null, 2) + '</pre>';
} else {
html += '<p class="empty">No matching sessions</p>';
}
} catch (err) {
html += `<h2 style="color:#f44">Search Error</h2><pre style="color:#f44">${err.name}: ${err.message}\n\n${err.stack}</pre>`;
}
results.innerHTML = html;
}
async function renderWordProfile(word) {
const [audio, allSentences, srs] = await Promise.all([
MoDB.get(MoDB.S.AUDIO, word.id),
MoDB.getAll(MoDB.S.SENTENCES),
MoDB.get(MoDB.S.SRS, word.id),
]);
const sentences = allSentences.filter(s => s.wordId === word.id);
let html = `<h2>Word Profile: <span style="color:var(--highlight)">${word.hanzi}</span></h2><div class="profile">`;
html += `<div class="profile-section"><h3>Word</h3>`;
html += `<div class="profile-row"><span class="label">Pinyin</span><span class="value">${word.pinyin || '—'} <span style="color:var(--muted)">(${word.pinyinToneless || '—'})</span></span></div>`;
html += `<div class="profile-row"><span class="label">Meaning</span><span class="value">${word.meaning || '—'}</span></div>`;
html += `<div class="profile-row"><span class="label">Source</span><span class="value">${word.source}</span></div>`;
html += `<div class="profile-row"><span class="label">Enriched</span><span class="value ${word.enriched ? 'ok' : 'missing'}">${word.enriched ? '✓ Yes' : '✗ No'}</span></div>`;
html += `<div class="profile-row"><span class="label">Updated</span><span class="value">${new Date(word.updatedAt).toLocaleString()}</span></div>`;
html += `</div>`;
html += `<div class="profile-section"><h3>Audio</h3>`;
if (audio) {
const hasWordAudio = audio.wordAudio && audio.wordAudio.byteLength > 0;
const sentenceAudioCount = (audio.sentenceAudios || []).filter(sa => sa.audio && (sa.audio.byteLength > 0 || (sa.audio instanceof ArrayBuffer && sa.audio.byteLength > 0))).length;
html += `<div class="profile-row"><span class="label">Word Audio</span><span class="value ${hasWordAudio ? 'ok' : 'missing'}">${hasWordAudio ? `<span class="blob-badge">✓ Stored (${audio.wordAudio.byteLength.toLocaleString()} bytes)</span>` : '✗ Missing'}</span></div>`;
html += `<div class="profile-row"><span class="label">Sentence Audios</span><span class="value ${sentenceAudioCount > 0 ? 'ok' : 'missing'}">${sentenceAudioCount} / ${(audio.sentenceAudios || []).length} with blob data</span></div>`;
html += `<div class="profile-row"><span class="label">Audio Source</span><span class="value">${audio.source || '—'}</span></div>`;
html += `<div class="profile-row"><span class="label">Audio Updated</span><span class="value">${new Date(audio.updatedAt).toLocaleString()}</span></div>`;
} else {
html += `<div class="profile-row"><span class="label">Status</span><span class="value missing">✗ No audio record</span></div>`;
}
html += `</div>`;
const sentenceAudioCount = audio && audio.sentenceAudios
? audio.sentenceAudios.filter(sa => sa.audio && sa.audio.byteLength > 0).length
: 0;
html += `<div class="profile-section"><h3>Sentences (${sentences.length})</h3>`;
if (sentences.length === 0) {
html += `<div class="profile-row missing">No sentences generated yet.</div>`;
} else {
for (const s of sentences) {
const hasAudio = sentenceAudioCount > 0;
html += `<div class="sentence-block">`;
html += `<div class="sentence-line"><span class="label">ZH</span><span class="value">${s.zh || '—'}</span></div>`;
html += `<div class="sentence-line"><span class="label">ES</span><span class="value">${s.es || '—'}</span></div>`;
html += `<div class="sentence-line"><span class="label">Audio</span><span class="value ${hasAudio ? 'ok' : 'missing'}">${hasAudio ? '<span class="blob-badge">✓ Stored</span>' : '✗ Missing'}</span></div>`;
html += `</div>`;
}
}
html += `</div>`;
html += `<div class="profile-section"><h3>SRS</h3>`;
if (srs) {
html += `<div class="profile-row"><span class="label">Interval</span><span class="value">${srs.interval} day(s)</span></div>`;
html += `<div class="profile-row"><span class="label">Ease</span><span class="value">${srs.ease.toFixed(2)}</span></div>`;
html += `<div class="profile-row"><span class="label">Due</span><span class="value">${srs.due ? new Date(srs.due).toLocaleString() : 'Now'}</span></div>`;
html += `<div class="profile-row"><span class="label">Reps</span><span class="value">${srs.reps}</span></div>`;
html += `<div class="profile-row"><span class="label">Lapses</span><span class="value">${srs.lapses}</span></div>`;
html += `<div class="profile-row"><span class="label">Hidden</span><span class="value ${srs.hidden ? 'warn' : 'ok'}">${srs.hidden ? 'Hidden (rated)' : 'Active'}</span></div>`;
} else {
html += `<div class="profile-row missing">Not studied yet.</div>`;
}
html += `</div>`;
html += '</div>';
return html;
}
async function liveStats() {
await MoDB.open();
const [words, audio, sentences, srs, sessions] = await Promise.all([
MoDB.getAllWords(),
MoDB.getAll(MoDB.S.AUDIO),
MoDB.getAll(MoDB.S.SENTENCES),
MoDB.getAll(MoDB.S.SRS),
MoDB.getAll(MoDB.S.SESSIONS),
]);
const enriched = words.filter(w => w.enriched).length;
const withWordAudio = audio.filter(a => a.wordAudio && a.wordAudio.byteLength > 0).length;
const withSentAudio = audio.filter(a => a.sentenceAudios && a.sentenceAudios.some(sa => sa.audio && sa.audio.byteLength > 0)).length;
const totalSentAudioBlobs = audio.reduce((sum, a) => sum + (a.sentenceAudios || []).filter(sa => sa.audio && sa.audio.byteLength > 0).length, 0);
const totalAudioBytes = audio.reduce((sum, a) => {
let s = (a.wordAudio && a.wordAudio.byteLength) || 0;
s += (a.sentenceAudios || []).reduce((t, sa) => t + ((sa.audio && sa.audio.byteLength) || 0), 0);
return sum + s;
}, 0);
const enrichedPct = words.length ? Math.round((enriched / words.length) * 100) : 0;
const srsDue = srs.filter(s => !s.hidden && s.due && s.due <= Date.now()).length;
const sourceBreakdown = {};
for (const w of words) sourceBreakdown[w.source || 'unknown'] = (sourceBreakdown[w.source || 'unknown'] || 0) + 1;
let html = '<h2 style="margin-top:0">📊 Live Stats</h2>';
html += '<div class="dash-grid">';
html += `<div class="dash-card"><div class="num">${words.length.toLocaleString()}</div><div class="lbl">Words</div><div class="sub">${enriched} enriched (${enrichedPct}%)</div></div>`;
html += `<div class="dash-card"><div class="num">${withWordAudio.toLocaleString()}</div><div class="lbl">Word Audio</div></div>`;
html += `<div class="dash-card"><div class="num">${totalSentAudioBlobs.toLocaleString()}</div><div class="lbl">Sentence Clips</div><div class="sub">${withSentAudio} words</div></div>`;
html += `<div class="dash-card"><div class="num">${sentences.length.toLocaleString()}</div><div class="lbl">Sentences</div></div>`;
html += `<div class="dash-card"><div class="num">${srs.length.toLocaleString()}</div><div class="lbl">SRS Items</div><div class="sub">${srsDue} due now</div></div>`;
html += `<div class="dash-card"><div class="num">${sessions.length.toLocaleString()}</div><div class="lbl">Sessions</div><div class="sub">${sessions.reduce((a, s) => a + (s.readCount || 0), 0)} total reads</div></div>`;
html += `<div class="dash-card"><div class="num">${(totalAudioBytes / 1024 / 1024).toFixed(1)}</div><div class="lbl">MB Audio</div></div>`;
html += '</div>';
html += '<h2 class="store" style="margin-top:8px">Source Breakdown</h2>';
html += '<table><tr><th>Source</th><th>Count</th><th>Share</th></tr>';
const srcEntries = Object.entries(sourceBreakdown).sort((a, b) => b[1] - a[1]);
for (const [src, count] of srcEntries) {
const pct = Math.round((count / words.length) * 100);
html += `<tr><td class="field">${src}</td><td>${count.toLocaleString()}</td><td><div style="display:flex;align-items:center;gap:8px"><div style="flex:1;height:6px;background:var(--panel-bg);border-radius:3px;overflow:hidden"><div style="width:${pct}%;height:100%;background:var(--highlight)"></div></div><span style="font-size:11px;color:var(--muted)">${pct}%</span></div></td></tr>`;
}
html += '</table>';
html += '<h2 class="store">Recent Additions</h2>';
const recent = words.slice().sort((a, b) => (b.createdAt || b.updatedAt || 0) - (a.createdAt || a.updatedAt || 0)).slice(0, 10);
if (recent.length === 0) {
html += '<p class="empty">No words yet.</p>';
} else {
html += '<div class="word-grid">';
for (const w of recent) {
html += `<div class="word-card" onclick="openWordModal('${escHtml(w.id)}')">
<div class="hanzi">${escHtml(w.hanzi)}</div>
<div class="pinyin">${escHtml(w.pinyin || '—')}</div>
<div class="meaning">${escHtml(w.meaning || '—')}</div>
<div class="meta"><span>${new Date(w.createdAt || w.updatedAt).toLocaleDateString()}</span><span>src: ${w.source}</span></div>
</div>`;
}
html += '</div>';
}
html += `<div style="margin-top:14px"><button class="btn-primary" onclick="liveStats()">🔄 Refresh</button></div>`;
document.getElementById('results').innerHTML = html;
}
async function exportDB() {
try {
await MoBackup.exportAndDownload();
} catch (err) {
console.error('Export failed:', err);
alert('Export failed: ' + err.message);
}
}
async function importDB(input) {
const file = input.files[0];
if (!file) return;
input.value = '';
const results = document.getElementById('results');
results.innerHTML = '<p class="empty-state">Importing backup…</p>';
try {
const text = await file.text();
await MoBackup.fullImport(text);
results.innerHTML = '<div class="empty-state"><span style="color:var(--success);font-size:2rem">✓</span><p>Backup restored successfully.<br>' + file.name + '</p><button class="btn-primary" onclick="inspect()">View Stores</button></div>';
} catch (err) {
console.error('Import failed:', err);
results.innerHTML = '<div class="empty-state"><span style="color:var(--danger);font-size:2rem">✗</span><p>Import failed.<br><code style="font-size:12px">' + escHtml(err.message) + '</code></p></div>';
}
}
async function clearDB() {
if (!confirm('This will delete ALL data in MoDB. Are you sure?')) return;
const req = indexedDB.deleteDatabase('MoDB');
req.onsuccess = () => { alert('MoDB deleted. Reload page.'); };
req.onerror = () => { alert('Failed to delete MoDB'); };
}
// Auto-load Browse on startup
browseWords();
</script>
<!-- Word Detail Modal -->
<div class="modal-overlay" id="wordModal" onclick="if(event.target===this)closeWordModal()">
<div class="modal-panel">
<button class="modal-close" onclick="closeWordModal()" title="Close">✕</button>
<button class="modal-back" onclick="closeWordModal()">← Back to Browse</button>
<div id="wordModalContent"></div>
</div>
</div>
</body>
</html>