Merge branch 'feat/i18n-js' - JS-based internationalization

This commit is contained in:
2025-12-30 16:11:23 +01:00
12 changed files with 612 additions and 965 deletions

View File

@@ -9,7 +9,7 @@ Code Crispies is an interactive CSS/Tailwind learning platform built with pure J
## Commands ## Commands
```bash ```bash
npm start # Start dev server at http://localhost:1312 npm start # Start dev server at http://localhost:1234
npm run build # Production build to dist/ npm run build # Production build to dist/
npm run test # Run tests once npm run test # Run tests once
npm run test.watch # Run tests in watch mode npm run test.watch # Run tests in watch mode

54
Makefile Normal file
View File

@@ -0,0 +1,54 @@
# Code Crispies - Interactive CSS Learning Platform
.PHONY: help dev build test test-watch test-coverage format clean install deploy
# Default port
PORT = 1234
help:
@echo "Code Crispies - Development Commands"
@echo ""
@echo "Development:"
@echo " make dev - Start dev server (port $(PORT))"
@echo " make build - Production build to dist/"
@echo ""
@echo "Testing:"
@echo " make test - Run tests once"
@echo " make test-watch - Run tests in watch mode"
@echo " make test-coverage - Run tests with coverage"
@echo ""
@echo "Other:"
@echo " make format - Format all source files"
@echo " make clean - Remove build artifacts"
@echo " make install - Install dependencies"
# Development
dev:
npm start
# Build
build:
npm run build
# Testing
test:
npm run test
test-watch:
npm run test.watch
test-coverage:
npm run test.coverage
# Formatting
format:
npm run format
npm run format.lessons
# Clean
clean:
rm -rf dist/ node_modules/.vite/
# Install
install:
npm install

34
flake.nix Normal file
View File

@@ -0,0 +1,34 @@
{
description = "Code Crispies - Interactive CSS/HTML/Tailwind learning platform";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = nixpkgs.legacyPackages.${system};
in {
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
nodejs_20
nodePackages.npm
gnumake
];
shellHook = ''
echo "Code Crispies Development Environment"
echo ""
echo "Commands:"
echo " make dev - Start dev server (port 1234)"
echo " make build - Production build"
echo " make test - Run tests"
echo " make format - Format code"
echo ""
'';
};
}
);
}

View File

