Lashtw commited on
Commit
df8a47a
·
verified ·
1 Parent(s): c465c27

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +480 -38
index.html CHANGED
@@ -12,6 +12,8 @@
12
  <script src="https://cdn.jsdelivr.net/npm/qrcode-generator/qrcode.js"></script>
13
  <!-- 載入 Pako 壓縮函式庫 -->
14
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.1.0/pako.min.js"></script>
 
 
15
  <style>
16
  /* 定義閃卡的翻轉效果 */
17
  .flip-container {
@@ -89,6 +91,10 @@
89
  border-radius: 10px;
90
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
91
  }
 
 
 
 
92
  </style>
93
  </head>
94
  <body class="bg-gray-50 min-h-screen flex flex-col items-center p-4 sm:p-8 font-sans">
@@ -126,7 +132,7 @@
126
  <div class="mb-4">
127
  <div class="relative mb-3 border-b pb-2">
128
  <h3 class="text-lg font-semibold text-gray-600 text-center">主要功能</h3>
129
- <button id="reset-crowns-btn" class="absolute right-0 top-1/2 -translate-y-1/2 text-xs bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold py-1 px-3 rounded-full transition-colors disabled:bg-gray-300">重置皇冠</button>
130
  </div>
131
  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
132
  <button data-mode="review" class="mode-btn bg-sky-500 hover:bg-sky-600">複習模式</button>
@@ -151,9 +157,18 @@
151
  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
152
  <button data-mode="hard" class="mode-btn bg-red-700 hover:bg-red-800">🧠 困難單字複習</button>
153
  <button data-mode="speed" class="mode-btn bg-slate-700 hover:bg-slate-800">⚡ 極速挑戰 ⚡</button>
 
154
  </div>
155
  </div>
156
 
 
 
 
 
 
 
 
 
157
  <!-- 教師工具 -->
158
  <div id="teacher-tools" class="mt-8 pt-4 border-t flex justify-end items-center gap-3">
159
  <button id="grade-report-btn" class="text-white font-semibold py-2 px-5 rounded-full transition-transform hover:scale-105 bg-blue-500 hover:bg-blue-600 text-sm">📊 成績報告</button>
@@ -181,6 +196,29 @@
181
  <button id="save-title-btn" class="bg-indigo-600 text-white font-bold py-2 px-6 rounded-full hover:bg-indigo-700 shrink-0 transition-colors">儲存標題</button>
182
  </div>
183
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
  <!-- 新增單字區塊 -->
186
  <div id="add-words-section" class="mb-6 p-4 bg-gray-50 rounded-2xl hidden">
@@ -241,6 +279,13 @@
241
  <div id="flashcard-container" class="flip-container w-full h-full transform transition-transform duration-300">
242
  <div class="flipper w-full h-full">
243
  <div class="front flex flex-col justify-center items-center">
 
 
 
 
 
 
 
244
  <span id="front-display" class="text-5xl font-bold text-center"></span>
245
  <div class="absolute bottom-6 right-6 flex items-center gap-2">
246
  <button id="speak-slow-btn" class="speak-btn p-4 rounded-full bg-white/30 hover:bg-white/50 transition-colors hidden">
@@ -343,6 +388,14 @@
343
  <label for="edit-chinese-input" class="block text-sm font-semibold text-gray-700 mb-1">中文</label>
344
  <input id="edit-chinese-input" type="text" class="w-full p-3 border border-gray-300 rounded-lg text-lg">
345
  </div>
 
 
 
 
 
 
 
 
346
  </div>
347
  <div class="flex justify-end gap-4 mt-8">
348
  <button type="button" id="cancel-edit-btn" class="px-6 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors">取消</button>
@@ -351,6 +404,28 @@
351
  </div>
352
  </div>
353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  <!-- 分享連結 Modal -->
355
  <div id="share-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 p-4">
356
  <div class="bg-white p-8 rounded-2xl shadow-xl w-full max-w-lg">
@@ -485,17 +560,31 @@
485
  const addWordsBtn = document.getElementById('add-words-btn');
486
  const cancelAddWordsBtn = document.getElementById('cancel-add-words-btn');
487
  const wordListContainer = document.getElementById('word-list-container');
 
 
 
 
 
 
 
488
 
489
  // 學習介面
490
  const flashcardContainer = document.getElementById('flashcard-container');
491
  const frontDisplay = document.getElementById('front-display');
492
  const backDisplay = document.getElementById('back-display');
 
 
 
 
493
  const speakBtn = document.getElementById('speak-btn');
494
  const speakSlowBtn = document.getElementById('speak-slow-btn');
495
  const modeTitle = document.getElementById('mode-title');
496
  const backToMenuBtn = document.getElementById('back-to-menu-btn');
497
  const progressBarContainer = document.getElementById('progress-bar-container');
498
  const progressBar = document.getElementById('progress-bar');
 
 
 
499
 
500
  // 測驗相關
501
  const quizContainer = document.getElementById('quiz-container');
@@ -536,6 +625,8 @@
536
  const editWordIndexInput = document.getElementById('edit-word-index');
537
  const editEnglishInput = document.getElementById('edit-english-input');
538
  const editChineseInput = document.getElementById('edit-chinese-input');
 
 
539
  const saveEditBtn = document.getElementById('save-edit-btn');
540
  const cancelEditBtn = document.getElementById('cancel-edit-btn');
541
  const shareModal = document.getElementById('share-modal');
@@ -559,6 +650,12 @@
559
  const wordToDeleteSpan = document.getElementById('word-to-delete');
560
  const cancelDeleteBtn = document.getElementById('cancel-delete-btn');
561
  const confirmDeleteBtn = document.getElementById('confirm-delete-btn');
 
 
 
 
 
 
562
 
563
  // 音效元素
564
  const correctSound = document.getElementById('correct-sound');
@@ -586,11 +683,14 @@
586
  let currentSpeedCard = null;
587
  let currentSpeedQuestionType = '';
588
  let quizStartTime = 0;
 
 
589
 
590
  const modeDetails = {
591
  'review': { title: '複習模式' }, 'zh-en': { title: '中翻英測驗' },
592
  'en-zh': { title: '英翻中測驗' }, 'listen': { title: '聽力測驗' },
593
  'speed': { title: '極速挑戰' }, 'hard': { title: '困難單字複習' },
 
594
  };
595
 
596
  // --- 視圖管理 ---
