-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquizgen.html
More file actions
843 lines (763 loc) · 46.2 KB
/
Copy pathquizgen.html
File metadata and controls
843 lines (763 loc) · 46.2 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
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>教學平台測驗題目生成器 v5.0 (Multi-AI)</title>
<script src="https://cdn.tailwindcss.com"></script>
<!-- SheetJS/xlsx library for creating .xlsx files -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<!-- pdf.js for reading PDF files -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Noto Sans TC', sans-serif;
background-color: #f5f3ff; /* Fallback */
background-image: linear-gradient(to top right, #f5f3ff, #eef2ff); /* Gradient background */
}
.loader {
border: 5px solid #f3f3f3;
border-top: 5px solid #6366f1; /* Indigo color for loader */
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.image-preview-item {
position: relative;
}
.remove-image-btn {
position: absolute;
top: -0.5rem;
right: -0.5rem;
background-color: rgba(0, 0, 0, 0.7);
color: white;
border-radius: 50%;
width: 1.5rem;
height: 1.5rem;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-weight: bold;
line-height: 1;
transition: background-color 0.2s;
}
.remove-image-btn:hover {
background-color: rgba(239, 68, 68, 0.9); /* Red on hover */
}
.tab-btn {
cursor: pointer;
padding: 0.75rem 1rem;
border-bottom: 3px solid transparent;
transition: all 0.3s ease;
font-weight: 500;
white-space: nowrap;
}
.tab-btn.active {
color: #4f46e5; /* indigo-600 */
border-bottom-color: #4f46e5;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
</style>
</head>
<body class="text-gray-800">
<!-- Main Container -->
<div class="container mx-auto p-4 md:p-8">
<!-- Header -->
<header class="text-center mb-10">
<h1 class="text-4xl md:text-5xl font-bold text-indigo-700">教學平台測驗題目生成器</h1>
<p class="text-lg text-gray-500 mt-3"> 超方便生成器,一鍵生成 Wordwall、Kahoot、Wayground、LoiLoNote 格式測驗 </p>
</header>
<!-- Main Content Layout -->
<main class="max-w-4xl mx-auto space-y-8">
<!-- Step 0: API Key Input -->
<div class="bg-white p-4 rounded-2xl shadow-lg border border-gray-100">
<h2 class="text-2xl font-bold mb-4 text-indigo-600 flex items-center"><span class="bg-indigo-600 text-white rounded-full h-8 w-8 flex items-center justify-center mr-3">🔑</span>啟用 AI 功能</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label for="ai-provider-select" class="block text-sm font-medium text-gray-700">AI 模型供應商:</label>
<select id="ai-provider-select" class="mt-1 block w-full p-3 border border-gray-300 bg-white rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
<option value="google" selected>Google Gemini</option>
<option value="openai">OpenAI (ChatGPT)</option>
</select>
</div>
<div>
<label for="api-key-input" class="block text-sm font-medium text-gray-700">API 金鑰 (必填):</label>
<input type="password" id="api-key-input" class="mt-1 block w-full p-3 border border-gray-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500" placeholder="請貼上您選擇的供應商金鑰">
</div>
</div>
<p id="api-key-help-text" class="text-xs text-gray-500 mt-2">您可以從 <a href="https://aistudio.google.com/app/apikey" target="_blank" class="text-indigo-600 underline">Google AI Studio</a> 免費取得金鑰。</p>
</div>
<!-- Step 1: Input -->
<div class="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
<h2 class="text-2xl font-bold mb-5 text-indigo-600 flex items-center"><span class="bg-indigo-600 text-white rounded-full h-8 w-8 flex items-center justify-center mr-3">1</span>提供內容</h2>
<!-- Tabs for Input Method -->
<div class="border-b border-gray-200 mb-6 overflow-x-auto">
<nav class="-mb-px flex space-x-2 md:space-x-4" aria-label="Tabs">
<button id="tab-paste-text" class="tab-btn active">📋 貼上文字</button>
<button id="tab-upload-file" class="tab-btn">📄 上傳檔案</button>
<button id="tab-upload-image" class="tab-btn">🖼️ 上傳圖片</button>
<button id="tab-ai-generate" class="tab-btn">✨ AI生成內文</button>
</nav>
</div>
<!-- Tab 1: Paste Text -->
<div id="content-paste-text" class="tab-content active">
<label for="text-input" class="block text-sm font-medium text-gray-700 mb-1">貼上文章或教學內容:</label>
<textarea id="text-input" rows="8" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition" placeholder="請在此貼上您的教學文字內容..."></textarea>
<div class="flex justify-end mt-2">
<button id="copy-content-btn" class="bg-indigo-100 text-indigo-700 font-semibold py-2 px-4 rounded-lg hover:bg-indigo-200 transition duration-300 flex items-center text-sm hidden">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" 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"></path>
</svg>
複製文章內容
</button>
</div>
</div>
<!-- Tab 2: Upload File -->
<div id="content-upload-file" class="tab-content">
<label for="file-input" class="block text-sm font-medium text-gray-700 mb-2">上傳文字檔:</label>
<label for="file-input" class="flex flex-col items-center justify-center w-full h-48 px-4 transition bg-white border-2 border-gray-300 border-dashed rounded-lg appearance-none cursor-pointer hover:border-indigo-400 focus:outline-none hover:bg-indigo-50">
<span class="flex items-center space-x-2">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<span class="font-medium text-gray-600">
點擊此處上傳文字檔
<span class="text-indigo-600">或拖曳檔案到這裡</span>
</span>
</span>
<p class="text-xs text-gray-500 mt-1">支援 .txt 及 .pdf 格式</p>
</label>
<input type="file" id="file-input" class="hidden" accept=".txt,.pdf">
<p id="file-name-display" class="mt-2 text-sm text-center text-gray-600"></p>
</div>
<!-- Tab 3: Upload Image -->
<div id="content-upload-image" class="tab-content">
<label for="image-input" class="block text-sm font-medium text-gray-700 mb-2">上傳圖片 (支援多張圖片):</label>
<label for="image-input" class="flex flex-col items-center justify-center w-full h-32 px-4 transition bg-white border-2 border-gray-300 border-dashed rounded-lg appearance-none cursor-pointer hover:border-indigo-400 focus:outline-none hover:bg-indigo-50">
<span class="flex items-center space-x-2">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span class="font-medium text-gray-600">
點擊此處上傳圖片
<span class="text-indigo-600">或拖曳檔案到這裡</span>
</span>
</span>
<p class="text-xs text-gray-500 mt-1">支援 .jpg, .png, .gif, .webp 格式 (僅限 Google Gemini 模型)</p>
</label>
<input type="file" id="image-input" class="hidden" accept="image/*" multiple>
<div id="image-preview-container" class="mt-4 grid grid-cols-2 md:grid-cols-4 gap-4"></div>
</div>
<!-- Tab 4: AI Generate Content -->
<div id="content-ai-generate" class="tab-content">
<div class="space-y-4">
<div>
<label for="topic-input" class="block text-sm font-medium text-gray-700 mb-1">請輸入測驗主題、單字或語詞:</label>
<input type="text" id="topic-input" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition" placeholder="例如:光合作用、永續發展、apple, banana, run...">
</div>
<div>
<label for="student-level-select" class="block text-sm font-medium text-gray-700 mb-1">請選擇學生程度 (K12):</label>
<select id="student-level-select" class="w-full p-3 border border-gray-300 bg-white rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
<option value="1-2" selected>低年級</option>
<option value="3-4">中年級</option>
<option value="5-6">高年級</option>
<option value="7-9">國中</option>
<option value="9-12">高中</option>
</select>
</div>
<button id="generate-content-btn" class="w-full bg-emerald-500 text-white font-bold py-3 px-4 rounded-lg hover:bg-emerald-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition duration-300 flex items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z" />
</svg>
生成學習內文
</button>
<p class="text-xs text-center text-gray-500">AI 將根據您的輸入生成學習短文,並自動填入「貼上文字」頁籤中。</p>
</div>
</div>
</div>
<!-- Step 2: Options -->
<div class="bg-white p-6 rounded-2xl shadow-lg border border-gray-100">
<h2 class="text-2xl font-bold mb-5 text-indigo-600 flex items-center"><span class="bg-indigo-600 text-white rounded-full h-8 w-8 flex items-center justify-center mr-3">2</span>設定選項</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label for="num-questions" class="block text-sm font-medium text-gray-700">題目數量:</label>
<input type="number" id="num-questions" value="5" min="1" max="50" class="mt-1 block w-full p-3 border border-gray-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
</div>
<div>
<label for="format-select" class="block text-sm font-medium text-gray-700">匯出格式:</label>
<select id="format-select" class="mt-1 block w-full p-3 border border-gray-300 bg-white rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 h-[50px]">
<option value="" disabled selected>請選擇...</option>
<option value="wordwall">Wordwall</option>
<option value="kahoot">Kahoot!</option>
<option value="wayground">Wayground</option>
<option value="loilonote">LoiLoNote</option>
</select>
</div>
<div>
<label for="question-type-select" class="block text-sm font-medium text-gray-700">題目類型:</label>
<select id="question-type-select" class="mt-1 block w-full p-3 border border-gray-300 bg-white rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 h-[50px]">
<option value="multiple_choice" selected>選擇題</option>
<option value="true_false">是非題</option>
<option value="mixed">是非+選擇題</option>
</select>
</div>
<div>
<label for="difficulty-select" class="block text-sm font-medium text-gray-700">題目難度:</label>
<select id="difficulty-select" class="mt-1 block w-full p-3 border border-gray-300 bg-white rounded-lg shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 h-[50px]">
<option value="中等" selected>中等 (預設)</option>
<option value="簡單">簡單</option>
<option value="困難">困難</option>
</select>
</div>
</div>
</div>
<!-- Step 3: Generate and Download Button -->
<div class="mt-8">
<button id="generate-and-download-btn" class="w-full bg-indigo-600 text-white font-bold py-4 px-4 rounded-xl hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-300 ease-in-out transform hover:-translate-y-1 flex items-center justify-center text-xl shadow-lg hover:shadow-xl hover:shadow-indigo-500/30">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 mr-3" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-8.707l-3-3a1 1 0 00-1.414 0l-3 3a1 1 0 001.414 1.414L9 9.414V13a1 1 0 102 0V9.414l1.293 1.293a1 1 0 001.414-1.414z" clip-rule="evenodd" />
</svg>
✨ 一鍵 AI 生成並下載
</button>
</div>
</main>
<!-- Footer -->
<footer class="text-center mt-12 text-sm text-gray-500">
<p><span id="version-btn" class="cursor-pointer hover:text-indigo-600 hover:underline">v5.0 (Multi-AI)</span> | 由 Google Gemini 強力驅動 | <a href="https://bit.ly/Aliang" target="_blank" class="text-indigo-500 hover:underline">丫亮校長練功坊</a></p>
</footer>
</div>
<!-- Loading Overlay -->
<div id="loading-overlay" class="fixed inset-0 bg-gray-800 bg-opacity-60 flex items-center justify-center z-50 hidden">
<div class="bg-white p-8 rounded-lg shadow-xl flex flex-col items-center">
<div class="loader"></div>
<p id="loading-text" class="mt-4 text-lg font-semibold text-gray-700">AI 為您生成中...</p>
</div>
</div>
<!-- Toast Notification -->
<div id="toast" class="fixed bottom-5 right-5 bg-green-500 text-white py-2 px-5 rounded-lg shadow-xl opacity-0 transition-opacity duration-300">
<p id="toast-message"></p>
</div>
<!-- Version History Modal -->
<div id="version-modal" class="fixed inset-0 bg-gray-800 bg-opacity-60 flex items-center justify-center z-50 hidden">
<div class="bg-white p-6 rounded-lg shadow-xl w-11/12 md:w-1/2 max-w-lg relative">
<h3 class="text-2xl font-bold text-indigo-700 mb-4">版本修正歷程</h3>
<button id="close-modal-btn" class="absolute top-4 right-4 text-gray-500 hover:text-gray-800 text-2xl">×</button>
<div id="version-history-content" class="space-y-4 max-h-80 overflow-y-auto pr-4">
<!-- History will be populated by script -->
</div>
</div>
</div>
<script>
// Set up pdf.js worker
pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js`;
// DOM Elements
const textInput = document.getElementById('text-input');
const fileInput = document.getElementById('file-input');
const fileNameDisplay = document.getElementById('file-name-display');
const imageInput = document.getElementById('image-input');
const imagePreviewContainer = document.getElementById('image-preview-container');
const numQuestionsInput = document.getElementById('num-questions');
const formatSelect = document.getElementById('format-select');
const generateAndDownloadBtn = document.getElementById('generate-and-download-btn');
const loadingOverlay = document.getElementById('loading-overlay');
const loadingText = document.getElementById('loading-text');
const toast = document.getElementById('toast');
const toastMessage = document.getElementById('toast-message');
const versionBtn = document.getElementById('version-btn');
const versionModal = document.getElementById('version-modal');
const closeModalBtn = document.getElementById('close-modal-btn');
const versionHistoryContent = document.getElementById('version-history-content');
const questionTypeSelect = document.getElementById('question-type-select');
const difficultySelect = document.getElementById('difficulty-select');
const copyContentBtn = document.getElementById('copy-content-btn');
const apiKeyInput = document.getElementById('api-key-input');
const aiProviderSelect = document.getElementById('ai-provider-select');
const apiKeyHelpText = document.getElementById('api-key-help-text');
// New Tab Feature Elements
const tabPasteText = document.getElementById('tab-paste-text');
const tabUploadFile = document.getElementById('tab-upload-file');
const tabUploadImage = document.getElementById('tab-upload-image');
const tabAiGenerate = document.getElementById('tab-ai-generate');
const contentPasteText = document.getElementById('content-paste-text');
const contentUploadFile = document.getElementById('content-upload-file');
const contentUploadImage = document.getElementById('content-upload-image');
const contentAiGenerate = document.getElementById('content-ai-generate');
const topicInput = document.getElementById('topic-input');
const generateContentBtn = document.getElementById('generate-content-btn');
const studentLevelSelect = document.getElementById('student-level-select');
// --- Version History Data ---
const versionHistory = [
{ version: "v5.0 (Multi-AI)", notes: ["✨【重大更新】支援多種 AI 模型!現在您可以選擇使用 Google Gemini, OpenAI (ChatGPT) 。", "新增「AI 模型供應商」下拉選單。", "重構 API 請求邏輯以適應不同供應商。"] },
{ version: "v4.2 (Standalone)", notes: ["✨ 重新設計「提供內容」區塊,將貼上文字、上傳檔案、上傳圖片、AI生成內文各自獨立為頁籤,優化操作流程。"] },
{ version: "v4.1 (Standalone)", notes: ["將 API 金鑰輸入框移至最上方,作為獨立的啟用步驟。"] },
{ version: "v4.0 (Standalone)", notes: ["✨ 新增 API 金鑰輸入框,使程式可完全脫離 Canvas 環境獨立運作。", "優化錯誤提示,引導使用者申請並填入自己的免費 API 金鑰。"] },
{ version: "v3.6", notes: ["修正大量出題時(如超過20題)的生成失敗問題。", "優化批次生成邏輯,確保 AI 請求的穩定性。"] },
{ version: "v3.4", notes: ["✨ 新增「複製文章內容」按鈕,方便老師將 AI 生成的內文分享至其他平台。"] },
{ version: "v3.3", notes: ["✨ 新增「是非+選擇題」混合題型。", "調整題型選項,移除「填空題」。"] }
];
function populateVersionHistory() {
let html = '';
versionHistory.forEach(v => {
html += `
<div>
<h4 class="font-bold text-lg">${v.version} ${v.current ? '<span class="text-sm font-normal text-indigo-600">(目前版本)</span>' : ''}</h4>
<ul class="list-disc list-inside text-gray-600">
${v.notes.map(note => `<li>${note}</li>`).join('')}
</ul>
</div>
`;
});
versionHistoryContent.innerHTML = html;
}
function getApiKey() {
const userKey = apiKeyInput.value.trim();
if (!userKey) {
throw new Error('API 金鑰為必填項!請從您選擇的 AI 供應商取得金鑰並貼入欄位中。');
}
return userKey;
}
function updateApiKeyHelpText() {
const provider = aiProviderSelect.value;
let link = '';
let linkText = '';
switch(provider) {
case 'openai':
link = 'https://platform.openai.com/api-keys';
linkText = 'OpenAI Platform';
break;
case 'google':
default:
link = 'https://aistudio.google.com/app/apikey';
linkText = 'Google AI Studio';
break;
}
apiKeyHelpText.innerHTML = `您可以從 <a href="${link}" target="_blank" class="text-indigo-600 underline">${linkText}</a> 免費取得金鑰。`;
}
// --- Core API Configuration ---
function getApiConfig() {
const provider = aiProviderSelect.value;
const apiKey = getApiKey();
switch (provider) {
case 'openai':
return {
apiUrl: 'https://api.openai.com/v1/chat/completions',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
buildPayload: (systemPrompt, userParts, jsonSchema, model = 'gpt-4o') => {
const payload = {
model: model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userParts.map(p => p.text).join('\n') }
],
};
if (jsonSchema) {
payload.response_format = { type: "json_object" };
}
return payload;
},
parseResponse: async (response, isJson) => {
const result = await response.json();
const content = result.choices?.[0]?.message?.content;
if (!content) throw new Error('AI 回應中沒有有效的內容。');
return isJson ? JSON.parse(content).questions : content;
}
};
case 'google':
default:
return {
apiUrl: `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=${apiKey}`,
headers: { 'Content-Type': 'application/json' },
buildPayload: (systemPrompt, userParts, jsonSchema) => {
const payload = {
contents: [{ parts: userParts }],
systemInstruction: { parts: [{ text: systemPrompt }] },
};
if (jsonSchema) {
payload.generationConfig = { responseMimeType: "application/json", responseSchema: jsonSchema };
}
return payload;
},
parseResponse: async (response, isJson) => {
const result = await response.json();
const jsonText = result.candidates?.[0]?.content?.parts?.[0]?.text;
if (!jsonText) throw new Error('API 回應格式錯誤。');
return isJson ? JSON.parse(jsonText) : jsonText;
}
};
}
}
/**
* ✨ New Feature: Generate learning content from a topic using Gemini API.
*/
async function generateContentFromTopic() {
const topic = topicInput.value;
const studentLevel = studentLevelSelect.value;
if (!topic.trim()) {
showToast('請輸入一個主題、單字或語詞!', 'error');
return;
}
loadingOverlay.classList.remove('hidden');
loadingText.textContent = 'AI 為您生成內文中...';
try {
const config = getApiConfig();
const wordCountMap = { '1-2': 200, '3-4': 400, '5-6': 600, '7-9': 800, '9-12': 1000 };
const wordCount = wordCountMap[studentLevel];
const studentGradeText = studentLevelSelect.options[studentLevelSelect.selectedIndex].text;
let systemPrompt;
const userQuery = `主題/單字:${topic}`;
const isWordList = topic.includes(',') || /^[a-zA-Z\s,]+$/.test(topic) && topic.split(/\s+|,/).filter(Boolean).length <= 10;
if (isWordList) {
systemPrompt = `你是一位為K12學生編寫教材的創意寫作專家。請使用使用者提供的單字或語詞,為「${studentGradeText}」的學生,撰寫一篇有趣且連貫、長度約為 ${wordCount} 字的故事或閱讀短文。請確保這些詞彙自然地融入文章中。你的回應只能有文章本身,不要包含任何標題或額外文字。`;
} else {
systemPrompt = `你是一位知識淵博的教材編寫專家。請根據使用者提供的主題,為「${studentGradeText}」的學生,生成一段約 ${wordCount} 字的簡潔科普短文。你的回應只能有文章本身,不要包含任何標題或額外文字。`;
}
// For text generation, we don't pass a jsonSchema
const payload = config.buildPayload(systemPrompt, [{ text: userQuery }]);
const response = await fetch(config.apiUrl, {
method: 'POST',
headers: config.headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
if (response.status === 401) throw new Error('API 請求失敗 (401): 授權無效。請確認您填寫的 API 金鑰是否正確。');
const errorBody = await response.text();
console.error("API Error Body:", errorBody);
throw new Error(`API 請求失敗: ${response.status}`);
}
const generatedText = await config.parseResponse(response, false); // isJson = false
if (generatedText) {
textInput.value = generatedText;
showToast('學習內文已成功生成!', 'success');
copyContentBtn.classList.remove('hidden');
tabPasteText.click();
} else {
throw new Error('AI未能生成內容,請稍後再試。');
}
} catch (error) {
console.error('生成內文時發生錯誤:', error);
showToast(error.message, 'error');
} finally {
loadingOverlay.classList.add('hidden');
}
}
/**
* Main handler to start the generation and export process.
*/
async function handleGenerateAndDownload() {
const text = textInput.value;
const totalQuestions = parseInt(numQuestionsInput.value, 10);
const selectedFormat = formatSelect.value;
const questionType = questionTypeSelect.value;
const difficulty = difficultySelect.value;
const provider = aiProviderSelect.value;
if (!text.trim() && uploadedImages.length === 0) {
showToast('請先輸入文字、或上傳圖片!', 'error');
return;
}
if (uploadedImages.length > 0 && provider !== 'google') {
showToast(`您選擇的 ${provider.charAt(0).toUpperCase() + provider.slice(1)} 模型不支援圖片輸入,請選擇 Google Gemini 或移除圖片。`, 'error');
return;
}
if (!selectedFormat) {
showToast('請選擇匯出檔案格式!', 'error');
return;
}
if (totalQuestions <= 0) {
showToast('題目數量必須大於 0!', 'error');
return;
}
loadingOverlay.classList.remove('hidden');
loadingText.textContent = 'AI 為您生成題目中...';
try {
getApiKey(); // Check for API key before starting batch process
const BATCH_SIZE = 8;
const numBatches = Math.ceil(totalQuestions / BATCH_SIZE);
let allGeneratedQs = [];
for (let i = 0; i < numBatches; i++) {
const questionsInBatch = Math.min(BATCH_SIZE, totalQuestions - allGeneratedQs.length);
if (questionsInBatch <= 0) break;
const batchResult = await generateSingleBatch(questionsInBatch, questionType, difficulty, text, uploadedImages, selectedFormat);
allGeneratedQs = allGeneratedQs.concat(batchResult);
}
if (allGeneratedQs.length > 0) {
exportFile(selectedFormat, questionType, allGeneratedQs);
} else {
throw new Error("AI 未能生成任何題目,請檢查您的輸入內容或稍後再試。");
}
} catch(error) {
console.error('生成題目時發生錯誤:', error);
showToast(error.message, 'error');
} finally {
loadingOverlay.classList.add('hidden');
}
}
async function generateSingleBatch(questionsInBatch, questionType, difficulty, text, images, selectedFormat) {
const config = getApiConfig();
const provider = aiProviderSelect.value;
let systemPrompt, jsonSchema;
const needsExplanation = selectedFormat === 'loilonote' || selectedFormat === 'wayground';
const mcProperties = { text: { type: "STRING" }, options: { type: "ARRAY", items: { type: "STRING" } }, correct: { type: "ARRAY", items: { type: "INTEGER" } }, time: { type: "INTEGER" } };
let mcRequired = ["text", "options", "correct", "time"];
if (needsExplanation) { mcProperties.explanation = { type: "STRING" }; mcRequired.push("explanation");}
const tfProperties = { text: { type: "STRING" }, is_correct: { type: "BOOLEAN" } };
let tfRequired = ["text", "is_correct"];
if (needsExplanation) { tfProperties.explanation = { type: "STRING" }; tfRequired.push("explanation");}
const jsonSchemaText = (props) => JSON.stringify(props).replace(/"/g, "'");
switch(questionType) {
case 'true_false':
jsonSchema = { type: "ARRAY", items: { type: "OBJECT", properties: tfProperties, required: tfRequired }};
systemPrompt = `你是一位專門輸出 JSON 的助手。請根據使用者提供的內容,生成${questionsInBatch}題${difficulty}難度的「是非題」。你的回應必須是一個 JSON 物件,且只有一個名為 "questions" 的 key,其 value 為一個 JSON 陣列。陣列中的每個物件都代表一題是非題,且必須符合以下結構:${jsonSchemaText(tfProperties)}。你的回應必須是「單一個」JSON 物件,不包含任何前後文、註解或 markdown 標籤。`;
break;
case 'mixed':
jsonSchema = { type: "ARRAY", items: { type: "OBJECT", properties: mcProperties, required: mcRequired }};
systemPrompt = `你是一位專門輸出 JSON 的助手。請根據使用者提供的內容,生成${questionsInBatch}題${difficulty}難度的「選擇題」與「是非題」混合題組。是非題請用 ["是", "否"] 作為選項。你的回應必須是一個 JSON 物件,且只有一個名為 "questions" 的 key,其 value 為一個 JSON 陣列。陣列中的每個物件都代表一題,且必須符合以下結構:${jsonSchemaText(mcProperties)}。你的回應必須是「單一個」JSON 物件,不包含任何前後文、註解或 markdown 標籤。`;
break;
case 'multiple_choice':
default:
jsonSchema = { type: "ARRAY", items: { type: "OBJECT", properties: mcProperties, required: mcRequired }};
systemPrompt = `你是一位專門輸出 JSON 的助手。請根據使用者提供的內容,生成${questionsInBatch}題${difficulty}難度的「選擇題」。每題必須有4個選項。你的回應必須是一個 JSON 物件,且只有一個名為 "questions" 的 key,其 value 為一個 JSON 陣列。陣列中的每個物件都代表一題選擇題,且必須符合以下結構:${jsonSchemaText(mcProperties)}。你的回應必須是「單一個」JSON 物件,不包含任何前後文、註解或 markdown 標籤。`;
break;
}
const userParts = [{ text: "請根據以下提供的文字和圖片內容出題。" }];
if(text.trim()){ userParts.push({ text: `文字內容:\n${text}`}); }
if (provider === 'google') {
images.forEach(img => {
userParts.push({ inlineData: { mimeType: img.type, data: img.data } });
});
}
const payload = config.buildPayload(systemPrompt, userParts, jsonSchema);
const response = await fetch(config.apiUrl, {
method: 'POST',
headers: config.headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
if (response.status === 401) throw new Error('API 請求失敗 (401): 授權無效。請確認您選擇的 AI 供應商及對應的 API 金鑰是否正確。');
const errorBody = await response.text();
console.error("API Error Body:", errorBody);
throw new Error(`API 請求失敗,狀態碼: ${response.status}`);
}
try {
return await config.parseResponse(response, true); // isJson = true
} catch (e) {
console.error("Failed to parse response:", e);
throw new Error('API 回應了無效的格式,請嘗試減少題目數量。');
}
}
// --- File Handling (Text/PDF) ---
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (!file) { fileNameDisplay.textContent = ''; return; }
fileNameDisplay.textContent = `已選擇檔案:${file.name}`;
const reader = new FileReader();
if (file.type === 'application/pdf') {
reader.onload = async (e) => {
const typedarray = new Uint8Array(e.target.result);
try {
const pdf = await pdfjsLib.getDocument(typedarray).promise;
let text = '';
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const content = await page.getTextContent();
text += content.items.map(item => item.str).join(' ');
}
textInput.value = text;
} catch (error) {
console.error("讀取PDF失敗:", error);
showToast("無法讀取此PDF檔案。", "error");
fileNameDisplay.textContent = '';
}
};
reader.readAsArrayBuffer(file);
} else { // Assume text file
reader.onload = (e) => { textInput.value = e.target.result; };
reader.readAsText(file);
}
});
// --- Image Handling ---
let uploadedImages = []; // To store { type, data } for each image
imageInput.addEventListener('change', (event) => {
const files = event.target.files;
if (!files) return;
imagePreviewContainer.innerHTML = '';
uploadedImages = [];
Array.from(files).forEach((file, index) => {
const reader = new FileReader();
reader.onload = (e) => {
const fullBase64 = e.target.result;
const base64Data = fullBase64.split(',')[1];
const imageObject = { id: Date.now() + index, type: file.type, data: base64Data };
uploadedImages.push(imageObject);
const previewWrapper = document.createElement('div');
previewWrapper.className = 'image-preview-item';
const imgElement = document.createElement('img');
imgElement.src = fullBase64;
imgElement.className = 'w-full h-32 object-cover rounded-lg shadow-md';
const removeBtn = document.createElement('div');
removeBtn.className = 'remove-image-btn';
removeBtn.innerHTML = '×';
removeBtn.onclick = () => {
uploadedImages = uploadedImages.filter(img => img.id !== imageObject.id);
previewWrapper.remove();
};
previewWrapper.appendChild(imgElement);
previewWrapper.appendChild(removeBtn);
imagePreviewContainer.appendChild(previewWrapper);
};
reader.readAsDataURL(file);
});
});
// --- Export Function ---
function exportFile(format, questionType, questions) {
if (!questions || questions.length === 0) {
showToast('沒有可匯出的題目!', 'error');
return;
}
let data, filename;
try {
const standardMCQs = questions.map(q => {
if (q.hasOwnProperty('is_correct')) { // Check if it is a true/false question
return {
text: q.text,
options: ['是', '否'],
correct: [q.is_correct ? 0 : 1],
time: 30,
explanation: q.explanation || ''
};
}
return q;
});
switch (format) {
case 'wordwall':
data = standardMCQs.map(q => ({
'問題': q.text,
'選項1': q.options[0] || '', '選項2': q.options[1] || '',
'選項3': q.options[2] || '', '選項4': q.options[3] || '',
'正確選項': q.correct.length > 0 ? (q.correct[0] + 1) : '',
}));
filename = 'Wordwall_Quiz.xlsx';
break;
case 'kahoot':
const kahootData = [
['Kahoot Quiz Template'], ['Add questions, answers, and time limits. Have fun!'], [], [],
['Question', 'Answer 1', 'Answer 2', 'Answer 3', 'Answer 4', 'Time limit (sec)', 'Correct answer(s)']
];
standardMCQs.forEach(q => {
kahootData.push([
q.text,
q.options[0] || '', q.options[1] || '', q.options[2] || '', q.options[3] || '',
q.time, q.correct.map(i => i + 1).join(',')
]);
});
const ws = XLSX.utils.aoa_to_sheet(kahootData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
XLSX.writeFile(wb, 'Kahoot_Quiz.xlsx');
showToast('Kahoot 檔案已下載!', 'success');
return;
case 'wayground':
data = standardMCQs.map(q => ({
'Question Text': q.text,
'Question Type': q.correct.length > 1 ? 'Checkbox' : 'Multiple Choice',
'Option 1': q.options[0] || '', 'Option 2': q.options[1] || '',
'Option 3': q.options[2] || '', 'Option 4': q.options[3] || '',
'Option 5': '', 'Correct Answer': q.correct.map(i => i + 1).join(','),
'Time in seconds': q.time, 'Image Link': '',
'Answer explanation': q.explanation || ''
}));
filename = 'Wayground_Quiz.xlsx';
break;
case 'loilonote':
data = standardMCQs.map(q => ({
'問題(請勿編輯標題)': q.text,
'務必作答(若此問題需要回答,請輸入1)': 1,
'每題得分(未填入的部分將被自動設為1)': 1,
'正確答案的選項(若有複數正確答案選項,請用「、」或「 , 」來分隔選項編號)': q.correct.map(i => i + 1).join(','),
'說明': q.explanation || '',
'選項1': q.options[0] || '', '選項2': q.options[1] || '',
'選項3': q.options[2] || '', '選項4': q.options[3] || '',
}));
filename = 'LoiLoNote_Quiz.xlsx';
break;
default: throw new Error('Unknown format');
}
const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
XLSX.writeFile(workbook, filename);
showToast(`${format.charAt(0).toUpperCase() + format.slice(1)} 檔案已下載!`, 'success');
} catch (error) {
console.error('Export failed:', error);
showToast('匯出失敗,請檢查主控台錯誤。', 'error');
}
};
// --- Utility Functions ---
function showToast(message, type = 'success') {
toastMessage.textContent = message;
toast.className = `fixed bottom-5 right-5 text-white py-2 px-5 rounded-lg shadow-xl opacity-0 transition-opacity duration-300 ${type === 'success' ? 'bg-green-500' : 'bg-red-500'}`;
toast.classList.remove('opacity-0');
setTimeout(() => { toast.classList.add('opacity-0'); }, 4000);
}
function copyContentToClipboard() {
const textToCopy = textInput.value;
if (!textToCopy.trim()) {
showToast('沒有內容可以複製!', 'error');
return;
}
const tempTextArea = document.createElement('textarea');
tempTextArea.value = textToCopy;
document.body.appendChild(tempTextArea);
tempTextArea.select();
try {
document.execCommand('copy');
showToast('文章內容已成功複製!', 'success');
} catch (err) {
console.error('複製失敗:', err);
showToast('無法複製內容,您的瀏覽器可能不支援此功能。', 'error');
} finally {
document.body.removeChild(tempTextArea);
}
}
// --- Initial setup on page load ---
document.addEventListener('DOMContentLoaded', () => {
populateVersionHistory();
updateApiKeyHelpText(); // Initial call
});
// --- Event Listeners ---
generateAndDownloadBtn.addEventListener('click', handleGenerateAndDownload);
generateContentBtn.addEventListener('click', generateContentFromTopic);
copyContentBtn.addEventListener('click', copyContentToClipboard);
aiProviderSelect.addEventListener('change', updateApiKeyHelpText);
// Tab switching logic
const tabs = [tabPasteText, tabUploadFile, tabUploadImage, tabAiGenerate];
const contents = [contentPasteText, contentUploadFile, contentUploadImage, contentAiGenerate];
tabs.forEach((tab, index) => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
contents.forEach(c => c.classList.remove('active'));
tab.classList.add('active');
contents[index].classList.add('active');
});
});
// Modal closing logic
versionBtn.addEventListener('click', () => { versionModal.classList.remove('hidden'); });
closeModalBtn.addEventListener('click', () => { versionModal.classList.add('hidden'); });
versionModal.addEventListener('click', (event) => {
if (event.target === versionModal) { versionModal.classList.add('hidden'); }
});
</script>
</body>
</html>