@@ -1,594 +0,0 @@
import { LessonEngine } from "./impl/LessonEngine.js";
import { CodeEditor } from "./impl/CodeEditor.js";
import { renderLesson, renderModuleList, renderLevelIndicator, updateActiveLessonInSidebar } from "./helpers/renderer.js";
import { loadModules } from "./config/lessons.de.js";
// Simplified state - LessonEngine now manages lesson state and progress
const state = {
userSettings: {
disableFeedbackErrors: false
},
showExpected: false
};
// DOM elements - updated for new layout
const elements = {
// Header
menuBtn: document.getElementById("menu-btn"),
helpBtn: document.getElementById("help-btn"),
// Left panel
lessonTitle: document.getElementById("lesson-title"),
lessonDescription: document.getElementById("lesson-description"),
taskInstruction: document.getElementById("task-instruction"),
codeInput: document.getElementById("code-input"),
runBtn: document.getElementById("run-btn"),
undoBtn: document.getElementById("undo-btn"),
redoBtn: document.getElementById("redo-btn"),
resetCodeBtn: document.getElementById("reset-code-btn"),
hintArea: document.getElementById("hint-area"),
editorContent: document.querySelector(".editor-content"),
codeEditor: document.querySelector(".code-editor"),
// Right panel
previewArea: document.getElementById("preview-area"),
showExpectedBtn: document.getElementById("show-expected-btn"),
expectedOverlay: document.getElementById("expected-overlay"),
previewWrapper: document.querySelector(".preview-wrapper"),
prevBtn: document.getElementById("prev-btn"),
nextBtn: document.getElementById("next-btn"),
levelIndicator: document.getElementById("level-indicator"),
// Sidebar
sidebarDrawer: document.getElementById("sidebar-drawer"),
sidebarBackdrop: document.getElementById("sidebar-backdrop"),
closeSidebar: document.getElementById("close-sidebar"),
moduleList: document.getElementById("module-list"),
progressFill: document.getElementById("progress-fill"),
progressText: document.getElementById("progress-text"),
resetBtn: document.getElementById("reset-btn"),
disableFeedbackToggle: document.getElementById("disable-feedback-toggle"),
// Dialogs
helpDialog: document.getElementById("help-dialog"),
helpDialogClose: document.getElementById("help-dialog-close"),
resetDialog: document.getElementById("reset-dialog"),
resetDialogClose: document.getElementById("reset-dialog-close"),
cancelReset: document.getElementById("cancel-reset"),
confirmReset: document.getElementById("confirm-reset")
};
// Initialize the lesson engine - now the single source of truth
const lessonEngine = new LessonEngine();
// Code editor instance (initialized later)
let codeEditor = null;
let currentMode = "css";
// ================= SIDEBAR FUNCTIONS =================
// Track element that opened sidebar for focus return
let sidebarTrigger = null;
function openSidebar() {
// Store trigger element for focus return
sidebarTrigger = document.activeElement;
elements.sidebarDrawer.classList.add("open");
elements.sidebarBackdrop.classList.add("visible");
// Move focus to close button for keyboard users
elements.closeSidebar.focus();
}
function closeSidebar() {
elements.sidebarDrawer.classList.remove("open");
elements.sidebarBackdrop.classList.remove("visible");
// Return focus to trigger element
if (sidebarTrigger && typeof sidebarTrigger.focus === "function") {
sidebarTrigger.focus();
sidebarTrigger = null;
}
}
// ================= EXPECTED RESULT TOGGLE =================
function toggleExpectedResult() {
state.showExpected = !state.showExpected;
if (state.showExpected) {
elements.expectedOverlay.classList.add("visible");
elements.showExpectedBtn.textContent = "Lösung ausblenden";
elements.showExpectedBtn.classList.add("btn-primary");
} else {
elements.expectedOverlay.classList.remove("visible");
elements.showExpectedBtn.textContent = "Lösung zeigen";
elements.showExpectedBtn.classList.remove("btn-primary");
}
}
// ================= HINT SYSTEM =================
function showHint(message, step, total, isSuccess = false) {
const hintClass = isSuccess ? "hint hint-success" : "hint";
elements.hintArea.innerHTML = `
<div class="${hintClass}">
<span class="hint-progress">${step}/${total}</span>
<span class="hint-message">${message}</span>
</div>
`;
}
function clearHint() {
elements.hintArea.innerHTML = "";
}
function showSuccessHint(message) {
elements.hintArea.innerHTML = `
<div class="hint hint-success">
<span class="hint-progress">✓</span>
<span class="hint-message">${message}</span>
</div>
`;
}
// ================= PROGRESS DISPLAY =================
function updateProgressDisplay() {
const stats = lessonEngine.getProgressStats();
elements.progressFill.style.width = `${stats.percentComplete}%`;
elements.progressText.textContent = `${stats.percentComplete}% abgeschlossen (${stats.totalCompleted}/${stats.totalLessons})`;
}
// ================= USER SETTINGS =================
function loadUserSettings() {
const savedSettings = localStorage.getItem("codeCrispies.settings");
if (savedSettings) {
try {
const settings = JSON.parse(savedSettings);
state.userSettings = { ...state.userSettings, ...settings };
elements.disableFeedbackToggle.checked = !state.userSettings.disableFeedbackErrors;
} catch (e) {
console.error("Fehler beim Laden der Einstellungen:", e);
}
}
}
function saveUserSettings() {
localStorage.setItem("codeCrispies.settings", JSON.stringify(state.userSettings));
}
// ================= MODULE INITIALIZATION =================
async function initializeModules() {
try {
const modules = await loadModules();
lessonEngine.setModules(modules);
// Use the new renderModuleList function with both callbacks
renderModuleList(elements.moduleList, modules, selectModule, selectLesson);
// Load saved progress and select appropriate module
const progressData = lessonEngine.loadUserProgress();
const lastModuleId = progressData?.lastModuleId;
if (lastModuleId && modules.find((m) => m.id === lastModuleId)) {
selectModule(lastModuleId);
} else if (modules.length > 0) {
selectModule(modules[0].id);
}
updateProgressDisplay();
} catch (error) {
console.error("Module konnten nicht geladen werden:", error);
elements.lessonDescription.textContent = "Module konnten nicht geladen werden. Bitte Seite neu laden.";
}
}
// ================= MODULE/LESSON SELECTION =================
function selectModule(moduleId) {
const success = lessonEngine.setModuleById(moduleId);
if (!success) return;
// Update module list UI to highlight the active module
const moduleItems = elements.moduleList.querySelectorAll(".module-header");
moduleItems.forEach((item) => {
item.classList.remove("active");
if (item.dataset.moduleId === moduleId) {
item.classList.add("active");
}
});
loadCurrentLesson();
resetSuccessIndicators();
// Close sidebar after selection on mobile
if (window.innerWidth <= 768) {
closeSidebar();
}
}
function selectLesson(moduleId, lessonIndex) {
const currentState = lessonEngine.getCurrentState();
if (!currentState.module || currentState.module.id !== moduleId) {
lessonEngine.setModuleById(moduleId);
}
lessonEngine.setLessonByIndex(lessonIndex);
loadCurrentLesson();
// Close sidebar after selection on mobile
if (window.innerWidth <= 768) {
closeSidebar();
}
}
// ================= LESSON LOADING =================
function resetSuccessIndicators() {
elements.codeEditor.classList.remove("success-highlight");
elements.lessonTitle.classList.remove("success-text");
elements.nextBtn.classList.remove("success");
elements.taskInstruction.classList.remove("success-instruction");
elements.runBtn.classList.remove("success");
elements.previewWrapper?.classList.remove("matched");
}
function updateEditorForMode(mode) {
const editorLabel = document.querySelector(".editor-label");
const modeConfig = {
html: {
placeholder: "HTML hier eingeben... Probiere: nav>ul>li*3 dann Tab drücken",
label: "HTML-Editor",
cmMode: "html"
},
tailwind: {
placeholder: "Tailwind-Klassen eingeben (z.B. bg-blue-500 text-white p-4)",
label: "Tailwind-Klassen",
cmMode: "css"
},
css: {
placeholder: "CSS-Code hier eingeben...",
label: "CSS-Editor",
cmMode: "css"
}
};
const config = modeConfig[mode] || modeConfig.css;
if (editorLabel) editorLabel.textContent = config.label;
// Update CodeMirror mode if needed
if (codeEditor && currentMode !== config.cmMode) {
currentMode = config.cmMode;
codeEditor.setMode(config.cmMode);
}
}
function loadCurrentLesson() {
const engineState = lessonEngine.getCurrentState();
if (!engineState.module || !engineState.lesson) {
return;
}
const lesson = engineState.lesson;
const mode = lesson.mode || engineState.module?.mode || "css";
// Update UI based on mode
updateEditorForMode(mode);
// Reset any success indicators
resetSuccessIndicators();
// Clear hints
clearHint();
// Hide expected overlay
state.showExpected = false;
elements.expectedOverlay.classList.remove("visible");
elements.showExpectedBtn.textContent = "Lösung zeigen";
elements.showExpectedBtn.classList.remove("btn-primary");
// Update UI
renderLesson(
elements.lessonTitle,
elements.lessonDescription,
elements.taskInstruction,
elements.previewArea,
null, // editorPrefix no longer used
null, // codeInput no longer used (using CodeMirror)
null, // editorSuffix no longer used
lesson
);
// Set user code in CodeMirror
if (codeEditor) {
codeEditor.setValue(engineState.userCode);
}
// Update Run button text based on completion status
if (engineState.isCompleted) {
elements.runBtn.innerHTML = '<img src="./gear.svg" alt="" />Erneut anwenden';
// Add completion badge if not present
if (!document.querySelector(".completion-badge")) {
const badge = document.createElement("span");
badge.className = "completion-badge";
badge.textContent = "Erledigt";
elements.lessonTitle.appendChild(badge);
}
} else {
elements.runBtn.innerHTML = '<img src="./gear.svg" alt="" />Ausführen';
// Remove completion badge if exists
const badge = document.querySelector(".completion-badge");
if (badge) badge.remove();
}
// Update level indicator
renderLevelIndicator(elements.levelIndicator, engineState.lessonIndex + 1, engineState.totalLessons);
// Update active lesson in sidebar
updateActiveLessonInSidebar(engineState.module.id, engineState.lessonIndex);
// Update navigation buttons
updateNavigationButtons();
// Update progress display
updateProgressDisplay();
// Focus on the code editor
if (codeEditor) {
codeEditor.focus();
}
// Render the expected/solution preview
lessonEngine.renderExpectedPreview();
}
// ================= LIVE PREVIEW =================
let previewTimer = null;
function handleEditorChange(code) {
if (previewTimer) {
clearTimeout(previewTimer);
}
previewTimer = setTimeout(() => {
runCode();
}, 800);
}
// ================= NAVIGATION =================
function updateNavigationButtons() {
const engineState = lessonEngine.getCurrentState();
elements.prevBtn.disabled = !engineState.canGoPrev;
elements.nextBtn.disabled = !engineState.canGoNext;
elements.prevBtn.classList.toggle("btn-disabled", !engineState.canGoPrev);
elements.nextBtn.classList.toggle("btn-disabled", !engineState.canGoNext);
}
function nextLesson() {
const success = lessonEngine.nextLesson();
if (success) {
loadCurrentLesson();
}
}
function prevLesson() {
const success = lessonEngine.previousLesson();
if (success) {
loadCurrentLesson();
}
}
// ================= CODE EXECUTION =================
function resetCode() {
// Reset editor to initial code for current lesson
lessonEngine.reset();
const engineState = lessonEngine.getCurrentState();
if (codeEditor && engineState.lesson) {
codeEditor.setValue(engineState.lesson.initialCode || "");
}
// Clear hints and success indicators
clearHint();
resetSuccessIndicators();
}
function runCode() {
const userCode = codeEditor ? codeEditor.getValue() : "";
// Rotate the Run button icon
const runButtonImg = document.querySelector("#run-btn img");
if (runButtonImg) {
const currentRotation = parseInt(runButtonImg.style.transform?.match(/\d+/)?.[0] || "0");
runButtonImg.style.transform = `rotate(${currentRotation + 180}deg)`;
}
// Apply the code to the preview via LessonEngine
lessonEngine.applyUserCode(userCode, true);
// Validate code using LessonEngine
const validationResult = lessonEngine.validateCode();
if (validationResult.isValid) {
// Show success hint
showSuccessHint(validationResult.message || "CRISPY! ٩(◕‿◕)۶ Dein Code funktioniert.");
// Update Run button
elements.runBtn.innerHTML = '<img src="./gear.svg" alt="" />Erneut anwenden';
elements.runBtn.classList.add("success");
// Add completion badge
if (!document.querySelector(".completion-badge")) {
const badge = document.createElement("span");
badge.className = "completion-badge";
badge.textContent = "Erledigt";
elements.lessonTitle.appendChild(badge);
}
// Add success visual indicators
elements.codeEditor.classList.add("success-highlight");
elements.lessonTitle.classList.add("success-text");
elements.nextBtn.classList.add("success");
elements.taskInstruction.classList.add("success-instruction");
// Show match animation
elements.previewWrapper?.classList.add("matched");
setTimeout(() => {
elements.previewWrapper?.classList.remove("matched");
}, 2500);
updateNavigationButtons();
updateProgressDisplay();
} else {
// Reset success indicators
resetSuccessIndicators();
// Show hint with step progress
const step = validationResult.validCases + 1;
const total = validationResult.totalCases;
// Only show hints if enabled
if (!state.userSettings.disableFeedbackErrors) {
showHint(validationResult.message || "Weiter versuchen!", step, total);
}
}
}
// ================= DIALOGS =================
function showHelp() {
elements.helpDialog.showModal();
}
function closeHelpDialog() {
elements.helpDialog.close();
}
function showResetConfirmation() {
elements.resetDialog.showModal();
}
function closeResetDialog() {
elements.resetDialog.close();
}
function handleResetConfirm() {
lessonEngine.clearProgress();
closeResetDialog();
closeSidebar();
// Reload first module
const modules = lessonEngine.modules;
if (modules.length > 0) {
selectModule(modules[0].id);
}
updateProgressDisplay();
}
// ================= INITIALIZATION =================
function initCodeEditor() {
const container = elements.editorContent;
if (!container) return;
// Remove the textarea - CodeMirror will replace it
const textarea = container.querySelector("textarea");
if (textarea) {
textarea.remove();
}
// Initialize CodeMirror
codeEditor = new CodeEditor(container, {
mode: currentMode,
placeholder: "Code hier eingeben...",
onChange: handleEditorChange
});
codeEditor.init("");
}
function init() {
loadUserSettings();
// Initialize CodeMirror editor
initCodeEditor();
// Load modules after editor is ready
initializeModules().catch(console.error);
// Sidebar controls
elements.menuBtn.addEventListener("click", openSidebar);
elements.closeSidebar.addEventListener("click", closeSidebar);
elements.sidebarBackdrop.addEventListener("click", closeSidebar);
// Expected result toggle
elements.showExpectedBtn.addEventListener("click", toggleExpectedResult);
// Navigation
elements.prevBtn.addEventListener("click", prevLesson);
elements.nextBtn.addEventListener("click", nextLesson);
elements.runBtn.addEventListener("click", runCode);
// Editor tools
elements.undoBtn.addEventListener("click", () => {
if (codeEditor) codeEditor.undo();
});
elements.redoBtn.addEventListener("click", () => {
if (codeEditor) codeEditor.redo();
});
elements.resetCodeBtn.addEventListener("click", resetCode);
// Dialogs
elements.helpBtn.addEventListener("click", showHelp);
elements.helpDialogClose.addEventListener("click", closeHelpDialog);
elements.helpDialog.addEventListener("click", (e) => {
if (e.target === elements.helpDialog) closeHelpDialog();
});
elements.resetBtn.addEventListener("click", showResetConfirmation);
elements.resetDialogClose.addEventListener("click", closeResetDialog);
elements.resetDialog.addEventListener("click", (e) => {
if (e.target === elements.resetDialog) closeResetDialog();
});
elements.cancelReset.addEventListener("click", closeResetDialog);
elements.confirmReset.addEventListener("click", handleResetConfirm);
// Settings
elements.disableFeedbackToggle.addEventListener("change", (e) => {
state.userSettings.disableFeedbackErrors = !e.target.checked;
saveUserSettings();
});
// Click on editor content to focus CodeMirror
elements.editorContent?.addEventListener("click", () => {
if (codeEditor) codeEditor.focus();
});
// Keyboard shortcuts
document.addEventListener("keydown", (e) => {
// Ctrl+Enter to run code
if (e.ctrlKey && e.key === "Enter") {
runCode();
e.preventDefault();
}
// Escape to close sidebar (dialogs handle Escape natively)
if (e.key === "Escape") {
closeSidebar();
}
});
}
// Start the application
init();

