srdusr
aboutsummaryrefslogtreecommitdiffstats
path: root/web/src/app.js
blob: cc4e0d2d9c7d9923cf0b048b15ac89f4fdc591e9 (plain) (blame)
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
import { renderMainMenu } from './screens/mainMenu.js';
import { renderTypingGame } from './screens/typingGame.js';
import { renderEndScreen } from './screens/endScreen.js';
import { renderPassiveMode } from './screens/passiveMode.js';
import { renderStatsScreen } from './screens/statsScreen.js';
import { renderPlaceholderScreen } from './screens/placeholderScreen.js';
import { renderAccountScreen } from './screens/accountScreen.js';
import { renderLeaderboardScreen } from './screens/leaderboardScreen.js';
import { renderFriendsScreen } from './screens/friendsScreen.js';
import { renderMultiplayerScreen } from './screens/multiplayerScreen.js';
import { renderLyricsScreen } from './screens/lyricsScreen.js';
import { renderPublicProfileScreen } from './screens/publicProfileScreen.js';
import { renderStoreScreen } from './screens/storeScreen.js';
import { createGame, freeGame } from './game.js';
import { getSettings } from './settings.js';
import { generateWordStream, generateWeakKeyStream, wordCountForDuration } from './wordGenerator.js';
import { getWeakChars } from './keyStats.js';

const FALLBACK_TEXT = { category: 'general', content: 'The quick brown fox jumps over the lazy dog.', attribution: 'Traditional pangram' };

function uniqueCategories(items) {
    const set = new Set();
    for (const t of items) if (t.category) set.add(t.category);
    return Array.from(set).sort();
}

