Files
Zauberwald/src/app.ts
T

103 lines
2.8 KiB
TypeScript
Raw Normal View History

import type { ScreenName } from "./types";
import { openDB, getProgress, saveProgress } from "./storage/db";
import { initWelcomeScreen, initLessonScreen } from "./ui/screens";
import { initForestScreen } from "./forest/scene";
let db: IDBDatabase;
let lessonCleanup: (() => void) | null = null;
export function showScreen(name: ScreenName): void {
document.querySelectorAll(".screen").forEach((el) => {
el.classList.remove("screen--active");
});
const target = document.getElementById(`screen-${name}`);
if (target) {
target.classList.add("screen--active");
}
}
export function getDB(): IDBDatabase {
return db;
}
const MAX_LEVEL = 6;
async function handleLessonComplete(completedLevel: number): Promise<void> {
// Update progress after lesson completion
const progress = await getProgress(db);
if (!progress) return;
// Add level to completedLevels if not already there
if (!progress.completedLevels.includes(completedLevel)) {
progress.completedLevels.push(completedLevel);
}
// Advance to next level if this was the current level (LEVL-02, LEVL-03)
// Cap at MAX_LEVEL + 1 so we don't go beyond defined levels
if (completedLevel === progress.currentLevel && completedLevel < MAX_LEVEL) {
progress.currentLevel = completedLevel + 1;
}
// Increment session count
progress.totalSessions++;
// Add today's date if not already recorded
const today = new Date().toISOString().split("T")[0]!;
if (!progress.sessionDates.includes(today)) {
progress.sessionDates.push(today);
}
await saveProgress(db, progress);
// Re-init forest screen with updated progress, then navigate
await initForestScreen(db, startLessonFromForest);
showScreen("forest");
}
async function handleLessonCancel(): Promise<void> {
await initForestScreen(db, startLessonFromForest);
showScreen("forest");
}
function startLessonFromForest(level: number): void {
// Clean up previous lesson if any
if (lessonCleanup) {
lessonCleanup();
lessonCleanup = null;
}
// Get layout from progress (already loaded)
getProgress(db).then((progress) => {
const layout = progress?.selectedLayout ?? "de";
showScreen("lesson");
lessonCleanup = initLessonScreen(
db,
level,
layout,
handleLessonComplete,
handleLessonCancel,
);
});
}
export async function initApp(): Promise<void> {
db = await openDB();
const progress = await getProgress(db);
if (progress && progress.selectedCharacter) {
// Returning user -- init forest and go there
await initForestScreen(db, startLessonFromForest);
showScreen("forest");
} else {
// First time -- show welcome, then forest after setup
initWelcomeScreen(db, async (screen: ScreenName) => {
showScreen(screen);
if (screen === "forest") {
await initForestScreen(db, startLessonFromForest);
}
});
showScreen("welcome");
}
}