View File

@@ -2,6 +2,7 @@ import { LessonEngine } from "./impl/LessonEngine.js";
import { CodeEditor } from "./impl/CodeEditor.js"; import { CodeEditor } from "./impl/CodeEditor.js";
import { renderLesson, renderModuleList, renderLevelIndicator, updateActiveLessonInSidebar } from "./helpers/renderer.js"; import { renderLesson, renderModuleList, renderLevelIndicator, updateActiveLessonInSidebar } from "./helpers/renderer.js";
import { loadModules } from "./config/lessons.js"; import { loadModules } from "./config/lessons.js";
import { initI18n, t, getLanguage, setLanguage, applyTranslations } from "./i18n.js";
// Simplified state - LessonEngine now manages lesson state and progress // Simplified state - LessonEngine now manages lesson state and progress
const state = { const state = {
@@ -15,6 +16,7 @@ const state = {
const elements = { const elements = {
// Header // Header
menuBtn: document.getElementById("menu-btn"), menuBtn: document.getElementById("menu-btn"),
langBtn: document.getElementById("lang-btn"),
helpBtn: document.getElementById("help-btn"), helpBtn: document.getElementById("help-btn"),
// Left panel // Left panel
@@ -100,15 +102,42 @@ function toggleExpectedResult() {
if (state.showExpected) { if (state.showExpected) {
elements.expectedOverlay.classList.add("visible"); elements.expectedOverlay.classList.add("visible");
elements.showExpectedBtn.textContent = "Hide Expected"; elements.showExpectedBtn.textContent = t("hideExpected");
elements.showExpectedBtn.classList.add("btn-primary"); elements.showExpectedBtn.classList.add("btn-primary");
} else { } else {
elements.expectedOverlay.classList.remove("visible"); elements.expectedOverlay.classList.remove("visible");
elements.showExpectedBtn.textContent = "Show Expected"; elements.showExpectedBtn.textContent = t("showExpected");
elements.showExpectedBtn.classList.remove("btn-primary"); elements.showExpectedBtn.classList.remove("btn-primary");
} }
} }
// ================= LANGUAGE TOGGLE =================
async function toggleLanguage() {
const currentLang = getLanguage();
const newLang = currentLang === "en" ? "de" : "en";
setLanguage(newLang);
applyTranslations();
// Reload lessons in new language
const engineState = lessonEngine.getCurrentState();
const currentModuleId = engineState.module?.id;
const currentLessonIndex = engineState.lessonIndex;
const modules = await loadModules(newLang);
lessonEngine.setModules(modules);
renderModuleList(elements.moduleList, modules, selectModule, selectLesson);
// Restore position in current module/lesson
if (currentModuleId) {
lessonEngine.setModuleById(currentModuleId);
lessonEngine.setLessonByIndex(currentLessonIndex);
loadCurrentLesson();
}
updateProgressDisplay();
}
// ================= HINT SYSTEM ================= // ================= HINT SYSTEM =================
function showHint(message, step, total, isSuccess = false) { function showHint(message, step, total, isSuccess = false) {
@@ -139,7 +168,11 @@ function showSuccessHint(message) {
function updateProgressDisplay() { function updateProgressDisplay() {
const stats = lessonEngine.getProgressStats(); const stats = lessonEngine.getProgressStats();
elements.progressFill.style.width = `${stats.percentComplete}%`; elements.progressFill.style.width = `${stats.percentComplete}%`;
elements.progressText.textContent = `${stats.percentComplete}% Complete (${stats.totalCompleted}/${stats.totalLessons})`; elements.progressText.textContent = t("progressText", {
percent: stats.percentComplete,
completed: stats.totalCompleted,
total: stats.totalLessons
});
} }
// ================= USER SETTINGS ================= // ================= USER SETTINGS =================
@@ -165,7 +198,7 @@ function saveUserSettings() {
async function initializeModules() { async function initializeModules() {
try { try {
const modules = await loadModules(); const modules = await loadModules(getLanguage());
lessonEngine.setModules(modules); lessonEngine.setModules(modules);
// Use the new renderModuleList function with both callbacks // Use the new renderModuleList function with both callbacks
@@ -184,7 +217,7 @@ async function initializeModules() {
updateProgressDisplay(); updateProgressDisplay();
} catch (error) { } catch (error) {
console.error("Failed to load modules:", error); console.error("Failed to load modules:", error);
elements.lessonDescription.textContent = "Failed to load modules. Please refresh the page."; elements.lessonDescription.textContent = t("failedToLoad");
} }
} }
@@ -248,7 +281,7 @@ function updateEditorForMode(mode) {
cmMode: "html" cmMode: "html"
}, },
tailwind: { tailwind: {
placeholder: "Enter Tailwind classes (e.g., bg-blue-500 text-white p-4)", placeholder: t("tailwindPlaceholder"),
label: "Tailwind Classes", label: "Tailwind Classes",
cmMode: "css" cmMode: "css"
}, },
@@ -296,7 +329,7 @@ function loadCurrentLesson() {
// Hide expected overlay // Hide expected overlay
state.showExpected = false; state.showExpected = false;
elements.expectedOverlay.classList.remove("visible"); elements.expectedOverlay.classList.remove("visible");
elements.showExpectedBtn.textContent = "Show Expected"; elements.showExpectedBtn.textContent = t("showExpected");
elements.showExpectedBtn.classList.remove("btn-primary"); elements.showExpectedBtn.classList.remove("btn-primary");
// Update UI // Update UI
@@ -318,17 +351,17 @@ function loadCurrentLesson() {
// Update Run button text based on completion status // Update Run button text based on completion status
if (engineState.isCompleted) { if (engineState.isCompleted) {
elements.runBtn.innerHTML = '<img src="./gear.svg" alt="" />Re-run'; elements.runBtn.querySelector("span").textContent = t("rerun");
// Add completion badge if not present // Add completion badge if not present
if (!document.querySelector(".completion-badge")) { if (!document.querySelector(".completion-badge")) {
const badge = document.createElement("span"); const badge = document.createElement("span");
badge.className = "completion-badge"; badge.className = "completion-badge";
badge.textContent = "Completed"; badge.textContent = t("completed");
elements.lessonTitle.appendChild(badge); elements.lessonTitle.appendChild(badge);
} }
} else { } else {
elements.runBtn.innerHTML = '<img src="./gear.svg" alt="" />Run'; elements.runBtn.querySelector("span").textContent = t("run");
// Remove completion badge if exists // Remove completion badge if exists
const badge = document.querySelector(".completion-badge"); const badge = document.querySelector(".completion-badge");
@@ -448,17 +481,17 @@ function runCode() {
if (validationResult.isValid) { if (validationResult.isValid) {
// Show success hint // Show success hint
showSuccessHint(validationResult.message || "CRISPY! ٩(◕‿◕)۶ Your code works correctly."); showSuccessHint(validationResult.message || t("successMessage"));
// Update Run button // Update Run button
elements.runBtn.innerHTML = '<img src="./gear.svg" alt="" />Re-run'; elements.runBtn.querySelector("span").textContent = t("rerun");
elements.runBtn.classList.add("success"); elements.runBtn.classList.add("success");
// Add completion badge // Add completion badge
if (!document.querySelector(".completion-badge")) { if (!document.querySelector(".completion-badge")) {
const badge = document.createElement("span"); const badge = document.createElement("span");
badge.className = "completion-badge"; badge.className = "completion-badge";
badge.textContent = "Completed"; badge.textContent = t("completed");
elements.lessonTitle.appendChild(badge); elements.lessonTitle.appendChild(badge);
} }
@@ -486,7 +519,7 @@ function runCode() {
// Only show hints if enabled // Only show hints if enabled
if (!state.userSettings.disableFeedbackErrors) { if (!state.userSettings.disableFeedbackErrors) {
showHint(validationResult.message || "Keep trying!", step, total); showHint(validationResult.message || t("keepTrying"), step, total);
} }
} }
} }
@@ -546,6 +579,9 @@ function initCodeEditor() {
} }
function init() { function init() {
// Initialize i18n before anything else
initI18n();
loadUserSettings(); loadUserSettings();
// Initialize CodeMirror editor // Initialize CodeMirror editor
@@ -559,6 +595,9 @@ function init() {
elements.closeSidebar.addEventListener("click", closeSidebar); elements.closeSidebar.addEventListener("click", closeSidebar);
elements.sidebarBackdrop.addEventListener("click", closeSidebar); elements.sidebarBackdrop.addEventListener("click", closeSidebar);
// Language toggle
elements.langBtn.addEventListener("click", toggleLanguage);
// Expected result toggle // Expected result toggle
elements.showExpectedBtn.addEventListener("click", toggleExpectedResult); elements.showExpectedBtn.addEventListener("click", toggleExpectedResult);

View File

@@ -1,63 +1,112 @@
/** /**
* Lesson Config - Functions for loading lesson configurations * Lesson Config - Functions for loading lesson configurations
* Supports English and German lesson content
*/ */
// Import lesson configs // English lesson imports
import basicSelectorsConfig from "../../lessons/00-basic-selectors.json"; import basicSelectorsEN from "../../lessons/00-basic-selectors.json";
import advancedSelectorsConfig from "../../lessons/01-advanced-selectors.json"; import advancedSelectorsEN from "../../lessons/01-advanced-selectors.json";
import tailwindConfig from "../../lessons/10-tailwind-basics.json"; import boxModelEN from "../../lessons/01-box-model.json";
// CSS lessons import unitsVariablesEN from "../../lessons/05-units-variables.json";
import boxModelConfig from "../../lessons/01-box-model.json"; import transitionsAnimationsEN from "../../lessons/06-transitions-animations.json";
import flexboxConfig from "../../lessons/flexbox.json"; import responsiveEN from "../../lessons/08-responsive.json";
import responsiveConfig from "../../lessons/08-responsive.json"; import tailwindEN from "../../lessons/10-tailwind-basics.json";
import unitsVariablesConfig from "../../lessons/05-units-variables.json"; import htmlElementsEN from "../../lessons/20-html-elements.json";
import transitionsAnimationsConfig from "../../lessons/06-transitions-animations.json"; import htmlFormsBasicEN from "../../lessons/21-html-forms-basic.json";
// HTML lessons import htmlFormsValidationEN from "../../lessons/22-html-forms-validation.json";
import htmlElementsConfig from "../../lessons/20-html-elements.json"; import htmlDetailsSummaryEN from "../../lessons/23-html-details-summary.json";
import htmlFormsBasicConfig from "../../lessons/21-html-forms-basic.json"; import htmlProgressMeterEN from "../../lessons/24-html-progress-meter.json";
import htmlFormsValidationConfig from "../../lessons/22-html-forms-validation.json"; import htmlDatalistEN from "../../lessons/25-html-datalist.json";
import htmlDetailsSummaryConfig from "../../lessons/23-html-details-summary.json"; import htmlDataAttributesEN from "../../lessons/26-html-data-attributes.json";
import htmlProgressMeterConfig from "../../lessons/24-html-progress-meter.json"; import htmlDialogEN from "../../lessons/27-html-dialog.json";
import htmlDatalistConfig from "../../lessons/25-html-datalist.json"; import htmlFormsFieldsetEN from "../../lessons/28-html-forms-fieldset.json";
import htmlDataAttributesConfig from "../../lessons/26-html-data-attributes.json"; import htmlFigureEN from "../../lessons/29-html-figure.json";
import htmlDialogConfig from "../../lessons/27-html-dialog.json"; import htmlTablesEN from "../../lessons/30-html-tables.json";
import htmlFormsFieldsetConfig from "../../lessons/28-html-forms-fieldset.json"; import htmlMarqueeEN from "../../lessons/31-html-marquee.json";
import htmlFigureConfig from "../../lessons/29-html-figure.json"; import htmlSvgEN from "../../lessons/32-html-svg.json";
import htmlTablesConfig from "../../lessons/30-html-tables.json"; import flexboxEN from "../../lessons/flexbox.json";
import htmlMarqueeConfig from "../../lessons/31-html-marquee.json";
import htmlSvgConfig from "../../lessons/32-html-svg.json";
// Module store // German lesson imports
const moduleStore = [ import basicSelectorsDE from "../../lessons/de/00-basic-selectors.json";
htmlElementsConfig, import advancedSelectorsDE from "../../lessons/de/01-advanced-selectors.json";
htmlFormsBasicConfig, import boxModelDE from "../../lessons/de/01-box-model.json";
htmlFormsValidationConfig, import unitsVariablesDE from "../../lessons/de/05-units-variables.json";
htmlDetailsSummaryConfig, import transitionsAnimationsDE from "../../lessons/de/06-transitions-animations.json";
htmlProgressMeterConfig, import responsiveDE from "../../lessons/de/08-responsive.json";
htmlDatalistConfig, import tailwindDE from "../../lessons/de/10-tailwind-basics.json";
htmlDataAttributesConfig, import htmlElementsDE from "../../lessons/de/20-html-elements.json";
htmlDialogConfig, import htmlFormsBasicDE from "../../lessons/de/21-html-forms-basic.json";
htmlFormsFieldsetConfig, import htmlFormsValidationDE from "../../lessons/de/22-html-forms-validation.json";
htmlFigureConfig, import htmlDetailsSummaryDE from "../../lessons/de/23-html-details-summary.json";
htmlTablesConfig, import htmlProgressMeterDE from "../../lessons/de/24-html-progress-meter.json";
htmlMarqueeConfig, import htmlDatalistDE from "../../lessons/de/25-html-datalist.json";
htmlSvgConfig, import htmlDataAttributesDE from "../../lessons/de/26-html-data-attributes.json";
boxModelConfig, import htmlDialogDE from "../../lessons/de/27-html-dialog.json";
flexboxConfig, import htmlFormsFieldsetDE from "../../lessons/de/28-html-forms-fieldset.json";
responsiveConfig, import htmlFigureDE from "../../lessons/de/29-html-figure.json";
unitsVariablesConfig, import htmlTablesDE from "../../lessons/de/30-html-tables.json";
transitionsAnimationsConfig, import htmlMarqueeDE from "../../lessons/de/31-html-marquee.json";
basicSelectorsConfig, import htmlSvgDE from "../../lessons/de/32-html-svg.json";
advancedSelectorsConfig, import flexboxDE from "../../lessons/de/flexbox.json";
tailwindConfig
// English module store
const moduleStoreEN = [
htmlElementsEN,
htmlFormsBasicEN,
htmlFormsValidationEN,
htmlDetailsSummaryEN,
htmlProgressMeterEN,
htmlDatalistEN,
htmlDataAttributesEN,
htmlDialogEN,
htmlFormsFieldsetEN,
htmlFigureEN,
htmlTablesEN,
htmlMarqueeEN,
htmlSvgEN,
boxModelEN,
flexboxEN,
responsiveEN,
unitsVariablesEN,
transitionsAnimationsEN,
basicSelectorsEN,
advancedSelectorsEN,
tailwindEN
];
// German module store
const moduleStoreDE = [
htmlElementsDE,
htmlFormsBasicDE,
htmlFormsValidationDE,
htmlDetailsSummaryDE,
htmlProgressMeterDE,
htmlDatalistDE,
htmlDataAttributesDE,
htmlDialogDE,
htmlFormsFieldsetDE,
htmlFigureDE,
htmlTablesDE,
htmlMarqueeDE,
htmlSvgDE,
boxModelDE,
flexboxDE,
responsiveDE,
unitsVariablesDE,
transitionsAnimationsDE,
basicSelectorsDE,
advancedSelectorsDE,
tailwindDE
]; ];
/** /**
* Load all available modules * Load all available modules for a given language
* @param {string} language - Language code ('en' or 'de')
* @returns {Promise<Array>} Promise resolving to array of modules * @returns {Promise<Array>} Promise resolving to array of modules
*/ */
export async function loadModules() { export async function loadModules(language = "en") {
return moduleStore.map((module) => ({ const store = language === "de" ? moduleStoreDE : moduleStoreEN;
return store.map((module) => ({
...module, ...module,
lessons: module.lessons.map((lesson) => ({ lessons: module.lessons.map((lesson) => ({
...lesson, ...lesson,
@@ -69,10 +118,12 @@ export async function loadModules() {
/** /**
* Get a module by its ID * Get a module by its ID
* @param {string} moduleId - The module ID to find * @param {string} moduleId - The module ID to find
* @param {string} language - Language code ('en' or 'de')
* @returns {Object|null} The module object or null if not found * @returns {Object|null} The module object or null if not found
*/ */
export function getModuleById(moduleId) { export function getModuleById(moduleId, language = "en") {
return moduleStore.find((module) => module.id === moduleId) || null; const store = language === "de" ? moduleStoreDE : moduleStoreEN;
return store.find((module) => module.id === moduleId) || null;
} }
/** /**
@@ -118,20 +169,23 @@ function validateModuleConfig(config) {
/** /**
* Add a custom module to the store * Add a custom module to the store
* @param {Object} moduleConfig - The module configuration to add * @param {Object} moduleConfig - The module configuration to add
* @param {string} language - Language code ('en' or 'de')
* @returns {boolean} Success status * @returns {boolean} Success status
*/ */
export function addCustomModule(moduleConfig) { export function addCustomModule(moduleConfig, language = "en") {
try { try {
validateModuleConfig(moduleConfig); validateModuleConfig(moduleConfig);
const store = language === "de" ? moduleStoreDE : moduleStoreEN;
// Check if module with same ID already exists // Check if module with same ID already exists
const existingIndex = moduleStore.findIndex((m) => m.id === moduleConfig.id); const existingIndex = store.findIndex((m) => m.id === moduleConfig.id);
if (existingIndex >= 0) { if (existingIndex >= 0) {
// Replace existing module // Replace existing module
moduleStore[existingIndex] = moduleConfig; store[existingIndex] = moduleConfig;
} else { } else {
// Add new module // Add new module
moduleStore.push(moduleConfig); store.push(moduleConfig);
} }
return true; return true;

View File

@@ -1,6 +1,7 @@
/** /**
* Renderer - Handles UI updates for the CSS learning platform * Renderer - Handles UI updates for the CSS learning platform
*/ */
import { t } from "../i18n.js";
// Feedback elements cache // Feedback elements cache
let feedbackElement = null; let feedbackElement = null;
@@ -77,7 +78,7 @@ export function renderModuleList(container, modules, onSelectModule, onSelectLes
lessonItem.classList.add("lesson-list-item"); lessonItem.classList.add("lesson-list-item");
lessonItem.dataset.moduleId = module.id; lessonItem.dataset.moduleId = module.id;
lessonItem.dataset.lessonIndex = index; lessonItem.dataset.lessonIndex = index;
lessonItem.textContent = lesson.title || `Lesson ${index + 1}`; lessonItem.textContent = lesson.title || t("lessonFallback", { index: index + 1 });
// Mark lesson as completed if in progress data // Mark lesson as completed if in progress data
if (progress[module.id] && progress[module.id].completed.includes(index)) { if (progress[module.id] && progress[module.id].completed.includes(index)) {
@@ -137,7 +138,7 @@ export function renderModuleList(container, modules, onSelectModule, onSelectLes
*/ */
export function renderLesson(titleEl, descriptionEl, taskEl, previewEl, prefixEl, inputEl, suffixEl, lesson) { export function renderLesson(titleEl, descriptionEl, taskEl, previewEl, prefixEl, inputEl, suffixEl, lesson) {
// Set lesson title and description // Set lesson title and description
titleEl.textContent = lesson.title || "Untitled Lesson"; titleEl.textContent = lesson.title || t("untitledLesson");
descriptionEl.innerHTML = lesson.description || ""; descriptionEl.innerHTML = lesson.description || "";
// Set task instructions // Set task instructions
@@ -162,7 +163,7 @@ export function renderLesson(titleEl, descriptionEl, taskEl, previewEl, prefixEl
* @param {number} total - The total number of levels * @param {number} total - The total number of levels
*/ */
export function renderLevelIndicator(element, current, total) { export function renderLevelIndicator(element, current, total) {
element.textContent = `Lesson ${current} of ${total}`; element.textContent = t("levelIndicator", { current, total });
} }
/** /**

287
src/i18n.js Normal file
View File

@@ -0,0 +1,287 @@
/**
* Internationalization module for Code Crispies
*/
const translations = {
en: {
// Page
pageTitle: "CODE CRISPIES - Learn CSS Interactively",
skipLink: "Skip to main content",
// Header
menuOpen: "Open menu",
langSwitch: "DE",
langSwitchLabel: "Sprache wechseln: Deutsch",
help: "Help",
// Instructions
loading: "Loading...",
selectLesson: "Please select a lesson to begin.",
editorLabel: "CSS Editor",
undoTitle: "Undo (Ctrl+Z)",
redoTitle: "Redo (Ctrl+Shift+Z)",
resetCodeTitle: "Reset to initial code",
run: "Run",
rerun: "Re-run",
// Preview
yourOutput: "Your Output",
showExpected: "Show Expected",
hideExpected: "Hide Expected",
previous: "Previous",
next: "Next",
levelIndicator: "Lesson {current} of {total}",
// Sidebar
menu: "Menu",
closeMenu: "Close menu",
progress: "Progress",
progressText: "{percent}% Complete ({completed}/{total})",
lessons: "Lessons",
settings: "Settings",
showHints: "Show Hints",
resetAllProgress: "Reset All Progress",
openSource: "Open Source:",
by: "by",
// Help dialog
helpTitle: "Help",
aboutTitle: "About Code Crispies",
aboutText: "Code Crispies is a free, open-source platform for learning web development through hands-on exercises. No account required - just start coding!",
learningModesTitle: "Learning Modes",
modeCss: "<strong>CSS</strong> - Write CSS rules to style elements",
modeTailwind: "<strong>Tailwind</strong> - Apply utility classes directly in HTML",
modeHtml: "<strong>HTML</strong> - Practice semantic markup and native elements",
gettingStartedTitle: "Getting Started",
gettingStartedText: "Open the menu (☰) to browse lesson modules. Each module covers a specific topic with progressive exercises.",
completingLessonsTitle: "Completing Lessons",
completingStep1: "Read the task instructions on the left",
completingStep2: "Write your code in the editor",
completingStep3: "Watch the live preview update as you type",
completingStep4: "Follow hints to fix any issues",
completingStep5: "Click <strong>Next</strong> when complete",
editorToolsTitle: "Editor Tools",
editorToolUndo: "<strong>↶ Undo</strong> / <strong>↷ Redo</strong> - Navigate edit history",
editorToolReset: "<strong>⟲ Reset</strong> - Restore initial code for current lesson",
editorToolExpected: "<strong>Show Expected</strong> - Toggle the target result overlay",
keyboardShortcutsTitle: "Keyboard Shortcuts",
shortcutRun: "<kbd>Ctrl+Enter</kbd> - Validate immediately",
shortcutUndo: "<kbd>Ctrl+Z</kbd> - Undo",
shortcutRedo: "<kbd>Ctrl+Shift+Z</kbd> - Redo",
emmetTitle: "Emmet Shortcuts (HTML mode)",
emmetText: "Type abbreviations and press <kbd>Tab</kbd> to expand:",
emmetClass: "<kbd>div.box</kbd> → div with class",
emmetChildren: "<kbd>ul>li*3</kbd> → ul with 3 li children",
emmetNested: "<kbd>form>input+button</kbd> → nested structure",
emmetContent: "<kbd>p{Hello}</kbd> → p with text content",
// Reset dialog
resetDialogTitle: "Reset Progress",
resetDialogText: "Are you sure you want to reset all your progress? This cannot be undone.",
cancel: "Cancel",
resetAll: "Reset All",
// Dynamic content
completed: "Completed",
successMessage: "CRISPY! ٩(◕‿◕)۶ Your code works correctly.",
keepTrying: "Keep trying!",
failedToLoad: "Failed to load modules. Please refresh the page.",
tailwindPlaceholder: "Enter Tailwind classes (e.g., bg-blue-500 text-white p-4)",
lessonFallback: "Lesson {index}",
untitledLesson: "Untitled Lesson"
},
de: {
// Page
pageTitle: "CODE CRISPIES - CSS interaktiv lernen",
skipLink: "Zum Hauptinhalt springen",
// Header
menuOpen: "Menü öffnen",
langSwitch: "EN",
langSwitchLabel: "Switch language: English",
help: "Hilfe",
// Instructions
loading: "Laden...",
selectLesson: "Bitte wähle eine Lektion aus, um zu beginnen.",
editorLabel: "CSS-Editor",
undoTitle: "Rückgängig (Strg+Z)",
redoTitle: "Wiederholen (Strg+Umschalt+Z)",
resetCodeTitle: "Auf Anfangscode zurücksetzen",
run: "Ausführen",
rerun: "Erneut anwenden",
// Preview
yourOutput: "Deine Ausgabe",
showExpected: "Lösung zeigen",
hideExpected: "Lösung ausblenden",
previous: "Zurück",
next: "Weiter",
levelIndicator: "Lektion {current} von {total}",
// Sidebar
menu: "Menü",
closeMenu: "Menü schließen",
progress: "Fortschritt",
progressText: "{percent}% abgeschlossen ({completed}/{total})",
lessons: "Lektionen",
settings: "Einstellungen",
showHints: "Hinweise anzeigen",
resetAllProgress: "Fortschritt zurücksetzen",
openSource: "Open Source:",
by: "von",
// Help dialog
helpTitle: "Hilfe",
aboutTitle: "Über Code Crispies",
aboutText: "Code Crispies ist eine kostenlose Open-Source-Plattform zum Erlernen von Webentwicklung durch praktische Übungen. Kein Konto erforderlich - einfach loslegen!",
learningModesTitle: "Lernmodi",
modeCss: "<strong>CSS</strong> - Schreibe CSS-Regeln zum Stylen von Elementen",
modeTailwind: "<strong>Tailwind</strong> - Wende Utility-Klassen direkt im HTML an",
modeHtml: "<strong>HTML</strong> - Übe semantisches Markup und native Elemente",
gettingStartedTitle: "Erste Schritte",
gettingStartedText: "Öffne das Menü (☰), um Lektionsmodule zu durchsuchen. Jedes Modul behandelt ein Thema mit aufeinander aufbauenden Übungen.",
completingLessonsTitle: "Lektionen abschließen",
completingStep1: "Lies die Aufgabenstellung auf der linken Seite",
completingStep2: "Schreibe deinen Code im Editor",
completingStep3: "Beobachte die Live-Vorschau während du tippst",
completingStep4: "Folge den Hinweisen, um Fehler zu beheben",
completingStep5: "Klicke auf <strong>Weiter</strong>, wenn du fertig bist",
editorToolsTitle: "Editor-Werkzeuge",
editorToolUndo: "<strong>↶ Rückgängig</strong> / <strong>↷ Wiederholen</strong> - Bearbeitungsverlauf navigieren",
editorToolReset: "<strong>⟲ Zurücksetzen</strong> - Ursprünglichen Code wiederherstellen",
editorToolExpected: "<strong>Lösung zeigen</strong> - Zielergebnis ein-/ausblenden",
keyboardShortcutsTitle: "Tastenkürzel",
shortcutRun: "<kbd>Strg+Enter</kbd> - Sofort validieren",
shortcutUndo: "<kbd>Strg+Z</kbd> - Rückgängig",
shortcutRedo: "<kbd>Strg+Umschalt+Z</kbd> - Wiederholen",
emmetTitle: "Emmet-Kürzel (HTML-Modus)",
emmetText: "Tippe Abkürzungen und drücke <kbd>Tab</kbd> zum Erweitern:",
emmetClass: "<kbd>div.box</kbd> → div mit Klasse",
emmetChildren: "<kbd>ul>li*3</kbd> → ul mit 3 li-Kindern",
emmetNested: "<kbd>form>input+button</kbd> → verschachtelte Struktur",
emmetContent: "<kbd>p{Hallo}</kbd> → p mit Textinhalt",
// Reset dialog
resetDialogTitle: "Fortschritt zurücksetzen",
resetDialogText: "Bist du sicher, dass du deinen gesamten Fortschritt zurücksetzen möchtest? Dies kann nicht rückgängig gemacht werden.",
cancel: "Abbrechen",
resetAll: "Alles zurücksetzen",
// Dynamic content
completed: "Erledigt",
successMessage: "CRISPY! ٩(◕‿◕)۶ Dein Code funktioniert.",
keepTrying: "Weiter versuchen!",
failedToLoad: "Module konnten nicht geladen werden. Bitte Seite neu laden.",
tailwindPlaceholder: "Tailwind-Klassen eingeben (z.B. bg-blue-500 text-white p-4)",
lessonFallback: "Lektion {index}",
untitledLesson: "Unbenannte Lektion"
}
};
let currentLang = "en";
/**
* Detect initial language from localStorage or browser
*/
export function detectLanguage() {
// Check localStorage first
const stored = localStorage.getItem("codeCrispies.language");
if (stored && translations[stored]) {
return stored;
}
// Check browser language
const browserLang = navigator.language.split("-")[0];
if (translations[browserLang]) {
return browserLang;
}
return "en";
}
/**
* Get current language
*/
export function getLanguage() {
return currentLang;
}
/**
* Set language and persist to localStorage
*/
export function setLanguage(lang) {
if (!translations[lang]) {
console.warn(`Language "${lang}" not supported, falling back to English`);
lang = "en";
}
currentLang = lang;
localStorage.setItem("codeCrispies.language", lang);
document.documentElement.lang = lang;
}
/**
* Get a translation by key with optional interpolation
* @param {string} key - Translation key
* @param {Object} params - Optional parameters for interpolation
*/
export function t(key, params = {}) {
const text = translations[currentLang]?.[key] || translations.en[key] || key;
if (Object.keys(params).length === 0) {
return text;
}
// Replace {param} placeholders
return text.replace(/\{(\w+)\}/g, (match, param) => {
return params[param] !== undefined ? params[param] : match;
});
}
/**
* Apply translations to all elements with data-i18n attribute
*/
export function applyTranslations() {
// Update page title
document.title = t("pageTitle");
// Update elements with data-i18n attribute (text content)
document.querySelectorAll("[data-i18n]").forEach((el) => {
const key = el.dataset.i18n;
el.textContent = t(key);
});
// Update elements with data-i18n-html attribute (innerHTML)
document.querySelectorAll("[data-i18n-html]").forEach((el) => {
const key = el.dataset.i18nHtml;
el.innerHTML = t(key);
});
// Update elements with data-i18n-title attribute
document.querySelectorAll("[data-i18n-title]").forEach((el) => {
const key = el.dataset.i18nTitle;
el.title = t(key);
});
// Update elements with data-i18n-aria-label attribute
document.querySelectorAll("[data-i18n-aria-label]").forEach((el) => {
const key = el.dataset.i18nAriaLabel;
el.setAttribute("aria-label", t(key));
});
// Update elements with data-i18n-placeholder attribute
document.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
const key = el.dataset.i18nPlaceholder;
el.placeholder = t(key);
});
}
/**
* Initialize i18n system
*/
export function initI18n() {
const lang = detectLanguage();
setLanguage(lang);
applyTranslations();
}

View File

@@ -1,213 +0,0 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="./favicon.ico" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CODE CRISPIES - CSS interaktiv lernen</title>
<link rel="stylesheet" href="main.css" />
</head>
<body>
<a href="#main-content" class="skip-link">Zum Hauptinhalt springen</a>
<div class="app-container">
<!-- Minimaler Header -->
<header class="header">
<button id="menu-btn" class="menu-toggle" aria-label="Menü öffnen">
<span class="hamburger-line"></span>
<span class="hamburger-line"></span>
<span class="hamburger-line"></span>
</button>
<div class="logo">
<img src="./bowl.png" width="40" alt="CODE CRISPIES Logo" />
<h1>CODE<span>CRISPIES</span></h1>
</div>
<div class="header-actions">
<a href="./index.html" class="lang-switch" aria-label="Switch language: English">EN</a>
<button id="help-btn" class="help-toggle" aria-label="Hilfe">?</button>
</div>
</header>
<!-- Hauptlayout -->
<main class="game-layout" id="main-content">
<!-- Linke Spalte: Anleitung + Editor -->
<div class="left-panel">
<section class="instructions">
<span class="module-pill" id="module-pill">Laden...</span>
<h2 id="lesson-title">Laden...</h2>
<div class="lesson-description" id="lesson-description">
Bitte wähle eine Lektion aus, um zu beginnen.
</div>
<div class="task-instruction" id="task-instruction">
<!-- Aufgabenanweisungen werden hier angezeigt -->
</div>
</section>
<section class="editor-section">
<div class="code-editor">
<div class="editor-header">
<label for="code-input" class="editor-label">CSS-Editor</label>
<div class="editor-actions">
<div class="editor-tools">
<button id="undo-btn" class="btn btn-icon" title="Rückgängig (Strg+Z)"></button>
<button id="redo-btn" class="btn btn-icon" title="Wiederholen (Strg+Umschalt+Z)"></button>
<button id="reset-code-btn" class="btn btn-icon" title="Auf Anfangscode zurücksetzen"></button>
</div>
<button id="run-btn" class="btn btn-run">
<img src="./gear.svg" alt="" />Ausführen
</button>
</div>
</div>
<div class="editor-content">
<!-- Textarea wird durch CodeMirror ersetzt -->
<textarea id="code-input" class="code-input" spellcheck="false" autocomplete="off" style="display: none;"></textarea>
</div>
</div>
<div class="hint-area" id="hint-area">
<!-- Hinweise werden hier angezeigt -->
</div>
</section>
</div>
<!-- Rechte Spalte: Vorschau + Navigation -->
<div class="right-panel">
<div class="preview-section">
<div class="preview-header">
<span class="preview-label">Deine Ausgabe</span>
<button id="show-expected-btn" class="btn btn-small">Lösung zeigen</button>
</div>
<div class="preview-wrapper">
<div class="preview-frame" id="preview-area">
<!-- Vorschau-Iframe wird hier angezeigt -->
</div>
<div class="expected-overlay" id="expected-overlay">
<div class="expected-frame" id="preview-expected">
<!-- Erwartetes Ergebnis (umschaltbar) -->
</div>
</div>
</div>
</div>
<div class="game-controls">
<button id="prev-btn" class="btn">Zurück</button>
<div class="level-indicator" id="level-indicator">Lektion 0/0</div>
<button id="next-btn" class="btn btn-primary">Weiter</button>
</div>
</div>
</main>
<!-- Seitenleisten-Hintergrund -->
<div class="sidebar-backdrop" id="sidebar-backdrop"></div>
<!-- Ausklappbare Seitenleiste -->
<aside class="sidebar-drawer" id="sidebar-drawer" aria-label="Navigationsmenü">
<div class="sidebar-header">
<h3>Menü</h3>
<button id="close-sidebar" class="close-btn" aria-label="Menü schließen">&times;</button>
</div>
<div class="sidebar-section">
<h4>Fortschritt</h4>
<div class="progress-display" id="progress-display">
<div class="progress-bar">
<div class="progress-fill" id="progress-fill"></div>
</div>
<span class="progress-text" id="progress-text">0% abgeschlossen</span>
</div>
</div>
<nav class="sidebar-section" aria-label="Lektionsnavigation">
<h4 id="lessons-heading">Lektionen</h4>
<div class="module-list" id="module-list" role="tree" aria-labelledby="lessons-heading">
<!-- Modulliste wird hier eingefügt -->
</div>
</nav>
<div class="sidebar-section">
<h4>Einstellungen</h4>
<label class="toggle-switch">
<input type="checkbox" id="disable-feedback-toggle" checked />
<span class="toggle-slider"></span>
<span class="toggle-label">Hinweise anzeigen</span>
</label>
<button id="reset-btn" class="btn btn-text">Fortschritt zurücksetzen</button>
</div>
<footer class="app-footer">
Open Source:
<a href="https://github.com/nextlevelshit/code-crispies" target="_blank">GitHub</a>
von <a href="https://dailysh.it" title="Michael W. Czechowski">mwc</a>
</footer>
</aside>
<!-- Hilfe-Dialog -->
<dialog id="help-dialog" class="dialog">
<div class="dialog-header">
<h3>Hilfe</h3>
<button id="help-dialog-close" class="dialog-close" aria-label="Schließen">&times;</button>
</div>
<div class="dialog-content">
<h4>Über Code Crispies</h4>
<p>Code Crispies ist eine kostenlose Open-Source-Plattform zum Erlernen von Webentwicklung durch praktische Übungen. Kein Konto erforderlich - einfach loslegen!</p>
<h4>Lernmodi</h4>
<ul>
<li><strong>CSS</strong> - Schreibe CSS-Regeln zum Stylen von Elementen</li>
<li><strong>Tailwind</strong> - Wende Utility-Klassen direkt im HTML an</li>
<li><strong>HTML</strong> - Übe semantisches Markup und native Elemente</li>
</ul>
<h4>Erste Schritte</h4>
<p>Öffne das Menü (☰), um Lektionsmodule zu durchsuchen. Jedes Modul behandelt ein Thema mit aufeinander aufbauenden Übungen.</p>
<h4>Lektionen abschließen</h4>
<ol>
<li>Lies die Aufgabenstellung auf der linken Seite</li>
<li>Schreibe deinen Code im Editor</li>
<li>Klicke auf <strong>Ausführen</strong> oder drücke <kbd>Strg+Enter</kbd></li>
<li>Folge den Hinweisen, um Fehler zu beheben</li>
<li>Klicke auf <strong>Weiter</strong>, wenn du fertig bist</li>
</ol>
<h4>Editor-Werkzeuge</h4>
<ul>
<li><strong>↶ Rückgängig</strong> / <strong>↷ Wiederholen</strong> - Bearbeitungsverlauf navigieren</li>
<li><strong>⟲ Zurücksetzen</strong> - Ursprünglichen Code wiederherstellen</li>
<li><strong>Lösung zeigen</strong> - Zielergebnis ein-/ausblenden</li>
</ul>
<h4>Tastenkürzel</h4>
<ul>
<li><kbd>Strg+Enter</kbd> - Code ausführen</li>
<li><kbd>Strg+Z</kbd> - Rückgängig</li>
<li><kbd>Strg+Umschalt+Z</kbd> - Wiederholen</li>
</ul>
<h4>Emmet-Kürzel (HTML-Modus)</h4>
<p>Tippe Abkürzungen und drücke <kbd>Tab</kbd> zum Erweitern:</p>
<ul>
<li><kbd>div.box</kbd> → div mit Klasse</li>
<li><kbd>ul>li*3</kbd> → ul mit 3 li-Kindern</li>
<li><kbd>form>input+button</kbd> → verschachtelte Struktur</li>
<li><kbd>p{Hallo}</kbd> → p mit Textinhalt</li>
</ul>
</div>
</dialog>
<!-- Zurücksetzen-Bestätigungsdialog -->
<dialog id="reset-dialog" class="dialog">
<div class="dialog-header">
<h3>Fortschritt zurücksetzen</h3>
<button id="reset-dialog-close" class="dialog-close" aria-label="Schließen">&times;</button>
</div>
<div class="dialog-content">
<p>Bist du sicher, dass du deinen gesamten Fortschritt zurücksetzen möchtest? Dies kann nicht rückgängig gemacht werden.</p>
<div class="dialog-actions">
<button id="cancel-reset" class="btn">Abbrechen</button>
<button id="confirm-reset" class="btn btn-ghost">Alles zurücksetzen</button>
</div>
</div>
</dialog>
</div>
<script type="module" src="app.de.js"></script>
</body>
</html>

View File

@@ -8,11 +8,10 @@
<link rel="stylesheet" href="main.css" /> <link rel="stylesheet" href="main.css" />
</head> </head>
<body> <body>
<a href="#main-content" class="skip-link">Skip to main content</a> <a href="#main-content" class="skip-link" data-i18n="skipLink">Skip to main content</a>
<div class="app-container"> <div class="app-container">
<!-- Minimal Header -->
<header class="header"> <header class="header">
<button id="menu-btn" class="menu-toggle" aria-label="Open menu"> <button id="menu-btn" class="menu-toggle" data-i18n-aria-label="menuOpen" aria-label="Open menu">
<span class="hamburger-line"></span> <span class="hamburger-line"></span>
<span class="hamburger-line"></span> <span class="hamburger-line"></span>
<span class="hamburger-line"></span> <span class="hamburger-line"></span>
@@ -22,49 +21,43 @@
<h1>CODE<span>CRISPIES</span></h1> <h1>CODE<span>CRISPIES</span></h1>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<a href="./index.de.html" class="lang-switch" aria-label="Sprache wechseln: Deutsch">DE</a> <button id="lang-btn" class="lang-switch" data-i18n-aria-label="langSwitchLabel" data-i18n="langSwitch" aria-label="Sprache wechseln: Deutsch">DE</button>
<button id="help-btn" class="help-toggle" aria-label="Help">?</button> <button id="help-btn" class="help-toggle" data-i18n-aria-label="help" aria-label="Help">?</button>
</div> </div>
</header> </header>
<!-- Main Game Layout -->
<main class="game-layout" id="main-content"> <main class="game-layout" id="main-content">
<!-- Left Panel: Instructions + Editor --> <!-- Left Panel: Instructions + Editor -->
<div class="left-panel"> <div class="left-panel">
<section class="instructions"> <section class="instructions">
<span class="module-pill" id="module-pill">Loading...</span> <span class="module-pill" id="module-pill" data-i18n="loading">Loading...</span>
<h2 id="lesson-title">Loading...</h2> <h2 id="lesson-title" data-i18n="loading">Loading...</h2>
<div class="lesson-description" id="lesson-description"> <div class="lesson-description" id="lesson-description" data-i18n="selectLesson">
Please select a lesson to begin. Please select a lesson to begin.
</div> </div>
<div class="task-instruction" id="task-instruction"> <div class="task-instruction" id="task-instruction"></div>
<!-- Task instructions will be shown here -->
</div>
</section> </section>
<section class="editor-section"> <section class="editor-section">
<div class="code-editor"> <div class="code-editor">
<div class="editor-header"> <div class="editor-header">
<label for="code-input" class="editor-label">CSS Editor</label> <label for="code-input" class="editor-label" data-i18n="editorLabel">CSS Editor</label>
<div class="editor-actions"> <div class="editor-actions">
<div class="editor-tools"> <div class="editor-tools">
<button id="undo-btn" class="btn btn-icon" title="Undo (Ctrl+Z)"></button> <button id="undo-btn" class="btn btn-icon" data-i18n-title="undoTitle" title="Undo (Ctrl+Z)"></button>
<button id="redo-btn" class="btn btn-icon" title="Redo (Ctrl+Shift+Z)"></button> <button id="redo-btn" class="btn btn-icon" data-i18n-title="redoTitle" title="Redo (Ctrl+Shift+Z)"></button>
<button id="reset-code-btn" class="btn btn-icon" title="Reset to initial code"></button> <button id="reset-code-btn" class="btn btn-icon" data-i18n-title="resetCodeTitle" title="Reset to initial code"></button>
</div> </div>
<button id="run-btn" class="btn btn-run"> <button id="run-btn" class="btn btn-run">
<img src="./gear.svg" alt="" />Run <img src="./gear.svg" alt="" /><span data-i18n="run">Run</span>
</button> </button>
</div> </div>
</div> </div>
<div class="editor-content"> <div class="editor-content">
<!-- Textarea is replaced by CodeMirror; autocomplete off prevents browser form restoration -->
<textarea id="code-input" class="code-input" spellcheck="false" autocomplete="off" style="display: none;"></textarea> <textarea id="code-input" class="code-input" spellcheck="false" autocomplete="off" style="display: none;"></textarea>
</div> </div>
</div> </div>
<div class="hint-area" id="hint-area"> <div class="hint-area" id="hint-area"></div>
<!-- Hints displayed inline here -->
</div>
</section> </section>
</div> </div>
@@ -72,24 +65,20 @@
<div class="right-panel"> <div class="right-panel">
<div class="preview-section"> <div class="preview-section">
<div class="preview-header"> <div class="preview-header">
<span class="preview-label">Your Output</span> <span class="preview-label" data-i18n="yourOutput">Your Output</span>
<button id="show-expected-btn" class="btn btn-small">Show Expected</button> <button id="show-expected-btn" class="btn btn-small" data-i18n="showExpected">Show Expected</button>
</div> </div>
<div class="preview-wrapper"> <div class="preview-wrapper">
<div class="preview-frame" id="preview-area"> <div class="preview-frame" id="preview-area"></div>
<!-- User's preview iframe will be shown here -->
</div>
<div class="expected-overlay" id="expected-overlay"> <div class="expected-overlay" id="expected-overlay">
<div class="expected-frame" id="preview-expected"> <div class="expected-frame" id="preview-expected"></div>
<!-- Expected result iframe (toggleable) -->
</div>
</div> </div>
</div> </div>
</div> </div>
<div class="game-controls"> <div class="game-controls">
<button id="prev-btn" class="btn">Previous</button> <button id="prev-btn" class="btn" data-i18n="previous">Previous</button>
<div class="level-indicator" id="level-indicator">Level 0/0</div> <div class="level-indicator" id="level-indicator">Level 0/0</div>
<button id="next-btn" class="btn btn-primary">Next</button> <button id="next-btn" class="btn btn-primary" data-i18n="next">Next</button>
</div> </div>
</div> </div>
</main> </main>
@@ -98,14 +87,14 @@
<div class="sidebar-backdrop" id="sidebar-backdrop"></div> <div class="sidebar-backdrop" id="sidebar-backdrop"></div>
<!-- Slide-out Sidebar --> <!-- Slide-out Sidebar -->
<aside class="sidebar-drawer" id="sidebar-drawer" aria-label="Navigation menu"> <aside class="sidebar-drawer" id="sidebar-drawer" data-i18n-aria-label="menu" aria-label="Menu">
<div class="sidebar-header"> <div class="sidebar-header">
<h3>Menu</h3> <h3 data-i18n="menu">Menu</h3>
<button id="close-sidebar" class="close-btn" aria-label="Close menu">&times;</button> <button id="close-sidebar" class="close-btn" data-i18n-aria-label="closeMenu" aria-label="Close menu">&times;</button>
</div> </div>
<div class="sidebar-section"> <div class="sidebar-section">
<h4>Progress</h4> <h4 data-i18n="progress">Progress</h4>
<div class="progress-display" id="progress-display"> <div class="progress-display" id="progress-display">
<div class="progress-bar"> <div class="progress-bar">
<div class="progress-fill" id="progress-fill"></div> <div class="progress-fill" id="progress-fill"></div>
@@ -115,79 +104,77 @@
</div> </div>
<nav class="sidebar-section" aria-label="Lesson navigation"> <nav class="sidebar-section" aria-label="Lesson navigation">
<h4 id="lessons-heading">Lessons</h4> <h4 id="lessons-heading" data-i18n="lessons">Lessons</h4>
<div class="module-list" id="module-list" role="tree" aria-labelledby="lessons-heading"> <div class="module-list" id="module-list" role="tree" aria-labelledby="lessons-heading"></div>
<!-- Module list will be populated here -->
</div>
</nav> </nav>
<div class="sidebar-section"> <div class="sidebar-section">
<h4>Settings</h4> <h4 data-i18n="settings">Settings</h4>
<label class="toggle-switch"> <label class="toggle-switch">
<input type="checkbox" id="disable-feedback-toggle" checked /> <input type="checkbox" id="disable-feedback-toggle" checked />
<span class="toggle-slider"></span> <span class="toggle-slider"></span>
<span class="toggle-label">Show Hints</span> <span class="toggle-label" data-i18n="showHints">Show Hints</span>
</label> </label>
<button id="reset-btn" class="btn btn-text">Reset All Progress</button> <button id="reset-btn" class="btn btn-text" data-i18n="resetAllProgress">Reset All Progress</button>
</div> </div>
<footer class="app-footer"> <footer class="app-footer">
Open Source: <span data-i18n="openSource">Open Source:</span>
<a href="https://github.com/nextlevelshit/code-crispies" target="_blank">GitHub</a> <a href="https://github.com/nextlevelshit/code-crispies" target="_blank">GitHub</a>
by <a href="https://dailysh.it" title="Michael W. Czechowski">mwc</a> <span data-i18n="by">by</span> <a href="https://dailysh.it" title="Michael W. Czechowski">mwc</a>
</footer> </footer>
</aside> </aside>
<!-- Help Dialog --> <!-- Help Dialog -->
<dialog id="help-dialog" class="dialog"> <dialog id="help-dialog" class="dialog">
<div class="dialog-header"> <div class="dialog-header">
<h3>Help</h3> <h3 data-i18n="helpTitle">Help</h3>
<button id="help-dialog-close" class="dialog-close" aria-label="Close">&times;</button> <button id="help-dialog-close" class="dialog-close" aria-label="Close">&times;</button>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
<h4>About Code Crispies</h4> <h4 data-i18n="aboutTitle">About Code Crispies</h4>
<p>Code Crispies is a free, open-source platform for learning web development through hands-on exercises. No account required - just start coding!</p> <p data-i18n="aboutText">Code Crispies is a free, open-source platform for learning web development through hands-on exercises. No account required - just start coding!</p>
<h4>Learning Modes</h4> <h4 data-i18n="learningModesTitle">Learning Modes</h4>
<ul> <ul>
<li><strong>CSS</strong> - Write CSS rules to style elements</li> <li data-i18n-html="modeCss"><strong>CSS</strong> - Write CSS rules to style elements</li>
<li><strong>Tailwind</strong> - Apply utility classes directly in HTML</li> <li data-i18n-html="modeTailwind"><strong>Tailwind</strong> - Apply utility classes directly in HTML</li>
<li><strong>HTML</strong> - Practice semantic markup and native elements</li> <li data-i18n-html="modeHtml"><strong>HTML</strong> - Practice semantic markup and native elements</li>
</ul> </ul>
<h4>Getting Started</h4> <h4 data-i18n="gettingStartedTitle">Getting Started</h4>
<p>Open the menu (☰) to browse lesson modules. Each module covers a specific topic with progressive exercises.</p> <p data-i18n="gettingStartedText">Open the menu (☰) to browse lesson modules. Each module covers a specific topic with progressive exercises.</p>
<h4>Completing Lessons</h4> <h4 data-i18n="completingLessonsTitle">Completing Lessons</h4>
<ol> <ol>
<li>Read the task instructions on the left</li> <li data-i18n="completingStep1">Read the task instructions on the left</li>
<li>Write your code in the editor</li> <li data-i18n="completingStep2">Write your code in the editor</li>
<li>Click <strong>Run</strong> or press <kbd>Ctrl+Enter</kbd> to test</li> <li data-i18n="completingStep3">Watch the live preview update as you type</li>
<li>Follow hints to fix any issues</li> <li data-i18n="completingStep4">Follow hints to fix any issues</li>
<li>Click <strong>Next</strong> when complete</li> <li data-i18n-html="completingStep5">Click <strong>Next</strong> when complete</li>
</ol> </ol>
<h4>Editor Tools</h4> <h4 data-i18n="editorToolsTitle">Editor Tools</h4>
<ul> <ul>
<li><strong>↶ Undo</strong> / <strong>↷ Redo</strong> - Navigate edit history</li> <li data-i18n-html="editorToolUndo"><strong>↶ Undo</strong> / <strong>↷ Redo</strong> - Navigate edit history</li>
<li><strong>⟲ Reset</strong> - Restore initial code for current lesson</li> <li data-i18n-html="editorToolReset"><strong>⟲ Reset</strong> - Restore initial code for current lesson</li>
<li><strong>Show Expected</strong> - Toggle the target result overlay</li> <li data-i18n-html="editorToolExpected"><strong>Show Expected</strong> - Toggle the target result overlay</li>
</ul> </ul>
<h4>Keyboard Shortcuts</h4> <h4 data-i18n="keyboardShortcutsTitle">Keyboard Shortcuts</h4>
<ul> <ul>
<li><kbd>Ctrl+Enter</kbd> - Run your code</li> <li data-i18n-html="shortcutRun"><kbd>Ctrl+Enter</kbd> - Validate immediately</li>
<li><kbd>Ctrl+Z</kbd> - Undo</li> <li data-i18n-html="shortcutUndo"><kbd>Ctrl+Z</kbd> - Undo</li>
<li><kbd>Ctrl+Shift+Z</kbd> - Redo</li> <li data-i18n-html="shortcutRedo"><kbd>Ctrl+Shift+Z</kbd> - Redo</li>
</ul> </ul>
<h4>Emmet Shortcuts (HTML mode)</h4> <h4 data-i18n="emmetTitle">Emmet Shortcuts (HTML mode)</h4>
<p>Type abbreviations and press <kbd>Tab</kbd> to expand:</p> <p data-i18n-html="emmetText">Type abbreviations and press <kbd>Tab</kbd> to expand:</p>
<ul> <ul>
<li><kbd>div.box</kbd> → div with class</li> <li data-i18n-html="emmetClass"><kbd>div.box</kbd> → div with class</li>
<li><kbd>ul>li*3</kbd> → ul with 3 li children</li> <li data-i18n-html="emmetChildren"><kbd>ul>li*3</kbd> → ul with 3 li children</li>
<li><kbd>form>input+button</kbd> → nested structure</li> <li data-i18n-html="emmetNested"><kbd>form>input+button</kbd> → nested structure</li>
<li><kbd>p{Hello}</kbd> → p with text content</li> <li data-i18n-html="emmetContent"><kbd>p{Hello}</kbd> → p with text content</li>
</ul> </ul>
</div> </div>
</dialog> </dialog>
@@ -195,14 +182,14 @@
<!-- Reset Confirmation Dialog --> <!-- Reset Confirmation Dialog -->
<dialog id="reset-dialog" class="dialog"> <dialog id="reset-dialog" class="dialog">
<div class="dialog-header"> <div class="dialog-header">
<h3>Reset Progress</h3> <h3 data-i18n="resetDialogTitle">Reset Progress</h3>
<button id="reset-dialog-close" class="dialog-close" aria-label="Close">&times;</button> <button id="reset-dialog-close" class="dialog-close" aria-label="Close">&times;</button>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
<p>Are you sure you want to reset all your progress? This cannot be undone.</p> <p data-i18n="resetDialogText">Are you sure you want to reset all your progress? This cannot be undone.</p>
<div class="dialog-actions"> <div class="dialog-actions">
<button id="cancel-reset" class="btn">Cancel</button> <button id="cancel-reset" class="btn" data-i18n="cancel">Cancel</button>
<button id="confirm-reset" class="btn btn-ghost">Reset All</button> <button id="confirm-reset" class="btn btn-ghost" data-i18n="resetAll">Reset All</button>
</div> </div>
</div> </div>
</dialog> </dialog>

View File

@@ -30,10 +30,7 @@ describe("Renderer Module", () => {
renderModuleList(container, modules, onSelectModule, onSelectLesson); renderModuleList(container, modules, onSelectModule, onSelectLesson);
// Check if heading is created // Check if module headers are created (heading is now in HTML, not added by renderer)
expect(container.innerHTML).toContain("<h3>Lessons</h3>");
// Check if module headers are created
const moduleHeaders = container.querySelectorAll(".module-header"); const moduleHeaders = container.querySelectorAll(".module-header");
expect(moduleHeaders.length).toBe(2); expect(moduleHeaders.length).toBe(2);
@@ -46,7 +43,8 @@ describe("Renderer Module", () => {
const container = document.getElementById("module-list"); const container = document.getElementById("module-list");
renderModuleList(container, [], vi.fn(), vi.fn()); renderModuleList(container, [], vi.fn(), vi.fn());
expect(container.innerHTML).toContain("<h3>Lessons</h3>"); // Container should be empty (heading is now in HTML, not added by renderer)
expect(container.innerHTML).toBe("");
expect(container.querySelectorAll(".module-header").length).toBe(0); expect(container.querySelectorAll(".module-header").length).toBe(0);
}); });

View File

@@ -10,11 +10,11 @@ export default defineConfig((env) => ({
sourcemap: true sourcemap: true
}, },
server: { server: {
port: 1312, port: 1234,
open: false open: false
}, },
preview: { preview: {
port: 1312, port: 1234,
open: false open: false
} }
})); }));