-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1277 lines (1146 loc) · 65.6 KB
/
index.html
File metadata and controls
1277 lines (1146 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>SQLite Browser & Explorer</title>
<link rel="icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="/favicon.png">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/sql.js@1.10.3/dist/sql-wasm.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
dark: {
bg: '#09090b',
surface: '#18181b',
border: '#27272a',
text: '#fafafa',
muted: '#a1a1aa'
}
}
}
}
}
</script>
<style>
:root {
--bg-main: #f9fafb;
--bg-surface: #ffffff;
--border-color: #e5e7eb;
--text-main: #1f2937;
--text-muted: #6b7280;
--scrollbar-track: #f1f1f1;
--scrollbar-thumb: #c1c1c1;
--scrollbar-thumb-hover: #a8a8a8;
}
.dark {
--bg-main: #000000;
--bg-surface: #18181b;
--border-color: #27272a;
--text-main: #ffffff;
--text-muted: #a1a1aa;
--scrollbar-track: #18181b;
--scrollbar-thumb: #3f3f46;
--scrollbar-thumb-hover: #71717a;
}
body {
font-family: 'Roboto', sans-serif;
}
.custom-scrollbar::-webkit-scrollbar {
width: 10px;
height: 10px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: var(--scrollbar-track);
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: var(--scrollbar-thumb);
border-radius: 5px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: var(--scrollbar-thumb-hover);
}
.fade-in {
animation: fadeIn 0.15s ease-in-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(-5px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
th.dragging {
opacity: 0.4;
background-color: #e5e7eb;
border: 2px dashed #9ca3af;
}
th.drag-over-left {
border-left: 3px solid #2563eb;
}
th.drag-over-right {
border-right: 3px solid #2563eb;
}
.sort-badge {
font-size: 0.65rem;
height: 16px;
width: 16px;
line-height: 16px;
text-align: center;
border-radius: 50%;
background-color: #dbeafe;
color: #1e40af;
font-weight: 700;
display: inline-block;
margin-left: 2px;
}
/* Loading Overlay */
#loadingOverlay {
background: rgba(var(--bg-surface-rgb, 255, 255, 255), 0.8);
backdrop-filter: blur(2px);
}
.dark #loadingOverlay {
background: rgba(0, 0, 0, 0.85);
}
@keyframes pulse-ring {
0% {
box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.7);
}
70% {
box-shadow: 0 0 0 6px rgba(37, 99, 235, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(37, 99, 235, 0);
}
}
.pulse-animation {
animation: pulse-ring 2s infinite;
}
</style>
</head>
<body
class="bg-gray-50 text-gray-800 h-screen flex flex-col overflow-hidden transition-colors duration-300 dark:bg-black dark:text-zinc-100">
<div id="loadingOverlay" class="fixed inset-0 z-50 flex items-center justify-center hidden">
<div class="flex flex-col items-center">
<span class="material-symbols-outlined text-4xl animate-spin text-blue-600 mb-2">progress_activity</span>
<span class="text-sm font-medium text-gray-600" id="loadingText">Processing...</span>
</div>
</div>
<header
class="bg-white border-b border-gray-200 px-6 py-3 flex items-center justify-between shadow-sm z-20 dark:bg-zinc-900 dark:border-zinc-800 dark:shadow-none transition-colors">
<div class="flex items-center gap-4">
<!-- Upload Button -->
<div class="group relative">
<div class="bg-blue-600 text-white p-2 rounded-lg cursor-pointer hover:bg-blue-700 transition-colors shadow-md hover:shadow-lg active:scale-95 duration-200"
onclick="document.getElementById('dbFileInput').click()">
<span class="material-symbols-outlined text-xl block">upload_file</span>
</div>
<input type="file" id="dbFileInput" class="hidden" accept=".db,.sqlite,.sqlite3" multiple
onchange="handleFileUpload(event)">
</div>
<!-- DB Info -->
<div class="flex flex-col" id="dbInfoContainer">
<h1 class="text-lg font-semibold text-gray-800 leading-tight dark:text-zinc-100 flex items-center gap-2"
id="dbName">
No Database
</h1>
<p class="text-xs text-gray-500 dark:text-zinc-500" id="dbMeta">Load a .sqlite file to begin</p>
</div>
<!-- Table Selector -->
<div class="hidden h-8 w-px bg-gray-200 mx-2 dark:bg-zinc-800 md:block"></div>
<div class="hidden flex items-center gap-3" id="tableSelectorContainer">
<label for="tableSelect" class="text-sm font-medium text-gray-500 dark:text-zinc-400">Table:</label>
<div class="relative group">
<select id="tableSelect" onchange="loadTable(this.value)"
class="appearance-none bg-gray-50 border border-gray-300 text-gray-900 text-sm font-medium font-mono rounded-lg pl-3 pr-10 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 hover:bg-blue-100 hover:border-blue-400 hover:text-blue-900 transition-all cursor-pointer shadow-sm min-w-[150px] dark:bg-zinc-950 dark:border-zinc-700 dark:text-zinc-100 dark:hover:bg-blue-900/40 dark:hover:border-blue-600 dark:hover:text-blue-200 dark:focus:ring-blue-600">
</select>
<div
class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500 dark:text-zinc-500 group-hover:text-gray-700 dark:group-hover:text-zinc-300">
<span class="material-symbols-outlined text-lg">expand_more</span>
</div>
</div>
</div>
</div>
<!-- Global Actions -->
<div class="flex items-center gap-3">
<!-- Search -->
<div class="relative hidden md:block group">
<span
class="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-lg dark:text-zinc-500 group-focus-within:text-blue-500 transition-colors">search</span>
<input
class="pl-10 pr-4 py-1.5 border border-gray-300 rounded-lg text-sm bg-gray-50 focus:bg-white focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 w-48 focus:w-64 transition-all dark:bg-zinc-950 dark:border-zinc-700 dark:text-zinc-200 dark:placeholder-zinc-600 dark:focus:bg-zinc-900 dark:focus:border-blue-500 dark:focus:ring-blue-500/20"
id="globalSearch" placeholder="Search data..." type="text">
</div>
<div class="h-6 w-px bg-gray-200 mx-1 dark:bg-zinc-800"></div>
<!-- Toolbar Buttons -->
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 hover:text-gray-900 transition-all dark:bg-zinc-900 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800 dark:hover:text-zinc-100"
onclick="toggleQueryPanel()" title="SQL Query Editor">
<span class="material-symbols-outlined text-lg">terminal</span> <span
class="hidden sm:inline">Query</span>
</button>
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 hover:text-gray-900 transition-all dark:bg-zinc-900 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800 dark:hover:text-zinc-100"
onclick="exportData()" title="Export CSV">
<span class="material-symbols-outlined text-lg">download</span>
</button>
<button
class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-red-600 bg-white border border-red-200 rounded-lg hover:bg-red-50 transition-all dark:bg-zinc-900 dark:border-red-900/30 dark:text-red-400 dark:hover:bg-red-900/20 dark:hover:border-red-900/50"
onclick="clearAllData()" title="Reset Session">
<span class="material-symbols-outlined text-lg">delete_sweep</span>
</button>
<!-- Theme Toggle -->
<button
class="flex items-center justify-center p-1.5 text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-white"
onclick="toggleTheme()" id="themeToggle" title="Toggle Theme">
<span class="material-symbols-outlined text-xl" id="themeIcon">dark_mode</span>
</button>
</div>
</header>
<div class="hidden bg-white border-b border-gray-200 shadow-inner flex-shrink-0 transition-all duration-300 ease-in-out dark:bg-zinc-900 dark:border-zinc-800"
id="queryPanel">
<div class="p-4 max-w-7xl mx-auto">
<div class="flex gap-4 mb-3">
<div class="flex bg-gray-100 p-1 rounded-lg dark:bg-zinc-800">
<button
class="px-4 py-1.5 text-sm font-medium rounded-md shadow-sm bg-white text-gray-900 transition-all dark:bg-zinc-700 dark:text-zinc-100"
id="modeSql" onclick="setQueryMode('sql')">SQL</button>
<button
class="px-4 py-1.5 text-sm font-medium rounded-md text-gray-500 hover:text-gray-900 transition-all flex items-center gap-1 dark:text-zinc-400 dark:hover:text-zinc-100"
id="modeAi" onclick="setQueryMode('ai')">
AI
</button>
</div>
<div class="flex-1" id="sampleQueriesContainer">
<select
class="w-full text-sm border-gray-300 border rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-zinc-800 dark:border-zinc-700 dark:text-zinc-200"
id="sampleQueries" onchange="loadSampleQuery(this.value)">
<option value="">-- Load a Sample Query --</option>
<option value="SELECT * FROM {{table}} LIMIT 10">First 10 Rows</option>
<option value="SELECT COUNT(*) as total FROM {{table}}">Count All Records</option>
<option value="SELECT * FROM {{table}} ORDER BY RANDOM() LIMIT 10">Random 10 Records</option>
</select>
</div>
</div>
<div class="relative">
<textarea
class="w-full font-mono text-sm bg-gray-50 border border-gray-300 rounded-lg p-4 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all resize-y dark:bg-zinc-800 dark:border-zinc-700 dark:text-zinc-200 dark:placeholder-zinc-500"
id="queryInput" placeholder="SELECT * FROM..." rows="4"></textarea>
<div class="absolute bottom-3 right-3 flex gap-2">
<button
class="px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-300 rounded hover:bg-gray-50 dark:bg-zinc-700 dark:border-zinc-600 dark:text-zinc-300 dark:hover:bg-zinc-600"
onclick="clearQuery()">Clear</button>
<button id="runQueryBtn"
class="px-4 py-1.5 text-xs font-bold text-white bg-blue-600 rounded hover:bg-blue-700 shadow-sm flex items-center gap-1 dark:bg-blue-700 dark:hover:bg-blue-600"
onclick="executeCustomQuery()">
<span class="material-symbols-outlined text-sm">play_arrow</span> Run
</button>
</div>
</div>
<div class="mt-2 text-xs text-gray-500 hidden dark:text-zinc-400" id="queryStatus"></div>
</div>
</div>
<div
class="px-6 py-3 bg-white border-b border-gray-200 flex items-center justify-between flex-shrink-0 dark:bg-zinc-900 dark:border-zinc-800">
<div class="flex items-center gap-2">
<span
class="text-sm font-medium text-gray-600 bg-gray-100 px-2 py-1 rounded dark:bg-zinc-800 dark:text-zinc-300"
id="totalRecords">0
Records</span>
<span
class="hidden text-xs font-medium text-blue-700 bg-blue-50 px-2 py-1 rounded border border-blue-100 flex items-center gap-1 cursor-pointer hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-300 dark:border-blue-800"
id="filterBadge" onclick="clearAllFilters()">
Filters Active <span class="material-symbols-outlined text-xs">close</span>
</span>
<span class="text-xs text-gray-400 ml-2 italic hidden md:inline dark:text-zinc-500">Shift+Click to
multi-sort. Drag headers to
reorder.</span>
</div>
<div class="flex items-center gap-2">
<button
class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-600 bg-white border border-gray-300 rounded hover:bg-gray-50 hover:text-blue-600 transition-colors dark:bg-zinc-800 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-blue-400"
onclick="toggleColumnManager(event)">
<span class="material-symbols-outlined text-lg">view_column</span> Columns
</button>
<button
class="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-600 bg-white border border-gray-300 rounded hover:bg-gray-50 hover:text-red-600 transition-colors dark:bg-zinc-800 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-700 dark:hover:text-red-400"
onclick="resetView()">
<span class="material-symbols-outlined text-lg">restart_alt</span> Reset
</button>
</div>
</div>
<div class="flex-1 overflow-auto relative custom-scrollbar bg-white dark:bg-zinc-900">
<table class="w-full text-left border-collapse">
<thead
class="bg-gray-50 sticky top-0 z-10 shadow-sm text-xs uppercase text-gray-500 font-semibold tracking-wider dark:bg-zinc-800 dark:text-zinc-300 dark:shadow-black/50">
<tr id="tableHeaderRow">
</tr>
</thead>
<tbody class="divide-y divide-gray-200 text-sm text-gray-700 dark:divide-zinc-700 dark:text-zinc-200"
id="tableBody">
</tbody>
</tbody>
</table>
<!-- Pending Overlay -->
<div id="pendingOverlay"
class="hidden absolute inset-0 bg-white/50 z-20 flex items-start justify-center pt-20 backdrop-blur-[1px] transition-all duration-300 dark:bg-black/80">
<div
class="bg-white border border-blue-200 shadow-lg rounded-lg px-6 py-4 flex flex-col items-center dark:bg-zinc-900 dark:border-blue-900">
<span
class="material-symbols-outlined text-blue-600 text-3xl mb-2 dark:text-blue-400">arrow_upward</span>
<p class="font-medium text-gray-800 dark:text-zinc-100">New SQL Generated</p>
<p class="text-xs text-gray-500 mb-3 dark:text-zinc-400">Table data is from previous query.</p>
<button onclick="executeCustomQuery()"
class="px-4 py-2 bg-blue-600 text-white text-sm font-bold rounded hover:bg-blue-700 shadow-md transform transition-transform hover:scale-105">
Click Run to Execute
</button>
</div>
</div>
<div class="flex flex-col items-center justify-center h-64 text-gray-400 dark:text-zinc-500" id="emptyState">
<span class="material-symbols-outlined text-6xl mb-2">upload_file</span>
<p class="text-lg font-medium text-gray-500 dark:text-zinc-400">No database loaded</p>
<p class="text-sm text-gray-400 mb-4 dark:text-zinc-500">Upload a .db or .sqlite file to begin</p>
<button
class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600"
onclick="document.getElementById('dbFileInput').click()">Select File</button>
</div>
</div>
<footer
class="bg-white border-t border-gray-200 px-6 py-3 flex items-center justify-between flex-shrink-0 text-sm dark:bg-zinc-900 dark:border-zinc-800">
<div class="flex items-center gap-2 text-gray-600 dark:text-zinc-400">
<span>Rows:</span>
<select
class="border-gray-300 border rounded py-1 px-2 focus:ring-blue-500 focus:border-blue-500 bg-transparent cursor-pointer dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-300"
id="rowsPerPage" onchange="changeRowsPerPage(this.value)">
<option value="10">10</option>
<option selected="" value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
<div class="flex items-center gap-4">
<span class="text-gray-600 dark:text-zinc-400" id="pageInfo">Page 1 of 1</span>
<div class="flex gap-1">
<button
class="p-1 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-600 dark:text-zinc-400 dark:hover:bg-zinc-800"
id="btnPrev" onclick="prevPage()" disabled="">
<span class="material-symbols-outlined">chevron_left</span>
</button>
<button
class="p-1 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-600 dark:text-zinc-400 dark:hover:bg-zinc-800"
id="btnNext" onclick="nextPage()" disabled="">
<span class="material-symbols-outlined">chevron_right</span>
</button>
</div>
</div>
</footer>
<div class="hidden absolute z-50 bg-white border border-gray-200 rounded-lg shadow-xl w-64 text-sm fade-in dark:bg-zinc-900 dark:border-zinc-800 dark:shadow-zinc-950"
id="columnManager" style="top: 130px; right: 24px;">
<div
class="p-3 border-b border-gray-200 bg-gray-50 rounded-t-lg flex justify-between items-center dark:bg-zinc-800 dark:border-zinc-700">
<span class="font-semibold text-gray-700 dark:text-zinc-200">Manage Columns</span>
<button class="text-gray-400 hover:text-gray-700 dark:hover:text-zinc-200"
onclick="document.getElementById('columnManager').classList.add('hidden')"><span
class="material-symbols-outlined text-lg">close</span></button>
</div>
<div class="p-2 max-h-64 overflow-y-auto custom-scrollbar" id="columnList"></div>
</div>
<div class="hidden absolute z-50 bg-white border border-gray-200 rounded-lg shadow-xl w-80 text-sm fade-in dark:bg-zinc-900 dark:border-zinc-800 dark:shadow-zinc-950"
id="filterPopover">
<div
class="p-3 border-b border-gray-200 bg-gray-50 rounded-t-lg flex justify-between items-center dark:bg-zinc-800 dark:border-zinc-700">
<span class="font-semibold text-gray-700 dark:text-zinc-200" id="filterTitle">Filter Column</span>
<button class="text-gray-400 hover:text-gray-700 dark:hover:text-zinc-200"
onclick="closeFilterPopover()"><span class="material-symbols-outlined text-lg">close</span></button>
</div>
<div class="p-4 space-y-3" id="filterContent"></div>
<div
class="p-3 border-t border-gray-200 bg-gray-50 rounded-b-lg flex justify-end gap-2 dark:bg-zinc-800 dark:border-zinc-700">
<button
class="px-3 py-1.5 text-gray-600 hover:bg-gray-200 rounded border border-gray-300 bg-white dark:bg-zinc-700 dark:text-zinc-300 dark:border-zinc-600 dark:hover:bg-zinc-600"
onclick="clearCurrentFilter()">Clear</button>
<button
class="px-3 py-1.5 text-white bg-blue-600 hover:bg-blue-700 rounded shadow-sm dark:bg-blue-700 dark:hover:bg-blue-600"
onclick="applyCurrentFilter()">Apply</button>
</div>
</div>
<script>
// --- 1. Global State & DB Variables ---
let db = null;
let SQL = null;
let allData = [];
let filteredData = [];
let columns = [];
let visibleColumns = [];
let columnStats = {};
let sortConfig = [];
let draggedColumn = null;
let tables = [];
let currentDbFile = null;
let suggestedQueries = [];
let tableSettings = {}; // { tableName: { visibleColumns, filters, sort, ... } }
// Multi-DB State
let databases = {}; // { name: { data: u8arr, size: int } }
let currentDbName = null;
let state = {
currentPage: 1,
rowsPerPage: 20,
columnFilters: {},
globalSearch: '',
darkMode: false
};
// --- 2. Theme Management ---
function initTheme() {
const savedTheme = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
setTheme(true);
} else {
setTheme(false);
}
}
function toggleTheme() {
setTheme(!state.darkMode);
}
function setTheme(isDark) {
state.darkMode = isDark;
const html = document.documentElement;
const themeIcon = document.getElementById('themeIcon');
if (isDark) {
html.classList.add('dark');
if (themeIcon) themeIcon.textContent = 'light_mode';
localStorage.setItem('theme', 'dark');
} else {
html.classList.remove('dark');
if (themeIcon) themeIcon.textContent = 'dark_mode';
localStorage.setItem('theme', 'light');
}
}
// --- 3. Caching & Persistence (IndexedDB) ---
const CACHE_KEYS = {
DB_FILE: 'simpledb_cached_file',
TABLES: 'simpledb_cached_tables',
CURRENT_TABLE: 'simpledb_current_table',
TABLE_SETTINGS: 'simpledb_table_settings',
PAGE_STATE: 'simpledb_page_state',
GLOBAL_SEARCH: 'simpledb_global_search',
AI_SAMPLE_QUERIES: 'simpledb_ai_sample_queries'
};
const IDB_CONFIG = {
DB_NAME: 'SimpleDB_Storage',
STORE_NAME: 'files',
VERSION: 1,
KEY: 'current_db_file'
};
function openIDB() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(IDB_CONFIG.DB_NAME, IDB_CONFIG.VERSION);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(IDB_CONFIG.STORE_NAME)) {
db.createObjectStore(IDB_CONFIG.STORE_NAME);
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function saveFileToIDB(fileData) {
try {
const db = await openIDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_CONFIG.STORE_NAME, 'readwrite');
const store = tx.objectStore(IDB_CONFIG.STORE_NAME);
store.put(fileData, IDB_CONFIG.KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
} catch (e) { console.error("IDB Save Error:", e); }
}
async function getFileFromIDB() {
try {
const db = await openIDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_CONFIG.STORE_NAME, 'readonly');
const store = tx.objectStore(IDB_CONFIG.STORE_NAME);
const req = store.get(IDB_CONFIG.KEY);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
} catch (e) { return null; }
}
async function clearIDB() {
try {
const db = await openIDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_CONFIG.STORE_NAME, 'readwrite');
const store = tx.objectStore(IDB_CONFIG.STORE_NAME);
store.delete(IDB_CONFIG.KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
} catch (e) { console.error(e); }
}
function saveToCache() {
try {
const currentTable = document.getElementById('tableSelect')?.value;
if (currentTable) {
tableSettings[currentTable] = {
visibleColumns: visibleColumns,
columnStats: columnStats,
filters: state.columnFilters,
sortConfig: sortConfig
};
}
const cacheData = {
[CACHE_KEYS.DB_FILE]: currentDbFile,
[CACHE_KEYS.TABLES]: tables,
[CACHE_KEYS.CURRENT_TABLE]: currentTable || '',
[CACHE_KEYS.TABLE_SETTINGS]: tableSettings,
[CACHE_KEYS.PAGE_STATE]: { currentPage: state.currentPage, rowsPerPage: state.rowsPerPage },
[CACHE_KEYS.GLOBAL_SEARCH]: state.globalSearch,
[CACHE_KEYS.AI_SAMPLE_QUERIES]: suggestedQueries
};
Object.entries(cacheData).forEach(([key, value]) => {
if (value !== null && value !== undefined) localStorage.setItem(key, JSON.stringify(value));
});
} catch (error) { console.warn('Failed to save to cache:', error); }
}
function loadFromCache() {
try {
const cachedFile = localStorage.getItem(CACHE_KEYS.DB_FILE);
if (cachedFile) currentDbFile = JSON.parse(cachedFile);
const cachedTables = localStorage.getItem(CACHE_KEYS.TABLES);
if (cachedTables) tables = JSON.parse(cachedTables);
const cachedSettings = localStorage.getItem(CACHE_KEYS.TABLE_SETTINGS);
if (cachedSettings) tableSettings = JSON.parse(cachedSettings);
const cachedPageState = localStorage.getItem(CACHE_KEYS.PAGE_STATE);
if (cachedPageState) {
const pageState = JSON.parse(cachedPageState);
state.currentPage = pageState.currentPage || 1;
state.rowsPerPage = pageState.rowsPerPage || 20;
}
const cachedGlobalSearch = localStorage.getItem(CACHE_KEYS.GLOBAL_SEARCH);
if (cachedGlobalSearch) {
state.globalSearch = JSON.parse(cachedGlobalSearch);
document.getElementById('globalSearch').value = state.globalSearch;
}
const cachedQueries = localStorage.getItem(CACHE_KEYS.AI_SAMPLE_QUERIES);
if (cachedQueries) suggestedQueries = JSON.parse(cachedQueries);
return true;
} catch (error) { return false; }
}
function clearCache() {
Object.values(CACHE_KEYS).forEach(key => localStorage.removeItem(key));
clearIDB();
}
// --- 4. Initialization ---
document.addEventListener('DOMContentLoaded', async () => {
try {
const config = { locateFile: filename => `https://cdn.jsdelivr.net/npm/sql.js@1.10.3/dist/${filename}` };
SQL = await initSqlJs(config);
initTheme();
const restored = loadFromCache();
if (restored && currentDbFile) tryRestoreFromCache();
} catch (e) { console.error("Failed to load SQL.js", e); }
});
async function tryRestoreFromCache() {
if (!currentDbFile || !SQL) return;
const loadingOverlay = document.getElementById('loadingOverlay');
try {
loadingOverlay.classList.remove('hidden');
const savedUint8 = await getFileFromIDB();
if (savedUint8) {
db = new SQL.Database(savedUint8);
if (tables.length > 0) {
populateTableSelector(tables);
document.getElementById('dbName').textContent = currentDbFile.name;
document.getElementById('dbMeta').textContent = `${(currentDbFile.size / 1024 / 1024).toFixed(2)} MB • SQLite (Restored)`;
document.getElementById('emptyState').classList.add('hidden');
const cachedCurrentTable = localStorage.getItem(CACHE_KEYS.CURRENT_TABLE);
const tableToLoad = (cachedCurrentTable && tables.includes(JSON.parse(cachedCurrentTable)))
? JSON.parse(cachedCurrentTable) : tables[0];
if (tableToLoad) {
document.getElementById('tableSelect').value = tableToLoad;
loadTable(tableToLoad);
}
if (suggestedQueries.length > 0) populateSampleQueries();
generateDbAnalysis(); // Refresh analysis in background
}
}
} catch (e) { console.error("Restore failed", e); }
finally { loadingOverlay.classList.add('hidden'); }
}
// --- 5. File Handling ---
function handleFileUpload(event) {
const files = event.target.files;
if (!files || files.length === 0) return;
const loadingOverlay = document.getElementById('loadingOverlay');
loadingOverlay.classList.remove('hidden');
let processed = 0;
Array.from(files).forEach(file => {
const reader = new FileReader();
reader.onload = function () {
try {
const uints = new Uint8Array(reader.result);
databases[file.name] = { data: uints, size: file.size };
// Always switch to the newly uploaded file
switchDatabase(file.name);
if (++processed === files.length) {
loadingOverlay.classList.add('hidden');
}
} catch (e) {
alert("Load Error: " + e.message);
loadingOverlay.classList.add('hidden');
}
};
reader.readAsArrayBuffer(file);
});
}
function switchDatabase(dbName) {
if (dbName === '__add_new__') {
document.getElementById('dbFileInput').click();
updateDbSelector(); // Reset selector
return;
}
if (!databases[dbName]) return;
currentDbName = dbName;
try {
// Init SQL.js with new data
db = new SQL.Database(databases[dbName].data);
// Update UI
updateDbSelector();
document.getElementById('emptyState').classList.add('hidden');
// Load tables
const res = db.exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
if (res.length > 0 && res[0].values.length > 0) {
tables = res[0].values.map(v => v[0]);
populateTableSelector(tables);
loadTable(tables[0]);
} else {
tables = [];
populateTableSelector([]);
// Handle empty DB case
}
suggestedQueries = [];
generateDbAnalysis();
// saveToCache(); // TODO: Update cache logic for multi-db if needed
} catch (e) { console.error(e); alert("Failed to switch DB: " + e.message); }
}
function updateDbSelector() {
const container = document.getElementById('dbInfoContainer');
if (Object.keys(databases).length > 0) {
// Always show Selector to allow adding new DBs easily
container.innerHTML = `
<div class="relative group">
<select onchange="switchDatabase(this.value)" class="appearance-none bg-transparent font-semibold text-lg text-gray-800 dark:text-zinc-100 pr-8 py-1 focus:outline-none cursor-pointer">
${Object.keys(databases).map(d => `<option value="${d}" ${d === currentDbName ? 'selected' : ''}>${d}</option>`).join('')}
<hr>
<option value="__add_new__" class="text-blue-600 dark:text-blue-400 font-medium">+ Add Database...</option>
</select>
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center text-gray-400 dark:text-zinc-500">
<span class="material-symbols-outlined">expand_more</span>
</div>
</div>
<p class="text-xs text-gray-500 dark:text-zinc-500" id="dbMeta">${(databases[currentDbName].size / 1024 / 1024).toFixed(2)} MB • SQLite</p>
`;
} else {
// Should technically not happen if we are here, but valid for empty state
container.innerHTML = `
<h1 class="text-lg font-semibold text-gray-800 leading-tight dark:text-zinc-100 flex items-center gap-2" id="dbName">No Database</h1>
<p class="text-xs text-gray-500 dark:text-zinc-500" id="dbMeta">Load a .sqlite file to begin</p>
`;
}
}
function populateTableSelector(tableList) {
const select = document.getElementById('tableSelect');
const options = tableList.map(t => {
let count = '?';
try {
const res = db.exec(`SELECT COUNT(*) as c FROM "${t}"`);
if (res.length > 0) count = res[0].values[0][0];
} catch (e) { }
return `<option value="${t}">${t} (${count})</option>`;
});
select.innerHTML = options.join('');
document.getElementById('tableSelectorContainer').classList.remove('hidden');
}
function loadTable(tableName) {
const loadingOverlay = document.getElementById('loadingOverlay');
loadingOverlay.classList.remove('hidden');
setTimeout(() => {
try {
const res = db.exec(`SELECT * FROM "${tableName}" LIMIT 5000`);
if (res.length > 0) {
columns = res[0].columns;
allData = res[0].values.map(row => {
let obj = {};
columns.forEach((col, i) => obj[col] = row[i]);
return obj;
});
} else {
const colRes = db.exec(`PRAGMA table_info("${tableName}")`);
columns = colRes[0].values.map(r => r[1]);
allData = [];
}
restoreTableState(tableName);
localStorage.setItem(CACHE_KEYS.CURRENT_TABLE, JSON.stringify(tableName));
saveToCache();
populateSampleQueries();
} catch (e) { alert("Error reading table: " + e.message); }
finally { loadingOverlay.classList.add('hidden'); }
}, 50);
}
function restoreTableState(tableName) {
const settings = tableSettings[tableName];
if (settings) {
visibleColumns = settings.visibleColumns ? settings.visibleColumns.filter(c => columns.includes(c)) : [...columns];
if (visibleColumns.length === 0) visibleColumns = [...columns];
columnStats = settings.columnStats || {};
state.columnFilters = settings.filters || {};
sortConfig = settings.sortConfig || [];
} else {
visibleColumns = [...columns];
columnStats = {};
state.columnFilters = {};
sortConfig = [];
}
processData();
}
// --- 6. AI Features (Analysis & Query Generation) ---
async function generateDbAnalysis() {
if (!tables.length) return;
const hasQueries = suggestedQueries.length > 0;
const allTablesConfigured = tables.every(t => tableSettings[t] && tableSettings[t].visibleColumns);
if (hasQueries && allTablesConfigured) return;
const select = document.getElementById('sampleQueries');
select.innerHTML = '<option>✨ Analyzing Database...</option>';
select.disabled = true;
const toast = document.createElement('div');
toast.className = 'fixed bottom-4 right-4 bg-blue-600 text-white px-4 py-3 rounded shadow-lg z-50 flex items-center animate-pulse';
toast.innerHTML = '<span class="material-symbols-outlined mr-2 animate-spin">auto_awesome</span> AI is analyzing your database...';
document.body.appendChild(toast);
try {
let ollamaUrl = localStorage.getItem('ollama_url') || 'http://localhost:11434';
const currentTable = document.getElementById('tableSelect')?.value;
for (const tableName of tables) {
toast.innerHTML = `<span class="material-symbols-outlined mr-2 animate-spin">auto_awesome</span> Analyzing ${tableName}...`;
let schemaContext = '';
const res = db.exec(`PRAGMA table_info("${tableName}")`);
if (res.length > 0 && res[0].values) {
const cols = res[0].values.map(r => r[1]).join(', ');
schemaContext = `Table: ${tableName} (Cols: ${cols})`;
}
const prompt = `Analyze this table: ${schemaContext}. Return JSON with "queries" (5 SQL objects with label, sql, table) and "columns" (5-7 important col names). Only return raw JSON.`;
try {
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gpt-oss:20b',
prompt: prompt,
stream: false,
options: { temperature: 0.1 }
})
});
const data = await response.json();
let jsonStr = data.response.replace(/```json/g, '').replace(/```/g, '').trim();
const result = JSON.parse(jsonStr);
if (result.queries) {
suggestedQueries = [...suggestedQueries, ...result.queries.map(q => ({ ...q, table: tableName }))];
populateSampleQueries();
}
if (result.columns) {
if (!tableSettings[tableName]) tableSettings[tableName] = {};
if (!tableSettings[tableName].visibleColumns) {
tableSettings[tableName].visibleColumns = result.columns;
if (tableName === currentTable) restoreTableState(tableName);
}
}
saveToCache();
} catch (err) { console.warn(err); }
}
toast.innerHTML = 'Analysis Complete!';
setTimeout(() => toast.remove(), 2000);
} catch (e) { if (toast) toast.remove(); }
finally { select.disabled = false; populateSampleQueries(); }
}
async function generateAIQuery(userPrompt) {
let ollamaUrl = localStorage.getItem('ollama_url') || 'http://localhost:11434';
let tableSchema = '';
const currentTable = document.getElementById('tableSelect')?.value;
tables.forEach(t => {
const res = db.exec(`PRAGMA table_info("${t}")`);
if (res.length > 0) tableSchema += `Table: ${t}\nColumns: ${res[0].values.map(r => r[1]).join(', ')}\n\n`;
});
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gpt-oss:20b',
prompt: `Expert SQL converter. Use schema:\n${tableSchema}\nUser: ${userPrompt}\nReturn ONLY SQL for "${currentTable}". No markdown.`,
stream: false
})
});
const data = await response.json();
return data.response?.trim().replace(/```sql/g, '').replace(/```/g, '');
}
function populateSampleQueries() {
const select = document.getElementById('sampleQueries');
const currentTable = document.getElementById('tableSelect')?.value;
let defaults = [
{ label: "First 10 Rows", sql: `SELECT * FROM "${currentTable}" LIMIT 10` },
{ label: "Record Count", sql: `SELECT COUNT(*) FROM "${currentTable}"` }
];
const filtered = suggestedQueries.filter(q => q.table === currentTable);
select.innerHTML = '<option value="">-- Sample Queries --</option>' +
[...defaults, ...filtered].map(q => `<option value="${q.sql.replace(/"/g, '"')}">${q.label}</option>`).join('');
}
function loadSampleQuery(val) {
if (!val) return;
document.getElementById('queryInput').value = val;
setQueryMode('sql');
}
async function executeCustomQuery() {
const sql = document.getElementById('queryInput').value;
if (!sql.trim()) return;
const status = document.getElementById('queryStatus');
status.classList.remove('hidden');
const isAiMode = document.getElementById('modeAi').classList.contains('bg-white');
if (isAiMode) {
status.innerHTML = '✨ Generating SQL...';
try {
const finalSql = await generateAIQuery(sql);
document.getElementById('queryInput').value = finalSql;
setQueryMode('sql');
status.innerHTML = 'SQL Generated. Click Run to Execute.';
document.getElementById('pendingOverlay').classList.remove('hidden');
} catch (e) { status.innerHTML = "AI Error: " + e.message; }
return;
}
status.innerHTML = 'Executing...';
setTimeout(() => {
try {
const res = db.exec(sql);
if (res.length === 0) { status.innerHTML = "Success. No results."; return; }
columns = res[0].columns;
allData = res[0].values.map(row => {
let obj = {}; columns.forEach((c, i) => obj[c] = row[i]); return obj;
});
filteredData = [...allData];
visibleColumns = [...columns];
analyzeColumns();
initTable();
updateTotalCount();
renderPagination();
status.innerHTML = `Success. ${allData.length} rows returned.`;
document.getElementById('pendingOverlay').classList.add('hidden');
} catch (e) { status.innerHTML = "Error: " + e.message; }
}, 100);
}
// --- 7. Rendering Logic ---
function analyzeColumns() {
columnStats = {};
const palette = [
{ bg: 'bg-blue-100', text: 'text-blue-800', darkBg: 'dark:bg-blue-900/40', darkText: 'dark:text-blue-200' },
{ bg: 'bg-green-100', text: 'text-green-800', darkBg: 'dark:bg-green-900/40', darkText: 'dark:text-green-200' },
{ bg: 'bg-purple-100', text: 'text-purple-800', darkBg: 'dark:bg-purple-900/40', darkText: 'dark:text-purple-200' },
{ bg: 'bg-yellow-100', text: 'text-yellow-800', darkBg: 'dark:bg-yellow-900/40', darkText: 'dark:text-yellow-200' },
{ bg: 'bg-pink-100', text: 'text-pink-800', darkBg: 'dark:bg-pink-900/40', darkText: 'dark:text-pink-200' },
{ bg: 'bg-gray-100', text: 'text-gray-800', darkBg: 'dark:bg-zinc-800', darkText: 'dark:text-zinc-300' }
];
if (allData.length === 0) return;
columns.forEach(col => {
const sampleVal = allData[0][col];
const type = typeof sampleVal;
if (type === 'string' && !col.toLowerCase().includes('id')) {
const uniqueValues = new Set(allData.slice(0, 1000).map(d => d[col]));
if (uniqueValues.size < 15 && uniqueValues.size > 1) {
const valueColorMap = {};
let colorIdx = 0;
Array.from(uniqueValues).sort().forEach(val => {
valueColorMap[val] = palette[colorIdx % palette.length];
colorIdx++;
});
columnStats[col] = { isEnum: true, options: Array.from(uniqueValues).sort(), colorMap: valueColorMap };
return;
}
}
columnStats[col] = { isEnum: false };
});
}
function initTable() {
renderHeader();
renderBody();
}
function renderHeader() {
const tr = document.getElementById('tableHeaderRow');
tr.innerHTML = visibleColumns.map((col) => {
const sortIndex = sortConfig.findIndex(s => s.col === col);
const isSorted = sortIndex !== -1;
const sortDir = isSorted ? sortConfig[sortIndex].dir : null;
const isFiltered = state.columnFilters[col];
return `