function pickRandom(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

function getRandomTextItem(items, category) {
    const pool = category && category !== 'random' ? items.filter(t => t.category === category) : items;
    return pool.length ? pickRandom(pool) : FALLBACK_TEXT;
}

export function startApp(root, localTexts) {
    let allTexts = localTexts;
    let categories = uniqueCategories(localTexts);
    let selectedCategory = localStorage.getItem('typerpunk:last_mode') || 'time';
    let customText = null; // { name, chunks: [{content, time}], language, timed }
    let session = { type: 'random', customIndex: 0 };
    let game = null;
    let cleanupScreen = null;

    const onlineUrl = window.TYPERPUNK_TEXTS_URL;
    if (onlineUrl) {
        fetch(onlineUrl, { cache: 'no-store' })
            .then(res => (res.ok ? res.json() : null))
            .then(data => {
                if (Array.isArray(data)) {
                    allTexts = data;
                    categories = uniqueCategories(data);
                }
            })
            .catch(() => {});
    }

    function teardown() {
        if (cleanupScreen) {
            cleanupScreen();
            cleanupScreen = null;
        }
    }

    // Which screen is showing, and whether leaving it costs the user
    // something. Escape is a global "get me out of here", but walking out of a
    // live race drops you from it for everyone else in the room too, so that
    // one case asks first.
    let currentScreenName = 'menu';
    let escapeIsCostly = () => false;

    function setScreen(name, costly = () => false) {
        currentScreenName = name;
        escapeIsCostly = costly;
    }

    function handleGlobalEscape(e) {
        if (e.key !== 'Escape') return;
        // Let an open popover close itself first - one Escape should not both
        // dismiss a menu and navigate away from the screen behind it.
        const openPopover = document.querySelector(
            '.mode-popover:not([hidden]), .rail-settings-panel:not([hidden]), .lang-popover:not([hidden]), .theme-gallery-popover:not([hidden])');
        if (openPopover) {
            openPopover.hidden = true;
            return;
        }
        if (currentScreenName === 'menu') return;
        if (escapeIsCostly() && !window.confirm('Leave the race? Your opponents will see you drop out.')) return;
        showMainMenu();
    }
    document.addEventListener('keydown', handleGlobalEscape);

    function showMainMenu() {
        teardown();
        freeGame(game);
        game = null;
        setScreen('menu');
        cleanupScreen = renderMainMenu(root, {
            onStartGame: () => { session = { type: 'random', customIndex: 0 }; startGame(); },
            categories,
            selectedCategory,
            onSelectCategory: cat => {
                selectedCategory = cat;
                try { localStorage.setItem('typerpunk:last_mode', cat); } catch {}
                showMainMenu();
            },
            // Picking a mode from the Single Player menu starts that mode --
            // choosing what to type and starting it are one action now, not a
            // selection followed by a second click on the same button.
            onPickAndStart: cat => {
                selectedCategory = cat;
                try { localStorage.setItem('typerpunk:last_mode', cat); } catch {}
                session = { type: 'random', customIndex: 0 };
                startGame();
            },
            customText,
            onLoadCustom: loaded => {
                customText = loaded;
                showMainMenu();
            },
            onClearCustom: () => {
                customText = null;
                showMainMenu();
            },
            onStartCustom: () => {
                session = { type: 'custom', customIndex: 0 };
                startGame();
            },
            onStartPassive: startPassive,
            onShowStats: showStats,
            onShowPlaceholder: showPlaceholder,
            onShowAccount: showAccount,
            onShowLeaderboard: showLeaderboard,
            onShowFriends: showFriends,
            onShowMultiplayer: showMultiplayer,
            onShowStore: showStore,
            onShowLyrics: showLyrics,
            onSimulateTest: simulateTest,
        });
    }

    // Dev-only shortcut: jumps straight to the end screen with synthetic
    // results, no actual typing needed - for iterating on the end screen's
    // design without retyping a full passage every time.
    function simulateTest() {
        teardown();
        const text = 'The quick brown fox jumps over the lazy dog while typing very quickly today, right now, in this exact moment.';
        const wpm = 70 + Math.random() * 90;
        const accuracy = 85 + Math.random() * 15;
        const time = 8 + Math.random() * 15;
        const charTimings = [];
        const keypressHistory = [];
        for (let i = 0; i < text.length; i++) {
            const t = (i / text.length) * time;
            const isCorrect = Math.random() * 100 < accuracy;
            charTimings.push({ time: t, isCorrect, index: i });
            keypressHistory.push({ time: t, isCorrect, index: i });
        }
        const incorrectChars = charTimings.filter(c => !c.isCorrect).length;
        const stats = {
            wpm, rawWpm: wpm * 1.08, accuracy, time,
            correctChars: text.length - incorrectChars, incorrectChars, totalChars: text.length,
            currentStreak: 0, bestStreak: Math.floor(text.length / 3),
        };
        showEndScreen({ stats, text, userInput: text, charTimings, keypressHistory, modeKey: null });
    }

    function showStats() {
        teardown();
        setScreen('stats');
        cleanupScreen = renderStatsScreen(root, { onBack: showMainMenu, onShowPlaceholder: showPlaceholder, onShowAccount: showAccount, onShowLeaderboard: showLeaderboard, onShowFriends: showFriends, onShowMultiplayer: showMultiplayer, onShowStore: showStore });
    }

    function showPlaceholder(title, description) {
        teardown();
        setScreen('placeholder');
        cleanupScreen = renderPlaceholderScreen(root, { title, description, onBack: showMainMenu, onShowStats: showStats, onShowPlaceholder: showPlaceholder, onShowAccount: showAccount, onShowLeaderboard: showLeaderboard, onShowFriends: showFriends, onShowMultiplayer: showMultiplayer, onShowStore: showStore });
    }

    function showAccount() {
        teardown();
        setScreen('account');
        cleanupScreen = renderAccountScreen(root, { onBack: showMainMenu, onShowStats: showStats, onShowPlaceholder: showPlaceholder, onShowLeaderboard: showLeaderboard, onShowFriends: showFriends, onShowMultiplayer: showMultiplayer, onShowStore: showStore });
    }

    function showLeaderboard() {
        teardown();
        setScreen('leaderboard');
        cleanupScreen = renderLeaderboardScreen(root, { onBack: showMainMenu, onShowPublicProfile: showPublicProfile, onShowStats: showStats, onShowPlaceholder: showPlaceholder, onShowAccount: showAccount, onShowFriends: showFriends, onShowMultiplayer: showMultiplayer, onShowStore: showStore });
    }

    function showPublicProfile(username) {
        teardown();
        setScreen('profile');
        cleanupScreen = renderPublicProfileScreen(root, { username, onBack: showLeaderboard, onShowStats: showStats, onShowPlaceholder: showPlaceholder, onShowAccount: showAccount, onShowLeaderboard: showLeaderboard, onShowFriends: showFriends, onShowMultiplayer: showMultiplayer, onShowStore: showStore });
    }

    function showFriends() {
        teardown();
        setScreen('friends');
        cleanupScreen = renderFriendsScreen(root, { onBack: showMainMenu, onShowStats: showStats, onShowPlaceholder: showPlaceholder, onShowAccount: showAccount, onShowLeaderboard: showLeaderboard, onShowMultiplayer: showMultiplayer, onShowStore: showStore });
    }

    function showMultiplayer() {
        teardown();
        setScreen('multiplayer', () => !!document.querySelector('.mp-opponents'));
        cleanupScreen = renderMultiplayerScreen(root, { onBack: showMainMenu, onFinish: showEndScreen, onShowStats: showStats, onShowPlaceholder: showPlaceholder, onShowAccount: showAccount, onShowLeaderboard: showLeaderboard, onShowFriends: showFriends, onShowStore: showStore });
    }

    function showStore() {
        teardown();
        setScreen('store');
        cleanupScreen = renderStoreScreen(root, { onBack: showMainMenu, onShowStats: showStats, onShowPlaceholder: showPlaceholder, onShowAccount: showAccount, onShowLeaderboard: showLeaderboard, onShowFriends: showFriends, onShowMultiplayer: showMultiplayer });
    }

    function showLyrics() {
        teardown();
        setScreen('lyrics');
        cleanupScreen = renderLyricsScreen(root, {
            onBack: showMainMenu,
            onLyricsReady: loaded => {
                customText = loaded;
                session = { type: 'custom', customIndex: 0 };
                startGame();
            },
            onShowStats: showStats,
            onShowPlaceholder: showPlaceholder,
            onShowAccount: showAccount,
            onShowLeaderboard: showLeaderboard,
            onShowFriends: showFriends,
            onShowMultiplayer: showMultiplayer,
            onShowStore: showStore,
        });
    }

    async function startGame() {
        teardown();
        let content;
        let attribution;
        let explanation;
        let language;
        let progress;
        let timeLimit;
        // Custom text has no stable, repeatable challenge to compare against,
        // so it's excluded from personal-best tracking (stays undefined).
        let modeKey;

        if (session.type === 'custom' && customText) {
            const chunk = customText.chunks[session.customIndex];
            content = chunk.content;
            attribution = customText.name;
            language = customText.language;
            progress = `${customText.name} · segment ${session.customIndex + 1}/${customText.chunks.length}`;
        } else if (selectedCategory === 'words') {
            const s = getSettings();
            content = generateWordStream(s.wordCount || 25, { punctuation: s.wordsPunctuation, numbers: s.wordsNumbers, tier: s.wordListTier, language: s.language });
            modeKey = `words-${s.wordCount || 25}`;
        } else if (selectedCategory === 'time') {
            const s = getSettings();
            timeLimit = s.timeDuration || 30;
            content = generateWordStream(wordCountForDuration(timeLimit), { punctuation: s.wordsPunctuation, numbers: s.wordsNumbers, tier: s.wordListTier, language: s.language });
            modeKey = `time-${timeLimit}`;
        } else if (selectedCategory === 'zen') {
            // No timer, no fixed length - type until you choose to stop (the
            // visible Finish button in the typing screen). No modeKey: like
            // custom text, there's no fixed-length challenge to compare a
            // "personal best" against since every session covers a different
            // amount of text.
            const s = getSettings();
            content = generateWordStream(800, { punctuation: s.wordsPunctuation, numbers: s.wordsNumbers, tier: s.wordListTier, language: s.language });
        } else if (selectedCategory === 'practice') {
            // Adaptive, personal, and different every time by nature - no
            // modeKey, same reasoning as Zen/Custom: there's no fixed
            // challenge here to compare a "personal best" against.
            const s = getSettings();
            const weakChars = getWeakChars();
            content = generateWeakKeyStream(wordCountForDuration(30), weakChars, { punctuation: s.wordsPunctuation, numbers: s.wordsNumbers });
        } else {
            const item = getRandomTextItem(allTexts, selectedCategory);
            content = item.content;
            attribution = item.attribution;
            // Code snippets highlight themselves; prose packs have no language
            // and fall through as plain text.
            language = item.language || undefined;
            explanation = item.explanation || undefined;
            modeKey = `quote-${selectedCategory || 'random'}`;
        }

        try {
            game = await createGame();
            game.set_text(content);
        } catch (err) {
            console.error('Failed to start game:', err);
            showMainMenu();
            return;
        }
        setScreen('typing');
        cleanupScreen = renderTypingGame(root, {
            game,
            text: content,
            attribution,
            explanation,
            language,
            progress,
            timeLimit,
            modeKey,
            zenMode: selectedCategory === 'zen' && !(session.type === 'custom' && customText),
            onFinish: showEndScreen,
            onMainMenu: showMainMenu,
            onRestart: startGame,
            onShowStats: showStats,
            onShowPlaceholder: showPlaceholder,
            onShowAccount: showAccount,
            onShowLeaderboard: showLeaderboard,
            onShowFriends: showFriends,
            onShowMultiplayer: showMultiplayer,
            onShowStore: showStore,
        });
    }

    function playAgain() {
        if (session.type === 'custom' && customText) {
            if (session.customIndex + 1 < customText.chunks.length) {
                session.customIndex += 1;
            } else {
                showMainMenu();
                return;
            }
        }
        startGame();
    }

    function showEndScreen(result) {
        teardown();
        setScreen('end');
        cleanupScreen = renderEndScreen(root, {
            ...result,
            onPlayAgain: playAgain,
            onMainMenu: showMainMenu,
            onShowStats: showStats,
            onShowPlaceholder: showPlaceholder,
            onShowAccount: showAccount,
            onShowLeaderboard: showLeaderboard,
            onShowFriends: showFriends,
            onShowMultiplayer: showMultiplayer,
            onShowStore: showStore,
        });
    }

    function startPassive() {
        teardown();
        if (!customText) {
            showMainMenu();
            return;
        }
        setScreen('passive');
        cleanupScreen = renderPassiveMode(root, {
            name: customText.name,
            chunks: customText.chunks,
            onExit: showMainMenu,
        });
    }

    const { skipMenu, favoriteMode } = getSettings();
    const bootMode = favoriteMode || selectedCategory;
    if (skipMenu && bootMode !== 'custom') {
        selectedCategory = bootMode;
        try { localStorage.setItem('typerpunk:last_mode', bootMode); } catch {}
        session = { type: 'random', customIndex: 0 };
        startGame();
    } else {
        showMainMenu();
    }
}