-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2915 lines (2459 loc) · 99.8 KB
/
script.js
File metadata and controls
2915 lines (2459 loc) · 99.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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// App state
let flashcards = [];
let currentCardIndex = 0;
let quizScore = { correct: 0, attempts: 0 };
let currentQuizCard = null;
let isShuffleMode = false;
let shuffledCards = [];
let studyStats = {
cardsStudied: 0,
lastStudyDate: null,
studyStreak: 0
};
// New practice mode scores
let practiceScores = {
typing: { correct: 0, attempts: 0 },
multipleChoice: { correct: 0, attempts: 0 },
fillBlank: { correct: 0, attempts: 0 },
scramble: { correct: 0, attempts: 0 },
listening: { correct: 0, attempts: 0 }
};
// Practice mode state
let currentPracticeMode = 'typing';
let currentPracticeCard = null;
let scrambledWord = '';
let isProcessingMCQuestion = false;
// Online/Offline detection
let isOnline = navigator.onLine;
// Test if we can actually access online voices
let canAccessOnlineVoices = false;
// DOM elements - will be initialized after DOM loads
let flashcardForm, wordInput, meaningInput, exampleInput, flashcard, cardWord, cardMeaning, cardExample;
let nextCardBtn, prevCardBtn, cardCounter, quizQuestion, quizAnswer, submitAnswerBtn, quizFeedback;
let scoreDisplay, resetScoreBtn, shuffleModeBtn, deleteCardBtn, exportDataBtn, importDataBtn;
let importFileInput, importImageBtn, importImageFileInput, clearAllDataBtn;
let mcScoreDisplay, mcQuestion, mcOptions, mcFeedback, resetMCScoreBtn;
let fbScoreDisplay, fbQuestion, fbAnswer, submitFBAnswerBtn, fbFeedback, resetFBScoreBtn;
let scrambleScoreDisplay, scrambleQuestion, scrambledWordEl, scrambleAnswer, submitScrambleAnswerBtn, scrambleFeedback, resetScrambleScoreBtn;
let listeningScoreDisplay, listeningQuestion, playWordBtn, listeningAnswer, submitListeningAnswerBtn, listeningFeedback, resetListeningScoreBtn;
let totalCardsEl, quizPercentageEl, cardsStudiedEl, studyStreakEl;
let modeButtons, practiceModes;
// Initialize DOM elements
function initDOMElements() {
flashcardForm = document.getElementById('flashcardForm');
wordInput = document.getElementById('word');
meaningInput = document.getElementById('meaning');
exampleInput = document.getElementById('example');
flashcard = document.getElementById('flashcard');
cardWord = document.getElementById('cardWord');
cardMeaning = document.getElementById('cardMeaning');
cardExample = document.getElementById('cardExample');
nextCardBtn = document.getElementById('nextCard');
prevCardBtn = document.getElementById('prevCard');
cardCounter = document.getElementById('cardCounter');
quizQuestion = document.getElementById('quizQuestion');
quizAnswer = document.getElementById('quizAnswer');
submitAnswerBtn = document.getElementById('submitAnswer');
quizFeedback = document.getElementById('quizFeedback');
scoreDisplay = document.getElementById('score');
resetScoreBtn = document.getElementById('resetScore');
shuffleModeBtn = document.getElementById('shuffleMode');
deleteCardBtn = document.getElementById('deleteCard');
exportDataBtn = document.getElementById('exportData');
importDataBtn = document.getElementById('importData');
importFileInput = document.getElementById('importFile');
importImageBtn = document.getElementById('importImage');
importImageFileInput = document.getElementById('importImageFile');
clearAllDataBtn = document.getElementById('clearAllData');
// Multiple choice elements
mcScoreDisplay = document.getElementById('mcScore');
mcQuestion = document.getElementById('mcQuestion');
mcOptions = document.getElementById('mcOptions');
mcFeedback = document.getElementById('mcFeedback');
resetMCScoreBtn = document.getElementById('resetMCScore');
// Fill in blank elements
fbScoreDisplay = document.getElementById('fbScore');
fbQuestion = document.getElementById('fbQuestion');
fbAnswer = document.getElementById('fbAnswer');
submitFBAnswerBtn = document.getElementById('submitFBAnswer');
fbFeedback = document.getElementById('fbFeedback');
resetFBScoreBtn = document.getElementById('resetFBScore');
// Scramble elements
scrambleScoreDisplay = document.getElementById('scrambleScore');
scrambleQuestion = document.getElementById('scrambleQuestion');
scrambledWordEl = document.getElementById('scrambledWord');
scrambleAnswer = document.getElementById('scrambleAnswer');
submitScrambleAnswerBtn = document.getElementById('submitScrambleAnswer');
scrambleFeedback = document.getElementById('scrambleFeedback');
resetScrambleScoreBtn = document.getElementById('resetScrambleScore');
// Listening elements
listeningScoreDisplay = document.getElementById('listeningScore');
listeningQuestion = document.getElementById('listeningQuestion');
playWordBtn = document.getElementById('playWord');
listeningAnswer = document.getElementById('listeningAnswer');
submitListeningAnswerBtn = document.getElementById('submitListeningAnswer');
listeningFeedback = document.getElementById('listeningFeedback');
resetListeningScoreBtn = document.getElementById('resetListeningScore');
// Statistics elements
totalCardsEl = document.getElementById('totalCards');
quizPercentageEl = document.getElementById('quizPercentage');
cardsStudiedEl = document.getElementById('cardsStudied');
studyStreakEl = document.getElementById('studyStreak');
// Practice mode elements
modeButtons = document.querySelectorAll('.mode-btn');
practiceModes = document.querySelectorAll('.practice-mode');
console.log('DOM elements initialized');
console.log('flashcardForm:', flashcardForm);
}
// Initialize app - Single consolidated initialization
document.addEventListener('DOMContentLoaded', function() {
console.log('App initialization started...');
// Initialize DOM elements first
initDOMElements();
// Initialize all components
initThemeToggle();
initSpeechSynthesis();
loadData();
setupEventListeners();
// Setup pronunciation buttons
setupPronunciationButtons();
// Preload voices for better offline support
preloadVoices();
// Initialize online/offline detection AFTER voices are loaded
initOnlineDetection();
// Update UI and displays first
updateUI();
updateButtonStates(); // Ensure button states are correct on load
updateStudyStreak();
// Register service worker
registerServiceWorker();
// Track study sessions
startStudySession();
// Save session data when page unloads
window.addEventListener('beforeunload', endStudySession);
});
// Register Service Worker for PWA
function registerServiceWorker() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('SW registered: ', registration);
})
.catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
});
}
}
// PWA Installation
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later
deferredPrompt = e;
// Show the install prompt
showInstallPrompt();
});
function showInstallPrompt() {
const installPrompt = document.getElementById('installPrompt');
const installBtn = document.getElementById('installBtn');
const closeBtn = document.getElementById('closeInstallPrompt');
if (installPrompt && deferredPrompt) {
installPrompt.classList.add('show');
installBtn.addEventListener('click', () => {
// Show the install prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the install prompt');
} else {
console.log('User dismissed the install prompt');
}
deferredPrompt = null;
installPrompt.classList.remove('show');
});
});
closeBtn.addEventListener('click', () => {
installPrompt.classList.remove('show');
});
}
}
// Load data from localStorage
function loadData() {
const savedFlashcards = localStorage.getItem('flashcards');
const savedScore = localStorage.getItem('quizScore');
const savedStats = localStorage.getItem('studyStats');
const savedPracticeScores = localStorage.getItem('practiceScores');
const savedCardIndex = localStorage.getItem('currentCardIndex');
if (savedFlashcards) {
flashcards = JSON.parse(savedFlashcards);
}
if (savedScore) {
quizScore = JSON.parse(savedScore);
}
if (savedStats) {
studyStats = JSON.parse(savedStats);
}
if (savedPracticeScores) {
practiceScores = JSON.parse(savedPracticeScores);
}
if (savedCardIndex) {
currentCardIndex = JSON.parse(savedCardIndex);
// Ensure currentCardIndex is within valid range
if (currentCardIndex >= flashcards.length) {
currentCardIndex = 0;
}
}
}
// Save data to localStorage
function saveData() {
localStorage.setItem('flashcards', JSON.stringify(flashcards));
localStorage.setItem('quizScore', JSON.stringify(quizScore));
localStorage.setItem('studyStats', JSON.stringify(studyStats));
localStorage.setItem('practiceScores', JSON.stringify(practiceScores));
localStorage.setItem('currentCardIndex', JSON.stringify(currentCardIndex));
}
// Setup event listeners
function setupEventListeners() {
console.log('Setting up event listeners...');
console.log('flashcardForm:', flashcardForm);
// Form submission
if (flashcardForm) {
flashcardForm.addEventListener('submit', addFlashcard);
console.log('Form event listener added');
} else {
console.error('flashcardForm not found!');
}
// Flashcard click to flip
flashcard.addEventListener('click', flipCard);
// Navigation buttons
nextCardBtn.addEventListener('click', nextCard);
prevCardBtn.addEventListener('click', prevCard);
// Quiz submission
submitAnswerBtn.addEventListener('click', submitQuizAnswer);
// Control buttons
resetScoreBtn.addEventListener('click', resetScore);
shuffleModeBtn.addEventListener('click', toggleShuffleMode);
deleteCardBtn.addEventListener('click', deleteCurrentCard);
exportDataBtn.addEventListener('click', exportFlashcards);
importDataBtn.addEventListener('click', () => importFileInput.click());
importFileInput.addEventListener('change', importFlashcards);
importImageBtn.addEventListener('click', () => importImageFileInput.click());
importImageFileInput.addEventListener('change', handleImageImport);
clearAllDataBtn.addEventListener('click', clearAllData);
// Practice mode switching
modeButtons.forEach(btn => {
btn.addEventListener('click', () => switchPracticeMode(btn.dataset.mode));
});
// Multiple choice
resetMCScoreBtn.addEventListener('click', () => resetPracticeScore('multipleChoice'));
// Fill in blank
submitFBAnswerBtn.addEventListener('click', submitFillBlankAnswer);
resetFBScoreBtn.addEventListener('click', () => resetPracticeScore('fillBlank'));
fbAnswer.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
submitFillBlankAnswer();
}
});
// Scramble
submitScrambleAnswerBtn.addEventListener('click', submitScrambleAnswer);
resetScrambleScoreBtn.addEventListener('click', () => resetPracticeScore('scramble'));
scrambleAnswer.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
submitScrambleAnswer();
}
});
// Listening
if (playWordBtn) {
playWordBtn.addEventListener('click', () => {
console.log('Play Word clicked, currentPracticeCard:', currentPracticeCard);
if (currentPracticeCard && currentPracticeCard.word) {
playWordBtn.textContent = '🔊 Playing...';
playWordBtn.disabled = true;
speakText(currentPracticeCard.word, 'en-US');
// Reset button after a short delay
setTimeout(() => {
if (playWordBtn) {
playWordBtn.textContent = '🔊 Play Word';
playWordBtn.disabled = false;
}
}, 2000);
} else {
showFeedback('No word available to play', 'error');
}
});
}
submitListeningAnswerBtn.addEventListener('click', submitListeningAnswer);
resetListeningScoreBtn.addEventListener('click', () => resetPracticeScore('listening'));
listeningAnswer.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
submitListeningAnswer();
}
});
// Enter key for quiz answer
quizAnswer.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
submitQuizAnswer();
}
});
}
// Add new flashcard
function addFlashcard(e) {
console.log('addFlashcard function called');
e.preventDefault();
const word = wordInput.value.trim();
const meaning = meaningInput.value.trim();
const example = exampleInput.value.trim();
if (!word || !meaning || !example) {
alert('Please fill in all fields');
return;
}
const newCard = {
id: Date.now(),
word: word,
meaning: meaning,
example: example
};
flashcards.push(newCard);
// Reset form
flashcardForm.reset();
// If this is the first card, set currentCardIndex to 0
if (flashcards.length === 1) {
currentCardIndex = 0;
}
// Display the current card
displayCurrentCard();
// Update button states immediately
updateButtonStates();
// Update all other UI elements
updateUI();
// Save the current card index
saveData();
// Show success message
showFeedback('Flashcard added successfully!', 'success');
}
// Centralized function to update button states
function updateButtonStates() {
if (flashcards.length === 0) {
nextCardBtn.disabled = true;
prevCardBtn.disabled = true;
deleteCardBtn.disabled = true;
} else {
nextCardBtn.disabled = currentCardIndex >= flashcards.length - 1;
prevCardBtn.disabled = currentCardIndex <= 0;
deleteCardBtn.disabled = false;
}
}
// Update UI based on current state
function updateUI() {
updateCardCounter();
updateScoreDisplay();
updateAllPracticeScores();
updatePracticeSection();
updateStatistics();
updateDisplay(); // Call updateDisplay to handle all display logic
// Update button states
updateButtonStates();
// Update pronunciation button states
updatePronunciationButtons();
// Initialize current practice mode
switchPracticeMode(currentPracticeMode);
}
// Display current card
function displayCurrentCard() {
if (flashcards.length === 0) return;
const card = getCurrentCard();
cardWord.textContent = card.word;
cardMeaning.textContent = card.meaning;
cardExample.textContent = card.example;
// Reset card to front
flashcard.classList.remove('flipped');
// Update pronunciation button states
updatePronunciationButtons();
}
// Get current card (handles shuffle mode)
function getCurrentCard() {
if (isShuffleMode && shuffledCards.length > 0) {
return shuffledCards[currentCardIndex];
}
return flashcards[currentCardIndex];
}
// Display empty state
function displayEmptyState() {
cardWord.textContent = 'No cards yet';
cardMeaning.textContent = 'Add some flashcards first!';
cardExample.textContent = '';
flashcard.classList.remove('flipped');
// Update pronunciation button states
updatePronunciationButtons();
}
// Flip card
function flipCard() {
if (flashcards.length === 0) return;
flashcard.classList.toggle('flipped');
// Track study activity
if (!flashcard.classList.contains('flipped')) {
studyStats.cardsStudied++;
updateStudyStreak();
saveData();
}
}
// Next card
function nextCard() {
if (flashcards.length === 0) return;
currentCardIndex = (currentCardIndex + 1) % flashcards.length;
displayCurrentCard();
updateCardCounter();
updateButtonStates(); // Update button states immediately
saveData(); // Save the current card index
}
// Previous card
function prevCard() {
if (flashcards.length === 0) return;
currentCardIndex = currentCardIndex === 0 ? flashcards.length - 1 : currentCardIndex - 1;
displayCurrentCard();
updateCardCounter();
updateButtonStates(); // Update button states immediately
saveData(); // Save the current card index
}
// Toggle shuffle mode
function toggleShuffleMode() {
isShuffleMode = !isShuffleMode;
if (isShuffleMode) {
// Create shuffled array
shuffledCards = [...flashcards].sort(() => Math.random() - 0.5);
shuffleModeBtn.textContent = '🔀 Shuffle Mode: ON';
shuffleModeBtn.classList.add('btn-primary');
shuffleModeBtn.classList.remove('btn-outline');
} else {
shuffledCards = [];
shuffleModeBtn.textContent = '🔀 Shuffle Mode: OFF';
shuffleModeBtn.classList.remove('btn-primary');
shuffleModeBtn.classList.add('btn-outline');
}
currentCardIndex = 0;
displayCurrentCard();
updateCardCounter();
updateButtonStates(); // Update button states immediately
saveData(); // Save the current card index
}
// Delete current card
function deleteCurrentCard() {
if (flashcards.length === 0) return;
if (confirm('Are you sure you want to delete this card?')) {
const cardToDelete = getCurrentCard();
flashcards = flashcards.filter(card => card.id !== cardToDelete.id);
if (isShuffleMode) {
shuffledCards = shuffledCards.filter(card => card.id !== cardToDelete.id);
}
if (flashcards.length === 0) {
currentCardIndex = 0;
} else if (currentCardIndex >= flashcards.length) {
currentCardIndex = flashcards.length - 1;
}
saveData();
updateUI();
updateButtonStates(); // Ensure button states are correct after deletion
showFeedback('Card deleted successfully!', 'success');
}
}
// Update card counter
function updateCardCounter() {
const total = isShuffleMode ? shuffledCards.length : flashcards.length;
cardCounter.textContent = `${currentCardIndex + 1} / ${total}`;
}
// Update score display
function updateScoreDisplay() {
scoreDisplay.textContent = `${quizScore.correct} / ${quizScore.attempts}`;
}
// Update all practice scores
function updateAllPracticeScores() {
mcScoreDisplay.textContent = `${practiceScores.multipleChoice.correct} / ${practiceScores.multipleChoice.attempts}`;
fbScoreDisplay.textContent = `${practiceScores.fillBlank.correct} / ${practiceScores.fillBlank.attempts}`;
scrambleScoreDisplay.textContent = `${practiceScores.scramble.correct} / ${practiceScores.scramble.attempts}`;
listeningScoreDisplay.textContent = `${practiceScores.listening.correct} / ${practiceScores.listening.attempts}`;
}
// Update practice section
function updatePracticeSection() {
// Hide all practice modes
practiceModes.forEach(mode => {
mode.style.display = 'none';
});
// Show current practice mode
const currentMode = document.getElementById(`${currentPracticeMode}-mode`);
if (currentMode) {
currentMode.style.display = 'block';
}
}
// Update statistics
function updateStatistics() {
totalCardsEl.textContent = flashcards.length;
// Calculate overall practice performance
const totalAttempts = Object.values(practiceScores).reduce((sum, score) => sum + score.attempts, 0);
const totalCorrect = Object.values(practiceScores).reduce((sum, score) => sum + score.correct, 0);
const percentage = totalAttempts > 0 ? Math.round((totalCorrect / totalAttempts) * 100) : 0;
quizPercentageEl.textContent = `${percentage}%`;
cardsStudiedEl.textContent = studyStats.cardsStudied;
studyStreakEl.textContent = `${studyStats.studyStreak} days`;
}
// Update study streak
function updateStudyStreak() {
const today = new Date().toDateString();
if (studyStats.lastStudyDate !== today) {
const lastDate = studyStats.lastStudyDate ? new Date(studyStats.lastStudyDate) : null;
const todayDate = new Date(today);
if (!lastDate || (todayDate - lastDate) / (1000 * 60 * 60 * 24) === 1) {
studyStats.studyStreak++;
} else if ((todayDate - lastDate) / (1000 * 60 * 60 * 24) > 1) {
studyStats.studyStreak = 1;
}
studyStats.lastStudyDate = today;
}
}
// Update quiz section
function updateQuizSection() {
if (flashcards.length === 0) {
quizQuestion.innerHTML = '<p>Add some flashcards to start the quiz!</p>';
quizAnswer.disabled = true;
submitAnswerBtn.disabled = true;
return;
}
// Select a random card for quiz
const randomIndex = Math.floor(Math.random() * flashcards.length);
currentQuizCard = flashcards[randomIndex];
quizQuestion.innerHTML = `<p>What is the English word for: <strong>${currentQuizCard.meaning}</strong>?</p>`;
quizAnswer.disabled = false;
submitAnswerBtn.disabled = false;
quizAnswer.value = '';
quizAnswer.blur(); // Remove focus to clear any highlighting
quizFeedback.textContent = '';
quizFeedback.className = 'quiz-feedback';
}
// Submit quiz answer
function submitQuizAnswer() {
if (!currentQuizCard) return;
const userAnswer = quizAnswer.value.trim().toLowerCase();
const correctAnswer = currentQuizCard.word.toLowerCase();
quizScore.attempts++;
if (userAnswer === correctAnswer) {
quizScore.correct++;
showQuizFeedback('Correct! 🎉', 'correct');
} else {
showQuizFeedback(`Wrong! The correct answer is: <strong>${currentQuizCard.word}</strong>`, 'incorrect');
}
saveData();
updateScoreDisplay();
updateStatistics();
// Disable inputs temporarily
quizAnswer.disabled = true;
submitAnswerBtn.disabled = true;
// Generate new question after 2 seconds
setTimeout(() => {
updateQuizSection();
}, 2000);
}
// Show quiz feedback
function showQuizFeedback(message, type) {
quizFeedback.innerHTML = message;
quizFeedback.className = `quiz-feedback ${type}`;
}
// Reset score
function resetScore() {
if (confirm('Are you sure you want to reset your quiz score?')) {
quizScore = { correct: 0, attempts: 0 };
saveData();
updateScoreDisplay();
updateStatistics();
showFeedback('Score reset successfully!', 'success');
}
}
// Export flashcards
function exportFlashcards() {
if (flashcards.length === 0) {
showFeedback('No flashcards to export!', 'error');
return;
}
const dataStr = JSON.stringify(flashcards, null, 2);
const dataBlob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = `flashcards_${new Date().toISOString().split('T')[0]}.json`;
link.click();
URL.revokeObjectURL(url);
showFeedback('Flashcards exported successfully!', 'success');
}
// Import flashcards
function importFlashcards(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const importedCards = JSON.parse(e.target.result);
if (!Array.isArray(importedCards)) {
throw new Error('Invalid file format');
}
// Add imported cards with new IDs
importedCards.forEach(card => {
card.id = Date.now() + Math.random();
flashcards.push(card);
});
saveData();
updateUI();
showFeedback(`${importedCards.length} flashcards imported successfully!`, 'success');
} catch (error) {
showFeedback('Error importing flashcards. Please check the file format.', 'error');
}
};
reader.readAsText(file);
event.target.value = ''; // Reset file input
}
// Clear all data
function clearAllData() {
if (confirm('Are you sure you want to clear ALL data? This cannot be undone!')) {
flashcards = [];
quizScore = { correct: 0, attempts: 0 };
studyStats = { cardsStudied: 0, lastStudyDate: null, studyStreak: 0 };
practiceScores = {
typing: { correct: 0, attempts: 0 },
multipleChoice: { correct: 0, attempts: 0 },
fillBlank: { correct: 0, attempts: 0 },
scramble: { correct: 0, attempts: 0 },
listening: { correct: 0, attempts: 0 }
};
currentCardIndex = 0;
isShuffleMode = false;
shuffledCards = [];
currentPracticeMode = 'typing';
currentPracticeCard = null;
scrambledWord = '';
isProcessingMCQuestion = false;
localStorage.clear();
updateUI();
showFeedback('All data cleared successfully!', 'success');
}
}
// Show general feedback
function showFeedback(message, type) {
// Create temporary feedback element
const feedback = document.createElement('div');
feedback.textContent = message;
feedback.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 15px 20px;
border-radius: 8px;
color: white;
font-weight: 600;
z-index: 1000;
animation: slideIn 0.3s ease;
`;
if (type === 'success') {
feedback.style.background = '#28a745';
} else if (type === 'error') {
feedback.style.background = '#dc3545';
} else if (type === 'warning') {
feedback.style.background = '#ffc107';
feedback.style.color = '#333';
} else {
feedback.style.background = '#17a2b8';
}
document.body.appendChild(feedback);
// Remove after 3 seconds
setTimeout(() => {
feedback.remove();
}, 3000);
}
// Add CSS animation for feedback
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
`;
document.head.appendChild(style);
// Practice Mode Functions
// Switch between practice modes
function switchPracticeMode(mode) {
currentPracticeMode = mode;
// Update active button
modeButtons.forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.mode === mode) {
btn.classList.add('active');
}
});
// Hide all practice modes
practiceModes.forEach(practiceMode => {
practiceMode.style.display = 'none';
});
// Show selected mode
const selectedMode = document.getElementById(`${mode}-mode`);
if (selectedMode) {
selectedMode.style.display = 'block';
}
// Initialize the selected mode
initializePracticeMode(mode);
}
// Initialize practice mode
function initializePracticeMode(mode) {
if (flashcards.length === 0) {
showEmptyPracticeState(mode);
return;
}
switch (mode) {
case 'typing':
updateQuizSection();
break;
case 'multiple-choice':
updateMultipleChoiceSection();
break;
case 'fill-blank':
updateFillBlankSection();
break;
case 'scramble':
updateScrambleSection();
break;
case 'listening':
updateListeningSection();
break;
}
}
// Show empty state for practice modes
function showEmptyPracticeState(mode) {
const questionElements = {
'typing': quizQuestion,
'multiple-choice': mcQuestion,
'fill-blank': fbQuestion,
'scramble': scrambleQuestion,
'listening': listeningQuestion
};
const element = questionElements[mode];
if (element) {
element.innerHTML = '<p>Add some flashcards to start practicing!</p>';
}
// Disable inputs for the current mode
disablePracticeInputs(mode);
}
// Disable practice inputs
function disablePracticeInputs(mode) {
const inputs = {
'typing': [quizAnswer, submitAnswerBtn],
'fill-blank': [fbAnswer, submitFBAnswerBtn],
'scramble': [scrambleAnswer, submitScrambleAnswerBtn],
'listening': [listeningAnswer, submitListeningAnswerBtn, playWordBtn]
};
const modeInputs = inputs[mode];
if (modeInputs) {
modeInputs.forEach(input => {
if (input) input.disabled = true;
});
}
}
// Enable practice inputs
function enablePracticeInputs(mode) {
const inputs = {
'typing': [quizAnswer, submitAnswerBtn],
'fill-blank': [fbAnswer, submitFBAnswerBtn],
'scramble': [scrambleAnswer, submitScrambleAnswerBtn],
'listening': [listeningAnswer, submitListeningAnswerBtn, playWordBtn]
};
const modeInputs = inputs[mode];
if (modeInputs) {
modeInputs.forEach(input => {
if (input) input.disabled = false;
});
}
}
// Multiple Choice Practice
function updateMultipleChoiceSection() {
if (flashcards.length === 0) {
showEmptyPracticeState('multiple-choice');
return;
}
// Reset processing flag
isProcessingMCQuestion = false;
// Clear any existing feedback
mcFeedback.textContent = '';
mcFeedback.className = 'quiz-feedback';
// Clear any existing option highlighting from previous questions
const existingOptions = document.querySelectorAll('.mc-option');
existingOptions.forEach(option => {
option.classList.remove('correct', 'incorrect');
option.style.pointerEvents = 'auto';
});
// Select a random card
const randomIndex = Math.floor(Math.random() * flashcards.length);
currentPracticeCard = flashcards[randomIndex];
mcQuestion.innerHTML = `<p>What is the English word for: <strong>${currentPracticeCard.meaning}</strong>?</p>`;
// Generate 4 options (1 correct + 3 wrong)
const options = generateMultipleChoiceOptions(currentPracticeCard);
// Clear previous options
mcOptions.innerHTML = '';
// Create option buttons
options.forEach((option, index) => {
const optionBtn = document.createElement('div');
optionBtn.className = 'mc-option';
optionBtn.textContent = option;
optionBtn.dataset.option = option;
optionBtn.addEventListener('click', () => selectMultipleChoiceOption(option));
mcOptions.appendChild(optionBtn);
});
// Move focus to body to prevent any visual highlighting
document.body.focus();
}
// Generate multiple choice options
function generateMultipleChoiceOptions(correctCard) {
const options = [correctCard.word];
// Get 3 random wrong answers
const otherCards = flashcards.filter(card => card.id !== correctCard.id);
const shuffledOthers = [...otherCards].sort(() => Math.random() - 0.5);
for (let i = 0; i < 3 && i < shuffledOthers.length; i++) {
options.push(shuffledOthers[i].word);
}
// If we don't have enough cards, add some generic words
while (options.length < 4) {
const genericWords = ['hello', 'world', 'learn', 'study', 'practice', 'word', 'language'];
const randomWord = genericWords[Math.floor(Math.random() * genericWords.length)];
if (!options.includes(randomWord)) {
options.push(randomWord);