@@ -626,10 +726,14 @@
626
  words.forEach((word, index) => {
627
  const item = document.createElement('div');
628
  item.className = 'list-item p-3 bg-gray-100 rounded-lg flex items-center justify-between';
 
 
 
629
  item.innerHTML = `
630
  <div class="flex items-center">
631
  <span class="w-8 text-sm text-gray-500">${index + 1}.</span>
632
  <p class="font-semibold text-gray-800">${word.english}</p>
 
633
  <p class="text-gray-600 ml-4">${word.chinese}</p>
634
  </div>
635
  <div class="flex gap-2">
@@ -646,9 +750,12 @@
646
  if (!button) return;
647
  const index = parseInt(button.dataset.index, 10);
648
  if (button.classList.contains('edit-btn')) {
 
649
  editWordIndexInput.value = index;
650
- editEnglishInput.value = words[index].english;
651
- editChineseInput.value = words[index].chinese;
 
 
652
  editWordModal.classList.remove('hidden');
653
  } else if (button.classList.contains('delete-btn')) {
654
  indexToDelete = index;
@@ -661,9 +768,17 @@
661
  const index = parseInt(editWordIndexInput.value, 10);
662
  const newEnglish = editEnglishInput.value.trim();
663
  const newChinese = editChineseInput.value.trim();
 
 
 
664
  if (index >= 0 && newEnglish && newChinese) {
665
  words[index].english = newEnglish;
666
  words[index].chinese = newChinese;
 
 
 
 
 
667
  saveWordsToStorage();
668
  renderWordList();
669
  editWordModal.classList.add('hidden');
@@ -752,10 +867,13 @@
752
  speedResultView.classList.add('hidden');
753
  hintDisplay.textContent = '';
754
  hintBtn.disabled = false;
 
 
755
 
756
  let frontText, backText;
757
 
758
  if (isSpeed) {
 
759
  switch (currentSpeedQuestionType) {
760
  case 'zh-en':
761
  frontText = card.chinese;
@@ -772,7 +890,7 @@
772
  frontText = '請聽發音';
773
  backText = card.english;
774
  [speakBtn, speakSlowBtn].forEach(btn => btn.classList.remove('hidden'));
775
- speakWord(card.english);
776
  answerInput.placeholder = "請輸入英文答案...";
777
  break;
778
  }
@@ -799,12 +917,24 @@
799
  case 'listen':
800
  frontText = '請聽發音'; backText = card.english;
801
  [speakBtn, speakSlowBtn].forEach(btn => btn.classList.remove('hidden'));
802
- speakWord(card.english);
803
  answerInput.placeholder = "請輸入英文答案...";
804
  break;
 
 
 
 
 
 
 
 
 
805
  }
806
  }
807
- frontDisplay.textContent = frontText;
 
 
 
808
  backDisplay.textContent = backText;
809
  setTimeout(() => answerInput.focus(), 100);
810
  };
@@ -841,7 +971,13 @@
841
  wordPool = [...words];
842
  }
843
 
844
- if (mode === 'review') {
 
 
 
 
 
 
845
  wordsForCurrentMode = wordPool;
846
  } else if (randomQuestionsCheckbox.checked) {
847
  const randomCount = parseInt(randomQuestionsCountInput.value, 10);
@@ -903,20 +1039,23 @@
903
 
904
  if (isReview) {
905
  const isFlipped = flashcardContainer.classList.contains('flipped');
906
- correctAnswer = isFlipped ? card.english.split('(')[0].trim() : card.chinese.split('(')[0].trim();
 
907
  answerLang = isFlipped ? 'en' : 'zh';
908
  } else {
909
  let effectiveMode = isSpeed ? currentSpeedQuestionType : (currentMode === 'hard' ? 'zh-en' : currentMode);
 
910
  switch (effectiveMode) {
911
- case 'zh-en': case 'listen':
912
- correctAnswer = card.english.split('(')[0].trim();
913
  answerLang = 'en';
914
  break;
915
  case 'en-zh':
916
- correctAnswer = card.chinese.split('(')[0].trim();
917
  answerLang = 'zh';
918
  break;
919
  }
 
920
  }
921
 
922
  let isCorrect;
@@ -929,8 +1068,8 @@
929
  };
930
  isCorrect = normalize(userAnswer) === normalize(correctAnswer);
931
  } else if (answerLang === 'zh') {
932
- const possibleAnswers = correctAnswer.split(/[;;]/).map(a => a.trim());
933
- isCorrect = possibleAnswers.some(ans => userAnswer.trim().includes(ans) && ans !== '');
934
  }
935
 
936
  if (isCorrect) {
@@ -976,7 +1115,7 @@
976
 
977
  quizStartTime = 0; // Reset timer
978
 
979
- if (currentMode !== 'hard') {
980
  completionStatus[currentMode] = true;
981
  localStorage.setItem('completionStatus', JSON.stringify(completionStatus));
982
  updateCompletionUI();
@@ -1098,10 +1237,10 @@
1098
  confetti({ particleCount: 150, spread: 70, origin: { y: 0.6 } });
1099
  };
1100
 
1101
- const speakWithBrowserTTS = (word, rate = 1) => {
1102
  if ('speechSynthesis' in window) {
1103
  window.speechSynthesis.cancel();
1104
- const wordToSpeak = word.split('(')[0].trim();
1105
  const utterance = new SpeechSynthesisUtterance(wordToSpeak);
1106
  utterance.lang = 'en-US';
1107
  utterance.rate = rate;
@@ -1113,7 +1252,16 @@
1113
  speakBtn.disabled = true;
1114
  speakSlowBtn.disabled = true;
1115
 
1116
- const wordToSpeak = word.split('(')[0].trim();
 
 
 
 
 
 
 
 
 
1117
  if (!wordToSpeak) {
1118
  speakBtn.disabled = false;
1119
  speakSlowBtn.disabled = false;
@@ -1122,7 +1270,6 @@
1122
 
1123
  const cleanedWord = wordToSpeak.replace(/[^a-zA-Z\s-]/g, '');
1124
 
1125
- // 【已修改】智慧判斷:如果是片語,直接用瀏覽器語音;如果是單字,才用 API
1126
  if (cleanedWord.includes(' ')) {
1127
  speakWithBrowserTTS(cleanedWord, 0.75);
1128
  speakBtn.disabled = false;
@@ -1152,32 +1299,29 @@
1152
  }
1153
 
1154
  if (audioUrl) {
 
1155
  apiAudioPlayer.src = audioUrl;
1156
  apiAudioPlayer.play().catch(error => {
1157
  console.error("Audio playback error:", error);
1158
  speakWithBrowserTTS(cleanedWord, 0.75);
1159
- }).finally(() => {
1160
- speakBtn.disabled = false;
1161
- speakSlowBtn.disabled = false;
1162
  });
1163
  } else {
1164
  speakWithBrowserTTS(cleanedWord, 0.75);
1165
- speakBtn.disabled = false;
1166
- speakSlowBtn.disabled = false;
1167
  }
1168
  } catch (error) {
1169
  console.error("Dictionary API error:", error);
1170
  speakWithBrowserTTS(cleanedWord, 0.75);
 
1171
  speakBtn.disabled = false;
1172
  speakSlowBtn.disabled = false;
1173
  }
1174
  };
1175
 
1176
  const getCurrentWordToSpeak = () => {
1177
- if (currentMode === 'speed' && currentSpeedCard) return currentSpeedCard.english;
1178
- if (currentMode === 'review' && wordsForCurrentMode[currentCardIndex]) return wordsForCurrentMode[currentCardIndex].english;
1179
- if (quizQueue.length > 0) return quizQueue[0].english;
1180
- return '';
1181
  };
1182
 
1183
  const updateCompletionUI = () => {
@@ -1238,6 +1382,217 @@
1238
  qrcodeContainer.textContent = 'QR碼產生失敗,網址可能過長。';
1239
  }
1240
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1241
 
1242
  // --- 事件監聽 ---
1243
  document.querySelectorAll('.mode-btn[data-mode]').forEach(btn => {
@@ -1249,7 +1604,10 @@
1249
  localStorage.removeItem('completionStatus');
1250
  updateCompletionUI();
1251
 
1252
- // Visual feedback
 
 
 
1253
  const originalText = resetCrownsBtn.textContent;
1254
  resetCrownsBtn.textContent = '已重置!';
1255
  resetCrownsBtn.disabled = true;
@@ -1264,7 +1622,6 @@
1264
  const isQuiz = !['review', 'speed', ''].includes(currentMode);
1265
  if (isQuiz && quizStartTime > 0) {
1266
  const attempted = wordsForCurrentMode.length - quizQueue.length;
1267
- // Only save if at least one question was attempted
1268
  if (attempted > 0) {
1269
  const elapsedTime = Math.round((Date.now() - quizStartTime) / 1000);
1270
  const reportData = {
@@ -1297,6 +1654,11 @@
1297
  }
1298
  });
1299
 
 
 
 
 
 
1300
  prevBtn.addEventListener('click', () => { if (currentCardIndex > 0) { currentCardIndex--; displayCard(); }});
1301
  nextBtn.addEventListener('click', () => { if (currentCardIndex < wordsForCurrentMode.length - 1) { currentCardIndex++; displayCard(); }});
1302
  quizForm.addEventListener('submit', (e) => { e.preventDefault(); checkAnswer(); });
@@ -1309,7 +1671,7 @@
1309
  speakSlowBtn.addEventListener('click', (e) => {
1310
  e.stopPropagation();
1311
  const word = getCurrentWordToSpeak();
1312
- if(word) speakWithBrowserTTS(word, 0.2);
1313
  });
1314
 
1315
  hintBtn.addEventListener('click', () => {
@@ -1318,8 +1680,8 @@
1318
  const questionType = currentMode === 'speed' ? currentSpeedQuestionType : (currentMode === 'hard' ? 'zh-en' : currentMode);
1319
  let correctAnswer;
1320
  switch (questionType) {
1321
- case 'zh-en': case 'listen': correctAnswer = card.english.split('(')[0].trim(); break;
1322
- case 'en-zh': correctAnswer = card.chinese.split('(')[0].trim(); break;
1323
  default: return;
1324
  }
1325
  if (correctAnswer) {
@@ -1350,7 +1712,6 @@
1350
  localStorage.setItem('flashcardsBookTitle', bookTitle);
1351
  localStorage.setItem('flashcardsLessonTitle', lessonTitle);
1352
  updateMainTitle();
1353
- // Simple feedback
1354
  const originalText = saveTitleBtn.textContent;
1355
  saveTitleBtn.textContent = '已儲存!';
1356
  saveTitleBtn.classList.remove('bg-indigo-600', 'hover:bg-indigo-700');
@@ -1386,7 +1747,7 @@
1386
  generateLinkBtn.disabled = true;
1387
 
1388
  try {
1389
- const wordsString = JSON.stringify(words);
1390
  const compressedData = pako.deflate(wordsString);
1391
  const base64Words = btoa(String.fromCharCode.apply(null, compressedData));
1392
 
@@ -1410,7 +1771,7 @@
1410
 
1411
  const longUrl = url.toString();
1412
 
1413
- const response = await fetch(`https://tinyurl.com/api-create.php?url=${encodeURIComponent(longUrl)}`);
1414
  if (response.ok) {
1415
  const shortUrl = await response.text();
1416
  shareLinkInput.value = shortUrl;
@@ -1506,9 +1867,83 @@
1506
  startRangeInput.addEventListener('input', updateRandomCountMax);
1507
  endRangeInput.addEventListener('input', updateRandomCountMax);
1508
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1509
 
1510
  // --- 應用程式初始化 ---
1511
  const initializeApp = () => {
 
 
 
 
 
1512
  const urlParams = new URLSearchParams(window.location.search);
1513
  const sharedData = urlParams.get('data');
1514
  let loadedFromUrl = false;
@@ -1533,10 +1968,15 @@
1533
  if (!loadedFromUrl) {
1534
  const storedWords = localStorage.getItem('flashcards');
1535
  if (storedWords && JSON.parse(storedWords).length > 0) {
1536
- words = JSON.parse(storedWords).map(word => ({ ...word, proficiency: word.proficiency || 0, incorrectCount: word.incorrectCount || 0 }));
 
 
 
 
1537
  } else {
1538
  const defaultWords = [
1539
- { english: 'yesterday (adv.)', chinese: '昨天' }, { english: 'study (v.)', chinese: '研讀' },
 
1540
  { english: 'jog (v.)', chinese: '慢跑' }, { english: 'watch (v.)', chinese: '觀看' },
1541
  { english: 'last (adj.)', chinese: '前一個的' }, { english: 'death (n.)', chinese: '死亡' },
1542
  { english: 'a few (adj.)', chinese: '一些' }, { english: 'ago (adv.)', chinese: '以前' },
@@ -1573,7 +2013,6 @@
1573
 
1574
  if (isLocked) {
1575
  settingsContainer.classList.add('opacity-50', 'pointer-events-none');
1576
- // 只隱藏分享與管理按鈕,保留成績報告按鈕
1577
  if (shareGameBtn) shareGameBtn.classList.add('hidden');
1578
  if (manageWordsBtn) manageWordsBtn.classList.add('hidden');
1579
  }
@@ -1586,6 +2025,9 @@
1586
  endRangeInput.max = words.length;
1587
  endRangeInput.placeholder = `到 ${words.length}`;
1588
  updateRandomCountMax();
 
 
 
1589
  showView('menu');
1590
  };
1591
  initializeApp();
 
12
  <script src="https://cdn.jsdelivr.net/npm/qrcode-generator/qrcode.js"></script>
13
  <!-- 載入 Pako 壓縮函式庫 -->
14
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.1.0/pako.min.js"></script>
15
+ <!-- 載入 PDF.js 函式庫 -->
16
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
17
  <style>
18
  /* 定義閃卡的翻轉效果 */
19
  .flip-container {
 
91
  border-radius: 10px;
92
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
93
  }
94
+ /* 進度條動畫 */
95
+ #ai-progress-bar-inner, #audio-preload-bar {
96
+ transition: width 0.3s ease-in-out;
97
+ }
98
  </style>
99
  </head>
100
  <body class="bg-gray-50 min-h-screen flex flex-col items-center p-4 sm:p-8 font-sans">
 
132
  <div class="mb-4">
133
  <div class="relative mb-3 border-b pb-2">
134
  <h3 class="text-lg font-semibold text-gray-600 text-center">主要功能</h3>
135
+ <button id="reset-crowns-btn" class="absolute right-0 top-1/2 -translate-y-1/2 text-xs bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold py-1 px-3 rounded-full transition-colors disabled:bg-gray-300">重置進度</button>
136
  </div>
137
  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
138
  <button data-mode="review" class="mode-btn bg-sky-500 hover:bg-sky-600">複習模式</button>
 
157
  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
158
  <button data-mode="hard" class="mode-btn bg-red-700 hover:bg-red-800">🧠 困難單字複習</button>
159
  <button data-mode="speed" class="mode-btn bg-slate-700 hover:bg-slate-800">⚡ 極速挑戰 ⚡</button>
160
+ <button data-mode="sentence-cloze" class="mode-btn bg-cyan-600 hover:bg-cyan-700">📝 情境克漏字</button>
161
  </div>
162
  </div>
163
 
164
+ <!-- Audio Preload Progress -->
165
+ <div id="audio-preload-container" class="hidden mt-4">
166
+ <p id="audio-preload-text" class="text-sm text-center text-gray-500 mb-1">正在預載語音檔案...</p>
167
+ <div class="w-full bg-gray-200 rounded-full h-2.5">
168
+ <div id="audio-preload-bar" class="bg-sky-600 h-2.5 rounded-full" style="width: 0%"></div>
169
+ </div>
170
+ </div>
171
+
172
  <!-- 教師工具 -->
173
  <div id="teacher-tools" class="mt-8 pt-4 border-t flex justify-end items-center gap-3">
174
  <button id="grade-report-btn" class="text-white font-semibold py-2 px-5 rounded-full transition-transform hover:scale-105 bg-blue-500 hover:bg-blue-600 text-sm">📊 成績報告</button>
 
196
  <button id="save-title-btn" class="bg-indigo-600 text-white font-bold py-2 px-6 rounded-full hover:bg-indigo-700 shrink-0 transition-colors">儲存標題</button>
197
  </div>
198
  </div>
199
+
200
+ <!-- AI 解析區塊 -->
201
+ <div class="mb-6 p-4 bg-violet-50 rounded-2xl border-2 border-dashed border-violet-200">
202
+ <h3 class="text-xl font-semibold mb-2 text-violet-800">🚀 透過 AI 從 PDF 建立單字庫</h3>
203
+ <div class="mb-4">
204
+ <label for="api-key-input" class="block text-sm font-semibold text-violet-700 mb-1">您的 Gemini API 金鑰</label>
205
+ <div class="flex items-center gap-2">
206
+ <input type="password" id="api-key-input" class="w-full p-2 border border-violet-300 rounded-lg" placeholder="請在此貼上您的 API 金鑰">
207
+ <button id="save-api-key-btn" class="bg-violet-500 text-white font-semibold py-2 px-4 rounded-lg hover:bg-violet-600 shrink-0">儲存</button>
208
+ </div>
209
+ <p class="text-xs text-gray-500 mt-1">金鑰將會儲存在您的瀏覽器中,方便下次使用。可從 <a href="https://aistudio.google.com/app/apikey" target="_blank" class="text-blue-500 hover:underline">Google AI Studio</a> 取得。</p>
210
+ </div>
211
+ <div class="flex items-center gap-4">
212
+ <input type="file" id="pdf-upload-input" accept=".pdf" class="block w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-violet-100 file:text-violet-700 hover:file:bg-violet-200"/>
213
+ <button id="parse-pdf-btn" class="bg-violet-600 text-white font-bold py-2 px-6 rounded-full hover:bg-violet-700 shrink-0 transition-colors disabled:bg-violet-300">AI智慧解析</button>
214
+ </div>
215
+ <div id="ai-progress-container" class="mt-3 hidden">
216
+ <div class="w-full bg-gray-200 rounded-full h-2.5">
217
+ <div id="ai-progress-bar-inner" class="bg-violet-600 h-2.5 rounded-full" style="width: 0%"></div>
218
+ </div>
219
+ </div>
220
+ <p id="parse-status" class="text-center text-sm text-violet-600 mt-2 h-5"></p>
221
+ </div>
222
 
223
  <!-- 新增單字區塊 -->
224
  <div id="add-words-section" class="mb-6 p-4 bg-gray-50 rounded-2xl hidden">
 
279
  <div id="flashcard-container" class="flip-container w-full h-full transform transition-transform duration-300">
280
  <div class="flipper w-full h-full">
281
  <div class="front flex flex-col justify-center items-center">
282
+ <div id="cloze-question-container" class="hidden w-full text-center">
283
+ <p id="sentence-en-display" class="text-3xl mb-2"></p>
284
+ <div class="text-center">
285
+ <button id="toggle-translation-btn" class="text-sm bg-white/20 hover:bg-white/30 text-white py-1 px-3 rounded-full mb-2">顯示翻譯</button>
286
+ <p id="sentence-zh-display" class="text-xl font-light hidden"></p>
287
+ </div>
288
+ </div>
289
  <span id="front-display" class="text-5xl font-bold text-center"></span>
290
  <div class="absolute bottom-6 right-6 flex items-center gap-2">
291
  <button id="speak-slow-btn" class="speak-btn p-4 rounded-full bg-white/30 hover:bg-white/50 transition-colors hidden">
 
388
  <label for="edit-chinese-input" class="block text-sm font-semibold text-gray-700 mb-1">中文</label>
389
  <input id="edit-chinese-input" type="text" class="w-full p-3 border border-gray-300 rounded-lg text-lg">
390
  </div>
391
+ <div>
392
+ <label for="edit-sentence-en-input" class="block text-sm font-semibold text-gray-700 mb-1">英文例句 (用 ___ 代表單字)</label>
393
+ <input id="edit-sentence-en-input" type="text" class="w-full p-3 border border-gray-300 rounded-lg text-lg">
394
+ </div>
395
+ <div>
396
+ <label for="edit-sentence-zh-input" class="block text-sm font-semibold text-gray-700 mb-1">中文例句</label>
397
+ <input id="edit-sentence-zh-input" type="text" class="w-full p-3 border border-gray-300 rounded-lg text-lg">
398
+ </div>
399
  </div>
400
  <div class="flex justify-end gap-4 mt-8">
401
  <button type="button" id="cancel-edit-btn" class="px-6 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors">取消</button>
 
404
  </div>
405
  </div>
406
 
407
+ <!-- AI 解析確認 Modal -->
408
+ <div id="parse-confirm-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 p-4">
409
+ <div class="bg-white p-8 rounded-2xl shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col">
410
+ <div class="flex justify-between items-center mb-4">
411
+ <h3 class="text-2xl font-bold text-gray-800">AI 解析結果預覽</h3>
412
+ <div class="flex items-center">
413
+ <input type="checkbox" id="select-all-checkbox" class="h-4 w-4 rounded text-indigo-600 focus:ring-indigo-500 border-gray-300 mr-2">
414
+ <label for="select-all-checkbox" class="text-sm font-medium text-gray-700">全選/取消全選</label>
415
+ </div>
416
+ </div>
417
+
418
+ <p class="text-gray-600 mb-6">請勾選您要新增至單字庫的項目。</p>
419
+ <div id="parse-results-container" class="flex-grow overflow-y-auto space-y-2 pr-2 border-t pt-4">
420
+ <!-- AI 解析結果將會顯示於此 -->
421
+ </div>
422
+ <div class="flex justify-end gap-4 mt-8 pt-4 border-t">
423
+ <button type="button" id="cancel-parse-btn" class="px-6 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors">取消</button>
424
+ <button type="button" id="confirm-parse-btn" class="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">確認新增</button>
425
+ </div>
426
+ </div>
427
+ </div>
428
+
429
  <!-- 分享連結 Modal -->
430
  <div id="share-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50 p-4">
431
  <div class="bg-white p-8 rounded-2xl shadow-xl w-full max-w-lg">
 
560
  const addWordsBtn = document.getElementById('add-words-btn');
561
  const cancelAddWordsBtn = document.getElementById('cancel-add-words-btn');
562
  const wordListContainer = document.getElementById('word-list-container');
563
+ const apiKeyInput = document.getElementById('api-key-input');
564
+ const saveApiKeyBtn = document.getElementById('save-api-key-btn');
565
+ const pdfUploadInput = document.getElementById('pdf-upload-input');
566
+ const parsePdfBtn = document.getElementById('parse-pdf-btn');
567
+ const parseStatus = document.getElementById('parse-status');
568
+ const aiProgressContainer = document.getElementById('ai-progress-container');
569
+ const aiProgressBarInner = document.getElementById('ai-progress-bar-inner');
570
 
571
  // 學習介面
572
  const flashcardContainer = document.getElementById('flashcard-container');
573
  const frontDisplay = document.getElementById('front-display');
574
  const backDisplay = document.getElementById('back-display');
575
+ const clozeQuestionContainer = document.getElementById('cloze-question-container');
576
+ const sentenceEnDisplay = document.getElementById('sentence-en-display');
577
+ const sentenceZhDisplay = document.getElementById('sentence-zh-display');
578
+ const toggleTranslationBtn = document.getElementById('toggle-translation-btn');
579
  const speakBtn = document.getElementById('speak-btn');
580
  const speakSlowBtn = document.getElementById('speak-slow-btn');
581
  const modeTitle = document.getElementById('mode-title');
582
  const backToMenuBtn = document.getElementById('back-to-menu-btn');
583
  const progressBarContainer = document.getElementById('progress-bar-container');
584
  const progressBar = document.getElementById('progress-bar');
585
+ const audioPreloadContainer = document.getElementById('audio-preload-container');
586
+ const audioPreloadBar = document.getElementById('audio-preload-bar');
587
+ const audioPreloadText = document.getElementById('audio-preload-text');
588
 
589
  // 測驗相關
590
  const quizContainer = document.getElementById('quiz-container');
 
625
  const editWordIndexInput = document.getElementById('edit-word-index');
626
  const editEnglishInput = document.getElementById('edit-english-input');
627
  const editChineseInput = document.getElementById('edit-chinese-input');
628
+ const editSentenceEnInput = document.getElementById('edit-sentence-en-input');
629
+ const editSentenceZhInput = document.getElementById('edit-sentence-zh-input');
630
  const saveEditBtn = document.getElementById('save-edit-btn');
631
  const cancelEditBtn = document.getElementById('cancel-edit-btn');
632
  const shareModal = document.getElementById('share-modal');
 
650
  const wordToDeleteSpan = document.getElementById('word-to-delete');
651
  const cancelDeleteBtn = document.getElementById('cancel-delete-btn');
652
  const confirmDeleteBtn = document.getElementById('confirm-delete-btn');
653
+ const parseConfirmModal = document.getElementById('parse-confirm-modal');
654
+ const parseResultsContainer = document.getElementById('parse-results-container');
655
+ const cancelParseBtn = document.getElementById('cancel-parse-btn');
656
+ const confirmParseBtn = document.getElementById('confirm-parse-btn');
657
+ const selectAllCheckbox = document.getElementById('select-all-checkbox');
658
+
659
 
660
  // 音效元素
661
  const correctSound = document.getElementById('correct-sound');
 
683
  let currentSpeedCard = null;
684
  let currentSpeedQuestionType = '';
685
  let quizStartTime = 0;
686
+ let parsedWordsFromAI = [];
687
+
688
 
689
  const modeDetails = {
690
  'review': { title: '複習模式' }, 'zh-en': { title: '中翻英測驗' },
691
  'en-zh': { title: '英翻中測驗' }, 'listen': { title: '聽力測驗' },
692
  'speed': { title: '極速挑戰' }, 'hard': { title: '困難單字複習' },
693
+ 'sentence-cloze': { title: '情境克漏字' },
694
  };
695
 
696
  // --- 視圖管理 ---
 
726
  words.forEach((word, index) => {
727
  const item = document.createElement('div');
728
  item.className = 'list-item p-3 bg-gray-100 rounded-lg flex items-center justify-between';
729
+ const hasSentenceIcon = word.sentence && word.sentence.en ?
730
+ `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-cyan-500 ml-2" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" /></svg>` : '';
731
+
732
  item.innerHTML = `
733
  <div class="flex items-center">
734
  <span class="w-8 text-sm text-gray-500">${index + 1}.</span>
735
  <p class="font-semibold text-gray-800">${word.english}</p>
736
+ ${hasSentenceIcon}
737
  <p class="text-gray-600 ml-4">${word.chinese}</p>
738
  </div>
739
  <div class="flex gap-2">
 
750
  if (!button) return;
751
  const index = parseInt(button.dataset.index, 10);
752
  if (button.classList.contains('edit-btn')) {
753
+ const word = words[index];
754
  editWordIndexInput.value = index;
755
+ editEnglishInput.value = word.english;
756
+ editChineseInput.value = word.chinese;
757
+ editSentenceEnInput.value = word.sentence?.en || '';
758
+ editSentenceZhInput.value = word.sentence?.zh || '';
759
  editWordModal.classList.remove('hidden');
760
  } else if (button.classList.contains('delete-btn')) {
761
  indexToDelete = index;
 
768
  const index = parseInt(editWordIndexInput.value, 10);
769
  const newEnglish = editEnglishInput.value.trim();
770
  const newChinese = editChineseInput.value.trim();
771
+ const newSentenceEn = editSentenceEnInput.value.trim();
772
+ const newSentenceZh = editSentenceZhInput.value.trim();
773
+
774
  if (index >= 0 && newEnglish && newChinese) {
775
  words[index].english = newEnglish;
776
  words[index].chinese = newChinese;
777
+ if (newSentenceEn && newSentenceZh) {
778
+ words[index].sentence = { en: newSentenceEn, zh: newSentenceZh };
779
+ } else {
780
+ delete words[index].sentence;
781
+ }
782
  saveWordsToStorage();
783
  renderWordList();
784
  editWordModal.classList.add('hidden');
 
867
  speedResultView.classList.add('hidden');
868
  hintDisplay.textContent = '';
869
  hintBtn.disabled = false;
870
+ frontDisplay.classList.add('hidden');
871
+ clozeQuestionContainer.classList.add('hidden');
872
 
873
  let frontText, backText;
874
 
875
  if (isSpeed) {
876
+ // 極速挑戰暫不支援克漏字
877
  switch (currentSpeedQuestionType) {
878
  case 'zh-en':
879
  frontText = card.chinese;
 
890
  frontText = '請聽發音';
891
  backText = card.english;
892
  [speakBtn, speakSlowBtn].forEach(btn => btn.classList.remove('hidden'));
893
+ speakWord(card);
894
  answerInput.placeholder = "請輸入英文答案...";
895
  break;
896
  }
 
917
  case 'listen':
918
  frontText = '請聽發音'; backText = card.english;
919
  [speakBtn, speakSlowBtn].forEach(btn => btn.classList.remove('hidden'));
920
+ speakWord(card);
921
  answerInput.placeholder = "請輸入英文答案...";
922
  break;
923
+ case 'sentence-cloze':
924
+ clozeQuestionContainer.classList.remove('hidden');
925
+ sentenceEnDisplay.textContent = card.sentence.en;
926
+ sentenceZhDisplay.textContent = `(${card.sentence.zh})`;
927
+ sentenceZhDisplay.classList.add('hidden');
928
+ toggleTranslationBtn.textContent = '顯示翻譯';
929
+ backText = card.english;
930
+ answerInput.placeholder = "請填入空格中的單字...";
931
+ break;
932
  }
933
  }
934
+ if (frontText) {
935
+ frontDisplay.classList.remove('hidden');
936
+ frontDisplay.textContent = frontText;
937
+ }
938
  backDisplay.textContent = backText;
939
  setTimeout(() => answerInput.focus(), 100);
940
  };
 
971
  wordPool = [...words];
972
  }
973
 
974
+ if (mode === 'sentence-cloze') {
975
+ wordsForCurrentMode = wordPool.filter(w => w.sentence && w.sentence.en && w.sentence.zh);
976
+ if (wordsForCurrentMode.length === 0) {
977
+ alert("題庫中沒有附帶例句的單字可供此模式使用。");
978
+ return;
979
+ }
980
+ } else if (mode === 'review') {
981
  wordsForCurrentMode = wordPool;
982
  } else if (randomQuestionsCheckbox.checked) {
983
  const randomCount = parseInt(randomQuestionsCountInput.value, 10);
 
1039
 
1040
  if (isReview) {
1041
  const isFlipped = flashcardContainer.classList.contains('flipped');
1042
+ let rawAnswer = isFlipped ? card.english : card.chinese;
1043
+ correctAnswer = rawAnswer.replace(/[\((\[【].*?[\))\]】]/g, "").trim();
1044
  answerLang = isFlipped ? 'en' : 'zh';
1045
  } else {
1046
  let effectiveMode = isSpeed ? currentSpeedQuestionType : (currentMode === 'hard' ? 'zh-en' : currentMode);
1047
+ let rawAnswer;
1048
  switch (effectiveMode) {
1049
+ case 'zh-en': case 'listen': case 'sentence-cloze':
1050
+ rawAnswer = card.english;
1051
  answerLang = 'en';
1052
  break;
1053
  case 'en-zh':
1054
+ rawAnswer = card.chinese;
1055
  answerLang = 'zh';
1056
  break;
1057
  }
1058
+ correctAnswer = rawAnswer.replace(/[\((\[【].*?[\))\]】]/g, "").trim();
1059
  }
1060
 
1061
  let isCorrect;
 
1068
  };
1069
  isCorrect = normalize(userAnswer) === normalize(correctAnswer);
1070
  } else if (answerLang === 'zh') {
1071
+ const possibleAnswers = correctAnswer.split(/[;;]/).map(a => a.trim()).filter(a => a);
1072
+ isCorrect = possibleAnswers.some(ans => userAnswer.trim().includes(ans));
1073
  }
1074
 
1075
  if (isCorrect) {
 
1115
 
1116
  quizStartTime = 0; // Reset timer
1117
 
1118
+ if (!['hard', 'sentence-cloze'].includes(currentMode)) {
1119
  completionStatus[currentMode] = true;
1120
  localStorage.setItem('completionStatus', JSON.stringify(completionStatus));
1121
  updateCompletionUI();
 
1237
  confetti({ particleCount: 150, spread: 70, origin: { y: 0.6 } });
1238
  };
1239
 
1240
+ const speakWithBrowserTTS = (wordText, rate = 1) => {
1241
  if ('speechSynthesis' in window) {
1242
  window.speechSynthesis.cancel();
1243
+ const wordToSpeak = wordText.replace(/[\((\[【].*?[\))\]】]/g, "").trim();
1244
  const utterance = new SpeechSynthesisUtterance(wordToSpeak);
1245
  utterance.lang = 'en-US';
1246
  utterance.rate = rate;
 
1252
  speakBtn.disabled = true;
1253
  speakSlowBtn.disabled = true;
1254
 
1255
+ if (word.audioUrl) {
1256
+ apiAudioPlayer.src = word.audioUrl;
1257
+ apiAudioPlayer.play().finally(() => {
1258
+ speakBtn.disabled = false;
1259
+ speakSlowBtn.disabled = false;
1260
+ });
1261
+ return;
1262
+ }
1263
+
1264
+ const wordToSpeak = word.english.replace(/[\((\[【].*?[\))\]】]/g, "").trim();
1265
  if (!wordToSpeak) {
1266
  speakBtn.disabled = false;
1267
  speakSlowBtn.disabled = false;
 
1270
 
1271
  const cleanedWord = wordToSpeak.replace(/[^a-zA-Z\s-]/g, '');
1272
 
 
1273
  if (cleanedWord.includes(' ')) {
1274
  speakWithBrowserTTS(cleanedWord, 0.75);
1275
  speakBtn.disabled = false;
 
1299
  }
1300
 
1301
  if (audioUrl) {
1302
+ word.audioUrl = audioUrl; // Cache the URL
1303
  apiAudioPlayer.src = audioUrl;
1304
  apiAudioPlayer.play().catch(error => {
1305
  console.error("Audio playback error:", error);
1306
  speakWithBrowserTTS(cleanedWord, 0.75);
 
 
 
1307
  });
1308
  } else {
1309
  speakWithBrowserTTS(cleanedWord, 0.75);
 
 
1310
  }
1311
  } catch (error) {
1312
  console.error("Dictionary API error:", error);
1313
  speakWithBrowserTTS(cleanedWord, 0.75);
1314
+ } finally {
1315
  speakBtn.disabled = false;
1316
  speakSlowBtn.disabled = false;
1317
  }
1318
  };
1319
 
1320
  const getCurrentWordToSpeak = () => {
1321
+ if (currentMode === 'speed' && currentSpeedCard) return currentSpeedCard;
1322
+ if (currentMode === 'review' && wordsForCurrentMode[currentCardIndex]) return wordsForCurrentMode[currentCardIndex];
1323
+ if (quizQueue.length > 0) return quizQueue[0];
1324
+ return null;
1325
  };
1326
 
1327
  const updateCompletionUI = () => {
 
1382
  qrcodeContainer.textContent = 'QR碼產生失敗,網址可能過長。';
1383
  }
1384
  };
1385
+
1386
+
1387
+ // --- AI PDF 解析功能 ---
1388
+ const updateAIProgressBar = (percentage) => {
1389
+ aiProgressBarInner.style.width = `${percentage}%`;
1390
+ };
1391
+
1392
+ pdfUploadInput.addEventListener('change', () => {
1393
+ parseStatus.textContent = '';
1394
+ aiProgressContainer.classList.add('hidden');
1395
+ });
1396
+
1397
+ parsePdfBtn.addEventListener('click', async () => {
1398
+ const file = pdfUploadInput.files[0];
1399
+ if (!file) {
1400
+ parseStatus.textContent = '請先選擇一個 PDF 檔案。';
1401
+ return;
1402
+ }
1403
+
1404
+ parseStatus.textContent = '準備開始解析...';
1405
+ parsePdfBtn.disabled = true;
1406
+ aiProgressContainer.classList.remove('hidden');
1407
+ updateAIProgressBar(0);
1408
+
1409
+ try {
1410
+ const fileReader = new FileReader();
1411
+ fileReader.onload = async (event) => {
1412
+ const typedarray = new Uint8Array(event.target.result);
1413
+
1414
+ pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js`;
1415
+
1416
+ const pdf = await pdfjsLib.getDocument(typedarray).promise;
1417
+ let fullText = '';
1418
+
1419
+ for (let i = 1; i <= pdf.numPages; i++) {
1420
+ parseStatus.textContent = `讀取 PDF 頁面 (${i}/${pdf.numPages})...`;
1421
+ updateAIProgressBar((i / pdf.numPages) * 70); // PDF 讀取佔 70% 進度
1422
+ const page = await pdf.getPage(i);
1423
+ const textContent = await page.getTextContent();
1424
+ const pageText = textContent.items.map(item => item.str).join(' ');
1425
+ fullText += pageText + '\n\n';
1426
+ }
1427
+
1428
+ parseStatus.textContent = 'AI 分析中,請稍候...';
1429
+ updateAIProgressBar(85); // 準備呼叫 AI
1430
+ await callGeminiToParseText(fullText);
1431
+ };
1432
+ fileReader.readAsArrayBuffer(file);
1433
+ } catch (error) {
1434
+ console.error('PDF 解析失敗:', error);
1435
+ parseStatus.textContent = 'PDF 解析失敗,請檢查檔案或控制台錯誤訊息。';
1436
+ parsePdfBtn.disabled = false;
1437
+ aiProgressContainer.classList.add('hidden');
1438
+ }
1439
+ });
1440
+
1441
+ async function callGeminiToParseText(text) {
1442
+ const apiKey = apiKeyInput.value.trim();
1443
+ if (!apiKey) {
1444
+ parseStatus.textContent = '錯誤:請先輸入您的 Gemini API 金鑰並儲存。';
1445
+ parsePdfBtn.disabled = false;
1446
+ aiProgressContainer.classList.add('hidden');
1447
+ return;
1448
+ }
1449
+ const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key=${apiKey}`;
1450
+
1451
+ const prompt = `
1452
+ 請分析以下從英文單字學習講義擷取的文字。你的任務是辨識出每一個單字條目,並為每個條目提取以下資訊:
1453
+ 1. "english": 完整的英文單字,包含詞性標註,例如 "yesterday (adv.)" 或 "study (v.)"。
1454
+ 2. "chinese": 對應的中文翻譯。
1455
+ 3. "sentence": 一個包含例句的物件。這個物件應該有兩個屬性:
1456
+ - "en": 英文例句。請將該條目的主要英文單字(不含詞性)替換成 "___"。
1457
+ - "zh": 完整的中文例句翻譯。
1458
+
1459
+ 規則:
1460
+ - 如果一個單字條目有多個例句,請只選擇第一個或最能代表該單字用法的例句。
1461
+ - 如果同一個單字因為詞性不同而有多個條目(例如 "study (v.)" 和 "study (n.)"),請將它們視為獨立的條目,並各自尋找一個代表性的例句。
1462
+ - 如果一個單字條目沒有提供例句,則省略 "sentence" 物件。
1463
+
1464
+ 請將所有解析出的單字條目,以一個 JSON 陣列的格式回傳。每一個陣列中的物件都應該符合上述的結構。
1465
+
1466
+ 這是你要分析的文字內容:
1467
+ ---
1468
+ ${text}
1469
+ ---
1470
+ `;
1471
+
1472
+ const payload = {
1473
+ contents: [{ parts: [{ text: prompt }] }],
1474
+ generationConfig: {
1475
+ responseMimeType: "application/json",
1476
+ responseSchema: {
1477
+ type: "ARRAY",
1478
+ items: {
1479
+ type: "OBJECT",
1480
+ properties: {
1481
+ english: { type: "STRING" },
1482
+ chinese: { type: "STRING" },
1483
+ sentence: {
1484
+ type: "OBJECT",
1485
+ properties: {
1486
+ en: { type: "STRING" },
1487
+ zh: { type: "STRING" }
1488
+ }
1489
+ }
1490
+ }
1491
+ }
1492
+ }
1493
+ }
1494
+ };
1495
+
1496
+ try {
1497
+ const response = await fetch(apiUrl, {
1498
+ method: 'POST',
1499
+ headers: { 'Content-Type': 'application/json' },
1500
+ body: JSON.stringify(payload)
1501
+ });
1502
+
1503
+ if (!response.ok) {
1504
+ const errorBody = await response.json();
1505
+ console.error('API Error:', errorBody);
1506
+ throw new Error(`API 請求失敗,狀態碼:${response.status}. 錯誤訊息: ${errorBody.error.message}`);
1507
+ }
1508
+ const result = await response.json();
1509
+
1510
+ if (result.candidates && result.candidates.length > 0 && result.candidates[0].content?.parts?.[0]?.text) {
1511
+ const jsonText = result.candidates[0].content.parts[0].text;
1512
+ parsedWordsFromAI = JSON.parse(jsonText);
1513
+
1514
+ updateAIProgressBar(100);
1515
+ parseStatus.textContent = 'AI 分析完成!請確認結果。';
1516
+ showParseConfirmation(parsedWordsFromAI);
1517
+ setTimeout(() => {
1518
+ aiProgressContainer.classList.add('hidden');
1519
+ parseStatus.textContent = '';
1520
+ }, 2000);
1521
+ } else {
1522
+ throw new Error("從 AI 收到無效的回應格式。");
1523
+ }
1524
+ } catch (error) {
1525
+ console.error('AI 解析失敗:', error);
1526
+ parseStatus.textContent = `AI 解析失敗: ${error.message}`;
1527
+ aiProgressContainer.classList.add('hidden');
1528
+ } finally {
1529
+ parsePdfBtn.disabled = false;
1530
+ }
1531
+ }
1532
+
1533
+ function showParseConfirmation(parsedWords) {
1534
+ parseResultsContainer.innerHTML = '';
1535
+ selectAllCheckbox.checked = true;
1536
+
1537
+ parsedWords.forEach((word, index) => {
1538
+ const item = document.createElement('div');
1539
+ item.className = 'p-3 bg-gray-50 rounded-md border flex items-start';
1540
+ item.innerHTML = `
1541
+ <input type="checkbox" checked id="word-checkbox-${index}" data-index="${index}" class="word-checkbox h-5 w-5 rounded text-indigo-600 focus:ring-indigo-500 border-gray-300 mr-4 mt-1">
1542
+ <div class="flex-1">
1543
+ <p><strong>英文:</strong> ${word.english}</p>
1544
+ <p><strong>中文:</strong> ${word.chinese}</p>
1545
+ ${word.sentence ? `
1546
+ <div class="mt-2 pt-2 border-t border-gray-200">
1547
+ <p class="text-sm text-gray-600"><strong>例句 (英):</strong> ${word.sentence.en}</p>
1548
+ <p class="text-sm text-gray-600"><strong>例句 (中):</strong> ${word.sentence.zh}</p>
1549
+ </div>
1550
+ ` : ''}
1551
+ </div>
1552
+ `;
1553
+ parseResultsContainer.appendChild(item);
1554
+ });
1555
+ parseConfirmModal.classList.remove('hidden');
1556
+ }
1557
+
1558
+ selectAllCheckbox.addEventListener('change', (e) => {
1559
+ const isChecked = e.target.checked;
1560
+ parseResultsContainer.querySelectorAll('.word-checkbox').forEach(checkbox => {
1561
+ checkbox.checked = isChecked;
1562
+ });
1563
+ });
1564
+
1565
+ confirmParseBtn.addEventListener('click', () => {
1566
+ const selectedWords = [];
1567
+ const checkboxes = parseResultsContainer.querySelectorAll('.word-checkbox:checked');
1568
+
1569
+ checkboxes.forEach(checkbox => {
1570
+ const index = parseInt(checkbox.dataset.index, 10);
1571
+ selectedWords.push(parsedWordsFromAI[index]);
1572
+ });
1573
+
1574
+ const newWords = selectedWords.map(word => ({
1575
+ ...word,
1576
+ proficiency: 0,
1577
+ incorrectCount: 0
1578
+ }));
1579
+ words.push(...newWords);
1580
+ saveWordsToStorage();
1581
+ renderWordList();
1582
+ preloadAudioFiles(); // 解析完後也預載新的音檔
1583
+ parseConfirmModal.classList.add('hidden');
1584
+ parseStatus.textContent = `成功新增 ${selectedWords.length} 個單字!`;
1585
+ pdfUploadInput.value = '';
1586
+ parsedWordsFromAI = [];
1587
+ });
1588
+
1589
+ cancelParseBtn.addEventListener('click', () => {
1590
+ parseConfirmModal.classList.add('hidden');
1591
+ parseStatus.textContent = '操作已取消。';
1592
+ pdfUploadInput.value = '';
1593
+ parsedWordsFromAI = [];
1594
+ });
1595
+
1596
 
1597
  // --- 事件監聽 ---
1598
  document.querySelectorAll('.mode-btn[data-mode]').forEach(btn => {
 
1604
  localStorage.removeItem('completionStatus');
1605
  updateCompletionUI();
1606
 
1607
+ highScore = 0;
1608
+ localStorage.removeItem('flashcardsHighScore');
1609
+ highscoreDisplay.textContent = highScore;
1610
+
1611
  const originalText = resetCrownsBtn.textContent;
1612
  resetCrownsBtn.textContent = '已重置!';
1613
  resetCrownsBtn.disabled = true;
 
1622
  const isQuiz = !['review', 'speed', ''].includes(currentMode);
1623
  if (isQuiz && quizStartTime > 0) {
1624
  const attempted = wordsForCurrentMode.length - quizQueue.length;
 
1625
  if (attempted > 0) {
1626
  const elapsedTime = Math.round((Date.now() - quizStartTime) / 1000);
1627
  const reportData = {
 
1654
  }
1655
  });
1656
 
1657
+ toggleTranslationBtn.addEventListener('click', () => {
1658
+ const isHidden = sentenceZhDisplay.classList.toggle('hidden');
1659
+ toggleTranslationBtn.textContent = isHidden ? '顯示翻譯' : '隱藏翻譯';
1660
+ });
1661
+
1662
  prevBtn.addEventListener('click', () => { if (currentCardIndex > 0) { currentCardIndex--; displayCard(); }});
1663
  nextBtn.addEventListener('click', () => { if (currentCardIndex < wordsForCurrentMode.length - 1) { currentCardIndex++; displayCard(); }});
1664
  quizForm.addEventListener('submit', (e) => { e.preventDefault(); checkAnswer(); });
 
1671
  speakSlowBtn.addEventListener('click', (e) => {
1672
  e.stopPropagation();
1673
  const word = getCurrentWordToSpeak();
1674
+ if(word) speakWithBrowserTTS(word.english, 0.2);
1675
  });
1676
 
1677
  hintBtn.addEventListener('click', () => {
 
1680
  const questionType = currentMode === 'speed' ? currentSpeedQuestionType : (currentMode === 'hard' ? 'zh-en' : currentMode);
1681
  let correctAnswer;
1682
  switch (questionType) {
1683
+ case 'zh-en': case 'listen': case 'sentence-cloze': correctAnswer = card.english.replace(/[\((\[【].*?[\))\]】]/g, "").trim(); break;
1684
+ case 'en-zh': correctAnswer = card.chinese.replace(/[\((\[【].*?[\))\]】]/g, "").trim(); break;
1685
  default: return;
1686
  }
1687
  if (correctAnswer) {
 
1712
  localStorage.setItem('flashcardsBookTitle', bookTitle);
1713
  localStorage.setItem('flashcardsLessonTitle', lessonTitle);
1714
  updateMainTitle();
 
1715
  const originalText = saveTitleBtn.textContent;
1716
  saveTitleBtn.textContent = '已儲存!';
1717
  saveTitleBtn.classList.remove('bg-indigo-600', 'hover:bg-indigo-700');
 
1747
  generateLinkBtn.disabled = true;
1748
 
1749
  try {
1750
+ const wordsString = JSON.stringify(words.map(({audioUrl, ...rest}) => rest)); // Don't share audioUrl
1751
  const compressedData = pako.deflate(wordsString);
1752
  const base64Words = btoa(String.fromCharCode.apply(null, compressedData));
1753
 
 
1771
 
1772
  const longUrl = url.toString();
1773
 
1774
+ const response = await fetch(`https://is.gd/create.php?format=simple&url=${encodeURIComponent(longUrl)}`);
1775
  if (response.ok) {
1776
  const shortUrl = await response.text();
1777
  shareLinkInput.value = shortUrl;
 
1867
  startRangeInput.addEventListener('input', updateRandomCountMax);
1868
  endRangeInput.addEventListener('input', updateRandomCountMax);
1869
 
1870
+ saveApiKeyBtn.addEventListener('click', () => {
1871
+ const apiKey = apiKeyInput.value.trim();
1872
+ if (apiKey) {
1873
+ localStorage.setItem('geminiApiKey', apiKey);
1874
+ const originalText = saveApiKeyBtn.textContent;
1875
+ saveApiKeyBtn.textContent = '已儲存!';
1876
+ setTimeout(() => {
1877
+ saveApiKeyBtn.textContent = originalText;
1878
+ }, 2000);
1879
+ } else {
1880
+ localStorage.removeItem('geminiApiKey');
1881
+ alert('API 金鑰已清除。');
1882
+ }
1883
+ });
1884
+
1885
+ async function preloadAudioFiles() {
1886
+ const wordsToPreload = words.filter(word => {
1887
+ const wordToSpeak = word.english.replace(/[\((\[【].*?[\))\]】]/g, "").trim();
1888
+ const cleanedWord = wordToSpeak.replace(/[^a-zA-Z\s-]/g, '');
1889
+ // 只預載沒有快取、且不是片語的單字
1890
+ return !word.audioUrl && !cleanedWord.includes(' ');
1891
+ });
1892
+
1893
+ if (wordsToPreload.length === 0) return;
1894
+
1895
+ audioPreloadContainer.classList.remove('hidden');
1896
+ let loadedCount = 0;
1897
+
1898
+ for (const word of wordsToPreload) {
1899
+ try {
1900
+ const wordToSpeak = word.english.replace(/[\((\[【].*?[\))\]】]/g, "").trim();
1901
+ const cleanedWord = wordToSpeak.replace(/[^a-zA-Z\s-]/g, '');
1902
+
1903
+ const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${cleanedWord}`);
1904
+ if (!response.ok) continue;
1905
+
1906
+ const data = await response.json();
1907
+ let audioUrl = '';
1908
+ if (data && data.length > 0) {
1909
+ for (const entry of data) {
1910
+ for (const phonetic of entry.phonetics || []) {
1911
+ if (phonetic.audio) {
1912
+ if (phonetic.audio.includes('-us.mp3')) {
1913
+ audioUrl = phonetic.audio;
1914
+ break;
1915
+ }
1916
+ if (!audioUrl) audioUrl = phonetic.audio;
1917
+ }
1918
+ }
1919
+ if (audioUrl) break;
1920
+ }
1921
+ }
1922
+ if (audioUrl) {
1923
+ word.audioUrl = audioUrl; // Cache the URL
1924
+ }
1925
+ } catch (error) {
1926
+ console.warn(`Could not preload audio for "${word.english}":`, error);
1927
+ }
1928
+ loadedCount++;
1929
+ const percentage = Math.round((loadedCount / wordsToPreload.length) * 100);
1930
+ audioPreloadBar.style.width = `${percentage}%`;
1931
+ }
1932
+
1933
+ audioPreloadText.textContent = '語音檔案預載完成!';
1934
+ setTimeout(() => {
1935
+ audioPreloadContainer.classList.add('hidden');
1936
+ }, 2000);
1937
+ }
1938
+
1939
 
1940
  // --- 應用程式初始化 ---
1941
  const initializeApp = () => {
1942
+ const savedApiKey = localStorage.getItem('geminiApiKey');
1943
+ if (savedApiKey) {
1944
+ apiKeyInput.value = savedApiKey;
1945
+ }
1946
+
1947
  const urlParams = new URLSearchParams(window.location.search);
1948
  const sharedData = urlParams.get('data');
1949
  let loadedFromUrl = false;
 
1968
  if (!loadedFromUrl) {
1969
  const storedWords = localStorage.getItem('flashcards');
1970
  if (storedWords && JSON.parse(storedWords).length > 0) {
1971
+ words = JSON.parse(storedWords).map(word => ({
1972
+ ...word,
1973
+ proficiency: word.proficiency || 0,
1974
+ incorrectCount: word.incorrectCount || 0
1975
+ }));
1976
  } else {
1977
  const defaultWords = [
1978
+ { english: 'yesterday (adv.)', chinese: '昨天', sentence: { en: 'I walked to school ___.', zh: '我昨天走路上學。' } },
1979
+ { english: 'study (v.)', chinese: '研讀' },
1980
  { english: 'jog (v.)', chinese: '慢跑' }, { english: 'watch (v.)', chinese: '觀看' },
1981
  { english: 'last (adj.)', chinese: '前一個的' }, { english: 'death (n.)', chinese: '死亡' },
1982
  { english: 'a few (adj.)', chinese: '一些' }, { english: 'ago (adv.)', chinese: '以前' },
 
2013
 
2014
  if (isLocked) {
2015
  settingsContainer.classList.add('opacity-50', 'pointer-events-none');
 
2016
  if (shareGameBtn) shareGameBtn.classList.add('hidden');
2017
  if (manageWordsBtn) manageWordsBtn.classList.add('hidden');
2018
  }
 
2025
  endRangeInput.max = words.length;
2026
  endRangeInput.placeholder = `到 ${words.length}`;
2027
  updateRandomCountMax();
2028
+
2029
+ preloadAudioFiles();
2030
+
2031
  showView('menu');
2032
  };
2033
  initializeApp();