-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
1136 lines (1014 loc) · 44 KB
/
App.tsx
File metadata and controls
1136 lines (1014 loc) · 44 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
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { MainMenu } from './components/MainMenu';
import { TypingGame } from './components/TypingGame';
import { ResultsModal } from './components/ResultsModal';
import { RoadmapMinimap } from './components/RoadmapMinimap';
import { VirtualKeyboard } from './components/VirtualKeyboard';
import { Hand } from './components/FingerGuide';
import { TypingVisualizer } from './components/TypingVisualizer';
import { useKhmerInput, normalizeKhmerText } from './hooks/useKhmerInput';
import { generatePracticeText } from './services/geminiService';
import { KEYBOARD_LAYOUT } from './utils/keyboardData';
import { CHALLENGES } from './utils/challenges';
import {
saveScore, getUserLevel, saveUserLevel, saveLevelProgress,
getUserXP, addXP, getStreak, updateStreak,
hasCompletedOnboarding, setOnboardingCompleted
} from './services/storageService';
import { getLevelData, LevelData } from './utils/levels';
import { Language, GameStats, Finger, Challenge } from './types';
import {
RefreshCw, Globe, Keyboard, Trophy, AlertCircle, Play,
ArrowLeft, Clock, Map, Star, ChevronRight, Flame, Zap,
Sparkles, Wifi, WifiOff, Cloud, BookOpen, User, Settings
} from 'lucide-react';
import { SettingsProvider, useSettings } from './contexts/SettingsContext';
import { SettingsPanel } from './components/SettingsPanel';
import { ProfilePage } from './components/ProfilePage';
import { LeaderboardPage } from './components/LeaderboardPage';
import { TypingParticles } from './components/TypingParticles';
import { KoompiBird } from './components/KoompiBird';
import { BiomeBackground } from './components/BiomeBackground';
import { MilestoneCelebration } from './components/MilestoneCelebration';
import { ToastContainer, useToast } from './components/Toast';
import { Onboarding } from './components/Onboarding';
import { getBiomeForLevel } from './utils/biomes';
import { audioService, useAudio } from './services/audioService';
type AppMode = 'menu' | 'practice' | 'challenge-play' | 'adventure' | 'profile' | 'leaderboard';
// Translation Dictionary
const UI_TEXT = {
en: {
streak: "Streak",
days: "Days",
experience: "Experience",
online: "ONLINE",
offline: "OFFLINE",
language: "Language",
heroTitle: "KOOMPI",
heroSubtitle: "Typing",
heroDesc: "Master Khmer & English typing through gamified adventures. Build your streak and level up!",
adventureTitle: "Adventure Path",
adventureDesc: "Journey from novice to master.",
currentLevel: "Current Level",
practiceTitle: "Quick Practice",
practiceDesc: "Relaxed typing with AI texts.",
randomDrills: "Random drills",
startSession: "Start Session",
challengeTitle: "Arena",
wpm: "WPM",
acc: "ACC",
menu: "Menu",
nextLevel: "Next Level",
tryAgain: "Try Again",
finished: "Finished!",
challengeFailed: "Challenge Failed",
challengeCompleted: "Challenge Completed!",
levelComplete: "Level Complete!",
practiceSession: "Great practice session!",
speed: "Speed",
accuracy: "Accuracy",
bestCombo: "Best Combo",
poweredBy: "Powered by",
goal: "Goal",
needs: "Needs",
minSpeed: "Min Speed",
minAcc: "Min Acc",
timeLimit: "Time Limit",
learningPath: "Learning Path",
quickPlay: "Quick Play",
guest: "Guest",
level: "Level",
xp: "XP",
topPerformers: "Top Performers",
player: "Player",
premium: "Premium",
unlockFeatures: "Unlock unlimited hearts and mastery quizzes.",
learnMore: "Learn More",
easy: "Easy",
medium: "Medium",
hard: "Hard"
},
km: {
streak: "ការបន្ត",
days: "ថ្ងៃ",
experience: "បទពិសោធន៍",
online: "អនឡាញ",
offline: "ក្រៅបណ្តាញ",
language: "ភាសា",
heroTitle: "KOOMPI",
heroSubtitle: "Typing",
heroDesc: "រៀនវាយអក្សរខ្មែរ និងអង់គ្លេស តាមរយៈការផ្សងព្រេង។ បង្កើនសមត្ថភាពរបស់អ្នក!",
adventureTitle: "វគ្គផ្សងព្រេង",
adventureDesc: "ចាប់ផ្តើមពីកម្រិតដំបូង រហូតដល់ក្លាយជាអ្នកជំនាញ។",
currentLevel: "កម្រិតបច្ចុប្បន្ន",
practiceTitle: "ការអនុវត្តសេរី",
practiceDesc: "វាយអក្សរដោយសេរីជាមួយអត្ថបទ AI ។ ល្អបំផុតសម្រាប់ការហ្វឹកហាត់ប្រចាំថ្ងៃ។",
randomDrills: "លំហាត់ចៃដន្យ",
startSession: "ចាប់ផ្តើម",
challengeTitle: "សមរភូមិប្រកួត",
wpm: "ពាក្យ/នាទី",
acc: "ត្រឹមត្រូវ",
menu: "ម៉ឺនុយ",
nextLevel: "កម្រិតបន្ទាប់",
tryAgain: "ព្យាយាមម្តងទៀត",
finished: "បានបញ្ចប់!",
challengeFailed: "បរាជ័យ",
challengeCompleted: "ជោគជ័យ!",
levelComplete: "ឆ្លងវគ្គ!",
practiceSession: "ការអនុវត្តបានល្អ!",
speed: "ល្បឿន",
accuracy: "ភាពត្រឹមត្រូវ",
bestCombo: "បន្តល្អបំផុត",
poweredBy: "ឧបត្ថម្ភដោយ",
goal: "គោលដៅ",
needs: "តម្រូវការ",
minSpeed: "ល្បឿនអប្បបរមា",
minAcc: "ត្រឹមត្រូវអប្បបរមា",
timeLimit: "ពេលវេលា",
learningPath: "ផ្លូវសិក្សា",
quickPlay: "ការលេងរហ័ស",
guest: "ភ្ញៀវ",
level: "កម្រិត",
xp: "ពិន្ទុ",
topPerformers: "អ្នកលេងល្អបំផុត",
player: "អ្នកលេង",
premium: "សេវាពិសេស",
unlockFeatures: "ដោះស្រាយមុខងារពិសេស និងការលេងគ្មានដែនកំណត់។",
learnMore: "ស្វែងយល់បន្ថែម",
easy: "ងាយស្រួល",
medium: "មធ្យម",
hard: "ពិបាក"
}
};
// --- Animated Background Components ---
const BackgroundDecor = () => (
<div className="absolute inset-0 overflow-hidden pointer-events-none -z-0">
<div className="absolute top-[5%] left-[10%] animate-float text-yellow-300 drop-shadow-lg"><Star className="w-8 h-8 fill-yellow-300" /></div>
<div className="absolute top-[15%] right-[20%] animate-float-delayed text-pink-300 drop-shadow-md"><Star className="w-6 h-6 fill-pink-300" /></div>
<div className="absolute top-[10%] left-[-10%] opacity-90 animate-drift text-white/80"><Cloud className="w-32 h-20 fill-white" /></div>
<div className="absolute top-[20%] left-[40%] opacity-70 animate-drift-slow text-white/60" style={{ animationDelay: '5s' }}><Cloud className="w-24 h-16 fill-white" /></div>
<div className="absolute top-[15%] left-[80%] opacity-80 animate-drift text-white/70" style={{ animationDelay: '15s' }}><Cloud className="w-40 h-24 fill-white" /></div>
</div>
);
// Reusable Footer Component
const KoompiFooter: React.FC<{ t: typeof UI_TEXT.en, lang: Language }> = ({ t, lang }) => (
<footer className="w-full py-6 flex justify-center items-center gap-2 mt-auto relative z-10">
<span className={`text-xs font-bold text-slate-600 flex items-center gap-1 ${lang === 'km' ? 'font-khmer' : ''}`}>
{lang === 'km' ? 'បង្កើតដោយ' : 'Built with'} <span className="text-red-500">❤️</span> {lang === 'km' ? 'ដោយ' : 'by'}
</span>
<a href="https://koompi.com" target="_blank" rel="noopener noreferrer" className="flex items-center group transition-all hover:scale-105">
<img src="/icons/koompi.png" alt="KOOMPI" className="h-6 w-auto opacity-90 group-hover:opacity-100 transition-opacity drop-shadow-sm" />
</a>
<span className={`text-xs font-bold text-slate-600 ${lang === 'km' ? 'font-khmer' : ''}`}>
{lang === 'km' ? 'សម្រាប់អ្នកកសាងជំនាន់ក្រោយ។' : 'for next generation of builders.'}
</span>
</footer>
);
// Main App Component - wrapper with SettingsProvider
export const App: React.FC = () => {
return (
<SettingsProvider>
<AppContent />
</SettingsProvider>
);
};
// Inner App Content
const AppContent: React.FC = () => {
const [mode, setMode] = useState<AppMode>('menu');
const [activeChallenge, setActiveChallenge] = useState<Challenge | null>(null);
// Adventure Mode State
const [currentLevelData, setCurrentLevelData] = useState<LevelData | null>(null);
// Set Khmer as default language
const [lang, setLang] = useState<Language>('km');
const [targetText, setTargetText] = useState("Loading...");
const [userInput, setUserInput] = useState("");
const [pressedKeys, setPressedKeys] = useState<Set<string>>(new Set());
const [isShiftActive, setIsShiftActive] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isOnline, setIsOnline] = useState(typeof navigator !== 'undefined' ? navigator.onLine : true);
// IME Composition State
const [isComposing, setIsComposing] = useState(false);
const hiddenInputRef = useRef<HTMLInputElement>(null);
const lastProcessedLength = useRef(0);
// Gamification State
const [userXP, setUserXP] = useState(0);
const [userStreak, setUserStreak] = useState(0);
const [combo, setCombo] = useState(0);
const [maxCombo, setMaxCombo] = useState(0);
const [xpGained, setXpGained] = useState(0);
// New: Reactive typing state
const [lastTypedTime, setLastTypedTime] = useState(Date.now());
const [particleTrigger, setParticleTrigger] = useState<{ x: number, y: number } | null>(null);
const [showShake, setShowShake] = useState(false);
const [showErrorFlash, setShowErrorFlash] = useState(false);
const audio = useAudio();
// DOM Refs for Teleprompter
const textContainerRef = useRef<HTMLDivElement>(null);
const activeCharRef = useRef<HTMLSpanElement>(null);
const [challengeTimeLeft, setChallengeTimeLeft] = useState<number | null>(null);
const [stats, setStats] = useState<GameStats>({
wpm: 0,
accuracy: 100,
charsTyped: 0,
errors: 0,
startTime: null
});
const [isFinished, setIsFinished] = useState(false);
const [challengeResult, setChallengeResult] = useState<{ success: boolean, message: string } | null>(null);
const [settingsOpen, setSettingsOpen] = useState(false);
const [milestoneLevel, setMilestoneLevel] = useState<number | null>(null);
const [showOnboarding, setShowOnboarding] = useState(!hasCompletedOnboarding());
// Toast notifications
const { toasts, addToast, dismissToast } = useToast();
const t = UI_TEXT[lang];
// Normalize target text for comparison (important for Khmer)
const normalizedTarget = normalizeKhmerText(targetText);
useEffect(() => {
setUserXP(getUserXP());
setUserStreak(getStreak());
// Initialize audio service
audio.initialize();
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
useEffect(() => {
if (activeCharRef.current && textContainerRef.current) {
const container = textContainerRef.current;
const char = activeCharRef.current;
const containerWidth = container.offsetWidth;
const charLeft = char.offsetLeft;
const charWidth = char.offsetWidth;
const targetScrollLeft = charLeft - (containerWidth / 2) + (charWidth / 2);
container.scrollTo({ left: targetScrollLeft, behavior: 'smooth' });
}
}, [userInput, targetText, mode]);
// Focus hidden input when in game mode
useEffect(() => {
if (mode !== 'menu' && hiddenInputRef.current && !isFinished && !isLoading) {
hiddenInputRef.current.focus();
}
}, [mode, isFinished, isLoading, lang]);
// Re-focus on click anywhere
useEffect(() => {
if (mode === 'menu') return;
const handleClick = () => {
if (hiddenInputRef.current && !isFinished && !isLoading) {
hiddenInputRef.current.focus();
}
};
document.addEventListener('click', handleClick);
return () => document.removeEventListener('click', handleClick);
}, [mode, isFinished, isLoading]);
const startPractice = () => {
setMode('practice');
setActiveChallenge(null);
loadNewText('medium');
};
const startDrill = async () => {
setMode('practice');
setActiveChallenge(null);
setIsLoading(true);
setChallengeResult(null);
setCombo(0);
// Lazy load storage to get keys
import('./services/storageService').then(async ({ getTopProblemKeys }) => {
const keys = getTopProblemKeys(5);
import('./services/geminiService').then(async ({ generateDrillText }) => {
const text = await generateDrillText(keys, lang);
setTargetText(text);
setUserInput("");
setStats({ wpm: 0, accuracy: 100, charsTyped: 0, errors: 0, startTime: null });
setIsLoading(false);
// Focus hidden input
setTimeout(() => {
if (hiddenInputRef.current) hiddenInputRef.current.focus();
}, 100);
});
});
};
const startChallenge = (challenge: Challenge) => {
setActiveChallenge(challenge);
setMode('challenge-play');
if (challenge.id === 'c_khmer_scholar') setLang('km');
else if (challenge.difficulty === 'easy' && challenge.id !== 'c_khmer_scholar') setLang('en');
loadNewText(challenge.difficulty);
};
const startLevel = async (level: number) => {
setMode('adventure');
loadLevel(level);
};
const loadLevel = async (level: number, forceLang?: Language) => {
setIsLoading(true);
resetGameState();
const l = forceLang || lang;
const data = await getLevelData(level, l);
setCurrentLevelData(data);
setTargetText(data.text);
setIsLoading(false);
// Focus hidden input
setTimeout(() => hiddenInputRef.current?.focus(), 100);
};
const nextLevel = () => {
if (currentLevelData) {
const nextLvl = currentLevelData.level + 1;
saveUserLevel(lang, nextLvl);
loadLevel(nextLvl);
}
};
const returnToMenu = () => {
setMode('menu');
setIsFinished(false);
setUserInput("");
setChallengeResult(null);
setChallengeTimeLeft(null);
setCurrentLevelData(null);
audio.stopMusic();
};
const toggleLanguage = () => {
setLang(prev => {
const newLang = prev === 'en' ? 'km' : 'en';
// Reload content with new language immediately
if (mode === 'practice') {
const difficulty = activeChallenge ? activeChallenge.difficulty : 'medium';
loadNewText(difficulty, newLang);
} else if (mode === 'adventure' && currentLevelData) {
// Reload current level with new language
loadLevel(currentLevelData.level, newLang);
} else if (mode === 'challenge-play' && activeChallenge) {
// Some challenges are lang locked, but if not:
if (activeChallenge.id !== 'c_khmer_scholar') {
loadNewText(activeChallenge.difficulty, newLang);
}
}
return newLang;
});
};
const changeDifficulty = (diff: 'easy' | 'medium' | 'hard') => {
// Only applies to practice/challenge modes usually, but we can store it or re-generate text
if (mode === 'practice') {
loadNewText(diff);
}
// For adventure, difficulty is usually fixed by level, but maybe we can adjust criteria?
// For now, only practice mode supports explicit difficulty change for text generation.
};
const resetGameState = () => {
setIsFinished(false);
setChallengeResult(null);
setUserInput("");
setPressedKeys(new Set());
setStats({ wpm: 0, accuracy: 100, charsTyped: 0, errors: 0, startTime: null });
setCombo(0);
setMaxCombo(0);
setXpGained(0);
lastProcessedLength.current = 0;
if (hiddenInputRef.current) {
hiddenInputRef.current.value = '';
}
};
const loadNewText = async (difficulty: 'easy' | 'medium' | 'hard', forceLang?: Language) => {
setIsLoading(true);
resetGameState();
const l = forceLang || lang;
if (activeChallenge?.criteria.timeLimitSeconds) {
setChallengeTimeLeft(activeChallenge.criteria.timeLimitSeconds);
} else {
setChallengeTimeLeft(null);
}
const text = await generatePracticeText(l, difficulty);
setTargetText(text);
setIsLoading(false);
// Focus hidden input
setTimeout(() => hiddenInputRef.current?.focus(), 100);
};
// Handle character typed (from hidden input or direct keyboard)
const handleCharacterTyped = useCallback((charTyped: string) => {
if (isLoading || isFinished || mode === 'menu') return;
if (!stats.startTime) {
setStats(prev => ({ ...prev, startTime: Date.now() }));
}
const expectedChar = normalizedTarget[userInput.length];
if (!expectedChar) return;
if (charTyped === expectedChar) {
const newUserInput = userInput + charTyped;
setUserInput(newUserInput);
setStats(prev => ({ ...prev, charsTyped: prev.charsTyped + 1 }));
setLastTypedTime(Date.now());
// Play typing sound
audio.playKeystroke(true);
// Trigger particles on fast typing (WPM > 30)
if (stats.wpm > 30 && activeCharRef.current) {
const rect = activeCharRef.current.getBoundingClientRect();
setParticleTrigger({ x: rect.left + rect.width / 2, y: rect.top });
}
setCombo(c => {
const next = c + 1;
if (next > maxCombo) setMaxCombo(next);
// Music Intensity Logic
if (next === 1) audio.startMusic();
if (next === 10) {
audio.playJingle('combo');
audio.setMusicIntensity(1);
// Micro-shake at 10 combo
setShowShake(true);
setTimeout(() => setShowShake(false), 150);
}
if (next === 25) {
audio.playJingle('combo');
// Micro-shake at 25 combo
setShowShake(true);
setTimeout(() => setShowShake(false), 150);
}
if (next === 30) audio.setMusicIntensity(2);
// Trigger stronger shake at high combo
if (next === 50) {
audio.playJingle('streak');
setShowShake(true);
setTimeout(() => setShowShake(false), 300);
}
return next;
});
if (newUserInput.length === normalizedTarget.length) {
finishGame();
}
} else {
setStats(prev => ({ ...prev, errors: prev.errors + 1 }));
setCombo(0);
audio.playKeystroke(false);
// Visual error feedback
setShowErrorFlash(true);
setTimeout(() => setShowErrorFlash(false), 150);
if (activeChallenge?.criteria.minAccuracy === 100) {
setIsFinished(true);
setChallengeResult({ success: false, message: t.challengeFailed });
}
}
}, [userInput, normalizedTarget, isLoading, isFinished, stats.startTime, mode, activeChallenge, maxCombo, t]);
// Handle backspace
const handleBackspace = useCallback(() => {
if (isLoading || isFinished || mode === 'menu') return;
setUserInput(prev => prev.slice(0, -1));
setCombo(0);
lastProcessedLength.current = Math.max(0, lastProcessedLength.current - 1);
}, [isLoading, isFinished, mode]);
// IME Composition handlers
const handleCompositionStart = useCallback(() => {
setIsComposing(true);
}, []);
const handleCompositionEnd = useCallback((e: React.CompositionEvent<HTMLInputElement>) => {
setIsComposing(false);
// CRITICAL FIX: On Linux IBus/Fcitx, e.data is often empty.
// The composed character is already in the input field's value.
// We must read from the input element directly.
const inputElement = hiddenInputRef.current;
if (!inputElement) return;
// First try e.data (works on some platforms)
let composedData = e.data;
// Fallback: read directly from input value (essential for Linux IME)
if (!composedData || composedData.length === 0) {
const inputValue = inputElement.value;
// Get only the new characters since last processed
composedData = inputValue.slice(lastProcessedLength.current);
}
// Process each composed character
if (composedData && composedData.length > 0) {
for (const char of composedData) {
handleCharacterTyped(char);
}
}
// Clear input after processing
inputElement.value = '';
lastProcessedLength.current = 0;
}, [handleCharacterTyped]);
// Handle input from hidden text field
const handleHiddenInput = useCallback((e: React.FormEvent<HTMLInputElement>) => {
if (isLoading || isFinished || mode === 'menu') return;
if (isComposing) return; // Wait for composition to end
const newValue = e.currentTarget.value;
const newChars = newValue.slice(lastProcessedLength.current);
if (newChars.length > 0) {
for (const char of newChars) {
handleCharacterTyped(char);
}
}
lastProcessedLength.current = newValue.length;
// Clear input periodically to prevent overflow
if (newValue.length > 100) {
e.currentTarget.value = '';
lastProcessedLength.current = 0;
}
}, [isLoading, isFinished, mode, isComposing, handleCharacterTyped]);
// Handle special keys in hidden input
const handleHiddenKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
if (isLoading || isFinished || mode === 'menu') return;
if (isComposing) return;
if (e.key === 'Backspace') {
e.preventDefault();
handleBackspace();
if (hiddenInputRef.current) {
hiddenInputRef.current.value = '';
lastProcessedLength.current = 0;
}
return;
}
// Prevent default for space to avoid page scrolling
if (e.key === ' ') {
e.preventDefault();
handleCharacterTyped(' ');
if (hiddenInputRef.current) {
hiddenInputRef.current.value = '';
lastProcessedLength.current = 0;
}
return;
}
// Handle Enter
if (e.key === 'Enter') {
e.preventDefault();
handleCharacterTyped('\n');
if (hiddenInputRef.current) {
hiddenInputRef.current.value = '';
lastProcessedLength.current = 0;
}
return;
}
}, [isLoading, isFinished, mode, isComposing, handleBackspace, handleCharacterTyped]);
// Handle keyboard visual feedback
const handleKeyDown = useCallback((e: KeyboardEvent) => {
if (isLoading || isFinished || mode === 'menu') return;
setPressedKeys(prev => {
const newSet = new Set(prev);
newSet.add(e.code);
return newSet;
});
if (e.key === 'Shift') {
setIsShiftActive(true);
}
}, [isLoading, isFinished, mode]);
const handleKeyUp = useCallback((e: KeyboardEvent) => {
setPressedKeys(prev => {
const newSet = new Set(prev);
newSet.delete(e.code);
return newSet;
});
if (e.key === 'Shift') {
setIsShiftActive(false);
}
}, []);
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
return () => {
window.removeEventListener('keydown', handleKeyDown);
window.removeEventListener('keyup', handleKeyUp);
};
}, [handleKeyDown, handleKeyUp]);
useEffect(() => {
if (!stats.startTime || isFinished) return;
const interval = setInterval(() => {
const now = Date.now();
const timeElapsedMin = (now - stats.startTime!) / 60000;
const wpm = Math.round((stats.charsTyped / 5) / (timeElapsedMin || 0.001));
const accuracy = stats.charsTyped > 0
? Math.round(((stats.charsTyped - stats.errors) / stats.charsTyped) * 100)
: 100;
setStats(prev => ({ ...prev, wpm, accuracy: Math.max(0, accuracy) }));
if (activeChallenge?.criteria.timeLimitSeconds) {
const elapsedSec = (now - stats.startTime!) / 1000;
const left = Math.max(0, activeChallenge.criteria.timeLimitSeconds - elapsedSec);
setChallengeTimeLeft(Math.ceil(left));
if (left <= 0) finishGame();
}
}, 500);
return () => clearInterval(interval);
}, [stats.startTime, isFinished, activeChallenge, stats.charsTyped, stats.errors]);
const finishGame = () => {
setIsFinished(true);
const baseXP = Math.floor(stats.charsTyped * 0.5);
const accBonus = stats.accuracy >= 95 ? 50 : 0;
const wpmBonus = stats.wpm >= 40 ? 50 : 0;
const totalXP = baseXP + accBonus + wpmBonus;
const newXP = addXP(totalXP);
const prevStreak = userStreak;
const newStreak = updateStreak();
setXpGained(totalXP);
setUserXP(newXP);
setUserStreak(newStreak);
// Show streak toast if streak was extended
if (newStreak > prevStreak) {
const streakMessage = lang === 'km'
? `ថ្ងៃទី ${newStreak} នៃការបន្ត! បន្តទៀត!`
: `Day ${newStreak} Streak! Keep it up!`;
addToast(streakMessage, 'streak', 5000);
}
if (mode === 'adventure' && currentLevelData) {
const { minAccuracy, minWpm } = currentLevelData.criteria;
// Check if requirements are met
const accMet = stats.accuracy >= minAccuracy;
const wpmMet = stats.wpm >= minWpm;
// Grace margin: Allow passing if VERY close (within 5% accuracy or 2 WPM)
// This prevents frustration from barely missing the mark
const accClose = stats.accuracy >= minAccuracy - 5;
const wpmClose = stats.wpm >= minWpm - 2;
// Success conditions:
// 1. Both requirements met = Full success
// 2. Both requirements close = Grace pass (1 star, encouraging message)
// 3. One met, one close = Grace pass
const fullSuccess = accMet && wpmMet;
const gracePass = (accClose && wpmClose) && !fullSuccess;
if (fullSuccess || gracePass) {
// Calculate Stars
let stars = 1; // Base star for passing
if (fullSuccess) {
// Bonus stars only for full success
if (stats.accuracy >= minAccuracy + 10) stars++; // Exceeded accuracy by 10%+
if (stats.wpm >= minWpm + 5) stars++; // Exceeded WPM by 5+
}
// Grace pass always gets 1 star (no bonus)
// Cap at 3
if (stars > 3) stars = 3;
saveLevelProgress(lang, currentLevelData.level, stars, totalXP);
if (gracePass) {
// Encouraging message for close attempts
const closeMsg = lang === 'km' ? 'ជិតបានហើយ! សូមបន្ត!' : 'Close enough! Keep going!';
setChallengeResult({ success: true, message: closeMsg });
} else {
setChallengeResult({ success: true, message: t.levelComplete });
}
audio.playJingle('level');
// Check for milestone levels (10, 50, 100, 150)
const completedLevel = currentLevelData.level + 1; // level is 0-indexed
const milestones = [10, 50, 100, 150];
if (milestones.includes(completedLevel)) {
// Delay milestone celebration to show after results modal
setTimeout(() => setMilestoneLevel(completedLevel), 1500);
}
} else {
// Build helpful failure message
const reasons: string[] = [];
if (!accClose) {
const diff = minAccuracy - stats.accuracy;
const msg = lang === 'km'
? `ត្រូវការ ${diff.toFixed(0)}% ទៀតសម្រាប់ភាពត្រឹមត្រូវ`
: `Need ${diff.toFixed(0)}% more accuracy`;
reasons.push(msg);
}
if (!wpmClose) {
const diff = minWpm - stats.wpm;
const msg = lang === 'km'
? `ត្រូវការ ${diff.toFixed(0)} WPM ទៀត`
: `Need ${diff.toFixed(0)} more WPM`;
reasons.push(msg);
}
setChallengeResult({ success: false, message: reasons.join('. ') });
}
return;
}
if (activeChallenge) {
let success = true;
let reasons: string[] = [];
if (activeChallenge.criteria.minWpm && stats.wpm < activeChallenge.criteria.minWpm) {
success = false;
reasons.push(`${t.speed} < ${activeChallenge.criteria.minWpm} ${t.wpm}`);
}
if (activeChallenge.criteria.minAccuracy && stats.accuracy < activeChallenge.criteria.minAccuracy) {
success = false;
reasons.push(`${t.accuracy} < ${activeChallenge.criteria.minAccuracy}%`);
}
if (success) {
setChallengeResult({ success: true, message: t.challengeCompleted });
saveScore(activeChallenge.id, stats.wpm, stats.accuracy);
} else {
setChallengeResult({ success: false, message: reasons.join('. ') });
}
return;
}
setChallengeResult({ success: true, message: t.practiceSession });
};
const getActiveFinger = (): Finger | null => {
if (isFinished) return null;
const nextChar = normalizedTarget[userInput.length];
if (!nextChar) return null;
for (const row of KEYBOARD_LAYOUT) {
for (const key of row) {
if (key[lang].normal === nextChar || key[lang].shift === nextChar) {
return key.finger;
}
}
}
if (nextChar === '\n') return 'R-pinky';
return null;
};
const activeFinger = getActiveFinger();
const progressPercent = Math.min(100, Math.max(0, (userInput.length / (normalizedTarget.length || 1)) * 100));
// Handle onboarding completion
const handleOnboardingComplete = () => {
setOnboardingCompleted();
setShowOnboarding(false);
};
// VIEW: ONBOARDING (first-time users)
if (showOnboarding) {
return <Onboarding lang={lang} onComplete={handleOnboardingComplete} />;
}
// VIEW: MAIN MENU
if (mode === 'menu') {
return (
<>
<MainMenu
lang={lang}
userXP={userXP}
userStreak={userStreak}
currentLevel={getUserLevel(lang)}
t={t}
onToggleLang={() => setLang(prev => prev === 'en' ? 'km' : 'en')}
onStartPractice={startPractice}
onStartDrill={startDrill}
onStartChallenge={startChallenge}
onSelectLevel={startLevel}
onOpenSettings={() => setSettingsOpen(true)}
onOpenProfile={() => setMode('profile')}
onOpenLeaderboard={() => setMode('leaderboard')}
/>
<SettingsPanel isOpen={settingsOpen} onClose={() => setSettingsOpen(false)} lang={lang} />
</>
);
}
if (mode === 'profile') {
return (
<div className={`min-h-screen bg-slate-50 text-slate-800 flex flex-col font-sans overflow-hidden ${lang === 'km' ? 'font-khmer' : ''}`}>
<ProfilePage lang={lang} onBack={() => setMode('menu')} />
</div>
);
}
if (mode === 'leaderboard') {
return (
<div className={`min-h-screen text-slate-800 flex flex-col font-sans overflow-hidden ${lang === 'km' ? 'font-khmer' : ''}`}>
<LeaderboardPage lang={lang} onBack={() => setMode('menu')} />
</div>
);
}
// Get current biome based on level
const currentBiome = currentLevelData ? getBiomeForLevel(currentLevelData.level) : 'sky';
// View: Game
return (
<>
<div className={`min-h-screen text-slate-800 flex flex-col font-sans overflow-hidden ${lang === 'km' ? 'font-khmer' : ''} relative ${showShake ? 'animate-shake' : ''}`}>
{/* Dynamic Biome Background */}
<BiomeBackground biome={currentBiome} />
{/* Error Flash Overlay */}
{showErrorFlash && (
<div className="fixed inset-0 bg-red-500/15 pointer-events-none z-[60] animate-error-flash" />
)}
{/* Particle Effects */}
<TypingParticles
active={!isFinished && !isLoading && stats.wpm > 30}
intensity={stats.wpm > 60 ? 'high' : stats.wpm > 40 ? 'medium' : 'low'}
theme={currentBiome}
triggerX={particleTrigger?.x}
triggerY={particleTrigger?.y}
combo={combo}
/>
{/* Koompi Bird Mascot */}
<div className="fixed bottom-4 left-4 z-40 hidden sm:block">
<KoompiBird
wpm={stats.wpm}
isTyping={!isFinished && userInput.length > 0}
isFinished={isFinished && challengeResult?.success === true}
lastTypedTime={lastTypedTime}
combo={combo}
hasError={showErrorFlash}
/>
</div>
{/* Hidden Input for IME Support - Critical for Khmer on Linux */}
<input
ref={hiddenInputRef}
type="text"
className="absolute opacity-0 pointer-events-none"
style={{ position: 'fixed', top: -1000, left: -1000, width: 1, height: 1 }}
onInput={handleHiddenInput}
onKeyDown={handleHiddenKeyDown}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
aria-label="Typing input"
tabIndex={0}
/>
{/* Full Screen Result Modal */}
{isFinished && (
<ResultsModal
stats={stats}
maxCombo={maxCombo}
xpGained={xpGained}
userStreak={userStreak}
challengeResult={challengeResult}
mode={mode}
activeChallenge={activeChallenge}
currentLevelData={currentLevelData}
lang={lang}
t={t}
onReturnToMenu={returnToMenu}
onNextLevel={nextLevel}
onTryAgain={() => {
if (mode === 'adventure' && currentLevelData) {
loadLevel(currentLevelData.level);
} else {
loadNewText(activeChallenge ? activeChallenge.difficulty : 'medium');
}
}}
/>
)}
{/* Milestone Celebration Modal */}
{milestoneLevel && (
<MilestoneCelebration
level={milestoneLevel}
lang={lang}
onClose={() => setMilestoneLevel(null)}
/>
)}
{/* Toast Notifications */}
<ToastContainer toasts={toasts} onDismiss={dismissToast} />
<header className="flex justify-between items-center p-2 sm:p-4 sticky top-0 z-50">
<div className="flex items-center gap-2 sm:gap-4">
<button onClick={returnToMenu} className="p-1.5 sm:p-2 hover:bg-white rounded-full transition-colors border border-transparent hover:border-slate-200 hover:shadow-sm" title={t.menu}>
<ArrowLeft className="w-4 h-4 sm:w-5 sm:h-5 text-slate-600" />
</button>
{/* Language Toggle In-Game */}
<button
onClick={toggleLanguage}
className="flex items-center gap-1 px-2 py-1 bg-white/50 hover:bg-white rounded-lg border border-transparent hover:border-slate-200 transition-all text-xs font-bold text-slate-600 uppercase"
title={t.language}
>
<Globe className="w-3 h-3" />
{lang}
</button>
<div>
<h1 className="text-sm sm:text-lg font-bold flex items-center gap-1.5 sm:gap-2 text-slate-800 font-khmer">
{mode === 'adventure' && currentLevelData ? (
<>
<span className="text-blue-500"><Map className="w-3 h-3 sm:w-4 sm:h-4" /></span>
<span className="truncate max-w-[120px] sm:max-w-none">{currentLevelData.title}</span>
</>
) : activeChallenge ? (
<>
<span className="text-yellow-500"><Trophy className="w-3 h-3 sm:w-4 sm:h-4" /></span>
<span className="truncate max-w-[120px] sm:max-w-none">{lang === 'km' && activeChallenge.title_km ? activeChallenge.title_km : activeChallenge.title}</span>
</>
) : (
<>
<span className="text-emerald-500"><Play className="w-3 h-3 sm:w-4 sm:h-4" /></span>
{t.practiceTitle}
</>
)}
</h1>
</div>
</div>
<div className="flex items-center gap-2 sm:gap-4 md:gap-6">
{/* Visualizer - hide on small screens */}
{!isFinished && (
<div className="hidden sm:block mr-1 sm:mr-2 transform hover:scale-110 transition-transform duration-300 drop-shadow-md">
<TypingVisualizer progress={progressPercent} wpm={stats.wpm} accuracy={stats.accuracy} />
</div>
)}
{/* Combo Counter */}
{combo > 5 && !isFinished && (
<div className="animate-bounce flex items-center gap-1 text-orange-500 font-black italic text-lg sm:text-2xl drop-shadow-sm">
<Flame className="w-4 h-4 sm:w-6 sm:h-6 fill-orange-500 text-orange-600 animate-pulse" />
{combo}x
</div>
)}
{/* Timer */}
{challengeTimeLeft !== null && (
<div className={`flex items-center gap-1 sm:gap-2 font-mono text-base sm:text-xl font-bold ${challengeTimeLeft < 10 ? 'text-rose-500 animate-pulse' : 'text-slate-700'}`}>
<Clock className="w-4 h-4 sm:w-5 sm:h-5" />
{challengeTimeLeft}s
</div>
)}