-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpracticescript.js
More file actions
1670 lines (1452 loc) · 59.2 KB
/
practicescript.js
File metadata and controls
1670 lines (1452 loc) · 59.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
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
// Reading Practice Script
class ReadingPractice {
constructor() {
this.currentStage = "paragraph";
this.currentSentenceIndex = 0;
this.currentWordIndex = 0;
this.starsEarned = 0;
this.isRecording = false;
this.calibrationComplete = true; // Track calibration state
this.isCalibrating = false; // Track if currently calibrating
// Practice content
this.paragraph =
"The brave little fox loved to explore the forest every morning. She would walk along the winding paths, listening to the birds sing their beautiful songs. Sometimes she would find interesting rocks or colorful flowers that made her day special. The fox knew that reading books was just like exploring the forest - every page held new adventures and discoveries waiting to be found.";
this.sentences = [
"The brave little fox loved to explore the forest every morning.",
"She would walk along the winding paths, listening to the birds sing their beautiful songs.",
"Sometimes she would find interesting rocks or colorful flowers that made her day special.",
"The fox knew that reading books was just like exploring the forest - every page held new adventures and discoveries waiting to be found.",
];
this.words = [
{
word: "explore",
phonetics: "/ɪkˈsplɔːr/",
meaning:
"To travel through or investigate a place to learn about it",
context: "...loved to explore the forest...",
hint: "Think of 'ex' (out) + 'plore' (like explore a new place)",
},
{
word: "winding",
phonetics: "/ˈwaɪn.dɪŋ/",
meaning: "Having many curves and turns",
context: "...along the winding paths...",
hint: "Think of 'wind' (like the wind blowing in curves) + 'ing'",
},
{
word: "listening",
phonetics: "/ˈlɪs.ən.ɪŋ/",
meaning: "Giving attention with the ear to hear sounds",
context: "...listening to the birds...",
hint: "Think of 'listen' + 'ing' (the action of hearing)",
},
{
word: "beautiful",
phonetics: "/ˈbjuː.tɪ.fəl/",
meaning: "Pleasing the senses or mind aesthetically",
context: "...sing their beautiful songs...",
hint: "Think of 'beauty' + 'ful' (full of beauty)",
},
{
word: "interesting",
phonetics: "/ˈɪn.trə.stɪŋ/",
meaning: "Arousing curiosity or interest",
context: "...find interesting rocks...",
hint: "Think of 'interest' + 'ing' (causing interest)",
},
{
word: "adventures",
phonetics: "/ədˈven.tʃərz/",
meaning: "Exciting or unusual experiences",
context: "...new adventures and discoveries...",
hint: "Think of 'adventure' + 's' (more than one adventure)",
},
];
this.initializeElements();
this.bindEvents();
}
initializeElements() {
// Screen elements
this.welcomeScreen = document.getElementById("welcomeScreen");
this.practiceInterface = document.getElementById("practiceInterface");
// Progress elements
this.progressSteps = document.querySelectorAll(".progress-step");
this.currentStageEl = document.getElementById("currentStage");
// Stage elements
this.paragraphStage = document.getElementById("paragraphStage");
this.sentenceStage = document.getElementById("sentenceStage");
this.wordStage = document.getElementById("wordStage");
this.completeStage = document.getElementById("completeStage");
// Paragraph elements
this.paragraphText = document.getElementById("paragraphText");
this.paragraphAudioBtn = document.getElementById("paragraphAudioBtn");
this.paragraphRecordBtn = document.getElementById("paragraphRecordBtn");
this.paragraphFeedback = document.getElementById("paragraphFeedback");
this.nextToSentence = document.getElementById("nextToSentence");
// Sentence elements
this.sentenceCounter = document.getElementById("sentenceCounter");
this.currentSentenceEl = document.getElementById("currentSentence");
this.sentenceAudioBtn = document.getElementById("sentenceAudioBtn");
this.sentenceRecordBtn = document.getElementById("sentenceRecordBtn");
this.sentenceFeedback = document.getElementById("sentenceFeedback");
this.prevSentence = document.getElementById("prevSentence");
this.nextSentence = document.getElementById("nextSentence");
// Word elements
this.wordCounter = document.getElementById("wordCounter");
this.practiceWord = document.getElementById("practiceWord");
this.wordPhonetics = document.getElementById("wordPhonetics");
this.wordHintBtn = document.getElementById("wordHintBtn");
this.wordAudioBtn = document.getElementById("wordAudioBtn");
this.wordRecordBtn = document.getElementById("wordRecordBtn");
this.wordFeedback = document.getElementById("wordFeedback");
this.prevWord = document.getElementById("prevWord");
this.nextWord = document.getElementById("nextWord");
// Completion elements
this.totalWords = document.getElementById("totalWords");
this.totalSentences = document.getElementById("totalSentences");
this.starsEarnedEl = document.getElementById("starsEarned");
this.practiceAgain = document.getElementById("practiceAgain");
this.backToProfile = document.getElementById("backToProfile");
// Navigation elements
this.backBtn = document.getElementById("backBtn");
this.homeBtn = document.getElementById("homeBtn");
this.settingsBtn = document.getElementById("settingsBtn");
// Modal elements
this.hintModal = document.getElementById("hintModal");
this.closeHint = document.getElementById("closeHint");
this.hintBody = document.getElementById("hintBody");
// Start button
this.startBtn = document.getElementById("startBtn");
}
bindEvents() {
// Start button
if (this.startBtn) {
this.startBtn.addEventListener("click", () => this.startPractice());
}
// Navigation
if (this.backBtn) {
this.backBtn.addEventListener("click", () => this.goBack());
}
if (this.homeBtn) {
this.homeBtn.addEventListener("click", () => this.goHome());
}
if (this.settingsBtn) {
this.settingsBtn.addEventListener("click", () =>
this.openSettings()
);
}
// Paragraph stage
if (this.paragraphAudioBtn) {
this.paragraphAudioBtn.addEventListener("click", () =>
this.playParagraphAudio()
);
}
if (this.paragraphRecordBtn) {
this.paragraphRecordBtn.addEventListener("click", () =>
this.recordParagraph()
);
}
if (this.nextToSentence) {
this.nextToSentence.addEventListener("click", () =>
this.moveToSentenceStage()
);
}
// Sentence stage
if (this.sentenceAudioBtn) {
this.sentenceAudioBtn.addEventListener("click", () =>
this.playSentenceAudio()
);
}
if (this.sentenceRecordBtn) {
this.sentenceRecordBtn.addEventListener("click", () =>
this.recordSentence()
);
}
if (this.prevSentence) {
this.prevSentence.addEventListener("click", () =>
this.previousSentence()
);
}
if (this.nextSentence) {
this.nextSentence.addEventListener("click", () =>
this.nextSentenceHandler()
);
}
// Word stage
if (this.wordHintBtn) {
this.wordHintBtn.addEventListener("click", () =>
this.showWordHint()
);
}
if (this.wordAudioBtn) {
this.wordAudioBtn.addEventListener("click", () =>
this.playWordAudio()
);
}
if (this.wordRecordBtn) {
this.wordRecordBtn.addEventListener("click", () =>
this.recordWord()
);
}
if (this.prevWord) {
this.prevWord.addEventListener("click", () => this.previousWord());
}
if (this.nextWord) {
this.nextWord.addEventListener("click", () =>
this.nextWordHandler()
);
}
// Completion
if (this.practiceAgain) {
this.practiceAgain.addEventListener("click", () =>
this.restartPractice()
);
}
if (this.backToProfile) {
this.backToProfile.addEventListener("click", () =>
this.goToProfile()
);
}
// Modal
if (this.closeHint) {
this.closeHint.addEventListener("click", () => this.hideHint());
}
if (this.hintModal) {
this.hintModal.addEventListener("click", (e) => {
if (e.target === this.hintModal) this.hideHint();
});
}
// Keyboard shortcuts
document.addEventListener("keydown", (e) => this.handleKeyboard(e));
}
async startPractice() {
console.log("🎯 startPractice called", {
calibrationComplete: this.calibrationComplete,
isCalibrating: this.isCalibrating,
buttonDataset: this.startBtn
? this.startBtn.dataset.calibrationComplete
: "N/A",
});
// Check calibration state from instance OR from button data attribute (fallback)
const isCalibrationComplete =
this.calibrationComplete ||
(this.startBtn &&
this.startBtn.dataset.calibrationComplete === "true");
// If calibration is not complete, start calibration first
if (!isCalibrationComplete) {
this.isCalibrating = true; // Set calibrating flag
this.startBtn.disabled = true;
this.startBtn.innerHTML =
'<i class="fas fa-spinner fa-spin"></i> <span>Initializing eye tracking...</span>';
// Initialize eye tracking and calibration
initializeEyeTracking();
return;
}
// If calibration is complete, start the actual reading practice
try {
console.log(
"✅ Starting reading practice (calibration already complete)"
);
// Update instance state if it wasn't set
if (!this.calibrationComplete) {
this.calibrationComplete = true;
this.isCalibrating = false;
}
// Show loading state
this.startBtn.disabled = true;
this.startBtn.innerHTML =
'<i class="fas fa-spinner fa-spin"></i> <span>Generating practice content...</span>';
toggleEyeTracking(true); // Pause eye tracking during content generation
// Generate content from API
await this.generatePracticeContent();
// Start the practice
this.welcomeScreen.style.display = "none";
this.practiceInterface.style.display = "block";
this.showParagraphStage();
this.updateProgress();
} catch (error) {
console.error("Error generating practice content:", error);
// Reset button state
this.startBtn.disabled = false;
this.startBtn.innerHTML =
'<i class="fas fa-play"></i> <span>Start Reading Practice</span>';
alert(
"Sorry, there was an error generating practice content. Please try again."
);
}
}
async generatePracticeContent() {
const baseUrl = "http://127.0.0.1:5001/generate";
try {
// Generate only the initial paragraph
const paragraphResponse = await fetch(`${baseUrl}?q=paragraph`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
if (!paragraphResponse.ok) {
throw new Error(
`Paragraph generation failed: ${paragraphResponse.status}`
);
}
const paragraphData = await paragraphResponse.json();
// Update only the paragraph content
if (paragraphData && paragraphData.text) {
this.paragraph = paragraphData.text;
this.paragraphText.textContent = this.paragraph;
}
} catch (error) {
console.error("API call failed:", error);
// Keep the default content if API fails
console.log("Using default practice content");
}
}
async generateSentencesFromRecording(audioBlob) {
const baseUrl = "http://127.0.0.1:5001";
try {
// Send audio to speech-to-text API
const formData = new FormData();
formData.append("file", audioBlob, "recording.mp3");
formData.append("json", this.paragraph);
console.log("📤 Sending audio to STT API...");
const sttResponse = await fetch(`${baseUrl}/stt`, {
method: "POST",
body: formData,
});
if (!sttResponse.ok) {
throw new Error(`Speech-to-text failed: ${sttResponse.status}`);
}
const sttData = await sttResponse.json();
console.log("✅ STT response received:", sttData);
// Call TTS API with the recognized words
if (sttData.words) {
console.log("🔊 Calling TTS API with words:", sttData.words);
const ttsResponse = await fetch(`${baseUrl}/tts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
words: sttData.words
}),
});
if (ttsResponse.ok) {
// Get base64 audio from TTS response
const ttsData = await ttsResponse.json();
console.log("🎵 Playing TTS audio feedback...");
const audio = new Audio("data:audio/mp3;base64," + ttsData.audio);
audio.play();
} else {
console.warn("⚠️ TTS API failed, continuing without audio feedback");
}
}
// Use the words from STT response to generate sentences
console.log("📝 Generating sentences from recognized words...");
const sentenceResponse = await fetch(
`${baseUrl}/generate?q=sentence`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
words: sttData.words || [],
}),
}
);
if (!sentenceResponse.ok) {
throw new Error(
`Sentence generation failed: ${sentenceResponse.status}`
);
}
const sentenceData = await sentenceResponse.json();
console.log("✅ Sentence generation complete:", sentenceData);
// Update sentences
if (sentenceData && sentenceData.sentences) {
this.sentences = sentenceData.sentences;
} else if (sentenceData && sentenceData.text) {
this.sentences = sentenceData.text
.split(/[.!?]+/)
.map((s) => s.trim())
.filter((s) => s.length > 0)
.map((s) => s + ".");
}
return true;
} catch (error) {
console.error("Error generating sentences from recording:", error);
// Log more detailed error information
if (error.message.includes('Failed to fetch')) {
console.error("❌ Backend server is not running at http://127.0.0.1:5001");
} else if (error.message.includes('Speech-to-text failed')) {
console.error("❌ STT API error:", error.message);
} else if (error.message.includes('Sentence generation failed')) {
console.error("❌ Sentence generation API error:", error.message);
} else {
console.error("❌ Unexpected error:", error.message);
}
return false;
}
}
async generateWordsFromRecording(audioBlob) {
const baseUrl = "http://127.0.0.1:5001";
try {
// Send audio to speech-to-text API
const formData = new FormData();
formData.append("file", audioBlob, "recording.mp3");
formData.append("json", this.sentences[this.currentSentenceIndex]);
const sttResponse = await fetch(`${baseUrl}/stt`, {
method: "POST",
body: formData,
});
if (!sttResponse.ok) {
throw new Error(`Speech-to-text failed: ${sttResponse.status}`);
}
const sttData = await sttResponse.json();
// Use the words from STT response to generate word practice
const wordResponse = await fetch(`${baseUrl}/generate?q=word`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
words: sttData.words || [],
}),
});
if (!wordResponse.ok) {
throw new Error(
`Word generation failed: ${wordResponse.status}`
);
}
const wordData = await wordResponse.json();
console.log("✅ Word generation complete:", wordData);
// Handle the new API response format: {"text": "asingleword"}
if (wordData && wordData.text) {
// Create a single word object for the word stage
this.words = [{
word: wordData.text,
phonetics: `/${wordData.text}/`,
meaning: `Practice word: ${wordData.text}`,
context: `Focus on the word '${wordData.text}'`,
hint: `Think about the word '${wordData.text}' and practice saying it slowly.`,
}];
} else if (wordData && wordData.words) {
// Fallback for old format
this.words = wordData.words.map((wordInfo, index) => {
if (typeof wordInfo === "string") {
return {
word: wordInfo,
phonetics: `/${wordInfo}/`,
meaning: `Practice word: ${wordInfo}`,
context: `...${wordInfo}...`,
hint: `Think about the word '${wordInfo}' and practice saying it slowly.`,
};
} else {
return wordInfo;
}
});
}
return true;
} catch (error) {
console.error("Error generating words from recording:", error);
return false;
}
}
extractWordsFromText(text) {
// Extract words from text, filter out common words
const words = text
.toLowerCase()
.replace(/[^\w\s]/g, "")
.split(/\s+/)
.filter((word) => word.length > 3)
.filter(
(word) =>
![
"this",
"that",
"with",
"have",
"will",
"been",
"from",
"they",
"know",
"want",
"been",
"good",
"much",
"some",
"time",
"very",
"when",
"come",
"here",
"just",
"like",
"long",
"make",
"many",
"over",
"such",
"take",
"than",
"them",
"well",
"were",
].includes(word)
);
// Remove duplicates and return
return [...new Set(words)];
}
extractKeyWords(text) {
// Extract key words that are good for practice (longer, more complex words)
const words = this.extractWordsFromText(text)
.filter((word) => word.length >= 5)
.slice(0, 6); // Limit to 6 words for practice
return words.length > 0
? words
: [
"explore",
"beautiful",
"adventure",
"interesting",
"wonderful",
"discover",
];
}
updateProgress() {
this.progressSteps.forEach((step, index) => {
const stage = step.dataset.stage;
step.className = "progress-step";
if (stage === this.currentStage) {
step.classList.add("active");
} else if (this.isStageCompleted(stage)) {
step.classList.add("completed");
} else {
step.classList.add("pending");
}
});
// Update stage indicator
const stageNames = {
paragraph: "Paragraph Reading",
sentence: "Sentence Practice",
word: "Word Focus",
};
this.currentStageEl.textContent =
stageNames[this.currentStage] || "Practice Complete";
}
isStageCompleted(stage) {
switch (stage) {
case "paragraph":
return this.currentStage !== "paragraph";
case "sentence":
return (
this.currentStage === "word" ||
this.currentStage === "complete"
);
case "word":
return this.currentStage === "complete";
default:
return false;
}
}
showParagraphStage() {
this.currentStage = "paragraph";
this.hideAllStages();
this.paragraphStage.style.display = "block";
this.updateProgress();
}
showSentenceStage() {
this.currentStage = "sentence";
this.hideAllStages();
this.sentenceStage.style.display = "block";
this.updateSentenceDisplay();
this.updateProgress();
}
showWordStage() {
this.currentStage = "word";
this.hideAllStages();
this.wordStage.style.display = "block";
this.updateWordDisplay();
this.updateProgress();
}
showCompleteStage() {
this.currentStage = "complete";
this.hideAllStages();
this.completeStage.style.display = "block";
this.updateCompletionStats();
this.updateProgress();
}
hideAllStages() {
this.paragraphStage.style.display = "none";
this.sentenceStage.style.display = "none";
this.wordStage.style.display = "none";
this.completeStage.style.display = "none";
}
// Paragraph stage methods
playParagraphAudio() {
this.simulateAudioPlayback(
this.paragraphAudioBtn,
"Playing story...",
"Listen to Story"
);
}
async recordParagraph() {
try {
const audioBlob = await this.recordAudio(this.paragraphRecordBtn);
if (audioBlob) {
// Show processing state
this.paragraphRecordBtn.innerHTML =
'<i class="fas fa-spinner fa-spin"></i><span>Processing...</span>';
this.paragraphRecordBtn.disabled = true;
// Generate sentences based on the recording
const success = await this.generateSentencesFromRecording(
audioBlob
);
if (success) {
this.paragraphFeedback.style.display = "block";
// Update feedback text
const feedbackTextElement = this.paragraphFeedback.querySelector('.feedback-text h4');
if (feedbackTextElement) {
feedbackTextElement.textContent = "Great Reading!";
}
const feedbackDescElement = this.paragraphFeedback.querySelector('.feedback-text p');
if (feedbackDescElement) {
feedbackDescElement.textContent = "Continue to Sentences";
}
this.starsEarned += 3;
} else {
// Provide more specific error message
console.error("❌ generateSentencesFromRecording failed");
alert(
"Sorry, there was an error processing your recording. Please check that the backend server is running at http://127.0.0.1:5001. Using default sentences."
);
}
// Reset button
this.paragraphRecordBtn.innerHTML =
'<i class="fas fa-microphone"></i><span>Try Again</span>';
this.paragraphRecordBtn.disabled = false;
}
} catch (error) {
console.error("Error recording paragraph:", error);
alert(
"Sorry, there was an error with the recording. Please try again."
);
}
}
moveToSentenceStage() {
if (this.sentences && this.sentences.length > 0) {
this.showSentenceStage();
} else {
alert(
"Please record the paragraph first to generate sentences for practice."
);
}
}
// Sentence stage methods
updateSentenceDisplay() {
this.sentenceCounter.textContent = `Sentence ${
this.currentSentenceIndex + 1
} of ${this.sentences.length}`;
this.currentSentenceEl.textContent =
this.sentences[this.currentSentenceIndex];
this.sentenceFeedback.style.display = "none";
// Update navigation buttons
this.prevSentence.style.display =
this.currentSentenceIndex > 0 ? "flex" : "none";
this.nextSentence.textContent =
this.currentSentenceIndex < this.sentences.length - 1
? "Next Sentence"
: "Continue to Words";
}
playSentenceAudio() {
this.simulateAudioPlayback(
this.sentenceAudioBtn,
"Playing sentence...",
"Listen"
);
}
async recordSentence() {
try {
const audioBlob = await this.recordAudio(this.sentenceRecordBtn);
if (audioBlob) {
// Show processing state
this.sentenceRecordBtn.innerHTML =
'<i class="fas fa-spinner fa-spin"></i><span>Processing...</span>';
this.sentenceRecordBtn.disabled = true;
// Generate words based on the recording
const success = await this.generateWordsFromRecording(
audioBlob
);
if (success) {
// Show feedback with updated text
this.sentenceFeedback.style.display = "block";
// Update feedback text to show "Perfect! Continue to words"
const feedbackTextElement = this.sentenceFeedback.querySelector('.feedback-text h4');
if (feedbackTextElement) {
feedbackTextElement.textContent = "Perfect!";
}
const feedbackDescElement = this.sentenceFeedback.querySelector('.feedback-text p');
if (feedbackDescElement) {
feedbackDescElement.textContent = "Continue to words";
}
this.starsEarned += 2;
} else {
alert(
"Sorry, there was an error processing your recording. Using default words."
);
}
// Reset button
this.sentenceRecordBtn.innerHTML =
'<i class="fas fa-microphone"></i><span>Try Again</span>';
this.sentenceRecordBtn.disabled = false;
}
} catch (error) {
console.error("Error recording sentence:", error);
alert(
"Sorry, there was an error with the recording. Please try again."
);
}
}
previousSentence() {
if (this.currentSentenceIndex > 0) {
this.currentSentenceIndex--;
this.updateSentenceDisplay();
}
}
nextSentenceHandler() {
if (this.currentSentenceIndex < this.sentences.length - 1) {
this.currentSentenceIndex++;
this.updateSentenceDisplay();
} else {
// Check if words have been generated from recording
if (
this.words &&
this.words.length > 0 &&
(this.words[0].word !== "explore" || this.words.length === 1)
) {
this.showWordStage();
} else {
alert(
"Please record a sentence first to generate words for practice."
);
}
}
}
// Word stage methods
updateWordDisplay() {
const word = this.words[this.currentWordIndex];
this.wordCounter.textContent = `Word ${this.currentWordIndex + 1} of ${
this.words.length
}`;
this.practiceWord.textContent = word.word;
this.wordPhonetics.textContent = word.phonetics;
// Update word info
const wordInfo = this.wordStage.querySelector(".word-info");
wordInfo.innerHTML = `
<div class="word-meaning">
<h4>Meaning:</h4>
<p>${word.meaning}</p>
</div>
<div class="word-context">
<h4>In the story:</h4>
<p>${word.context}</p>
</div>
`;
this.wordFeedback.style.display = "none";
// Update navigation buttons - for single word, always show "Finish Practice"
this.prevWord.style.display =
this.currentWordIndex > 0 ? "flex" : "none";
// If we only have one word (new API format), always show "Finish Practice"
if (this.words.length === 1) {
this.nextWord.textContent = "Finish Practice";
} else {
this.nextWord.textContent =
this.currentWordIndex < this.words.length - 1
? "Next Word"
: "Finish Practice";
}
}
showWordHint() {
const word = this.words[this.currentWordIndex];
this.hintBody.innerHTML = `
<p><strong>Hint:</strong> ${word.hint}</p>
<p><strong>Break it down:</strong> Try to sound out each part of the word slowly.</p>
<p><strong>Remember:</strong> Take your time and don't worry about being perfect!</p>
`;
this.hintModal.style.display = "flex";
}
hideHint() {
this.hintModal.style.display = "none";
}
playWordAudio() {
this.simulateAudioPlayback(
this.wordAudioBtn,
"Playing word...",
"Listen"
);
}
async recordWord() {
try {
const audioBlob = await this.recordAudio(this.wordRecordBtn);
if (audioBlob) {
// For word practice, we immediately show feedback without processing
// No API call needed for the final word stage
this.wordFeedback.style.display = "block";
// Update feedback text to show completion
const feedbackTextElement = this.wordFeedback.querySelector('.feedback-text h4');
if (feedbackTextElement) {
feedbackTextElement.textContent = "Excellent!";
}
const feedbackDescElement = this.wordFeedback.querySelector('.feedback-text p');
if (feedbackDescElement) {
feedbackDescElement.textContent = "Lesson completed!";
}
this.starsEarned += 1;
// Change the "Next Word" button to "Finish Practice" since this is the final stage
if (this.nextWord) {
this.nextWord.textContent = "Finish Practice";
}
}
} catch (error) {
console.error("Error recording word:", error);
alert(
"Sorry, there was an error with the recording. Please try again."
);
}
}
previousWord() {
if (this.currentWordIndex > 0) {
this.currentWordIndex--;
this.updateWordDisplay();
}
}
nextWordHandler() {
if (this.currentWordIndex < this.words.length - 1) {
this.currentWordIndex++;
this.updateWordDisplay();
} else {
this.showCompleteStage();
}
}
// Completion methods
updateCompletionStats() {
this.totalWords.textContent = this.words.length;
this.totalSentences.textContent = this.sentences.length;
this.starsEarnedEl.textContent = this.starsEarned;
}
restartPractice() {
this.currentStage = "paragraph";
this.currentSentenceIndex = 0;
this.currentWordIndex = 0;
this.starsEarned = 0;
this.showParagraphStage();
this.paragraphFeedback.style.display = "none";
this.updateProgress();
}
// Utility methods
async recordAudio(button) {
// Prevent multiple recordings by checking if already recording
if (this.isRecording) {
console.log("🚫 Recording already in progress, ignoring click");
return null;
}
try {
this.isRecording = true;
console.log("🎙️ Starting new recording session...");
// Request microphone access
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
// Create MediaRecorder
const mediaRecorder = new MediaRecorder(stream);
const audioChunks = [];
// Update button to show recording state
const originalContent = button.innerHTML;
button.innerHTML =
'<i class="fas fa-stop"></i><span>Recording... (Click to stop)</span>';
button.disabled = false;
// Collect audio data
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
console.log("📝 Audio data chunk received:", event.data.size, "bytes");
}
};
// Handle recording completion
return new Promise((resolve, reject) => {
let isRecordingStopped = false;
const cleanup = () => {
// Stop all tracks to release microphone