-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
790 lines (701 loc) · 37.8 KB
/
index.html
File metadata and controls
790 lines (701 loc) · 37.8 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
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text2SQL 智慧分析助手</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/sql.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked@11.1.1/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sql-formatter@15.0.2/dist/sql-formatter.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
}
}
}
}
</script>
<style>
/* 自定義滾動條 */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
/* 動畫 */
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.animate-fade-in-up { animation: fadeIn 0.3s ease-out forwards; }
.typing-dot { animation: typing 1.4s infinite ease-in-out both; }
.typing-dot:nth-child(1) { animation-delay: -0.32s; }
.typing-dot:nth-child(2) { animation-delay: -0.16s; }
@keyframes typing { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }
/* Markdown 樣式優化 */
.markdown-content p { margin-bottom: 0.5rem; line-height: 1.6; }
.markdown-content ul { list-style-type: disc; padding-left: 1.25rem; margin-bottom: 0.5rem; }
.markdown-content code {
background-color: #f1f5f9;
color: #ef4444;
padding: 0.1rem 0.3rem;
border-radius: 0.25rem;
font-family: 'JetBrains Mono', monospace;
font-size: 0.875em;
}
/* Toast 通知 */
#toast-container { position: fixed; top: 1rem; right: 1rem; z-index: 50; }
.toast {
background: white;
border-left: 4px solid #3b82f6;
padding: 1rem;
border-radius: 0.5rem;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
margin-bottom: 0.5rem;
transform: translateX(100%);
transition: transform 0.3s ease-out;
display: flex; align-items: center; gap: 0.5rem;
}
.toast.show { transform: translateX(0); }
.toast.error { border-left-color: #ef4444; }
/* Resizable dividers */
.resizer {
position: relative;
z-index: 10;
}
.resizer-vertical {
width: 8px;
cursor: col-resize;
background: transparent;
transition: background-color 0.2s;
flex-shrink: 0;
}
.resizer-vertical:hover,
.resizer-vertical.dragging {
background-color: rgba(59, 130, 246, 0.3);
}
.resizer-vertical::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 2px;
height: 30px;
background: #cbd5e1;
border-radius: 2px;
opacity: 0;
transition: opacity 0.2s;
}
.resizer-vertical:hover::before,
.resizer-vertical.dragging::before {
opacity: 1;
}
.resizer-horizontal {
height: 8px;
cursor: row-resize;
background: transparent;
transition: background-color 0.2s;
flex-shrink: 0;
}
.resizer-horizontal:hover,
.resizer-horizontal.dragging {
background-color: rgba(59, 130, 246, 0.3);
}
.resizer-horizontal::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 30px;
height: 2px;
background: #cbd5e1;
border-radius: 2px;
opacity: 0;
transition: opacity 0.2s;
}
.resizer-horizontal:hover::before,
.resizer-horizontal.dragging::before {
opacity: 1;
}
/* Disable selection during drag */
body.resizing {
user-select: none;
cursor: col-resize;
}
body.resizing-vertical {
cursor: row-resize;
}
</style>
</head>
<body class="bg-slate-50 text-slate-800 font-sans h-screen flex flex-col overflow-hidden">
<div id="toast-container"></div>
<header class="bg-white border-b border-slate-200 px-6 py-3 flex items-center justify-between shrink-0 shadow-sm z-10">
<div class="flex items-center gap-3">
<div class="bg-blue-600 p-1.5 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
</div>
<div>
<h1 class="font-bold text-slate-800 leading-tight">Text2SQL Dashboard</h1>
<p id="model-display" class="text-xs text-slate-500">Loading model info...</p>
</div>
</div>
<div class="flex items-center gap-3">
<button id="clear-conversation-btn" class="text-xs font-medium text-slate-600 hover:text-red-600 hover:bg-red-50 px-3 py-2 rounded-md transition-all flex items-center gap-1.5 border border-transparent hover:border-red-100">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
清空對話
</button>
</div>
</header>
<main class="flex-1 flex flex-col lg:flex-row overflow-hidden">
<div id="left-panel" class="flex-1 flex flex-col min-w-0 bg-white lg:border-r border-slate-200" style="min-width: 300px;">
<div id="chat-container" class="flex-1 overflow-y-auto p-4 space-y-6">
<div id="welcome-message" class="flex gap-4 max-w-3xl mx-auto animate-fade-in-up">
<div class="w-8 h-8 rounded-full bg-blue-100 border border-blue-200 flex items-center justify-center flex-shrink-0">
<span class="text-lg">🤖</span>
</div>
<div class="space-y-2">
<div class="bg-slate-50 p-5 rounded-2xl rounded-tl-none border border-slate-100 shadow-sm text-slate-700">
<p class="font-medium mb-2">你好!我是你的資料分析助手。</p>
<p class="text-sm text-slate-500 mb-3">我可以幫你查詢資料庫並生成可視化圖表。試試看問我:</p>
<div class="flex flex-wrap gap-2">
<button class="quick-query text-xs bg-white border border-slate-200 px-3 py-1.5 rounded-full hover:border-blue-400 hover:text-blue-600 transition cursor-pointer">
顯示上個月各產品類別的銷售總額
</button>
<button class="quick-query text-xs bg-white border border-slate-200 px-3 py-1.5 rounded-full hover:border-blue-400 hover:text-blue-600 transition cursor-pointer">
2009 年各月份銷售額?
</button>
</div>
</div>
</div>
</div>
</div>
<div class="p-4 border-t border-slate-100 bg-white">
<div class="max-w-3xl mx-auto relative">
<form id="query-form" class="relative group">
<input
type="text"
id="user-input"
class="w-full bg-slate-50 text-slate-700 border border-slate-200 rounded-xl py-3.5 pl-4 pr-14 focus:outline-none focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder-slate-400 shadow-sm"
placeholder="在此輸入您的數據問題..."
autocomplete="off"
>
<button
type="submit"
class="absolute right-2 top-2 bottom-2 aspect-square bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-all duration-200 flex items-center justify-center shadow-md hover:shadow-lg transform active:scale-95"
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z" />
</svg>
</button>
</form>
</div>
</div>
</div>
<!-- Vertical resizer between left and right panels -->
<div id="vertical-resizer" class="resizer resizer-vertical hidden lg:block"></div>
<div id="right-panel" class="flex flex-col h-[40vh] lg:h-full bg-slate-50 border-t lg:border-t-0 shadow-inner overflow-hidden" style="width: 450px; min-width: 300px; max-width: 800px;">
<div id="sql-panel" class="bg-[#282c34] flex flex-col border-b border-slate-700" style="height: 33%; min-height: 150px;">
<div class="px-4 py-2 bg-[#21252b] flex items-center justify-between border-b border-black/20">
<div class="flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
</svg>
<span class="text-slate-300 text-xs font-mono font-bold tracking-wide">GENERATED SQL</span>
</div>
<button id="copy-sql-btn" class="text-xs text-slate-400 hover:text-white flex items-center gap-1 transition-colors px-2 py-1 rounded hover:bg-white/10">
<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
Copy
</button>
</div>
<div class="flex-1 overflow-auto p-4 relative group custom-scrollbar">
<pre><code id="sql-display" class="language-sql bg-transparent text-xs font-mono leading-relaxed">-- 等待查詢...
SELECT * FROM waiting_for_input;</code></pre>
</div>
</div>
<!-- Horizontal resizer between SQL and Chart panels -->
<div id="horizontal-resizer" class="resizer resizer-horizontal"></div>
<div id="chart-panel" class="bg-white flex flex-col overflow-hidden" style="flex: 1;">
<div class="px-4 py-3 border-b border-slate-100 flex items-center justify-between bg-white">
<span class="text-slate-700 font-bold text-sm flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
Data Visualization
</span>
<div class="flex bg-slate-100 p-1 rounded-lg gap-1">
<button class="view-btn active" data-type="bar" title="長條圖">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>
</button>
<button class="view-btn" data-type="line" title="折線圖">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" /></svg>
</button>
<button class="view-btn" data-type="pie" title="圓餅圖">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 3.055A9.001 9.001 0 1020.945 13H11V3.055z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.488 9H15V3.512A9.025 9.025 0 0120.488 9z" /></svg>
</button>
<button class="view-btn" data-type="table" title="表格資料">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M3 14h18m-9-4v8m-7-8v8m14-8v8M3 20.25V3.75a.75.75 0 01.75-.75h16.5a.75.75 0 01.75.75v16.5a.75.75 0 01-.75.75H3.75a.75.75 0 01-.75-.75z" /></svg>
</button>
</div>
</div>
<div class="flex-1 p-4 relative flex items-center justify-center bg-white">
<canvas id="dataChart" class="w-full h-full"></canvas>
<div id="data-table-container" class="absolute inset-0 overflow-auto p-0 hidden bg-white"></div>
<div id="chart-placeholder" class="absolute inset-0 flex flex-col items-center justify-center text-slate-300 gap-3">
<svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
</svg>
<span class="text-sm font-medium">尚無數據可顯示</span>
</div>
</div>
</div>
</div>
</main>
<style>
.view-btn {
padding: 0.35rem 0.6rem;
border-radius: 0.375rem;
color: #64748b;
transition: all 0.2s;
}
.view-btn:hover { color: #1e293b; background-color: #e2e8f0; }
.view-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.view-btn.active {
background-color: white;
color: #3b82f6;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
font-weight: 500;
}
</style>
<script>
// --- 全局變數與配置 ---
const MAX_HISTORY_TURNS = 20;
let conversationHistory = [];
let lastSQL = null;
let currentChartData = null;
let currentRawData = null;
let currentViewMode = 'bar';
let myChart = null;
let thinkingMessageId = null;
// DOM Elements
const form = document.getElementById('query-form');
const input = document.getElementById('user-input');
const chatContainer = document.getElementById('chat-container');
const sqlDisplay = document.getElementById('sql-display');
const chartPlaceholder = document.getElementById('chart-placeholder');
const dataTableContainer = document.getElementById('data-table-container');
const canvas = document.getElementById('dataChart');
const ctx = canvas.getContext('2d');
const viewBtns = document.querySelectorAll('.view-btn');
// --- 初始化 ---
document.addEventListener('DOMContentLoaded', () => {
// 初始化 Highlight.js
hljs.highlightAll();
// 綁定 Quick Query 按鈕
document.querySelectorAll('.quick-query').forEach(btn => {
btn.addEventListener('click', (e) => {
input.value = e.target.innerText.trim();
form.requestSubmit();
});
});
updateButtonStates(null); // 初始禁用按鈕
// Fetch and display current model info
fetchModelInfo();
// Initialize resizers
initializeResizers();
});
// --- Resizer functionality ---
function initializeResizers() {
// Vertical resizer (between left and right panels)
const verticalResizer = document.getElementById('vertical-resizer');
const leftPanel = document.getElementById('left-panel');
const rightPanel = document.getElementById('right-panel');
if (verticalResizer && leftPanel && rightPanel) {
let isResizing = false;
let startX = 0;
let startLeftWidth = 0;
let startRightWidth = 0;
verticalResizer.addEventListener('mousedown', (e) => {
isResizing = true;
startX = e.clientX;
startLeftWidth = leftPanel.offsetWidth;
startRightWidth = rightPanel.offsetWidth;
document.body.classList.add('resizing');
verticalResizer.classList.add('dragging');
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
const deltaX = e.clientX - startX;
const newLeftWidth = startLeftWidth + deltaX;
const newRightWidth = startRightWidth - deltaX;
// Enforce min/max constraints
if (newLeftWidth >= 300 && newRightWidth >= 300 && newRightWidth <= 800) {
leftPanel.style.flex = 'none';
leftPanel.style.width = `${newLeftWidth}px`;
rightPanel.style.width = `${newRightWidth}px`;
}
});
document.addEventListener('mouseup', () => {
if (isResizing) {
isResizing = false;
document.body.classList.remove('resizing');
verticalResizer.classList.remove('dragging');
}
});
}
// Horizontal resizer (between SQL and Chart panels)
const horizontalResizer = document.getElementById('horizontal-resizer');
const sqlPanel = document.getElementById('sql-panel');
const chartPanel = document.getElementById('chart-panel');
if (horizontalResizer && sqlPanel && chartPanel) {
let isResizing = false;
let startY = 0;
let startSqlHeight = 0;
let containerHeight = 0;
horizontalResizer.addEventListener('mousedown', (e) => {
isResizing = true;
startY = e.clientY;
startSqlHeight = sqlPanel.offsetHeight;
containerHeight = rightPanel.offsetHeight;
document.body.classList.add('resizing', 'resizing-vertical');
horizontalResizer.classList.add('dragging');
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
const deltaY = e.clientY - startY;
const newSqlHeight = startSqlHeight + deltaY;
const newChartHeight = containerHeight - newSqlHeight - horizontalResizer.offsetHeight;
// Enforce min height constraints
if (newSqlHeight >= 150 && newChartHeight >= 200) {
sqlPanel.style.height = `${newSqlHeight}px`;
sqlPanel.style.flex = 'none';
chartPanel.style.flex = '1';
}
});
document.addEventListener('mouseup', () => {
if (isResizing) {
isResizing = false;
document.body.classList.remove('resizing', 'resizing-vertical');
horizontalResizer.classList.remove('dragging');
}
});
}
}
// --- Fetch Model Info ---
async function fetchModelInfo() {
try {
const response = await fetch('/api/model_info');
if (!response.ok) {
throw new Error(`Failed to fetch model info: ${response.status}`);
}
const data = await response.json();
const modelDisplay = document.getElementById('model-display');
if (modelDisplay) {
modelDisplay.textContent = `${data.display_name}`;
}
} catch (error) {
console.error('Error fetching model info:', error);
// Fallback to generic text if API fails
const modelDisplay = document.getElementById('model-display');
if (modelDisplay) {
modelDisplay.textContent = 'Powered by AI';
}
}
}
// --- Toast 通知系統 ---
function showToast(message, type = 'info') {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = `toast ${type === 'error' ? 'error' : ''}`;
toast.innerHTML = `
<span class="text-sm font-medium text-slate-700">${message}</span>
`;
container.appendChild(toast);
// Animation
requestAnimationFrame(() => toast.classList.add('show'));
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// --- Copy SQL 功能 ---
document.getElementById('copy-sql-btn').addEventListener('click', async () => {
const code = sqlDisplay.innerText;
try {
await navigator.clipboard.writeText(code);
showToast('SQL 已複製到剪貼簿');
} catch (err) {
showToast('複製失敗', 'error');
}
});
// --- 視圖切換邏輯 ---
viewBtns.forEach(btn => {
btn.addEventListener('click', () => {
const type = btn.dataset.type;
switchViewMode(type);
});
});
function switchViewMode(mode) {
if (!currentChartData && mode !== 'table') return;
currentViewMode = mode;
chartPlaceholder.style.display = 'none';
// UI State Update
viewBtns.forEach(btn => {
if(btn.dataset.type === mode) btn.classList.add('active');
else btn.classList.remove('active');
});
if (mode === 'table') {
canvas.style.display = 'none';
dataTableContainer.style.display = 'block';
renderTable(currentRawData);
} else {
dataTableContainer.style.display = 'none';
canvas.style.display = 'block';
updateChart(mode, currentChartData.data);
}
}
function updateButtonStates(hasData) {
viewBtns.forEach(btn => {
btn.disabled = !hasData;
if (!hasData) {
btn.classList.remove('active');
btn.classList.add('opacity-50', 'cursor-not-allowed');
} else {
btn.classList.remove('opacity-50', 'cursor-not-allowed');
}
});
if (hasData) {
// 重新激活當前模式的按鈕
const activeBtn = document.querySelector(`.view-btn[data-type="${currentViewMode}"]`);
if(activeBtn) activeBtn.classList.add('active');
}
}
// --- 聊天與 SSE 邏輯 ---
form.addEventListener('submit', async (e) => {
e.preventDefault();
const query = input.value.trim();
if (!query) return;
// Remove welcome message on first query
const welcomeMsg = document.getElementById('welcome-message');
if (welcomeMsg) {
welcomeMsg.remove();
}
addMessage('user', query, true);
input.value = '';
// 啟動思考狀態
const thinkingId = addThinkingMessage();
updateThinkingMessage(thinkingId, '分析數據請求...');
try {
const response = await fetch('/api/query/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, conversation_history: conversationHistory })
});
if (!response.ok) throw new Error(`API error: ${response.status}`);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
handleSSEEvent(JSON.parse(line.slice(6)), thinkingId);
} catch (e) { console.error('Parse error', e); }
}
}
}
} catch (error) {
removeThinkingMessage(thinkingId);
addMessage('ai', `⚠️ **系統錯誤**: ${error.message}`, false);
showToast('後端連接失敗', 'error');
}
});
function handleSSEEvent(event, thinkingId) {
switch (event.type) {
case 'phase':
updateThinkingMessage(thinkingId, event.message);
break;
case 'complete':
removeThinkingMessage(thinkingId);
addMessage('ai', event.message, true, event.sql);
if (event.sql) updateSQL(event.sql);
// 數據處理
currentChartData = event.chart_data;
currentRawData = event.raw_data;
if (event.chart_data) {
updateButtonStates(true);
// 預設優先顯示後端建議的圖表類型,如果沒有則保持當前選擇
const targetType = event.chart_data.type || 'bar';
// 如果當前是表格模式,保持表格;否則切換到圖表
if (currentViewMode !== 'table') {
switchViewMode(targetType);
} else {
switchViewMode('table');
}
} else {
updateButtonStates(false);
chartPlaceholder.style.display = 'flex';
chartPlaceholder.innerHTML = '<span class="text-sm text-slate-400">此查詢未返回可視化數據</span>';
}
break;
case 'error':
removeThinkingMessage(thinkingId);
addMessage('ai', `錯誤: ${event.message}`, false);
break;
}
}
// --- UI 輔助函數 ---
function addMessage(role, text, saveToHistory = true, sqlQuery = null) {
const div = document.createElement('div');
div.className = 'flex gap-4 animate-fade-in-up';
if (role === 'user') {
div.classList.add('flex-row-reverse');
div.innerHTML = `
<div class="w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center text-white text-xs flex-shrink-0 shadow-sm">You</div>
<div class="bg-blue-600 text-white px-5 py-3 rounded-2xl rounded-tr-none shadow-md max-w-[85%] leading-relaxed">
<p>${text}</p>
</div>
`;
} else {
const renderedHTML = marked.parse(text);
div.innerHTML = `
<div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white text-xs flex-shrink-0 shadow-sm">AI</div>
<div class="bg-white p-5 rounded-2xl rounded-tl-none shadow-sm border border-slate-100 max-w-[85%] markdown-content text-slate-700">
${renderedHTML}
</div>
`;
}
chatContainer.appendChild(div);
chatContainer.scrollTo({ top: chatContainer.scrollHeight, behavior: 'smooth' });
if (saveToHistory) {
let content = text + (sqlQuery ? `\n[Executed SQL: ${sqlQuery}]` : '');
conversationHistory.push({ role, content });
if (conversationHistory.length > MAX_HISTORY_TURNS * 2) conversationHistory = conversationHistory.slice(-(MAX_HISTORY_TURNS * 2));
}
}
function addThinkingMessage() {
const id = Date.now();
const div = document.createElement('div');
div.id = `thinking-${id}`;
div.className = 'flex gap-4 animate-fade-in-up';
div.innerHTML = `
<div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white text-xs flex-shrink-0">AI</div>
<div class="bg-white px-4 py-3 rounded-2xl rounded-tl-none shadow-sm border border-slate-100 flex items-center gap-3">
<div class="flex gap-1">
<div class="w-1.5 h-1.5 bg-blue-500 rounded-full typing-dot"></div>
<div class="w-1.5 h-1.5 bg-blue-500 rounded-full typing-dot"></div>
<div class="w-1.5 h-1.5 bg-blue-500 rounded-full typing-dot"></div>
</div>
<span id="phase-text-${id}" class="text-xs font-medium text-slate-500">正在思考...</span>
</div>
`;
chatContainer.appendChild(div);
chatContainer.scrollTo({ top: chatContainer.scrollHeight, behavior: 'smooth' });
return id;
}
function updateThinkingMessage(id, text) {
const el = document.getElementById(`phase-text-${id}`);
if (el) el.textContent = text;
}
function removeThinkingMessage(id) {
const el = document.getElementById(`thinking-${id}`);
if (el) el.remove();
}
function updateSQL(sqlCode) {
try {
const formatted = sqlFormatter.format(sqlCode, { language: 'sqlite', tabWidth: 2, keywordCase: 'upper' });
sqlDisplay.textContent = formatted;
hljs.highlightElement(sqlDisplay);
} catch (e) {
sqlDisplay.textContent = sqlCode; // Fallback if formatter fails
}
}
function updateChart(type, data) {
if (myChart) myChart.destroy();
// Chart.js 風格配置
Chart.defaults.font.family = "'Inter', sans-serif";
Chart.defaults.color = '#64748b';
myChart = new Chart(ctx, {
type: type,
data: data,
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { position: 'bottom', labels: { usePointStyle: true, padding: 20 } },
tooltip: {
backgroundColor: 'rgba(30, 41, 59, 0.9)',
padding: 12,
cornerRadius: 8,
titleFont: { size: 13, weight: 600 },
bodyFont: { size: 12 }
}
},
scales: type !== 'pie' ? {
y: { grid: { borderDash: [4, 4], color: '#f1f5f9' }, border: { display: false } },
x: { grid: { display: false }, border: { display: false } }
} : {}
}
});
}
function renderTable(rawData) {
if (!rawData || rawData.length === 0) {
dataTableContainer.innerHTML = '<div class="flex h-full items-center justify-center text-slate-400 text-sm">無數據</div>';
return;
}
const columns = Object.keys(rawData[0]);
let html = `
<div class="inline-block min-w-full align-middle">
<table class="min-w-full divide-y divide-slate-200">
<thead class="bg-slate-50 sticky top-0">
<tr>
${columns.map(col => `<th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider whitespace-nowrap">${col}</th>`).join('')}
</tr>
</thead>
<tbody class="bg-white divide-y divide-slate-200">
`;
rawData.forEach(row => {
html += '<tr class="hover:bg-slate-50 transition-colors">';
columns.forEach(col => {
const val = row[col] ?? '-';
html += `<td class="px-4 py-3 text-sm text-slate-700 whitespace-nowrap">${val}</td>`;
});
html += '</tr>';
});
html += '</tbody></table></div>';
dataTableContainer.innerHTML = html;
}
// 清空按鈕事件
document.getElementById('clear-conversation-btn').addEventListener('click', () => {
if(!confirm('確定要清空對話歷史嗎?')) return;
conversationHistory = [];
lastSQL = null;
currentChartData = null;
currentRawData = null;
// Reset UI
chatContainer.innerHTML = '';
// Re-add welcome message logic (simplified here)
location.reload(); // 簡單起見,刷新頁面是最乾淨的重置
});
</script>
</body>
</html>