-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
365 lines (316 loc) · 10.6 KB
/
app.js
File metadata and controls
365 lines (316 loc) · 10.6 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
/**
* app.js
* Main application orchestrator
*
* Central coordinator for game lifecycle, phase management, and module integration.
*/
// Import all modules
import { evaluateGuess, getFeedback, validateGuessInput, calculateFSRSGrade } from './game-engine.js';
import { getFromLocalStorage, setInLocalStorage } from './storage-manager.js';
import { getSupabaseClient } from './supabase-client.js';
import { initializeAuthFlow, isAuthenticated, getCurrentUser, setupAuthListeners } from './auth-manager.js';
import { initializeSpeechSynthesis, speakWord, repeatWord } from './tts-handler.js';
import { loadLessons, getAvailableLessons, buildLessonSession, buildReviewSession } from './lesson-manager.js';
import { initializeFSRS, createFSRSCard, updateFSRSCard, getFSRSCardByWord } from './fsrs-manager.js';
import { showWelcomeScreen, showGameScreen, updateProgressCounter } from './ui-renderer.js';
import { showErrorToast } from './error-handler.js';
// Game state
let gameState = {
currentLesson: null,
currentWords: [],
currentWordIndex: 0,
currentWord: null,
currentSentence: null,
attemptCount: 0,
gameStarted: false,
sessionStartTime: null
};
/**
* Initialize the application
* @returns {Promise<boolean>} True if initialization successful
*/
export async function initialize() {
console.log('[APP] ================================================');
console.log('[APP] Initializing Spelldle Application');
console.log('[APP] ================================================');
try {
// Step 1: Initialize core utilities
console.log('[APP] Step 1: Initializing core utilities...');
const supabase = getSupabaseClient();
console.log('[APP] ✓ Supabase client ready');
const storage = getFromLocalStorage('test', null);
console.log('[APP] ✓ Storage manager ready');
// Step 2: Initialize TTS
console.log('[APP] Step 2: Initializing text-to-speech...');
const ttsReady = initializeSpeechSynthesis();
console.log(`[APP] ${ttsReady ? '✓' : '✗'} TTS initialized`);
// Step 3: Initialize Auth
console.log('[APP] Step 3: Initializing authentication...');
const authReady = await initializeAuthFlow();
console.log(`[APP] ${authReady ? '✓' : '✗'} Auth ready`);
setupAuthListeners();
// Step 4: Initialize FSRS
console.log('[APP] Step 4: Initializing spaced repetition...');
const fsrsReady = await initializeFSRS();
console.log(`[APP] ${fsrsReady ? '✓' : '✗'} FSRS ready`);
// Step 5: Load lessons
console.log('[APP] Step 5: Loading lessons...');
try {
await loadLessons();
const lessons = getAvailableLessons();
console.log(`[APP] ✓ Loaded ${lessons.length} lessons:`, lessons);
populateLessonDropdown(lessons);
} catch (error) {
console.warn('[APP] Could not load external lessons, using fallback', error);
}
// Step 6: Setup UI
console.log('[APP] Step 6: Setting up user interface...');
setupGameUI();
showWelcomeScreen();
console.log('[APP] ✓ UI ready');
console.log('[APP] ================================================');
console.log('[APP] ✓ Application initialized successfully!');
console.log('[APP] ================================================');
return true;
} catch (error) {
console.error('[APP] ✗ Initialization failed:', error);
showErrorToast('Application initialization failed', 'error');
return false;
}
}
/**
* Setup game UI event listeners
*/
function setupGameUI() {
try {
// Lesson selection
const startButton = document.getElementById('startLessonButton');
if (startButton) {
startButton.onclick = startSelectedLesson;
}
// Guess input handling
const guessInput = document.getElementById('guessInput');
if (guessInput) {
guessInput.onkeydown = handleInputKeydown;
guessInput.oninput = handleInputChange;
}
// Submit button
const submitButton = document.getElementById('submitButton');
if (submitButton) {
submitButton.onclick = submitGuess;
}
// Repeat button
const repeatButton = document.getElementById('repeatButton');
if (repeatButton) {
repeatButton.onclick = handleRepeatWord;
}
// Play again button
const playAgainButton = document.querySelector('.play-again-button');
if (playAgainButton) {
playAgainButton.onclick = playAgain;
}
console.log('[APP] Game UI event listeners attached');
} catch (error) {
console.error('[APP] Failed to setup game UI:', error);
}
}
/**
* Populate lesson dropdown with available lessons
* @param {Array} lessons - Array of lesson names
*/
function populateLessonDropdown(lessons) {
try {
const dropdown = document.getElementById('lessonDropdown');
if (!dropdown) {
console.warn('[APP] Lesson dropdown not found in DOM');
return;
}
// Clear existing options except placeholder
dropdown.innerHTML = '<option value="">Select a lesson...</option>';
// Add lesson options
lessons.forEach(lesson => {
const option = document.createElement('option');
option.value = lesson;
option.textContent = lesson;
dropdown.appendChild(option);
});
console.log(`[APP] Populated dropdown with ${lessons.length} lessons`);
} catch (error) {
console.error('[APP] Failed to populate lesson dropdown:', error);
}
}
/**
* Start selected lesson
*/
async function startSelectedLesson() {
try {
const dropdown = document.getElementById('lessonDropdown');
if (!dropdown || !dropdown.value) {
showErrorToast('Please select a lesson', 'warning');
return;
}
console.log(`[APP] Starting lesson: ${dropdown.value}`);
// Build session — include due review words when authenticated
const session = isAuthenticated()
? await buildReviewSession(getCurrentUser().id, dropdown.value)
: await buildLessonSession(dropdown.value);
gameState.currentLesson = dropdown.value;
gameState.currentWords = session.words;
gameState.currentWordIndex = 0;
gameState.attemptCount = 0;
gameState.gameStarted = true;
gameState.sessionStartTime = Date.now();
// Show game screen
showGameScreen();
updateProgressCounter(1, gameState.currentWords.length);
// Load first word
loadNextWord();
} catch (error) {
console.error('[APP] Failed to start lesson:', error);
showErrorToast('Failed to start lesson', 'error');
}
}
/**
* Load next word
*/
function loadNextWord() {
try {
if (gameState.currentWordIndex >= gameState.currentWords.length) {
// Lesson complete
completeLesson();
return;
}
const wordData = gameState.currentWords[gameState.currentWordIndex];
gameState.currentWord = wordData.word;
gameState.currentSentence = wordData.sentence;
gameState.attemptCount = 0;
console.log(`[APP] Loaded word: "${gameState.currentWord}"`);
// Speak the word
speakWord(gameState.currentWord, gameState.currentSentence);
} catch (error) {
console.error('[APP] Failed to load next word:', error);
showErrorToast('Error loading word', 'error');
}
}
/**
* Handle input keydown (Enter to submit)
*/
function handleInputKeydown(event) {
if (event.key === 'Enter') {
submitGuess();
}
}
/**
* Handle input change
*/
function handleInputChange(event) {
// Optional: add input validation here
}
/**
* Submit current guess
*/
async function submitGuess() {
try {
const guessInput = document.getElementById('guessInput');
if (!guessInput) return;
const guess = guessInput.value.trim();
// Validate input
const validation = validateGuessInput(guess);
if (!validation.valid) {
showErrorToast(validation.message, 'warning');
return;
}
console.log(`[APP] Submitted guess: "${guess}" for word: "${gameState.currentWord}"`);
gameState.attemptCount++;
// Evaluate guess
const isCorrect = evaluateGuess(guess, gameState.currentWord);
if (isCorrect) {
// Record FSRS grade non-blocking (game continues regardless of outcome)
const grade = calculateFSRSGrade(gameState.attemptCount);
recordFSRSAttempt(gameState.currentWord, gameState.currentLesson, grade)
.catch(err => console.warn('[APP] FSRS record failed silently:', err));
showErrorToast('Correct!', 'success', 1000);
gameState.currentWordIndex++;
setTimeout(loadNextWord, 500);
} else {
// Incorrect - show clue phase
const feedback = getFeedback(guess, gameState.currentWord);
console.log('[APP] Feedback:', feedback);
// TODO: Show clue phase UI
showErrorToast('Incorrect - try again', 'warning');
}
guessInput.value = '';
} catch (error) {
console.error('[APP] Failed to submit guess:', error);
showErrorToast('Error submitting guess', 'error');
}
}
/**
* Handle repeat word button
*/
async function handleRepeatWord() {
try {
if (gameState.currentWord && gameState.currentSentence) {
await repeatWord(gameState.currentWord, gameState.currentSentence);
}
} catch (error) {
console.error('[APP] Failed to repeat word:', error);
}
}
/**
* Play again (reset lesson)
*/
function playAgain() {
try {
gameState.gameStarted = false;
gameState.currentWords = [];
gameState.currentWordIndex = 0;
showWelcomeScreen();
console.log('[APP] Game reset');
} catch (error) {
console.error('[APP] Failed to play again:', error);
}
}
/**
* Record FSRS attempt for a completed word
* Creates the card on first attempt, then updates it with the computed grade.
* Runs silently — failures do not interrupt gameplay.
* @param {string} word - The word that was practiced
* @param {string} lessonName - The lesson the word belongs to
* @param {number} grade - FSRS grade (1=Again, 2=Hard, 3=Good, 4=Easy)
*/
async function recordFSRSAttempt(word, lessonName, grade) {
if (!isAuthenticated()) return;
try {
let card = await getFSRSCardByWord(word, lessonName);
if (!card) {
card = await createFSRSCard(word, lessonName);
}
if (card) {
await updateFSRSCard(card.id, grade);
}
} catch (error) {
console.error('[APP] Failed to record FSRS attempt:', error);
}
}
/**
* Complete lesson
*/
function completeLesson() {
try {
console.log('[APP] Lesson completed!');
const duration = Math.floor((Date.now() - gameState.sessionStartTime) / 1000);
const stats = {
lesson: gameState.currentLesson,
wordsCount: gameState.currentWords.length,
duration: duration
};
console.log('[APP] Lesson stats:', stats);
showErrorToast('Lesson complete!', 'success', 2000);
} catch (error) {
console.error('[APP] Failed to complete lesson:', error);
}
}
export default {
initialize
};