style: run format first time
This commit is contained in:
72
package.json
72
package.json
@@ -1,38 +1,38 @@
|
|||||||
{
|
{
|
||||||
"name": "code-crispies",
|
"name": "code-crispies",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "An interactive platform for learning CSS through practical challenges",
|
"description": "An interactive platform for learning CSS through practical challenges",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "npm run dev",
|
"start": "npm run dev",
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test.watch": "vitest watch",
|
"test.watch": "vitest watch",
|
||||||
"test.coverage": "vitest run --coverage",
|
"test.coverage": "vitest run --coverage",
|
||||||
"format": "prettier --write src/ tests/ package.json vite.config.js vitest.config.js",
|
"format": "prettier --write src/ tests/ package.json vite.config.js vitest.config.js",
|
||||||
"format.lessons": "prettier --write lessons/*.json"
|
"format.lessons": "prettier --write lessons/*.json"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"css",
|
"css",
|
||||||
"html",
|
"html",
|
||||||
"learning",
|
"learning",
|
||||||
"interactive",
|
"interactive",
|
||||||
"education"
|
"education"
|
||||||
],
|
],
|
||||||
"author": "Michael Czechowski <mail@dailysh.it>",
|
"author": "Michael Czechowski <mail@dailysh.it>",
|
||||||
"license": "Copyright Michael Czechowski 2025",
|
"license": "Copyright Michael Czechowski 2025",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@testing-library/dom": "^10.4.0",
|
"@testing-library/dom": "^10.4.0",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@vitest/coverage-v8": "^3.1.3",
|
"@vitest/coverage-v8": "^3.1.3",
|
||||||
"jsdom": "^26.1.0",
|
"jsdom": "^26.1.0",
|
||||||
"prettier": "^3.5.3",
|
"prettier": "^3.5.3",
|
||||||
"vite": "^6.3.5",
|
"vite": "^6.3.5",
|
||||||
"vitest": "^3.1.3"
|
"vitest": "^3.1.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"whatwg-fetch": "^3.6.20"
|
"whatwg-fetch": "^3.6.20"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
569
src/app.js
569
src/app.js
@@ -1,39 +1,39 @@
|
|||||||
import { LessonEngine } from './impl/LessonEngine.js';
|
import { LessonEngine } from "./impl/LessonEngine.js";
|
||||||
import { renderLesson, renderModuleList, renderLevelIndicator, showFeedback } from './helpers/renderer.js';
|
import { renderLesson, renderModuleList, renderLevelIndicator, showFeedback } from "./helpers/renderer.js";
|
||||||
import { validateUserCode } from './helpers/validator.js';
|
import { validateUserCode } from "./helpers/validator.js";
|
||||||
import { loadModules } from './config/lessons.js';
|
import { loadModules } from "./config/lessons.js";
|
||||||
|
|
||||||
// Main Application state
|
// Main Application state
|
||||||
const state = {
|
const state = {
|
||||||
currentModule: null,
|
currentModule: null,
|
||||||
currentLessonIndex: 0,
|
currentLessonIndex: 0,
|
||||||
modules: [],
|
modules: [],
|
||||||
userProgress: {}, // Format: { moduleId: { completed: [0, 2, 3], current: 4 } }
|
userProgress: {} // Format: { moduleId: { completed: [0, 2, 3], current: 4 } }
|
||||||
};
|
};
|
||||||
|
|
||||||
// DOM elements
|
// DOM elements
|
||||||
const elements = {
|
const elements = {
|
||||||
moduleList: document.querySelector('.module-list'),
|
moduleList: document.querySelector(".module-list"),
|
||||||
lessonTitle: document.getElementById('lesson-title'),
|
lessonTitle: document.getElementById("lesson-title"),
|
||||||
lessonDescription: document.getElementById('lesson-description'),
|
lessonDescription: document.getElementById("lesson-description"),
|
||||||
taskInstruction: document.getElementById('task-instruction'),
|
taskInstruction: document.getElementById("task-instruction"),
|
||||||
previewArea: document.getElementById('preview-area'),
|
previewArea: document.getElementById("preview-area"),
|
||||||
editorPrefix: document.getElementById('editor-prefix'),
|
editorPrefix: document.getElementById("editor-prefix"),
|
||||||
codeInput: document.getElementById('code-input'),
|
codeInput: document.getElementById("code-input"),
|
||||||
editorSuffix: document.getElementById('editor-suffix'),
|
editorSuffix: document.getElementById("editor-suffix"),
|
||||||
prevBtn: document.getElementById('prev-btn'),
|
prevBtn: document.getElementById("prev-btn"),
|
||||||
nextBtn: document.getElementById('next-btn'),
|
nextBtn: document.getElementById("next-btn"),
|
||||||
runBtn: document.getElementById('run-btn'),
|
runBtn: document.getElementById("run-btn"),
|
||||||
levelIndicator: document.getElementById('level-indicator'),
|
levelIndicator: document.getElementById("level-indicator"),
|
||||||
modalContainer: document.getElementById('modal-container'),
|
modalContainer: document.getElementById("modal-container"),
|
||||||
modalTitle: document.getElementById('modal-title'),
|
modalTitle: document.getElementById("modal-title"),
|
||||||
modalContent: document.getElementById('modal-content'),
|
modalContent: document.getElementById("modal-content"),
|
||||||
modalClose: document.getElementById('modal-close'),
|
modalClose: document.getElementById("modal-close"),
|
||||||
moduleSelectorBtn: document.getElementById('module-selector-btn'),
|
moduleSelectorBtn: document.getElementById("module-selector-btn"),
|
||||||
resetBtn: document.getElementById('reset-btn'),
|
resetBtn: document.getElementById("reset-btn"),
|
||||||
helpBtn: document.getElementById('help-btn'),
|
helpBtn: document.getElementById("help-btn"),
|
||||||
lessonContainer: document.querySelector('.lesson-container'),
|
lessonContainer: document.querySelector(".lesson-container"),
|
||||||
editorContent: document.querySelector('.editor-content')
|
editorContent: document.querySelector(".editor-content")
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initialize the lesson engine
|
// Initialize the lesson engine
|
||||||
@@ -41,61 +41,61 @@ const lessonEngine = new LessonEngine();
|
|||||||
|
|
||||||
// Load user progress from localStorage
|
// Load user progress from localStorage
|
||||||
function loadUserProgress() {
|
function loadUserProgress() {
|
||||||
const savedProgress = localStorage.getItem('codeCrispiesProgress');
|
const savedProgress = localStorage.getItem("codeCrispiesProgress");
|
||||||
if (savedProgress) {
|
if (savedProgress) {
|
||||||
state.userProgress = JSON.parse(savedProgress);
|
state.userProgress = JSON.parse(savedProgress);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save user progress to localStorage
|
// Save user progress to localStorage
|
||||||
function saveUserProgress() {
|
function saveUserProgress() {
|
||||||
localStorage.setItem('codeCrispiesProgress', JSON.stringify(state.userProgress));
|
localStorage.setItem("codeCrispiesProgress", JSON.stringify(state.userProgress));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize the module list
|
// Initialize the module list
|
||||||
async function initializeModules() {
|
async function initializeModules() {
|
||||||
try {
|
try {
|
||||||
state.modules = await loadModules();
|
state.modules = await loadModules();
|
||||||
renderModuleList(elements.moduleList, state.modules, selectModule);
|
renderModuleList(elements.moduleList, state.modules, selectModule);
|
||||||
|
|
||||||
// Select the first module or the last one user was on
|
// Select the first module or the last one user was on
|
||||||
const lastModuleId = localStorage.getItem('lastModuleId');
|
const lastModuleId = localStorage.getItem("lastModuleId");
|
||||||
if (lastModuleId && state.modules.find(m => m.id === lastModuleId)) {
|
if (lastModuleId && state.modules.find((m) => m.id === lastModuleId)) {
|
||||||
selectModule(lastModuleId);
|
selectModule(lastModuleId);
|
||||||
} else if (state.modules.length > 0) {
|
} else if (state.modules.length > 0) {
|
||||||
selectModule(state.modules[0].id);
|
selectModule(state.modules[0].id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update progress indicator on module selector button
|
// Update progress indicator on module selector button
|
||||||
updateModuleSelectorButtonProgress();
|
updateModuleSelectorButtonProgress();
|
||||||
} 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 = "Failed to load modules. Please refresh the page.";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update progress indicator on module selector button
|
// Update progress indicator on module selector button
|
||||||
function updateModuleSelectorButtonProgress() {
|
function updateModuleSelectorButtonProgress() {
|
||||||
if (!state.modules.length) return;
|
if (!state.modules.length) return;
|
||||||
|
|
||||||
// Calculate overall progress across all modules
|
// Calculate overall progress across all modules
|
||||||
let totalLessons = 0;
|
let totalLessons = 0;
|
||||||
let totalCompleted = 0;
|
let totalCompleted = 0;
|
||||||
|
|
||||||
state.modules.forEach(module => {
|
state.modules.forEach((module) => {
|
||||||
totalLessons += module.lessons.length;
|
totalLessons += module.lessons.length;
|
||||||
const progress = state.userProgress[module.id];
|
const progress = state.userProgress[module.id];
|
||||||
if (progress && progress.completed) {
|
if (progress && progress.completed) {
|
||||||
totalCompleted += progress.completed.length;
|
totalCompleted += progress.completed.length;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const percentComplete = totalLessons > 0 ? Math.round((totalCompleted / totalLessons) * 100) : 0;
|
const percentComplete = totalLessons > 0 ? Math.round((totalCompleted / totalLessons) * 100) : 0;
|
||||||
|
|
||||||
// Create progress indicator
|
// Create progress indicator
|
||||||
const progressBar = document.createElement('div');
|
const progressBar = document.createElement("div");
|
||||||
progressBar.className = 'progress-indicator';
|
progressBar.className = "progress-indicator";
|
||||||
progressBar.style.cssText = `
|
progressBar.style.cssText = `
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 0;
|
bottom: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
@@ -105,211 +105,206 @@ function updateModuleSelectorButtonProgress() {
|
|||||||
border-radius: 0 3px 3px 0;
|
border-radius: 0 3px 3px 0;
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// Add progress percentage text
|
// Add progress percentage text
|
||||||
elements.moduleSelectorBtn.innerHTML = `Progress <span style="font-size: 0.8em; opacity: 0.8;">${percentComplete}%</span>`;
|
elements.moduleSelectorBtn.innerHTML = `Progress <span style="font-size: 0.8em; opacity: 0.8;">${percentComplete}%</span>`;
|
||||||
elements.moduleSelectorBtn.style.position = 'relative';
|
elements.moduleSelectorBtn.style.position = "relative";
|
||||||
|
|
||||||
// Remove any existing progress bar before adding new one
|
// Remove any existing progress bar before adding new one
|
||||||
const existingBar = elements.moduleSelectorBtn.querySelector('.progress-indicator');
|
const existingBar = elements.moduleSelectorBtn.querySelector(".progress-indicator");
|
||||||
if (existingBar) {
|
if (existingBar) {
|
||||||
existingBar.remove();
|
existingBar.remove();
|
||||||
}
|
}
|
||||||
|
|
||||||
elements.moduleSelectorBtn.appendChild(progressBar);
|
elements.moduleSelectorBtn.appendChild(progressBar);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Select a module
|
// Select a module
|
||||||
function selectModule(moduleId) {
|
function selectModule(moduleId) {
|
||||||
const selectedModule = state.modules.find(module => module.id === moduleId);
|
const selectedModule = state.modules.find((module) => module.id === moduleId);
|
||||||
if (!selectedModule) return;
|
if (!selectedModule) return;
|
||||||
|
|
||||||
state.currentModule = selectedModule;
|
state.currentModule = selectedModule;
|
||||||
|
|
||||||
// Update module list UI
|
// Update module list UI
|
||||||
const moduleItems = elements.moduleList.querySelectorAll('.module-list-item');
|
const moduleItems = elements.moduleList.querySelectorAll(".module-list-item");
|
||||||
moduleItems.forEach(item => {
|
moduleItems.forEach((item) => {
|
||||||
item.classList.remove('active');
|
item.classList.remove("active");
|
||||||
if (item.dataset.moduleId === moduleId) {
|
if (item.dataset.moduleId === moduleId) {
|
||||||
item.classList.add('active');
|
item.classList.add("active");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Load user progress for this module
|
// Load user progress for this module
|
||||||
if (!state.userProgress[moduleId]) {
|
if (!state.userProgress[moduleId]) {
|
||||||
state.userProgress[moduleId] = { completed: [], current: 0 };
|
state.userProgress[moduleId] = { completed: [], current: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
state.currentLessonIndex = state.userProgress[moduleId].current || 0;
|
state.currentLessonIndex = state.userProgress[moduleId].current || 0;
|
||||||
loadCurrentLesson();
|
loadCurrentLesson();
|
||||||
|
|
||||||
// Save the last selected module
|
// Save the last selected module
|
||||||
localStorage.setItem('lastModuleId', moduleId);
|
localStorage.setItem("lastModuleId", moduleId);
|
||||||
|
|
||||||
// Reset any success indicators
|
// Reset any success indicators
|
||||||
resetSuccessIndicators();
|
resetSuccessIndicators();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset success indicators
|
// Reset success indicators
|
||||||
function resetSuccessIndicators() {
|
function resetSuccessIndicators() {
|
||||||
elements.lessonContainer.classList.remove('success-highlight');
|
elements.lessonContainer.classList.remove("success-highlight");
|
||||||
elements.lessonTitle.classList.remove('success-text');
|
elements.lessonTitle.classList.remove("success-text");
|
||||||
const headings = elements.lessonContainer.querySelectorAll('h2, h3, h4');
|
const headings = elements.lessonContainer.querySelectorAll("h2, h3, h4");
|
||||||
headings.forEach(heading => heading.classList.remove('success-text'));
|
headings.forEach((heading) => heading.classList.remove("success-text"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load the current lesson
|
// Load the current lesson
|
||||||
function loadCurrentLesson() {
|
function loadCurrentLesson() {
|
||||||
if (!state.currentModule || !state.currentModule.lessons) {
|
if (!state.currentModule || !state.currentModule.lessons) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure lesson index is in bounds
|
// Make sure lesson index is in bounds
|
||||||
if (state.currentLessonIndex >= state.currentModule.lessons.length) {
|
if (state.currentLessonIndex >= state.currentModule.lessons.length) {
|
||||||
state.currentLessonIndex = state.currentModule.lessons.length - 1;
|
state.currentLessonIndex = state.currentModule.lessons.length - 1;
|
||||||
} else if (state.currentLessonIndex < 0) {
|
} else if (state.currentLessonIndex < 0) {
|
||||||
state.currentLessonIndex = 0;
|
state.currentLessonIndex = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
const lesson = state.currentModule.lessons[state.currentLessonIndex];
|
const lesson = state.currentModule.lessons[state.currentLessonIndex];
|
||||||
lessonEngine.setLesson(lesson);
|
lessonEngine.setLesson(lesson);
|
||||||
|
|
||||||
// Reset any success indicators
|
// Reset any success indicators
|
||||||
resetSuccessIndicators();
|
resetSuccessIndicators();
|
||||||
|
|
||||||
// Update UI
|
// Update UI
|
||||||
renderLesson(
|
renderLesson(
|
||||||
elements.lessonTitle,
|
elements.lessonTitle,
|
||||||
elements.lessonDescription,
|
elements.lessonDescription,
|
||||||
elements.taskInstruction,
|
elements.taskInstruction,
|
||||||
elements.previewArea,
|
elements.previewArea,
|
||||||
elements.editorPrefix,
|
elements.editorPrefix,
|
||||||
elements.codeInput,
|
elements.codeInput,
|
||||||
elements.editorSuffix,
|
elements.editorSuffix,
|
||||||
lesson
|
lesson
|
||||||
);
|
);
|
||||||
|
|
||||||
// Update level indicator
|
// Update level indicator
|
||||||
renderLevelIndicator(
|
renderLevelIndicator(elements.levelIndicator, state.currentLessonIndex + 1, state.currentModule.lessons.length);
|
||||||
elements.levelIndicator,
|
|
||||||
state.currentLessonIndex + 1,
|
|
||||||
state.currentModule.lessons.length
|
|
||||||
);
|
|
||||||
|
|
||||||
// Update navigation buttons
|
// Update navigation buttons
|
||||||
updateNavigationButtons();
|
updateNavigationButtons();
|
||||||
|
|
||||||
// Save current progress
|
// Save current progress
|
||||||
state.userProgress[state.currentModule.id].current = state.currentLessonIndex;
|
state.userProgress[state.currentModule.id].current = state.currentLessonIndex;
|
||||||
saveUserProgress();
|
saveUserProgress();
|
||||||
|
|
||||||
// Update progress indicator on module selector button
|
// Update progress indicator on module selector button
|
||||||
updateModuleSelectorButtonProgress();
|
updateModuleSelectorButtonProgress();
|
||||||
|
|
||||||
// Focus on the code editor by default
|
// Focus on the code editor by default
|
||||||
elements.codeInput.focus();
|
elements.codeInput.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update navigation buttons state
|
// Update navigation buttons state
|
||||||
function updateNavigationButtons() {
|
function updateNavigationButtons() {
|
||||||
elements.prevBtn.disabled = state.currentLessonIndex === 0;
|
elements.prevBtn.disabled = state.currentLessonIndex === 0;
|
||||||
elements.nextBtn.disabled = !state.currentModule ||
|
elements.nextBtn.disabled = !state.currentModule || state.currentLessonIndex === state.currentModule.lessons.length - 1;
|
||||||
state.currentLessonIndex === state.currentModule.lessons.length - 1;
|
|
||||||
|
|
||||||
// Style changes for disabled buttons
|
// Style changes for disabled buttons
|
||||||
if (elements.prevBtn.disabled) {
|
if (elements.prevBtn.disabled) {
|
||||||
elements.prevBtn.classList.add('btn-disabled');
|
elements.prevBtn.classList.add("btn-disabled");
|
||||||
} else {
|
} else {
|
||||||
elements.prevBtn.classList.remove('btn-disabled');
|
elements.prevBtn.classList.remove("btn-disabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (elements.nextBtn.disabled) {
|
if (elements.nextBtn.disabled) {
|
||||||
elements.nextBtn.classList.add('btn-disabled');
|
elements.nextBtn.classList.add("btn-disabled");
|
||||||
} else {
|
} else {
|
||||||
elements.nextBtn.classList.remove('btn-disabled');
|
elements.nextBtn.classList.remove("btn-disabled");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Go to the next lesson
|
// Go to the next lesson
|
||||||
function nextLesson() {
|
function nextLesson() {
|
||||||
if (!state.currentModule) return;
|
if (!state.currentModule) return;
|
||||||
|
|
||||||
if (state.currentLessonIndex < state.currentModule.lessons.length - 1) {
|
if (state.currentLessonIndex < state.currentModule.lessons.length - 1) {
|
||||||
state.currentLessonIndex++;
|
state.currentLessonIndex++;
|
||||||
loadCurrentLesson();
|
loadCurrentLesson();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Go to the previous lesson
|
// Go to the previous lesson
|
||||||
function prevLesson() {
|
function prevLesson() {
|
||||||
if (state.currentLessonIndex > 0) {
|
if (state.currentLessonIndex > 0) {
|
||||||
state.currentLessonIndex--;
|
state.currentLessonIndex--;
|
||||||
loadCurrentLesson();
|
loadCurrentLesson();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run the user code
|
// Run the user code
|
||||||
function runCode() {
|
function runCode() {
|
||||||
const userCode = elements.codeInput.value;
|
const userCode = elements.codeInput.value;
|
||||||
const lesson = state.currentModule.lessons[state.currentLessonIndex];
|
const lesson = state.currentModule.lessons[state.currentLessonIndex];
|
||||||
|
|
||||||
const validationResult = validateUserCode(userCode, lesson);
|
const validationResult = validateUserCode(userCode, lesson);
|
||||||
|
|
||||||
if (validationResult.isValid) {
|
if (validationResult.isValid) {
|
||||||
// Mark lesson as completed
|
// Mark lesson as completed
|
||||||
const moduleProgress = state.userProgress[state.currentModule.id];
|
const moduleProgress = state.userProgress[state.currentModule.id];
|
||||||
if (!moduleProgress.completed.includes(state.currentLessonIndex)) {
|
if (!moduleProgress.completed.includes(state.currentLessonIndex)) {
|
||||||
moduleProgress.completed.push(state.currentLessonIndex);
|
moduleProgress.completed.push(state.currentLessonIndex);
|
||||||
saveUserProgress();
|
saveUserProgress();
|
||||||
updateModuleSelectorButtonProgress();
|
updateModuleSelectorButtonProgress();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show success feedback with visual indicators
|
// Show success feedback with visual indicators
|
||||||
showFeedback(true, validationResult.message || 'Great job! Your code works correctly.');
|
showFeedback(true, validationResult.message || "Great job! Your code works correctly.");
|
||||||
|
|
||||||
// Add success visual indicators
|
// Add success visual indicators
|
||||||
elements.lessonContainer.classList.add('success-highlight');
|
elements.lessonContainer.classList.add("success-highlight");
|
||||||
elements.lessonTitle.classList.add('success-text');
|
elements.lessonTitle.classList.add("success-text");
|
||||||
const headings = elements.lessonContainer.querySelectorAll('h3, h4');
|
const headings = elements.lessonContainer.querySelectorAll("h3, h4");
|
||||||
headings.forEach(heading => heading.classList.add('success-text'));
|
headings.forEach((heading) => heading.classList.add("success-text"));
|
||||||
|
|
||||||
// Apply the code to see the result
|
// Apply the code to see the result
|
||||||
lessonEngine.applyUserCode(userCode);
|
lessonEngine.applyUserCode(userCode);
|
||||||
|
|
||||||
// Enable the next button if not already on the last lesson
|
// Enable the next button if not already on the last lesson
|
||||||
if (state.currentLessonIndex < state.currentModule.lessons.length - 1) {
|
if (state.currentLessonIndex < state.currentModule.lessons.length - 1) {
|
||||||
elements.nextBtn.disabled = false;
|
elements.nextBtn.disabled = false;
|
||||||
elements.nextBtn.classList.remove('btn-disabled');
|
elements.nextBtn.classList.remove("btn-disabled");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Reset any success indicators
|
// Reset any success indicators
|
||||||
resetSuccessIndicators();
|
resetSuccessIndicators();
|
||||||
|
|
||||||
// Show error feedback (with friendly message)
|
// Show error feedback (with friendly message)
|
||||||
showFeedback(false, validationResult.message || 'Not quite there yet! Let\'s try again.');
|
showFeedback(false, validationResult.message || "Not quite there yet! Let's try again.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show the module selector modal
|
// Show the module selector modal
|
||||||
function showModuleSelector() {
|
function showModuleSelector() {
|
||||||
elements.modalTitle.textContent = 'Select a Module';
|
elements.modalTitle.textContent = "Select a Module";
|
||||||
|
|
||||||
// Create module buttons
|
// Create module buttons
|
||||||
const moduleButtons = state.modules.map(module => {
|
const moduleButtons = state.modules.map((module) => {
|
||||||
const button = document.createElement('button');
|
const button = document.createElement("button");
|
||||||
button.classList.add('btn', 'module-button');
|
button.classList.add("btn", "module-button");
|
||||||
button.style.display = 'block';
|
button.style.display = "block";
|
||||||
button.style.width = '100%';
|
button.style.width = "100%";
|
||||||
button.style.marginBottom = '10px';
|
button.style.marginBottom = "10px";
|
||||||
button.style.padding = '15px';
|
button.style.padding = "15px";
|
||||||
button.style.textAlign = 'left';
|
button.style.textAlign = "left";
|
||||||
|
|
||||||
// Add completion status
|
// Add completion status
|
||||||
const progress = state.userProgress[module.id];
|
const progress = state.userProgress[module.id];
|
||||||
const completedCount = progress ? progress.completed.length : 0;
|
const completedCount = progress ? progress.completed.length : 0;
|
||||||
const totalLessons = module.lessons.length;
|
const totalLessons = module.lessons.length;
|
||||||
const percentComplete = Math.round((completedCount / totalLessons) * 100);
|
const percentComplete = Math.round((completedCount / totalLessons) * 100);
|
||||||
|
|
||||||
button.innerHTML = `
|
button.innerHTML = `
|
||||||
<strong>${module.title}</strong>
|
<strong>${module.title}</strong>
|
||||||
<div style="margin-top: 5px; font-size: 0.8rem; color: var(--light-text);">
|
<div style="margin-top: 5px; font-size: 0.8rem; color: var(--light-text);">
|
||||||
${module.description}
|
${module.description}
|
||||||
@@ -322,29 +317,29 @@ function showModuleSelector() {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
button.addEventListener('click', () => {
|
button.addEventListener("click", () => {
|
||||||
selectModule(module.id);
|
selectModule(module.id);
|
||||||
closeModal();
|
closeModal();
|
||||||
});
|
});
|
||||||
|
|
||||||
return button;
|
return button;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Clear and update modal content
|
// Clear and update modal content
|
||||||
elements.modalContent.innerHTML = '';
|
elements.modalContent.innerHTML = "";
|
||||||
moduleButtons.forEach(button => {
|
moduleButtons.forEach((button) => {
|
||||||
elements.modalContent.appendChild(button);
|
elements.modalContent.appendChild(button);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Show the modal
|
// Show the modal
|
||||||
elements.modalContainer.classList.remove('hidden');
|
elements.modalContainer.classList.remove("hidden");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Show help modal
|
// Show help modal
|
||||||
function showHelp() {
|
function showHelp() {
|
||||||
elements.modalTitle.textContent = 'Help';
|
elements.modalTitle.textContent = "Help";
|
||||||
|
|
||||||
elements.modalContent.innerHTML = `
|
elements.modalContent.innerHTML = `
|
||||||
<h3>How to Use Code Crispies</h3>
|
<h3>How to Use Code Crispies</h3>
|
||||||
<p>Code Crispies is an interactive platform for learning CSS through practical exercises.</p>
|
<p>Code Crispies is an interactive platform for learning CSS through practical exercises.</p>
|
||||||
|
|
||||||
@@ -378,14 +373,14 @@ function showHelp() {
|
|||||||
</ul>
|
</ul>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
elements.modalContainer.classList.remove('hidden');
|
elements.modalContainer.classList.remove("hidden");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset user progress
|
// Reset user progress
|
||||||
function resetProgress() {
|
function resetProgress() {
|
||||||
elements.modalTitle.textContent = 'Reset Progress';
|
elements.modalTitle.textContent = "Reset Progress";
|
||||||
|
|
||||||
elements.modalContent.innerHTML = `
|
elements.modalContent.innerHTML = `
|
||||||
<p>Are you sure you want to reset all your progress? This cannot be undone.</p>
|
<p>Are you sure you want to reset all your progress? This cannot be undone.</p>
|
||||||
<div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
|
<div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
|
||||||
<button id="cancel-reset" class="btn">Cancel</button>
|
<button id="cancel-reset" class="btn">Cancel</button>
|
||||||
@@ -393,94 +388,94 @@ function resetProgress() {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
document.getElementById('cancel-reset').addEventListener('click', closeModal);
|
document.getElementById("cancel-reset").addEventListener("click", closeModal);
|
||||||
document.getElementById('confirm-reset').addEventListener('click', () => {
|
document.getElementById("confirm-reset").addEventListener("click", () => {
|
||||||
localStorage.removeItem('codeCrispiesProgress');
|
localStorage.removeItem("codeCrispiesProgress");
|
||||||
localStorage.removeItem('lastModuleId');
|
localStorage.removeItem("lastModuleId");
|
||||||
state.userProgress = {};
|
state.userProgress = {};
|
||||||
closeModal();
|
closeModal();
|
||||||
|
|
||||||
// Reload the current module
|
// Reload the current module
|
||||||
if (state.currentModule) {
|
if (state.currentModule) {
|
||||||
const currentModuleId = state.currentModule.id;
|
const currentModuleId = state.currentModule.id;
|
||||||
selectModule(currentModuleId);
|
selectModule(currentModuleId);
|
||||||
} else if (state.modules.length > 0) {
|
} else if (state.modules.length > 0) {
|
||||||
selectModule(state.modules[0].id);
|
selectModule(state.modules[0].id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update progress indicator
|
// Update progress indicator
|
||||||
updateModuleSelectorButtonProgress();
|
updateModuleSelectorButtonProgress();
|
||||||
});
|
});
|
||||||
|
|
||||||
elements.modalContainer.classList.remove('hidden');
|
elements.modalContainer.classList.remove("hidden");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close the modal
|
// Close the modal
|
||||||
function closeModal() {
|
function closeModal() {
|
||||||
elements.modalContainer.classList.add('hidden');
|
elements.modalContainer.classList.add("hidden");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle clicks in the code editor to focus the input
|
// Handle clicks in the code editor to focus the input
|
||||||
function handleEditorClick() {
|
function handleEditorClick() {
|
||||||
elements.codeInput.focus();
|
elements.codeInput.focus();
|
||||||
|
|
||||||
// Add a temporary highlight class to show where the cursor is
|
// Add a temporary highlight class to show where the cursor is
|
||||||
elements.editorContent.classList.add('editor-focused');
|
elements.editorContent.classList.add("editor-focused");
|
||||||
|
|
||||||
// Remove the highlight after a short delay
|
// Remove the highlight after a short delay
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
elements.editorContent.classList.remove('editor-focused');
|
elements.editorContent.classList.remove("editor-focused");
|
||||||
}, 300);
|
}, 300);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle tab key in the code editor
|
// Handle tab key in the code editor
|
||||||
function handleTabKey(e) {
|
function handleTabKey(e) {
|
||||||
if (e.key === 'Tab') {
|
if (e.key === "Tab") {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
const start = e.target.selectionStart;
|
const start = e.target.selectionStart;
|
||||||
const end = e.target.selectionEnd;
|
const end = e.target.selectionEnd;
|
||||||
|
|
||||||
// Add two spaces at cursor position
|
// Add two spaces at cursor position
|
||||||
e.target.value = e.target.value.substring(0, start) + ' ' + e.target.value.substring(end);
|
e.target.value = e.target.value.substring(0, start) + " " + e.target.value.substring(end);
|
||||||
|
|
||||||
// Move cursor position after the inserted spaces
|
// Move cursor position after the inserted spaces
|
||||||
e.target.selectionStart = e.target.selectionEnd = start + 2;
|
e.target.selectionStart = e.target.selectionEnd = start + 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize the application
|
// Initialize the application
|
||||||
function init() {
|
function init() {
|
||||||
loadUserProgress();
|
loadUserProgress();
|
||||||
initializeModules();
|
initializeModules();
|
||||||
|
|
||||||
// Event listeners
|
// Event listeners
|
||||||
elements.prevBtn.addEventListener('click', prevLesson);
|
elements.prevBtn.addEventListener("click", prevLesson);
|
||||||
elements.nextBtn.addEventListener('click', nextLesson);
|
elements.nextBtn.addEventListener("click", nextLesson);
|
||||||
elements.runBtn.addEventListener('click', runCode);
|
elements.runBtn.addEventListener("click", runCode);
|
||||||
elements.modalClose.addEventListener('click', closeModal);
|
elements.modalClose.addEventListener("click", closeModal);
|
||||||
elements.moduleSelectorBtn.addEventListener('click', showModuleSelector);
|
elements.moduleSelectorBtn.addEventListener("click", showModuleSelector);
|
||||||
elements.resetBtn.addEventListener('click', resetProgress);
|
elements.resetBtn.addEventListener("click", resetProgress);
|
||||||
elements.helpBtn.addEventListener('click', showHelp);
|
elements.helpBtn.addEventListener("click", showHelp);
|
||||||
elements.codeInput.addEventListener('click', handleEditorClick);
|
elements.codeInput.addEventListener("click", handleEditorClick);
|
||||||
|
|
||||||
// Also make the editor container clickable to focus the text area
|
// Also make the editor container clickable to focus the text area
|
||||||
elements.editorContent.addEventListener('click', (e) => {
|
elements.editorContent.addEventListener("click", (e) => {
|
||||||
elements.codeInput.focus();
|
elements.codeInput.focus();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add tab key handler for the code input
|
// Add tab key handler for the code input
|
||||||
elements.codeInput.addEventListener('keydown', handleTabKey);
|
elements.codeInput.addEventListener("keydown", handleTabKey);
|
||||||
|
|
||||||
// Handle keyboard shortcuts
|
// Handle keyboard shortcuts
|
||||||
document.addEventListener('keydown', (e) => {
|
document.addEventListener("keydown", (e) => {
|
||||||
// Ctrl+Enter to run code
|
// Ctrl+Enter to run code
|
||||||
if (e.ctrlKey && e.key === 'Enter') {
|
if (e.ctrlKey && e.key === "Enter") {
|
||||||
runCode();
|
runCode();
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Start the application
|
// Start the application
|
||||||
init();
|
init();
|
||||||
|
|||||||
@@ -3,26 +3,21 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Import lesson configs
|
// Import lesson configs
|
||||||
import flexboxConfig from '../../lessons/flexbox.json';
|
import flexboxConfig from "../../lessons/flexbox.json";
|
||||||
import gridConfig from '../../lessons/grid.json';
|
import gridConfig from "../../lessons/grid.json";
|
||||||
import basicsConfig from '../../lessons/basics.json';
|
import basicsConfig from "../../lessons/basics.json";
|
||||||
import tailwindConfig from '../../lessons/tailwindcss.json';
|
import tailwindConfig from "../../lessons/tailwindcss.json";
|
||||||
|
|
||||||
// Module store
|
// Module store
|
||||||
const moduleStore = [
|
const moduleStore = [basicsConfig, flexboxConfig, gridConfig, tailwindConfig];
|
||||||
basicsConfig,
|
|
||||||
flexboxConfig,
|
|
||||||
gridConfig,
|
|
||||||
tailwindConfig
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load all available modules
|
* Load all available modules
|
||||||
* @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() {
|
||||||
// In a real app, we might load these from a server
|
// In a real app, we might load these from a server
|
||||||
return moduleStore;
|
return moduleStore;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,7 +26,7 @@ export async function loadModules() {
|
|||||||
* @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) {
|
||||||
return moduleStore.find(module => module.id === moduleId) || null;
|
return moduleStore.find((module) => module.id === moduleId) || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,20 +35,20 @@ export function getModuleById(moduleId) {
|
|||||||
* @returns {Promise<Object>} Promise resolving to the module config
|
* @returns {Promise<Object>} Promise resolving to the module config
|
||||||
*/
|
*/
|
||||||
export async function loadModuleFromUrl(url) {
|
export async function loadModuleFromUrl(url) {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`Failed to load module: ${response.status} ${response.statusText}`);
|
throw new Error(`Failed to load module: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const moduleConfig = await response.json();
|
const moduleConfig = await response.json();
|
||||||
validateModuleConfig(moduleConfig);
|
validateModuleConfig(moduleConfig);
|
||||||
|
|
||||||
return moduleConfig;
|
return moduleConfig;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading module from URL:', error);
|
console.error("Error loading module from URL:", error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -62,16 +57,16 @@ export async function loadModuleFromUrl(url) {
|
|||||||
* @throws {Error} If the configuration is invalid
|
* @throws {Error} If the configuration is invalid
|
||||||
*/
|
*/
|
||||||
function validateModuleConfig(config) {
|
function validateModuleConfig(config) {
|
||||||
// Required fields
|
// Required fields
|
||||||
if (!config.id) throw new Error('Module config missing "id"');
|
if (!config.id) throw new Error('Module config missing "id"');
|
||||||
if (!config.title) throw new Error('Module config missing "title"');
|
if (!config.title) throw new Error('Module config missing "title"');
|
||||||
if (!Array.isArray(config.lessons)) throw new Error('Module config missing "lessons" array');
|
if (!Array.isArray(config.lessons)) throw new Error('Module config missing "lessons" array');
|
||||||
|
|
||||||
// Check each lesson
|
// Check each lesson
|
||||||
config.lessons.forEach((lesson, index) => {
|
config.lessons.forEach((lesson, index) => {
|
||||||
if (!lesson.title) throw new Error(`Lesson ${index} missing "title"`);
|
if (!lesson.title) throw new Error(`Lesson ${index} missing "title"`);
|
||||||
if (!lesson.previewHTML) throw new Error(`Lesson ${index} missing "previewHTML"`);
|
if (!lesson.previewHTML) throw new Error(`Lesson ${index} missing "previewHTML"`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -80,22 +75,22 @@ function validateModuleConfig(config) {
|
|||||||
* @returns {boolean} Success status
|
* @returns {boolean} Success status
|
||||||
*/
|
*/
|
||||||
export function addCustomModule(moduleConfig) {
|
export function addCustomModule(moduleConfig) {
|
||||||
try {
|
try {
|
||||||
validateModuleConfig(moduleConfig);
|
validateModuleConfig(moduleConfig);
|
||||||
|
|
||||||
// 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 = moduleStore.findIndex((m) => m.id === moduleConfig.id);
|
||||||
if (existingIndex >= 0) {
|
if (existingIndex >= 0) {
|
||||||
// Replace existing module
|
// Replace existing module
|
||||||
moduleStore[existingIndex] = moduleConfig;
|
moduleStore[existingIndex] = moduleConfig;
|
||||||
} else {
|
} else {
|
||||||
// Add new module
|
// Add new module
|
||||||
moduleStore.push(moduleConfig);
|
moduleStore.push(moduleConfig);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error adding custom module:', error);
|
console.error("Error adding custom module:", error);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,22 +12,22 @@ let feedbackElement = null;
|
|||||||
* @param { Function} onSelectModule - Callback when a module is selected
|
* @param { Function} onSelectModule - Callback when a module is selected
|
||||||
*/
|
*/
|
||||||
export function renderModuleList(container, modules, onSelectModule) {
|
export function renderModuleList(container, modules, onSelectModule) {
|
||||||
// Clear the container
|
// Clear the container
|
||||||
container.innerHTML = '<h3>Modules</h3>';
|
container.innerHTML = "<h3>Modules</h3>";
|
||||||
|
|
||||||
// Create list items for each module
|
// Create list items for each module
|
||||||
modules.forEach(module => {
|
modules.forEach((module) => {
|
||||||
const moduleItem = document.createElement('div');
|
const moduleItem = document.createElement("div");
|
||||||
moduleItem.classList.add('module-list-item');
|
moduleItem.classList.add("module-list-item");
|
||||||
moduleItem.dataset.moduleId = module.id;
|
moduleItem.dataset.moduleId = module.id;
|
||||||
moduleItem.textContent = module.title;
|
moduleItem.textContent = module.title;
|
||||||
|
|
||||||
moduleItem.addEventListener('click', () => {
|
moduleItem.addEventListener("click", () => {
|
||||||
onSelectModule(module.id);
|
onSelectModule(module.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
container.appendChild(moduleItem);
|
container.appendChild(moduleItem);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -41,33 +41,24 @@ export function renderModuleList(container, modules, onSelectModule) {
|
|||||||
* @param {HTMLElement} suffixEl - The code editor suffix element
|
* @param {HTMLElement} suffixEl - The code editor suffix element
|
||||||
* @param {Object} lesson - The lesson object
|
* @param {Object} lesson - The lesson object
|
||||||
*/
|
*/
|
||||||
export function renderLesson(
|
export function renderLesson(titleEl, descriptionEl, taskEl, previewEl, prefixEl, inputEl, suffixEl, lesson) {
|
||||||
titleEl,
|
// Set lesson title and description
|
||||||
descriptionEl,
|
titleEl.textContent = lesson.title || "Untitled Lesson";
|
||||||
taskEl,
|
descriptionEl.innerHTML = lesson.description || "";
|
||||||
previewEl,
|
|
||||||
prefixEl,
|
|
||||||
inputEl,
|
|
||||||
suffixEl,
|
|
||||||
lesson
|
|
||||||
) {
|
|
||||||
// Set lesson title and description
|
|
||||||
titleEl.textContent = lesson.title || 'Untitled Lesson';
|
|
||||||
descriptionEl.innerHTML = lesson.description || '';
|
|
||||||
|
|
||||||
// Set task instructions
|
// Set task instructions
|
||||||
taskEl.innerHTML = lesson.task || '';
|
taskEl.innerHTML = lesson.task || "";
|
||||||
|
|
||||||
// Set code editor contents
|
// Set code editor contents
|
||||||
prefixEl.textContent = lesson.codePrefix || '';
|
prefixEl.textContent = lesson.codePrefix || "";
|
||||||
inputEl.value = lesson.initialCode || '';
|
inputEl.value = lesson.initialCode || "";
|
||||||
suffixEl.textContent = lesson.codeSuffix || '';
|
suffixEl.textContent = lesson.codeSuffix || "";
|
||||||
|
|
||||||
// Clear any existing feedback
|
// Clear any existing feedback
|
||||||
clearFeedback();
|
clearFeedback();
|
||||||
|
|
||||||
// Initial preview render with empty user code
|
// Initial preview render with empty user code
|
||||||
// The LessonEngine will handle this when it's first set
|
// The LessonEngine will handle this when it's first set
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -77,7 +68,7 @@ export function renderLesson(
|
|||||||
* @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 = `Lesson ${current} of ${total}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -86,34 +77,34 @@ export function renderLevelIndicator(element, current, total) {
|
|||||||
* @param {string} message - The feedback message
|
* @param {string} message - The feedback message
|
||||||
*/
|
*/
|
||||||
export function showFeedback(isSuccess, message) {
|
export function showFeedback(isSuccess, message) {
|
||||||
// Clear any existing feedback
|
// Clear any existing feedback
|
||||||
clearFeedback();
|
clearFeedback();
|
||||||
|
|
||||||
// Create feedback element
|
// Create feedback element
|
||||||
feedbackElement = document.createElement('div');
|
feedbackElement = document.createElement("div");
|
||||||
feedbackElement.classList.add(isSuccess ? 'feedback-success' : 'feedback-error');
|
feedbackElement.classList.add(isSuccess ? "feedback-success" : "feedback-error");
|
||||||
feedbackElement.textContent = message;
|
feedbackElement.textContent = message;
|
||||||
|
|
||||||
// Find where to insert the feedback
|
// Find where to insert the feedback
|
||||||
const insertAfter = document.querySelector('.code-editor');
|
const insertAfter = document.querySelector(".code-editor");
|
||||||
if (insertAfter && insertAfter.parentNode) {
|
if (insertAfter && insertAfter.parentNode) {
|
||||||
insertAfter.parentNode.insertBefore(feedbackElement, insertAfter.nextSibling);
|
insertAfter.parentNode.insertBefore(feedbackElement, insertAfter.nextSibling);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-remove feedback after some time if successful
|
// Auto-remove feedback after some time if successful
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
clearFeedback();
|
clearFeedback();
|
||||||
}, 5000);
|
}, 5000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear any existing feedback
|
* Clear any existing feedback
|
||||||
*/
|
*/
|
||||||
export function clearFeedback() {
|
export function clearFeedback() {
|
||||||
if (feedbackElement && feedbackElement.parentNode) {
|
if (feedbackElement && feedbackElement.parentNode) {
|
||||||
feedbackElement.parentNode.removeChild(feedbackElement);
|
feedbackElement.parentNode.removeChild(feedbackElement);
|
||||||
}
|
}
|
||||||
feedbackElement = null;
|
feedbackElement = null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,73 +9,73 @@
|
|||||||
* @returns {Object} Validation result with isValid and message properties
|
* @returns {Object} Validation result with isValid and message properties
|
||||||
*/
|
*/
|
||||||
export function validateUserCode(userCode, lesson) {
|
export function validateUserCode(userCode, lesson) {
|
||||||
if (!lesson || !lesson.validations) {
|
if (!lesson || !lesson.validations) {
|
||||||
return { isValid: true, message: 'No validations specified for this lesson.' };
|
return { isValid: true, message: "No validations specified for this lesson." };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the validations array from the lesson
|
// Get the validations array from the lesson
|
||||||
const validations = lesson.validations;
|
const validations = lesson.validations;
|
||||||
|
|
||||||
// Default validation result
|
// Default validation result
|
||||||
let result = {
|
let result = {
|
||||||
isValid: true,
|
isValid: true,
|
||||||
message: 'Your code looks good!'
|
message: "Your code looks good!"
|
||||||
};
|
};
|
||||||
|
|
||||||
// Process each validation rule
|
// Process each validation rule
|
||||||
for (const validation of validations) {
|
for (const validation of validations) {
|
||||||
const { type, value, message, options } = validation;
|
const { type, value, message, options } = validation;
|
||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'contains':
|
case "contains":
|
||||||
if (!containsValidation(userCode, value, options)) {
|
if (!containsValidation(userCode, value, options)) {
|
||||||
return { isValid: false, message: message || `Your code should include "${value}".` };
|
return { isValid: false, message: message || `Your code should include "${value}".` };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'not_contains':
|
case "not_contains":
|
||||||
if (containsValidation(userCode, value, options)) {
|
if (containsValidation(userCode, value, options)) {
|
||||||
return { isValid: false, message: message || `Your code should not include "${value}".` };
|
return { isValid: false, message: message || `Your code should not include "${value}".` };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'regex':
|
case "regex":
|
||||||
if (!regexValidation(userCode, value, options)) {
|
if (!regexValidation(userCode, value, options)) {
|
||||||
return { isValid: false, message: message || 'Your code does not match the expected pattern.' };
|
return { isValid: false, message: message || "Your code does not match the expected pattern." };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'property_value':
|
case "property_value":
|
||||||
if (!propertyValueValidation(userCode, value, options)) {
|
if (!propertyValueValidation(userCode, value, options)) {
|
||||||
return { isValid: false, message: message || `The "${value.property}" property should be set to "${value.expected}".` };
|
return { isValid: false, message: message || `The "${value.property}" property should be set to "${value.expected}".` };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'syntax':
|
case "syntax":
|
||||||
const syntaxResult = syntaxValidation(userCode);
|
const syntaxResult = syntaxValidation(userCode);
|
||||||
if (!syntaxResult.isValid) {
|
if (!syntaxResult.isValid) {
|
||||||
return { isValid: false, message: message || `CSS syntax error: ${syntaxResult.error}` };
|
return { isValid: false, message: message || `CSS syntax error: ${syntaxResult.error}` };
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'custom':
|
case "custom":
|
||||||
if (validation.validator && typeof validation.validator === 'function') {
|
if (validation.validator && typeof validation.validator === "function") {
|
||||||
const customResult = validation.validator(userCode);
|
const customResult = validation.validator(userCode);
|
||||||
if (!customResult.isValid) {
|
if (!customResult.isValid) {
|
||||||
return { isValid: false, message: customResult.message || message || 'Your code does not meet the requirements.' };
|
return { isValid: false, message: customResult.message || message || "Your code does not meet the requirements." };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
// Add more validation types as needed
|
// Add more validation types as needed
|
||||||
|
|
||||||
default:
|
default:
|
||||||
console.warn(`Unknown validation type: ${type}`);
|
console.warn(`Unknown validation type: ${type}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we've passed all validations, return success
|
// If we've passed all validations, return success
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -86,19 +86,19 @@ export function validateUserCode(userCode, lesson) {
|
|||||||
* @returns {boolean} Whether the validation passes
|
* @returns {boolean} Whether the validation passes
|
||||||
*/
|
*/
|
||||||
function containsValidation(code, value, options = {}) {
|
function containsValidation(code, value, options = {}) {
|
||||||
const { caseSensitive = true, wholeWord = false } = options;
|
const { caseSensitive = true, wholeWord = false } = options;
|
||||||
|
|
||||||
if (!caseSensitive) {
|
if (!caseSensitive) {
|
||||||
code = code.toLowerCase();
|
code = code.toLowerCase();
|
||||||
value = value.toLowerCase();
|
value = value.toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wholeWord) {
|
if (wholeWord) {
|
||||||
const regex = new RegExp(`\\b${escapeRegExp(value)}\\b`, caseSensitive ? '' : 'i');
|
const regex = new RegExp(`\\b${escapeRegExp(value)}\\b`, caseSensitive ? "" : "i");
|
||||||
return regex.test(code);
|
return regex.test(code);
|
||||||
}
|
}
|
||||||
|
|
||||||
return code.includes(value);
|
return code.includes(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -109,19 +109,19 @@ function containsValidation(code, value, options = {}) {
|
|||||||
* @returns {boolean} Whether the validation passes
|
* @returns {boolean} Whether the validation passes
|
||||||
*/
|
*/
|
||||||
function regexValidation(code, pattern, options = {}) {
|
function regexValidation(code, pattern, options = {}) {
|
||||||
const { caseSensitive = true, multiline = true } = options;
|
const { caseSensitive = true, multiline = true } = options;
|
||||||
|
|
||||||
let flags = '';
|
let flags = "";
|
||||||
if (!caseSensitive) flags += 'i';
|
if (!caseSensitive) flags += "i";
|
||||||
if (multiline) flags += 'm';
|
if (multiline) flags += "m";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const regex = new RegExp(pattern, flags);
|
const regex = new RegExp(pattern, flags);
|
||||||
return regex.test(code);
|
return regex.test(code);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Invalid regex in validation:', e);
|
console.error("Invalid regex in validation:", e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -132,27 +132,27 @@ function regexValidation(code, pattern, options = {}) {
|
|||||||
* @returns {boolean} Whether the validation passes
|
* @returns {boolean} Whether the validation passes
|
||||||
*/
|
*/
|
||||||
function propertyValueValidation(code, value, options = {}) {
|
function propertyValueValidation(code, value, options = {}) {
|
||||||
const { property, expected } = value;
|
const { property, expected } = value;
|
||||||
const { exact = false } = options;
|
const { exact = false } = options;
|
||||||
|
|
||||||
// Create a regex to extract the property value
|
// Create a regex to extract the property value
|
||||||
// This is a simplified version and might not handle all CSS syntax nuances
|
// This is a simplified version and might not handle all CSS syntax nuances
|
||||||
const propertyRegex = new RegExp(`${escapeRegExp(property)}\\s*:\\s*([^;\\}]+)`, 'i');
|
const propertyRegex = new RegExp(`${escapeRegExp(property)}\\s*:\\s*([^;\\}]+)`, "i");
|
||||||
const match = code.match(propertyRegex);
|
const match = code.match(propertyRegex);
|
||||||
|
|
||||||
if (!match) {
|
if (!match) {
|
||||||
// Property not found
|
// Property not found
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const actualValue = match[1].trim();
|
const actualValue = match[1].trim();
|
||||||
|
|
||||||
if (exact) {
|
if (exact) {
|
||||||
return actualValue === expected;
|
return actualValue === expected;
|
||||||
} else {
|
} else {
|
||||||
// Allow for flexible matching
|
// Allow for flexible matching
|
||||||
return actualValue.toLowerCase().includes(expected.toLowerCase());
|
return actualValue.toLowerCase().includes(expected.toLowerCase());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -161,16 +161,16 @@ function propertyValueValidation(code, value, options = {}) {
|
|||||||
* @returns {Object} Validation result
|
* @returns {Object} Validation result
|
||||||
*/
|
*/
|
||||||
function syntaxValidation(code) {
|
function syntaxValidation(code) {
|
||||||
try {
|
try {
|
||||||
// Create a hidden style element to test the CSS
|
// Create a hidden style element to test the CSS
|
||||||
const style = document.createElement('style');
|
const style = document.createElement("style");
|
||||||
style.textContent = code;
|
style.textContent = code;
|
||||||
document.head.appendChild(style);
|
document.head.appendChild(style);
|
||||||
document.head.removeChild(style);
|
document.head.removeChild(style);
|
||||||
return { isValid: true };
|
return { isValid: true };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return { isValid: false, error: e.message };
|
return { isValid: false, error: e.message };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -179,5 +179,5 @@ function syntaxValidation(code) {
|
|||||||
* @returns {string} Escaped string
|
* @returns {string} Escaped string
|
||||||
*/
|
*/
|
||||||
function escapeRegExp(string) {
|
function escapeRegExp(string) {
|
||||||
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,229 +2,229 @@
|
|||||||
* LessonEngine - Core class for managing lessons and applying/testing user code
|
* LessonEngine - Core class for managing lessons and applying/testing user code
|
||||||
* This file is the implementation of the LessonEngine class declaration from app.helpers
|
* This file is the implementation of the LessonEngine class declaration from app.helpers
|
||||||
*/
|
*/
|
||||||
import { validateUserCode } from '../helpers/validator.js';
|
import { validateUserCode } from "../helpers/validator.js";
|
||||||
import { showFeedback } from '../helpers/renderer.js';
|
import { showFeedback } from "../helpers/renderer.js";
|
||||||
|
|
||||||
export class LessonEngine {
|
export class LessonEngine {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.currentLesson = null;
|
this.currentLesson = null;
|
||||||
this.userCode = '';
|
this.userCode = "";
|
||||||
this.currentModule = null;
|
this.currentModule = null;
|
||||||
this.currentLessonIndex = 0;
|
this.currentLessonIndex = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the current module
|
* Set the current module
|
||||||
* @param {Object} module - The module object from the config
|
* @param {Object} module - The module object from the config
|
||||||
*/
|
*/
|
||||||
setModule(module) {
|
setModule(module) {
|
||||||
this.currentModule = module;
|
this.currentModule = module;
|
||||||
this.currentLessonIndex = 0;
|
this.currentLessonIndex = 0;
|
||||||
if (module && module.lessons && module.lessons.length > 0) {
|
if (module && module.lessons && module.lessons.length > 0) {
|
||||||
this.setLesson(module.lessons[0]);
|
this.setLesson(module.lessons[0]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the current lesson
|
* Set the current lesson
|
||||||
* @param {Object} lesson - The lesson object from the config
|
* @param {Object} lesson - The lesson object from the config
|
||||||
*/
|
*/
|
||||||
setLesson(lesson) {
|
setLesson(lesson) {
|
||||||
this.currentLesson = lesson;
|
this.currentLesson = lesson;
|
||||||
this.userCode = lesson.initialCode || '';
|
this.userCode = lesson.initialCode || "";
|
||||||
this.renderPreview();
|
this.renderPreview();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set lesson by index within the current module
|
* Set lesson by index within the current module
|
||||||
* @param {number} index - The lesson index
|
* @param {number} index - The lesson index
|
||||||
* @returns {boolean} Whether the operation was successful
|
* @returns {boolean} Whether the operation was successful
|
||||||
*/
|
*/
|
||||||
setLessonByIndex(index) {
|
setLessonByIndex(index) {
|
||||||
if (!this.currentModule || !this.currentModule.lessons) {
|
if (!this.currentModule || !this.currentModule.lessons) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (index < 0 || index >= this.currentModule.lessons.length) {
|
if (index < 0 || index >= this.currentModule.lessons.length) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.currentLessonIndex = index;
|
this.currentLessonIndex = index;
|
||||||
this.setLesson(this.currentModule.lessons[index]);
|
this.setLesson(this.currentModule.lessons[index]);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Move to the next lesson
|
* Move to the next lesson
|
||||||
* @returns {boolean} Whether the operation was successful
|
* @returns {boolean} Whether the operation was successful
|
||||||
*/
|
*/
|
||||||
nextLesson() {
|
nextLesson() {
|
||||||
return this.setLessonByIndex(this.currentLessonIndex + 1);
|
return this.setLessonByIndex(this.currentLessonIndex + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Move to the previous lesson
|
* Move to the previous lesson
|
||||||
* @returns {boolean} Whether the operation was successful
|
* @returns {boolean} Whether the operation was successful
|
||||||
*/
|
*/
|
||||||
previousLesson() {
|
previousLesson() {
|
||||||
return this.setLessonByIndex(this.currentLessonIndex - 1);
|
return this.setLessonByIndex(this.currentLessonIndex - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Apply user-written CSS to the preview area
|
* Apply user-written CSS to the preview area
|
||||||
* @param {string} code - User CSS code
|
* @param {string} code - User CSS code
|
||||||
*/
|
*/
|
||||||
applyUserCode(code) {
|
applyUserCode(code) {
|
||||||
if (!this.currentLesson) return;
|
if (!this.currentLesson) return;
|
||||||
|
|
||||||
this.userCode = code;
|
this.userCode = code;
|
||||||
this.renderPreview();
|
this.renderPreview();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Render the preview for the current lesson
|
* Render the preview for the current lesson
|
||||||
*/
|
*/
|
||||||
renderPreview() {
|
renderPreview() {
|
||||||
if (!this.currentLesson) return;
|
if (!this.currentLesson) return;
|
||||||
|
|
||||||
const { previewHTML, previewBaseCSS, previewContainer, sandboxCSS } = this.currentLesson;
|
const { previewHTML, previewBaseCSS, previewContainer, sandboxCSS } = this.currentLesson;
|
||||||
|
|
||||||
// Create an iframe for isolated preview rendering
|
// Create an iframe for isolated preview rendering
|
||||||
const iframe = document.createElement('iframe');
|
const iframe = document.createElement("iframe");
|
||||||
iframe.style.width = '100%';
|
iframe.style.width = "100%";
|
||||||
iframe.style.height = '100%';
|
iframe.style.height = "100%";
|
||||||
iframe.style.border = 'none';
|
iframe.style.border = "none";
|
||||||
iframe.title = 'Preview';
|
iframe.title = "Preview";
|
||||||
|
|
||||||
// Get the preview container
|
// Get the preview container
|
||||||
const container = document.getElementById(previewContainer || 'preview-area');
|
const container = document.getElementById(previewContainer || "preview-area");
|
||||||
|
|
||||||
// Clear the container and add the iframe
|
// Clear the container and add the iframe
|
||||||
container.innerHTML = '';
|
container.innerHTML = "";
|
||||||
container.appendChild(iframe);
|
container.appendChild(iframe);
|
||||||
|
|
||||||
// Create the complete CSS by combining base CSS with user code and sandbox CSS
|
// Create the complete CSS by combining base CSS with user code and sandbox CSS
|
||||||
const combinedCSS = `
|
const combinedCSS = `
|
||||||
/* Base CSS */
|
/* Base CSS */
|
||||||
${previewBaseCSS || ''}
|
${previewBaseCSS || ""}
|
||||||
|
|
||||||
/* User Code */
|
/* User Code */
|
||||||
${this.userCode || ''}
|
${this.userCode || ""}
|
||||||
|
|
||||||
/* Sandbox CSS (for visualizing the exercise) */
|
/* Sandbox CSS (for visualizing the exercise) */
|
||||||
${sandboxCSS || ''}
|
${sandboxCSS || ""}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// Write the content to the iframe
|
// Write the content to the iframe
|
||||||
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
|
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
|
||||||
iframeDoc.open();
|
iframeDoc.open();
|
||||||
iframeDoc.write(`
|
iframeDoc.write(`
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<style>${combinedCSS}</style>
|
<style>${combinedCSS}</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
${previewHTML || '<div>No preview available</div>'}
|
${previewHTML || "<div>No preview available</div>"}
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
`);
|
`);
|
||||||
iframeDoc.close();
|
iframeDoc.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate user code against the current lesson's requirements
|
* Validate user code against the current lesson's requirements
|
||||||
* @returns {Object} Validation result
|
* @returns {Object} Validation result
|
||||||
*/
|
*/
|
||||||
validateCode() {
|
validateCode() {
|
||||||
if (!this.currentLesson) {
|
if (!this.currentLesson) {
|
||||||
return { isValid: false, message: 'No active lesson to validate against.' };
|
return { isValid: false, message: "No active lesson to validate against." };
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = validateUserCode(this.userCode, this.currentLesson);
|
const result = validateUserCode(this.userCode, this.currentLesson);
|
||||||
|
|
||||||
// Display feedback to the user
|
// Display feedback to the user
|
||||||
showFeedback(result.isValid, result.message);
|
showFeedback(result.isValid, result.message);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the current state of the lesson
|
* Get the current state of the lesson
|
||||||
* @returns {Object} The current lesson state
|
* @returns {Object} The current lesson state
|
||||||
*/
|
*/
|
||||||
getCurrentState() {
|
getCurrentState() {
|
||||||
return {
|
return {
|
||||||
module: this.currentModule,
|
module: this.currentModule,
|
||||||
lesson: this.currentLesson,
|
lesson: this.currentLesson,
|
||||||
lessonIndex: this.currentLessonIndex,
|
lessonIndex: this.currentLessonIndex,
|
||||||
userCode: this.userCode,
|
userCode: this.userCode,
|
||||||
totalLessons: this.currentModule ? this.currentModule.lessons.length : 0
|
totalLessons: this.currentModule ? this.currentModule.lessons.length : 0
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Save progress to localStorage
|
* Save progress to localStorage
|
||||||
*/
|
*/
|
||||||
saveProgress() {
|
saveProgress() {
|
||||||
if (!this.currentModule || !this.currentLesson) return;
|
if (!this.currentModule || !this.currentLesson) return;
|
||||||
|
|
||||||
const progressData = {
|
const progressData = {
|
||||||
moduleId: this.currentModule.id,
|
moduleId: this.currentModule.id,
|
||||||
lessonIndex: this.currentLessonIndex,
|
lessonIndex: this.currentLessonIndex,
|
||||||
userCode: this.userCode,
|
userCode: this.userCode,
|
||||||
timestamp: new Date().toISOString()
|
timestamp: new Date().toISOString()
|
||||||
};
|
};
|
||||||
|
|
||||||
localStorage.setItem('cssQuest_progress', JSON.stringify(progressData));
|
localStorage.setItem("cssQuest_progress", JSON.stringify(progressData));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load progress from localStorage
|
* Load progress from localStorage
|
||||||
* @param {Array} modules - Available modules
|
* @param {Array} modules - Available modules
|
||||||
* @returns {Object|null} Loaded progress data or null if not found
|
* @returns {Object|null} Loaded progress data or null if not found
|
||||||
*/
|
*/
|
||||||
loadProgress(modules) {
|
loadProgress(modules) {
|
||||||
const savedProgress = localStorage.getItem('cssQuest_progress');
|
const savedProgress = localStorage.getItem("cssQuest_progress");
|
||||||
if (!savedProgress) return null;
|
if (!savedProgress) return null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const progressData = JSON.parse(savedProgress);
|
const progressData = JSON.parse(savedProgress);
|
||||||
|
|
||||||
// Find the module
|
// Find the module
|
||||||
const module = modules.find(m => m.id === progressData.moduleId);
|
const module = modules.find((m) => m.id === progressData.moduleId);
|
||||||
if (!module) return null;
|
if (!module) return null;
|
||||||
|
|
||||||
this.setModule(module);
|
this.setModule(module);
|
||||||
this.setLessonByIndex(progressData.lessonIndex);
|
this.setLessonByIndex(progressData.lessonIndex);
|
||||||
|
|
||||||
// Restore user code if available
|
// Restore user code if available
|
||||||
if (progressData.userCode) {
|
if (progressData.userCode) {
|
||||||
this.userCode = progressData.userCode;
|
this.userCode = progressData.userCode;
|
||||||
this.renderPreview();
|
this.renderPreview();
|
||||||
}
|
}
|
||||||
|
|
||||||
return progressData;
|
return progressData;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Error loading progress:', e);
|
console.error("Error loading progress:", e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reset the current state
|
* Reset the current state
|
||||||
*/
|
*/
|
||||||
reset() {
|
reset() {
|
||||||
if (this.currentLesson) {
|
if (this.currentLesson) {
|
||||||
this.userCode = this.currentLesson.initialCode || '';
|
this.userCode = this.currentLesson.initialCode || "";
|
||||||
this.renderPreview();
|
this.renderPreview();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear all saved progress
|
* Clear all saved progress
|
||||||
*/
|
*/
|
||||||
clearProgress() {
|
clearProgress() {
|
||||||
localStorage.removeItem('cssQuest_progress');
|
localStorage.removeItem("cssQuest_progress");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
160
src/index.html
160
src/index.html
@@ -1,90 +1,88 @@
|
|||||||
<!DOCTYPE html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" href="./public/favicon.ico" type="image/x-icon">
|
<link rel="icon" href="./public/favicon.ico" type="image/x-icon" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>CODE CRISPIES - Learn CSS Interactively</title>
|
<title>CODE CRISPIES - Learn CSS Interactively</title>
|
||||||
<link rel="stylesheet" href="main.css">
|
<link rel="stylesheet" href="main.css" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="app-container">
|
<div class="app-container">
|
||||||
<header class="header">
|
<header class="header">
|
||||||
<div class="logo">
|
<div class="logo">
|
||||||
<h1>🏵️ CODE CRISPIES</h1>
|
<h1>🏵️ CODE CRISPIES</h1>
|
||||||
</div>
|
</div>
|
||||||
<nav class="main-nav">
|
<nav class="main-nav">
|
||||||
<ul>
|
<ul>
|
||||||
<li><button id="module-selector-btn" class="btn">Progress</button></li>
|
<li><button id="module-selector-btn" class="btn">Progress</button></li>
|
||||||
<li><button id="reset-btn" class="btn">Reset Progress</button></li>
|
<li><button id="reset-btn" class="btn">Reset Progress</button></li>
|
||||||
<li><button id="help-btn" class="btn">Help</button></li>
|
<li><button id="help-btn" class="btn">Help</button></li>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main class="main-content">
|
<main class="main-content">
|
||||||
<div class="sidebar">
|
<div class="sidebar">
|
||||||
<div class="module-list">
|
<div class="module-list">
|
||||||
<!-- Module list will be populated here -->
|
<!-- Module list will be populated here -->
|
||||||
</div>
|
</div>
|
||||||
<div class="lesson-progress">
|
<div class="lesson-progress">
|
||||||
<!-- Lesson progress will be shown here -->
|
<!-- Lesson progress will be shown here -->
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="content-area">
|
<div class="content-area">
|
||||||
<div class="lesson-container">
|
<div class="lesson-container">
|
||||||
<h2 id="lesson-title">Loading...</h2>
|
<h2 id="lesson-title">Loading...</h2>
|
||||||
<div class="lesson-description" id="lesson-description">
|
<div class="lesson-description" id="lesson-description">Please select a lesson to begin.</div>
|
||||||
Please select a lesson to begin.
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="challenge-container">
|
<div class="challenge-container">
|
||||||
<div class="preview-area" id="preview-area">
|
<div class="preview-area" id="preview-area">
|
||||||
<!-- Preview of the challenge will be shown here -->
|
<!-- Preview of the challenge will be shown here -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="editor-container">
|
<div class="editor-container">
|
||||||
<div class="task-instruction" id="task-instruction">
|
<div class="task-instruction" id="task-instruction">
|
||||||
<!-- Task instructions will be shown here -->
|
<!-- Task instructions will be shown here -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="code-editor">
|
<div class="code-editor">
|
||||||
<div class="editor-header">
|
<div class="editor-header">
|
||||||
<span>CSS Editor</span>
|
<span>CSS Editor</span>
|
||||||
<button id="run-btn" class="btn btn-primary">Run</button>
|
<button id="run-btn" class="btn btn-primary">Run</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="editor-content">
|
<div class="editor-content">
|
||||||
<pre><code id="editor-prefix"></code></pre>
|
<pre><code id="editor-prefix"></code></pre>
|
||||||
<textarea id="code-input" class="code-input" spellcheck="false"></textarea>
|
<textarea id="code-input" class="code-input" spellcheck="false"></textarea>
|
||||||
<pre><code id="editor-suffix"></code></pre>
|
<pre><code id="editor-suffix"></code></pre>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="controls">
|
<div class="controls">
|
||||||
<button id="prev-btn" class="btn">Previous</button>
|
<button id="prev-btn" class="btn">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">Next</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<div id="modal-container" class="modal-container hidden">
|
<div id="modal-container" class="modal-container hidden">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h3 id="modal-title">Modal Title</h3>
|
<h3 id="modal-title">Modal Title</h3>
|
||||||
<button id="modal-close" class="modal-close">×</button>
|
<button id="modal-close" class="modal-close">×</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-content" id="modal-content">
|
<div class="modal-content" id="modal-content">
|
||||||
<!-- Modal content will be populated here -->
|
<!-- Modal content will be populated here -->
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script type="module" src="app.js"></script>
|
<script type="module" src="app.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
460
src/main.css
460
src/main.css
@@ -1,388 +1,394 @@
|
|||||||
:root {
|
:root {
|
||||||
--primary-color: #4a6bfd;
|
--primary-color: #4a6bfd;
|
||||||
--primary-light: #7a93fe;
|
--primary-light: #7a93fe;
|
||||||
--primary-dark: #244ae8;
|
--primary-dark: #244ae8;
|
||||||
--secondary-color: #ff7e5f;
|
--secondary-color: #ff7e5f;
|
||||||
--text-color: #2c3e50;
|
--text-color: #2c3e50;
|
||||||
--light-text: #777;
|
--light-text: #777;
|
||||||
--bg-color: #f9f9f9;
|
--bg-color: #f9f9f9;
|
||||||
--panel-bg: #ffffff;
|
--panel-bg: #ffffff;
|
||||||
--border-color: #e0e0e0;
|
--border-color: #e0e0e0;
|
||||||
--success-color: #2ecc71;
|
--success-color: #2ecc71;
|
||||||
--error-color: #e74c3c;
|
--error-color: #e74c3c;
|
||||||
--font-main: 'Inter', 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
--font-main: "Inter", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
--shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
|
--shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
|
||||||
}
|
}
|
||||||
|
|
||||||
* {
|
* {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: var(--font-main), serif;
|
font-family: var(--font-main), serif;
|
||||||
background-color: var(--bg-color);
|
background-color: var(--bg-color);
|
||||||
color: var(--text-color);
|
color: var(--text-color);
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
.app-container {
|
.app-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Header Styles */
|
/* Header Styles */
|
||||||
.header {
|
.header {
|
||||||
background-color: var(--panel-bg);
|
background-color: var(--panel-bg);
|
||||||
padding: 1rem 2rem;
|
padding: 1rem 2rem;
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
box-shadow: var(--shadow);
|
box-shadow: var(--shadow);
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: 0;
|
top: 0;
|
||||||
z-index: 100;
|
z-index: 100;
|
||||||
}
|
}
|
||||||
|
|
||||||
.logo h1 {
|
.logo h1 {
|
||||||
color: var(--text-color);
|
color: var(--text-color);
|
||||||
font-size: 1.7rem;
|
font-size: 1.7rem;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main-nav ul {
|
.main-nav ul {
|
||||||
display: flex;
|
display: flex;
|
||||||
list-style: none;
|
list-style: none;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Main Content Layout */
|
/* Main Content Layout */
|
||||||
.main-content {
|
.main-content {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-height: calc(100vh - 60px);
|
min-height: calc(100vh - 60px);
|
||||||
}
|
}
|
||||||
|
|
||||||
.sidebar {
|
.sidebar {
|
||||||
width: 240px;
|
width: 240px;
|
||||||
background-color: var(--panel-bg);
|
background-color: var(--panel-bg);
|
||||||
border-right: 1px solid var(--border-color);
|
border-right: 1px solid var(--border-color);
|
||||||
padding: 1.5rem 1rem;
|
padding: 1.5rem 1rem;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
height: calc(100vh - 60px);
|
height: calc(100vh - 60px);
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: 60px;
|
top: 60px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.content-area {
|
.content-area {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
max-width: calc(100% - 240px);
|
max-width: calc(100% - 240px);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Module List Styles */
|
/* Module List Styles */
|
||||||
.module-list {
|
.module-list {
|
||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.module-list-item {
|
.module-list-item {
|
||||||
padding: 0.75rem 1rem;
|
padding: 0.75rem 1rem;
|
||||||
margin-bottom: 0.5rem;
|
margin-bottom: 0.5rem;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: background-color 0.2s;
|
transition: background-color 0.2s;
|
||||||
}
|
}
|
||||||
|
|
||||||
.module-list-item:hover {
|
.module-list-item:hover {
|
||||||
background-color: rgba(74, 107, 253, 0.05);
|
background-color: rgba(74, 107, 253, 0.05);
|
||||||
}
|
}
|
||||||
|
|
||||||
.module-list-item.active {
|
.module-list-item.active {
|
||||||
background-color: rgba(74, 107, 253, 0.1);
|
background-color: rgba(74, 107, 253, 0.1);
|
||||||
color: var(--primary-color);
|
color: var(--primary-color);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Lesson Container */
|
/* Lesson Container */
|
||||||
.lesson-container {
|
.lesson-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-flow: column;
|
flex-flow: column;
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
justify-content: flex-start;
|
justify-content: flex-start;
|
||||||
gap: 2rem;
|
gap: 2rem;
|
||||||
background-color: var(--panel-bg);
|
background-color: var(--panel-bg);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
box-shadow: var(--shadow);
|
box-shadow: var(--shadow);
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
#lesson-title {
|
#lesson-title {
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
color: var(--primary-dark);
|
color: var(--primary-dark);
|
||||||
}
|
}
|
||||||
|
|
||||||
.lesson-description {
|
.lesson-description {
|
||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
color: var(--text-color);
|
color: var(--text-color);
|
||||||
line-height: 1.7;
|
line-height: 1.7;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Challenge Container */
|
/* Challenge Container */
|
||||||
.challenge-container {
|
.challenge-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 1.5rem;
|
gap: 1.5rem;
|
||||||
margin-bottom: 2rem;
|
margin-bottom: 2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (min-width: 1024px) {
|
@media (min-width: 1024px) {
|
||||||
.challenge-container {
|
.challenge-container {
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
}
|
}
|
||||||
|
|
||||||
.preview-area,
|
.preview-area,
|
||||||
.editor-container {
|
.editor-container {
|
||||||
width: 48%;
|
width: 48%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.preview-area {
|
.preview-area {
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
min-height: 300px;
|
min-height: 300px;
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.editor-container {
|
.editor-container {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.task-instruction {
|
.task-instruction {
|
||||||
background-color: rgba(74, 107, 253, 0.05);
|
background-color: rgba(74, 107, 253, 0.05);
|
||||||
border-left: 4px solid var(--primary-color);
|
border-left: 4px solid var(--primary-color);
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.code-editor {
|
.code-editor {
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.editor-header {
|
.editor-header {
|
||||||
background-color: #f5f5f5;
|
background-color: #f5f5f5;
|
||||||
padding: 0.5rem 1rem;
|
padding: 0.5rem 1rem;
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
color: var(--light-text);
|
color: var(--light-text);
|
||||||
border-bottom: 1px solid var(--border-color);
|
border-bottom: 1px solid var(--border-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
.editor-content {
|
.editor-content {
|
||||||
background-color: #1e1e1e;
|
background-color: #1e1e1e;
|
||||||
color: #d4d4d4;
|
color: #d4d4d4;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
cursor: text; /* Add text cursor to indicate it's editable */
|
cursor: text; /* Add text cursor to indicate it's editable */
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Style for when editor is clicked - pulse effect */
|
/* Style for when editor is clicked - pulse effect */
|
||||||
.editor-focused {
|
.editor-focused {
|
||||||
animation: focus-pulse 0.3s ease;
|
animation: focus-pulse 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Pulse animation */
|
/* Pulse animation */
|
||||||
@keyframes focus-pulse {
|
@keyframes focus-pulse {
|
||||||
0% { background-color: #1e1e1e; }
|
0% {
|
||||||
50% { background-color: #303030; }
|
background-color: #1e1e1e;
|
||||||
100% { background-color: #1e1e1e; }
|
}
|
||||||
|
50% {
|
||||||
|
background-color: #303030;
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
background-color: #1e1e1e;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
code {
|
code {
|
||||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||||
}
|
}
|
||||||
|
|
||||||
.code-input {
|
.code-input {
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
color: #d4d4d4;
|
color: #d4d4d4;
|
||||||
border: none;
|
border: none;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-height: 100px;
|
min-height: 100px;
|
||||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
padding: 0.5rem 0;
|
padding: 0.5rem 0;
|
||||||
outline: none;
|
outline: none;
|
||||||
resize: vertical;
|
resize: vertical;
|
||||||
caret-color: var(--primary-color);
|
caret-color: var(--primary-color);
|
||||||
caret-shape: block;
|
caret-shape: block;
|
||||||
transition: background-color 0.2s ease;
|
transition: background-color 0.2s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Controls */
|
/* Controls */
|
||||||
.controls {
|
.controls {
|
||||||
/*justify-self: end;*/
|
/*justify-self: end;*/
|
||||||
/*position: absolute;*/
|
/*position: absolute;*/
|
||||||
/*left: 2rem;*/
|
/*left: 2rem;*/
|
||||||
/*right: 2rem;*/
|
/*right: 2rem;*/
|
||||||
/*bottom: 2rem;*/
|
/*bottom: 2rem;*/
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
margin-top: 1.5rem;
|
margin-top: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.level-indicator {
|
.level-indicator {
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
color: var(--light-text);
|
color: var(--light-text);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Buttons */
|
/* Buttons */
|
||||||
.btn {
|
.btn {
|
||||||
padding: 0.5rem 1rem;
|
padding: 0.5rem 1rem;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
border: 1px solid var(--border-color);
|
border: 1px solid var(--border-color);
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
color: var(--text-color);
|
color: var(--text-color);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
font-family: var(--font-main);
|
font-family: var(--font-main);
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
transition: all 0.2s;
|
transition: all 0.2s;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn:hover {
|
.btn:hover {
|
||||||
background-color: #f5f5f5;
|
background-color: #f5f5f5;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary {
|
.btn-primary {
|
||||||
background-color: var(--primary-color);
|
background-color: var(--primary-color);
|
||||||
color: white;
|
color: white;
|
||||||
border: 1px solid var(--primary-dark);
|
border: 1px solid var(--primary-dark);
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary:hover {
|
.btn-primary:hover {
|
||||||
background-color: var(--primary-dark);
|
background-color: var(--primary-dark);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Modal */
|
/* Modal */
|
||||||
.modal-container {
|
.modal-container {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background-color: rgba(0, 0, 0, 0.5);
|
background-color: rgba(0, 0, 0, 0.5);
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.modal {
|
.modal {
|
||||||
background-color: var(--panel-bg);
|
background-color: var(--panel-bg);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
|
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
|
||||||
width: 90%;
|
width: 90%;
|
||||||
max-width: 600px;
|
max-width: 600px;
|
||||||
max-height: 80vh;
|
max-height: 80vh;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.modal-header {
|
.modal-header {
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
border-bottom: 1px solid var(--border-color);
|
border-bottom: 1px solid var(--border-color);
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.modal-content {
|
.modal-content {
|
||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.modal-close {
|
.modal-close {
|
||||||
background: none;
|
background: none;
|
||||||
border: none;
|
border: none;
|
||||||
font-size: 1.5rem;
|
font-size: 1.5rem;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
color: var(--light-text);
|
color: var(--light-text);
|
||||||
}
|
}
|
||||||
|
|
||||||
.hidden {
|
.hidden {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Feedback */
|
/* Feedback */
|
||||||
.feedback-success {
|
.feedback-success {
|
||||||
color: var(--success-color);
|
color: var(--success-color);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
margin-top: 1rem;
|
margin-top: 1rem;
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
background-color: rgba(46, 204, 113, 0.1);
|
background-color: rgba(46, 204, 113, 0.1);
|
||||||
border-left: 3px solid var(--success-color);
|
border-left: 3px solid var(--success-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
.feedback-error {
|
.feedback-error {
|
||||||
color: var(--error-color);
|
color: var(--error-color);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
margin-top: 1rem;
|
margin-top: 1rem;
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
background-color: rgba(231, 76, 60, 0.1);
|
background-color: rgba(231, 76, 60, 0.1);
|
||||||
border-left: 3px solid var(--error-color);
|
border-left: 3px solid var(--error-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Add these styles to your main.css file */
|
/* Add these styles to your main.css file */
|
||||||
|
|
||||||
/* Success highlight for lesson container */
|
/* Success highlight for lesson container */
|
||||||
.success-highlight {
|
.success-highlight {
|
||||||
box-shadow: 0 0 0 3px var(--success-color);
|
box-shadow: 0 0 0 3px var(--success-color);
|
||||||
transition: all 0.3s ease;
|
transition: all 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Success text color for headings */
|
/* Success text color for headings */
|
||||||
.success-text {
|
.success-text {
|
||||||
color: var(--success-color);
|
color: var(--success-color);
|
||||||
transition: color 0.3s ease;
|
transition: color 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Friendlier error feedback */
|
/* Friendlier error feedback */
|
||||||
.feedback-error {
|
.feedback-error {
|
||||||
color: #996633;
|
color: #996633;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
margin-top: 1rem;
|
margin-top: 1rem;
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
background-color: rgba(255, 248, 230, 0.5);
|
background-color: rgba(255, 248, 230, 0.5);
|
||||||
border-left: 3px solid #cc9944;
|
border-left: 3px solid #cc9944;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Module selector button with progress */
|
/* Module selector button with progress */
|
||||||
#module-selector-btn {
|
#module-selector-btn {
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Button disabled state */
|
/* Button disabled state */
|
||||||
.btn-disabled {
|
.btn-disabled {
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,28 @@
|
|||||||
import { afterEach } from 'vitest';
|
import { afterEach } from "vitest";
|
||||||
import '@testing-library/jest-dom/vitest';
|
import "@testing-library/jest-dom/vitest";
|
||||||
// import 'whatwg-fetch';
|
// import 'whatwg-fetch';
|
||||||
|
|
||||||
// Setup mock for localStorage
|
// Setup mock for localStorage
|
||||||
const localStorageMock = (() => {
|
const localStorageMock = (() => {
|
||||||
let store = {};
|
let store = {};
|
||||||
return {
|
return {
|
||||||
getItem(key) {
|
getItem(key) {
|
||||||
return store[key] || null;
|
return store[key] || null;
|
||||||
},
|
},
|
||||||
setItem(key, value) {
|
setItem(key, value) {
|
||||||
store[key] = String(value);
|
store[key] = String(value);
|
||||||
},
|
},
|
||||||
removeItem(key) {
|
removeItem(key) {
|
||||||
delete store[key];
|
delete store[key];
|
||||||
},
|
},
|
||||||
clear() {
|
clear() {
|
||||||
store = {};
|
store = {};
|
||||||
},
|
},
|
||||||
length: 0,
|
length: 0,
|
||||||
key() { return null; }
|
key() {
|
||||||
};
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// Mock the DOM environment
|
// Mock the DOM environment
|
||||||
@@ -80,14 +82,14 @@ window.localStorage = localStorageMock;
|
|||||||
|
|
||||||
// For iframe support in jsdom
|
// For iframe support in jsdom
|
||||||
if (!window.document.createRange) {
|
if (!window.document.createRange) {
|
||||||
window.document.createRange = () => ({
|
window.document.createRange = () => ({
|
||||||
setStart: () => {},
|
setStart: () => {},
|
||||||
setEnd: () => {},
|
setEnd: () => {},
|
||||||
commonAncestorContainer: {
|
commonAncestorContainer: {
|
||||||
nodeName: 'BODY',
|
nodeName: "BODY",
|
||||||
ownerDocument: document,
|
ownerDocument: document
|
||||||
},
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add fetch mock
|
// Add fetch mock
|
||||||
@@ -95,6 +97,6 @@ global.fetch = vi.fn();
|
|||||||
|
|
||||||
// Clean up after each test
|
// Clean up after each test
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
fetch.mockReset();
|
fetch.mockReset();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,184 +1,172 @@
|
|||||||
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||||
import { loadModules, getModuleById, loadModuleFromUrl, addCustomModule } from '../../src/config/lessons.js';
|
import { loadModules, getModuleById, loadModuleFromUrl, addCustomModule } from "../../src/config/lessons.js";
|
||||||
|
|
||||||
// Mock the module store for testing
|
// Mock the module store for testing
|
||||||
vi.mock('../../lessons/flexbox.json', () => ({ default: { id: 'flexbox', title: 'Flexbox', lessons: [] }}));
|
vi.mock("../../lessons/flexbox.json", () => ({ default: { id: "flexbox", title: "Flexbox", lessons: [] } }));
|
||||||
vi.mock('../../lessons/grid.json', () => ({ default: { id: 'grid', title: 'CSS Grid', lessons: [] }}));
|
vi.mock("../../lessons/grid.json", () => ({ default: { id: "grid", title: "CSS Grid", lessons: [] } }));
|
||||||
vi.mock('../../lessons/basics.json', () => ({ default: { id: 'basics', title: 'CSS Basics', lessons: [] }}));
|
vi.mock("../../lessons/basics.json", () => ({ default: { id: "basics", title: "CSS Basics", lessons: [] } }));
|
||||||
vi.mock('../../lessons/tailwindcss.json', () => ({ default: { id: 'tailwind', title: 'Tailwind CSS', lessons: [] }}));
|
vi.mock("../../lessons/tailwindcss.json", () => ({ default: { id: "tailwind", title: "Tailwind CSS", lessons: [] } }));
|
||||||
|
|
||||||
describe('Lessons Config Module', () => {
|
describe("Lessons Config Module", () => {
|
||||||
describe('loadModules', () => {
|
describe("loadModules", () => {
|
||||||
test('should return an array of modules', async () => {
|
test("should return an array of modules", async () => {
|
||||||
const modules = await loadModules();
|
const modules = await loadModules();
|
||||||
|
|
||||||
expect(Array.isArray(modules)).toBe(true);
|
expect(Array.isArray(modules)).toBe(true);
|
||||||
expect(modules.length).toBe(4);
|
expect(modules.length).toBe(4);
|
||||||
|
|
||||||
// Check if modules have the right structure
|
// Check if modules have the right structure
|
||||||
const moduleIds = modules.map(m => m.id);
|
const moduleIds = modules.map((m) => m.id);
|
||||||
expect(moduleIds).toContain('basics');
|
expect(moduleIds).toContain("basics");
|
||||||
expect(moduleIds).toContain('flexbox');
|
expect(moduleIds).toContain("flexbox");
|
||||||
expect(moduleIds).toContain('grid');
|
expect(moduleIds).toContain("grid");
|
||||||
expect(moduleIds).toContain('tailwind');
|
expect(moduleIds).toContain("tailwind");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('getModuleById', () => {
|
describe("getModuleById", () => {
|
||||||
test('should return a module by ID', async () => {
|
test("should return a module by ID", async () => {
|
||||||
// Load modules first to populate the module store
|
// Load modules first to populate the module store
|
||||||
await loadModules();
|
await loadModules();
|
||||||
|
|
||||||
const flexboxModule = getModuleById('flexbox');
|
const flexboxModule = getModuleById("flexbox");
|
||||||
expect(flexboxModule).not.toBeNull();
|
expect(flexboxModule).not.toBeNull();
|
||||||
expect(flexboxModule.id).toBe('flexbox');
|
expect(flexboxModule.id).toBe("flexbox");
|
||||||
expect(flexboxModule.title).toBe('Flexbox');
|
expect(flexboxModule.title).toBe("Flexbox");
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should return null for non-existent module ID', async () => {
|
test("should return null for non-existent module ID", async () => {
|
||||||
// Load modules first
|
// Load modules first
|
||||||
await loadModules();
|
await loadModules();
|
||||||
|
|
||||||
const nonExistentModule = getModuleById('non-existent');
|
const nonExistentModule = getModuleById("non-existent");
|
||||||
expect(nonExistentModule).toBeNull();
|
expect(nonExistentModule).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('loadModuleFromUrl', () => {
|
describe("loadModuleFromUrl", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
// Reset fetch mock
|
// Reset fetch mock
|
||||||
fetch.mockReset();
|
fetch.mockReset();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should load a module from a URL', async () => {
|
test("should load a module from a URL", async () => {
|
||||||
const mockModule = {
|
const mockModule = {
|
||||||
id: 'remote-module',
|
id: "remote-module",
|
||||||
title: 'Remote Module',
|
title: "Remote Module",
|
||||||
lessons: [
|
lessons: [{ title: "Lesson 1", previewHTML: "<div>Preview</div>" }]
|
||||||
{ title: 'Lesson 1', previewHTML: '<div>Preview</div>' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
// Mock the fetch response
|
// Mock the fetch response
|
||||||
fetch.mockResolvedValueOnce({
|
fetch.mockResolvedValueOnce({
|
||||||
ok: true,
|
ok: true,
|
||||||
json: async () => mockModule
|
json: async () => mockModule
|
||||||
});
|
});
|
||||||
|
|
||||||
const result = await loadModuleFromUrl('https://example.com/module.json');
|
const result = await loadModuleFromUrl("https://example.com/module.json");
|
||||||
|
|
||||||
expect(fetch).toHaveBeenCalledWith('https://example.com/module.json');
|
expect(fetch).toHaveBeenCalledWith("https://example.com/module.json");
|
||||||
expect(result).toEqual(mockModule);
|
expect(result).toEqual(mockModule);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should throw an error for failed fetch', async () => {
|
test("should throw an error for failed fetch", async () => {
|
||||||
fetch.mockResolvedValueOnce({
|
fetch.mockResolvedValueOnce({
|
||||||
ok: false,
|
ok: false,
|
||||||
status: 404,
|
status: 404,
|
||||||
statusText: 'Not Found'
|
statusText: "Not Found"
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(loadModuleFromUrl('https://example.com/not-found.json'))
|
await expect(loadModuleFromUrl("https://example.com/not-found.json")).rejects.toThrow("Failed to load module: 404 Not Found");
|
||||||
.rejects
|
});
|
||||||
.toThrow('Failed to load module: 404 Not Found');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('should validate module structure', async () => {
|
test("should validate module structure", async () => {
|
||||||
// Missing required fields
|
// Missing required fields
|
||||||
const invalidModule = {
|
const invalidModule = {
|
||||||
// Missing id
|
// Missing id
|
||||||
title: 'Invalid Module'
|
title: "Invalid Module"
|
||||||
// Missing lessons array
|
// Missing lessons array
|
||||||
};
|
};
|
||||||
|
|
||||||
fetch.mockResolvedValueOnce({
|
fetch.mockResolvedValueOnce({
|
||||||
ok: true,
|
ok: true,
|
||||||
json: async () => invalidModule
|
json: async () => invalidModule
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(loadModuleFromUrl('https://example.com/invalid.json'))
|
await expect(loadModuleFromUrl("https://example.com/invalid.json")).rejects.toThrow('Module config missing "id"');
|
||||||
.rejects
|
|
||||||
.toThrow('Module config missing "id"');
|
|
||||||
|
|
||||||
// Invalid lessons structure
|
// Invalid lessons structure
|
||||||
const moduleWithInvalidLessons = {
|
const moduleWithInvalidLessons = {
|
||||||
id: 'invalid-lessons',
|
id: "invalid-lessons",
|
||||||
title: 'Invalid Lessons',
|
title: "Invalid Lessons",
|
||||||
lessons: [
|
lessons: [{ /* Missing title */ previewHTML: "<div>Preview</div>" }]
|
||||||
{ /* Missing title */ previewHTML: '<div>Preview</div>' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
fetch.mockResolvedValueOnce({
|
fetch.mockResolvedValueOnce({
|
||||||
ok: true,
|
ok: true,
|
||||||
json: async () => moduleWithInvalidLessons
|
json: async () => moduleWithInvalidLessons
|
||||||
});
|
});
|
||||||
|
|
||||||
await expect(loadModuleFromUrl('https://example.com/invalid-lessons.json'))
|
await expect(loadModuleFromUrl("https://example.com/invalid-lessons.json")).rejects.toThrow('Lesson 0 missing "title"');
|
||||||
.rejects
|
});
|
||||||
.toThrow('Lesson 0 missing "title"');
|
});
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('addCustomModule', () => {
|
describe("addCustomModule", () => {
|
||||||
test('should add a new module to the store', async () => {
|
test("should add a new module to the store", async () => {
|
||||||
// Load modules first to get current count
|
// Load modules first to get current count
|
||||||
const initialModules = await loadModules();
|
const initialModules = await loadModules();
|
||||||
const initialCount = initialModules.length;
|
const initialCount = initialModules.length;
|
||||||
|
|
||||||
const customModule = {
|
const customModule = {
|
||||||
id: 'custom-module',
|
id: "custom-module",
|
||||||
title: 'Custom Module',
|
title: "Custom Module",
|
||||||
lessons: [
|
lessons: [{ title: "Custom Lesson", previewHTML: "<div>Preview</div>" }]
|
||||||
{ title: 'Custom Lesson', previewHTML: '<div>Preview</div>' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = addCustomModule(customModule);
|
const result = addCustomModule(customModule);
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
|
|
||||||
// Check if module was added
|
// Check if module was added
|
||||||
const updatedModules = await loadModules();
|
const updatedModules = await loadModules();
|
||||||
expect(updatedModules.length).toBe(initialCount + 1);
|
expect(updatedModules.length).toBe(initialCount + 1);
|
||||||
|
|
||||||
const addedModule = getModuleById('custom-module');
|
const addedModule = getModuleById("custom-module");
|
||||||
expect(addedModule).not.toBeNull();
|
expect(addedModule).not.toBeNull();
|
||||||
expect(addedModule.title).toBe('Custom Module');
|
expect(addedModule.title).toBe("Custom Module");
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should replace existing module with same ID', async () => {
|
test("should replace existing module with same ID", async () => {
|
||||||
// Add a module first
|
// Add a module first
|
||||||
const customModule = {
|
const customModule = {
|
||||||
id: 'replace-test',
|
id: "replace-test",
|
||||||
title: 'Original Module',
|
title: "Original Module",
|
||||||
lessons: [{ title: 'Original Lesson', previewHTML: '<div>Preview</div>' }]
|
lessons: [{ title: "Original Lesson", previewHTML: "<div>Preview</div>" }]
|
||||||
};
|
};
|
||||||
|
|
||||||
addCustomModule(customModule);
|
addCustomModule(customModule);
|
||||||
|
|
||||||
// Now replace it
|
// Now replace it
|
||||||
const replacementModule = {
|
const replacementModule = {
|
||||||
id: 'replace-test',
|
id: "replace-test",
|
||||||
title: 'Replacement Module',
|
title: "Replacement Module",
|
||||||
lessons: [{ title: 'New Lesson', previewHTML: '<div>New Preview</div>' }]
|
lessons: [{ title: "New Lesson", previewHTML: "<div>New Preview</div>" }]
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = addCustomModule(replacementModule);
|
const result = addCustomModule(replacementModule);
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
|
|
||||||
// Check if module was replaced
|
// Check if module was replaced
|
||||||
const updatedModule = getModuleById('replace-test');
|
const updatedModule = getModuleById("replace-test");
|
||||||
expect(updatedModule.title).toBe('Replacement Module');
|
expect(updatedModule.title).toBe("Replacement Module");
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should validate module before adding', () => {
|
test("should validate module before adding", () => {
|
||||||
const invalidModule = {
|
const invalidModule = {
|
||||||
// Missing required fields
|
// Missing required fields
|
||||||
title: 'Invalid Module'
|
title: "Invalid Module"
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = addCustomModule(invalidModule);
|
const result = addCustomModule(invalidModule);
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||||
import { renderModuleList, renderLesson, renderLevelIndicator, showFeedback, clearFeedback } from '../../src/helpers/renderer.js';
|
import { renderModuleList, renderLesson, renderLevelIndicator, showFeedback, clearFeedback } from "../../src/helpers/renderer.js";
|
||||||
|
|
||||||
describe('Renderer Module', () => {
|
describe("Renderer Module", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
// Reset the DOM between tests
|
// Reset the DOM between tests
|
||||||
document.body.innerHTML = `
|
document.body.innerHTML = `
|
||||||
<div id="module-list"></div>
|
<div id="module-list"></div>
|
||||||
<h2 id="title"></h2>
|
<h2 id="title"></h2>
|
||||||
<div id="description"></div>
|
<div id="description"></div>
|
||||||
@@ -16,163 +16,145 @@ describe('Renderer Module', () => {
|
|||||||
<div id="level-indicator"></div>
|
<div id="level-indicator"></div>
|
||||||
<div id="code-editor"></div>
|
<div id="code-editor"></div>
|
||||||
`;
|
`;
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('renderModuleList', () => {
|
describe("renderModuleList", () => {
|
||||||
test('should render a list of modules', () => {
|
test("should render a list of modules", () => {
|
||||||
const container = document.getElementById('module-list');
|
const container = document.getElementById("module-list");
|
||||||
const modules = [
|
const modules = [
|
||||||
{ id: 'mod1', title: 'Module 1' },
|
{ id: "mod1", title: "Module 1" },
|
||||||
{ id: 'mod2', title: 'Module 2' }
|
{ id: "mod2", title: "Module 2" }
|
||||||
];
|
];
|
||||||
const onSelectModule = vi.fn();
|
const onSelectModule = vi.fn();
|
||||||
|
|
||||||
renderModuleList(container, modules, onSelectModule);
|
renderModuleList(container, modules, onSelectModule);
|
||||||
|
|
||||||
// Check if heading is created
|
// Check if heading is created
|
||||||
expect(container.innerHTML).toContain('<h3>Modules</h3>');
|
expect(container.innerHTML).toContain("<h3>Modules</h3>");
|
||||||
|
|
||||||
// Check if module items are created
|
// Check if module items are created
|
||||||
const moduleItems = container.querySelectorAll('.module-list-item');
|
const moduleItems = container.querySelectorAll(".module-list-item");
|
||||||
expect(moduleItems.length).toBe(2);
|
expect(moduleItems.length).toBe(2);
|
||||||
expect(moduleItems[0].textContent).toBe('Module 1');
|
expect(moduleItems[0].textContent).toBe("Module 1");
|
||||||
expect(moduleItems[1].textContent).toBe('Module 2');
|
expect(moduleItems[1].textContent).toBe("Module 2");
|
||||||
|
|
||||||
// Test click event
|
// Test click event
|
||||||
moduleItems[0].click();
|
moduleItems[0].click();
|
||||||
expect(onSelectModule).toHaveBeenCalledWith('mod1');
|
expect(onSelectModule).toHaveBeenCalledWith("mod1");
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should handle empty module list', () => {
|
test("should handle empty module list", () => {
|
||||||
const container = document.getElementById('module-list');
|
const container = document.getElementById("module-list");
|
||||||
renderModuleList(container, [], vi.fn());
|
renderModuleList(container, [], vi.fn());
|
||||||
|
|
||||||
expect(container.innerHTML).toContain('<h3>Modules</h3>');
|
expect(container.innerHTML).toContain("<h3>Modules</h3>");
|
||||||
expect(container.querySelectorAll('.module-list-item').length).toBe(0);
|
expect(container.querySelectorAll(".module-list-item").length).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('renderLesson', () => {
|
describe("renderLesson", () => {
|
||||||
test('should render lesson content correctly', () => {
|
test("should render lesson content correctly", () => {
|
||||||
const titleEl = document.getElementById('title');
|
const titleEl = document.getElementById("title");
|
||||||
const descriptionEl = document.getElementById('description');
|
const descriptionEl = document.getElementById("description");
|
||||||
const taskEl = document.getElementById('task');
|
const taskEl = document.getElementById("task");
|
||||||
const previewEl = document.getElementById('preview');
|
const previewEl = document.getElementById("preview");
|
||||||
const prefixEl = document.getElementById('prefix');
|
const prefixEl = document.getElementById("prefix");
|
||||||
const inputEl = document.getElementById('input');
|
const inputEl = document.getElementById("input");
|
||||||
const suffixEl = document.getElementById('suffix');
|
const suffixEl = document.getElementById("suffix");
|
||||||
|
|
||||||
const lesson = {
|
const lesson = {
|
||||||
title: 'Test Lesson',
|
title: "Test Lesson",
|
||||||
description: '<p>Description text</p>',
|
description: "<p>Description text</p>",
|
||||||
task: '<p>Task instructions</p>',
|
task: "<p>Task instructions</p>",
|
||||||
codePrefix: 'body {',
|
codePrefix: "body {",
|
||||||
initialCode: ' color: red;',
|
initialCode: " color: red;",
|
||||||
codeSuffix: '}'
|
codeSuffix: "}"
|
||||||
};
|
};
|
||||||
|
|
||||||
renderLesson(
|
renderLesson(titleEl, descriptionEl, taskEl, previewEl, prefixEl, inputEl, suffixEl, lesson);
|
||||||
titleEl,
|
|
||||||
descriptionEl,
|
|
||||||
taskEl,
|
|
||||||
previewEl,
|
|
||||||
prefixEl,
|
|
||||||
inputEl,
|
|
||||||
suffixEl,
|
|
||||||
lesson
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(titleEl.textContent).toBe('Test Lesson');
|
expect(titleEl.textContent).toBe("Test Lesson");
|
||||||
expect(descriptionEl.innerHTML).toBe('<p>Description text</p>');
|
expect(descriptionEl.innerHTML).toBe("<p>Description text</p>");
|
||||||
expect(taskEl.innerHTML).toBe('<p>Task instructions</p>');
|
expect(taskEl.innerHTML).toBe("<p>Task instructions</p>");
|
||||||
expect(prefixEl.textContent).toBe('body {');
|
expect(prefixEl.textContent).toBe("body {");
|
||||||
expect(inputEl.value).toBe(' color: red;');
|
expect(inputEl.value).toBe(" color: red;");
|
||||||
expect(suffixEl.textContent).toBe('}');
|
expect(suffixEl.textContent).toBe("}");
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should handle missing lesson data with defaults', () => {
|
test("should handle missing lesson data with defaults", () => {
|
||||||
const titleEl = document.getElementById('title');
|
const titleEl = document.getElementById("title");
|
||||||
const descriptionEl = document.getElementById('description');
|
const descriptionEl = document.getElementById("description");
|
||||||
const taskEl = document.getElementById('task');
|
const taskEl = document.getElementById("task");
|
||||||
const prefixEl = document.getElementById('prefix');
|
const prefixEl = document.getElementById("prefix");
|
||||||
const inputEl = document.getElementById('input');
|
const inputEl = document.getElementById("input");
|
||||||
const suffixEl = document.getElementById('suffix');
|
const suffixEl = document.getElementById("suffix");
|
||||||
|
|
||||||
// Empty lesson object
|
// Empty lesson object
|
||||||
const lesson = {};
|
const lesson = {};
|
||||||
|
|
||||||
renderLesson(
|
renderLesson(titleEl, descriptionEl, taskEl, document.getElementById("preview"), prefixEl, inputEl, suffixEl, lesson);
|
||||||
titleEl,
|
|
||||||
descriptionEl,
|
|
||||||
taskEl,
|
|
||||||
document.getElementById('preview'),
|
|
||||||
prefixEl,
|
|
||||||
inputEl,
|
|
||||||
suffixEl,
|
|
||||||
lesson
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(titleEl.textContent).toBe('Untitled Lesson');
|
expect(titleEl.textContent).toBe("Untitled Lesson");
|
||||||
expect(descriptionEl.innerHTML).toBe('');
|
expect(descriptionEl.innerHTML).toBe("");
|
||||||
expect(taskEl.innerHTML).toBe('');
|
expect(taskEl.innerHTML).toBe("");
|
||||||
expect(prefixEl.textContent).toBe('');
|
expect(prefixEl.textContent).toBe("");
|
||||||
expect(inputEl.value).toBe('');
|
expect(inputEl.value).toBe("");
|
||||||
expect(suffixEl.textContent).toBe('');
|
expect(suffixEl.textContent).toBe("");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('renderLevelIndicator', () => {
|
describe("renderLevelIndicator", () => {
|
||||||
test('should update level indicator text', () => {
|
test("should update level indicator text", () => {
|
||||||
const element = document.getElementById('level-indicator');
|
const element = document.getElementById("level-indicator");
|
||||||
|
|
||||||
renderLevelIndicator(element, 3, 10);
|
renderLevelIndicator(element, 3, 10);
|
||||||
expect(element.textContent).toBe('Lesson 3 of 10');
|
expect(element.textContent).toBe("Lesson 3 of 10");
|
||||||
|
|
||||||
renderLevelIndicator(element, 1, 5);
|
renderLevelIndicator(element, 1, 5);
|
||||||
expect(element.textContent).toBe('Lesson 1 of 5');
|
expect(element.textContent).toBe("Lesson 1 of 5");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe.skip('showFeedback and clearFeedback', () => {
|
describe.skip("showFeedback and clearFeedback", () => {
|
||||||
test('should create success feedback element', () => {
|
test("should create success feedback element", () => {
|
||||||
const editor = document.getElementById('code-editor');
|
const editor = document.getElementById("code-editor");
|
||||||
showFeedback(true, 'Great job!');
|
showFeedback(true, "Great job!");
|
||||||
|
|
||||||
const feedback = document.querySelector('.feedback-success');
|
const feedback = document.querySelector(".feedback-success");
|
||||||
expect(feedback).not.toBeNull();
|
expect(feedback).not.toBeNull();
|
||||||
expect(feedback.textContent).toBe('Great job!');
|
expect(feedback.textContent).toBe("Great job!");
|
||||||
|
|
||||||
// Test auto clearing with setTimeout
|
// Test auto clearing with setTimeout
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
showFeedback(true, 'Auto clear test');
|
showFeedback(true, "Auto clear test");
|
||||||
vi.advanceTimersByTime(5001);
|
vi.advanceTimersByTime(5001);
|
||||||
expect(document.querySelector('.feedback-success')).toBeNull();
|
expect(document.querySelector(".feedback-success")).toBeNull();
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should create error feedback element', () => {
|
test("should create error feedback element", () => {
|
||||||
showFeedback(false, 'Try again');
|
showFeedback(false, "Try again");
|
||||||
|
|
||||||
const feedback = document.querySelector('.feedback-error');
|
const feedback = document.querySelector(".feedback-error");
|
||||||
expect(feedback).not.toBeNull();
|
expect(feedback).not.toBeNull();
|
||||||
expect(feedback.textContent).toBe('Try again');
|
expect(feedback.textContent).toBe("Try again");
|
||||||
|
|
||||||
// Error feedback should not auto-clear
|
// Error feedback should not auto-clear
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
vi.advanceTimersByTime(5001);
|
vi.advanceTimersByTime(5001);
|
||||||
expect(document.querySelector('.feedback-error')).not.toBeNull();
|
expect(document.querySelector(".feedback-error")).not.toBeNull();
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('should clear existing feedback', () => {
|
test("should clear existing feedback", () => {
|
||||||
showFeedback(false, 'Error message');
|
showFeedback(false, "Error message");
|
||||||
expect(document.querySelector('.feedback-error')).not.toBeNull();
|
expect(document.querySelector(".feedback-error")).not.toBeNull();
|
||||||
|
|
||||||
clearFeedback();
|
clearFeedback();
|
||||||
expect(document.querySelector('.feedback-error')).toBeNull();
|
expect(document.querySelector(".feedback-error")).toBeNull();
|
||||||
|
|
||||||
// Should work when called multiple times
|
// Should work when called multiple times
|
||||||
clearFeedback();
|
clearFeedback();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,239 +1,227 @@
|
|||||||
import { describe, it, expect, vi } from 'vitest';
|
import { describe, it, expect, vi } from "vitest";
|
||||||
import { validateUserCode } from '../../src/helpers/validator.js';
|
import { validateUserCode } from "../../src/helpers/validator.js";
|
||||||
|
|
||||||
describe('CSS Validator', () => {
|
describe("CSS Validator", () => {
|
||||||
// Mock document functions since we're not in a browser
|
// Mock document functions since we're not in a browser
|
||||||
document.createElement = vi.fn().mockImplementation(() => {
|
document.createElement = vi.fn().mockImplementation(() => {
|
||||||
return {
|
return {
|
||||||
textContent: '',
|
textContent: "",
|
||||||
parentNode: { removeChild: vi.fn() }
|
parentNode: { removeChild: vi.fn() }
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
// document.head = {
|
// document.head = {
|
||||||
// appendChild: vi.fn(),
|
// appendChild: vi.fn(),
|
||||||
// removeChild: vi.fn()
|
// removeChild: vi.fn()
|
||||||
// };
|
// };
|
||||||
|
|
||||||
describe('validateUserCode', () => {
|
describe("validateUserCode", () => {
|
||||||
it('should pass when no validations are specified', () => {
|
it("should pass when no validations are specified", () => {
|
||||||
const userCode = 'div { color: red; }';
|
const userCode = "div { color: red; }";
|
||||||
const lesson = { title: 'Test Lesson' };
|
const lesson = { title: "Test Lesson" };
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
|
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
expect(result.message).toContain('No validations specified');
|
expect(result.message).toContain("No validations specified");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should pass with empty validations array', () => {
|
it("should pass with empty validations array", () => {
|
||||||
const userCode = 'div { color: red; }';
|
const userCode = "div { color: red; }";
|
||||||
const lesson = {
|
const lesson = {
|
||||||
title: 'Test Lesson',
|
title: "Test Lesson",
|
||||||
validations: []
|
validations: []
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
|
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
expect(result.message).toBe('Your code looks good!');
|
expect(result.message).toBe("Your code looks good!");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should validate "contains" rule correctly', () => {
|
it('should validate "contains" rule correctly', () => {
|
||||||
const userCode = 'div { color: red; }';
|
const userCode = "div { color: red; }";
|
||||||
const lesson = {
|
const lesson = {
|
||||||
validations: [
|
validations: [{ type: "contains", value: "color: red", message: "Should use red color" }]
|
||||||
{ type: 'contains', value: 'color: red', message: 'Should use red color' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
|
|
||||||
const failLesson = {
|
const failLesson = {
|
||||||
validations: [
|
validations: [{ type: "contains", value: "color: blue", message: "Should use blue color" }]
|
||||||
{ type: 'contains', value: 'color: blue', message: 'Should use blue color' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const failResult = validateUserCode(userCode, failLesson);
|
const failResult = validateUserCode(userCode, failLesson);
|
||||||
expect(failResult.isValid).toBe(false);
|
expect(failResult.isValid).toBe(false);
|
||||||
expect(failResult.message).toBe('Should use blue color');
|
expect(failResult.message).toBe("Should use blue color");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should validate "not_contains" rule correctly', () => {
|
it('should validate "not_contains" rule correctly', () => {
|
||||||
const userCode = 'div { color: red; }';
|
const userCode = "div { color: red; }";
|
||||||
const lesson = {
|
const lesson = {
|
||||||
validations: [
|
validations: [{ type: "not_contains", value: "color: blue", message: "Should not use blue color" }]
|
||||||
{ type: 'not_contains', value: 'color: blue', message: 'Should not use blue color' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
|
|
||||||
const failLesson = {
|
const failLesson = {
|
||||||
validations: [
|
validations: [{ type: "not_contains", value: "color: red", message: "Should not use red color" }]
|
||||||
{ type: 'not_contains', value: 'color: red', message: 'Should not use red color' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const failResult = validateUserCode(userCode, failLesson);
|
const failResult = validateUserCode(userCode, failLesson);
|
||||||
expect(failResult.isValid).toBe(false);
|
expect(failResult.isValid).toBe(false);
|
||||||
expect(failResult.message).toBe('Should not use red color');
|
expect(failResult.message).toBe("Should not use red color");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should validate "regex" rule correctly', () => {
|
it('should validate "regex" rule correctly', () => {
|
||||||
const userCode = 'div { color: #ff0000; }';
|
const userCode = "div { color: #ff0000; }";
|
||||||
const lesson = {
|
const lesson = {
|
||||||
validations: [
|
validations: [{ type: "regex", value: "#[a-f0-9]{6}", message: "Should use hex color" }]
|
||||||
{ type: 'regex', value: '#[a-f0-9]{6}', message: 'Should use hex color' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
|
|
||||||
const failLesson = {
|
const failLesson = {
|
||||||
validations: [
|
validations: [{ type: "regex", value: "rgb\\(\\d+,\\s*\\d+,\\s*\\d+\\)", message: "Should use RGB color" }]
|
||||||
{ type: 'regex', value: 'rgb\\(\\d+,\\s*\\d+,\\s*\\d+\\)', message: 'Should use RGB color' }
|
};
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
const failResult = validateUserCode(userCode, failLesson);
|
const failResult = validateUserCode(userCode, failLesson);
|
||||||
expect(failResult.isValid).toBe(false);
|
expect(failResult.isValid).toBe(false);
|
||||||
expect(failResult.message).toBe('Should use RGB color');
|
expect(failResult.message).toBe("Should use RGB color");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should validate "property_value" rule correctly', () => {
|
it('should validate "property_value" rule correctly', () => {
|
||||||
const userCode = 'div { display: flex; }';
|
const userCode = "div { display: flex; }";
|
||||||
const lesson = {
|
const lesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{
|
{
|
||||||
type: 'property_value',
|
type: "property_value",
|
||||||
value: { property: 'display', expected: 'flex' },
|
value: { property: "display", expected: "flex" },
|
||||||
message: 'Should use display: flex'
|
message: "Should use display: flex"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
|
|
||||||
const failLesson = {
|
const failLesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{
|
{
|
||||||
type: 'property_value',
|
type: "property_value",
|
||||||
value: { property: 'display', expected: 'grid' },
|
value: { property: "display", expected: "grid" },
|
||||||
message: 'Should use display: grid'
|
message: "Should use display: grid"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const failResult = validateUserCode(userCode, failLesson);
|
const failResult = validateUserCode(userCode, failLesson);
|
||||||
expect(failResult.isValid).toBe(false);
|
expect(failResult.isValid).toBe(false);
|
||||||
expect(failResult.message).toBe('Should use display: grid');
|
expect(failResult.message).toBe("Should use display: grid");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle complex validation chains', () => {
|
it("should handle complex validation chains", () => {
|
||||||
const userCode = 'div { display: flex; color: red; }';
|
const userCode = "div { display: flex; color: red; }";
|
||||||
const lesson = {
|
const lesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{ type: 'contains', value: 'display: flex' },
|
{ type: "contains", value: "display: flex" },
|
||||||
{ type: 'contains', value: 'color: red' },
|
{ type: "contains", value: "color: red" },
|
||||||
{ type: 'not_contains', value: 'float:' }
|
{ type: "not_contains", value: "float:" }
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
|
|
||||||
// First failing validation should cause early return
|
// First failing validation should cause early return
|
||||||
const failLesson = {
|
const failLesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{ type: 'contains', value: 'display: flex' },
|
{ type: "contains", value: "display: flex" },
|
||||||
{ type: 'contains', value: 'border: 1px solid black', message: 'Missing border' },
|
{ type: "contains", value: "border: 1px solid black", message: "Missing border" },
|
||||||
{ type: 'not_contains', value: 'color: green' }
|
{ type: "not_contains", value: "color: green" }
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const failResult = validateUserCode(userCode, failLesson);
|
const failResult = validateUserCode(userCode, failLesson);
|
||||||
expect(failResult.isValid).toBe(false);
|
expect(failResult.isValid).toBe(false);
|
||||||
expect(failResult.message).toBe('Missing border');
|
expect(failResult.message).toBe("Missing border");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should validate "custom" rule correctly', () => {
|
it('should validate "custom" rule correctly', () => {
|
||||||
const userCode = 'div { margin: 10px; }';
|
const userCode = "div { margin: 10px; }";
|
||||||
const customValidator = (code) => {
|
const customValidator = (code) => {
|
||||||
return {
|
return {
|
||||||
isValid: code.includes('margin'),
|
isValid: code.includes("margin"),
|
||||||
message: 'Should include margin property'
|
message: "Should include margin property"
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const lesson = {
|
const lesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{
|
{
|
||||||
type: 'custom',
|
type: "custom",
|
||||||
validator: customValidator
|
validator: customValidator
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
|
|
||||||
const failValidator = (code) => {
|
const failValidator = (code) => {
|
||||||
return {
|
return {
|
||||||
isValid: code.includes('padding'),
|
isValid: code.includes("padding"),
|
||||||
message: 'Should include padding property'
|
message: "Should include padding property"
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const failLesson = {
|
const failLesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{
|
{
|
||||||
type: 'custom',
|
type: "custom",
|
||||||
validator: failValidator,
|
validator: failValidator,
|
||||||
message: 'Custom validation failed'
|
message: "Custom validation failed"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const failResult = validateUserCode(userCode, failLesson);
|
const failResult = validateUserCode(userCode, failLesson);
|
||||||
expect(failResult.isValid).toBe(false);
|
expect(failResult.isValid).toBe(false);
|
||||||
expect(failResult.message).toBe('Should include padding property');
|
expect(failResult.message).toBe("Should include padding property");
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle options in validations', () => {
|
it("should handle options in validations", () => {
|
||||||
// Case insensitive test
|
// Case insensitive test
|
||||||
const userCode = 'div { COLOR: Red; }';
|
const userCode = "div { COLOR: Red; }";
|
||||||
const lesson = {
|
const lesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{
|
{
|
||||||
type: 'contains',
|
type: "contains",
|
||||||
value: 'color: red',
|
value: "color: red",
|
||||||
options: { caseSensitive: false }
|
options: { caseSensitive: false }
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const result = validateUserCode(userCode, lesson);
|
const result = validateUserCode(userCode, lesson);
|
||||||
expect(result.isValid).toBe(true);
|
expect(result.isValid).toBe(true);
|
||||||
|
|
||||||
// With exact match required
|
// With exact match required
|
||||||
const exactLesson = {
|
const exactLesson = {
|
||||||
validations: [
|
validations: [
|
||||||
{
|
{
|
||||||
type: 'property_value',
|
type: "property_value",
|
||||||
value: { property: 'color', expected: 'red' },
|
value: { property: "color", expected: "red" },
|
||||||
options: { exact: true }
|
options: { exact: true }
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
};
|
};
|
||||||
|
|
||||||
const failExactResult = validateUserCode('div { color: RED; }', exactLesson);
|
const failExactResult = validateUserCode("div { color: RED; }", exactLesson);
|
||||||
expect(failExactResult.isValid).toBe(false);
|
expect(failExactResult.isValid).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from "vite";
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
root: './src',
|
root: "./src",
|
||||||
publicDir: './public',
|
publicDir: "./public",
|
||||||
build: {
|
build: {
|
||||||
outDir: '../dist',
|
outDir: "../dist",
|
||||||
emptyOutDir: true,
|
emptyOutDir: true,
|
||||||
sourcemap: true
|
sourcemap: true
|
||||||
},
|
},
|
||||||
server: {
|
server: {
|
||||||
port: 1312,
|
port: 1312,
|
||||||
open: false
|
open: false
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
// vitest.config.js
|
// vitest.config.js
|
||||||
import { defineConfig } from 'vitest/config';
|
import { defineConfig } from "vitest/config";
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
test: {
|
test: {
|
||||||
globals: true,
|
globals: true,
|
||||||
environment: 'jsdom',
|
environment: "jsdom",
|
||||||
setupFiles: ['./tests/setup.js'],
|
setupFiles: ["./tests/setup.js"],
|
||||||
include: ['tests/**/*.{test,spec}.js'],
|
include: ["tests/**/*.{test,spec}.js"],
|
||||||
coverage: {
|
coverage: {
|
||||||
reporter: ['text', 'json', 'html'],
|
reporter: ["text", "json", "html"],
|
||||||
exclude: ['node_modules/', 'tests/setup.js']
|
exclude: ["node_modules/", "tests/setup.js"]
|
||||||
},
|
},
|
||||||
server: {
|
server: {
|
||||||
deps: {
|
deps: {
|
||||||
inline: true
|
inline: true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user