style: run format first time
This commit is contained in:
201
src/app.js
201
src/app.js
@@ -1,39 +1,39 @@
|
||||
import { LessonEngine } from './impl/LessonEngine.js';
|
||||
import { renderLesson, renderModuleList, renderLevelIndicator, showFeedback } from './helpers/renderer.js';
|
||||
import { validateUserCode } from './helpers/validator.js';
|
||||
import { loadModules } from './config/lessons.js';
|
||||
import { LessonEngine } from "./impl/LessonEngine.js";
|
||||
import { renderLesson, renderModuleList, renderLevelIndicator, showFeedback } from "./helpers/renderer.js";
|
||||
import { validateUserCode } from "./helpers/validator.js";
|
||||
import { loadModules } from "./config/lessons.js";
|
||||
|
||||
// Main Application state
|
||||
const state = {
|
||||
currentModule: null,
|
||||
currentLessonIndex: 0,
|
||||
modules: [],
|
||||
userProgress: {}, // Format: { moduleId: { completed: [0, 2, 3], current: 4 } }
|
||||
userProgress: {} // Format: { moduleId: { completed: [0, 2, 3], current: 4 } }
|
||||
};
|
||||
|
||||
// DOM elements
|
||||
const elements = {
|
||||
moduleList: document.querySelector('.module-list'),
|
||||
lessonTitle: document.getElementById('lesson-title'),
|
||||
lessonDescription: document.getElementById('lesson-description'),
|
||||
taskInstruction: document.getElementById('task-instruction'),
|
||||
previewArea: document.getElementById('preview-area'),
|
||||
editorPrefix: document.getElementById('editor-prefix'),
|
||||
codeInput: document.getElementById('code-input'),
|
||||
editorSuffix: document.getElementById('editor-suffix'),
|
||||
prevBtn: document.getElementById('prev-btn'),
|
||||
nextBtn: document.getElementById('next-btn'),
|
||||
runBtn: document.getElementById('run-btn'),
|
||||
levelIndicator: document.getElementById('level-indicator'),
|
||||
modalContainer: document.getElementById('modal-container'),
|
||||
modalTitle: document.getElementById('modal-title'),
|
||||
modalContent: document.getElementById('modal-content'),
|
||||
modalClose: document.getElementById('modal-close'),
|
||||
moduleSelectorBtn: document.getElementById('module-selector-btn'),
|
||||
resetBtn: document.getElementById('reset-btn'),
|
||||
helpBtn: document.getElementById('help-btn'),
|
||||
lessonContainer: document.querySelector('.lesson-container'),
|
||||
editorContent: document.querySelector('.editor-content')
|
||||
moduleList: document.querySelector(".module-list"),
|
||||
lessonTitle: document.getElementById("lesson-title"),
|
||||
lessonDescription: document.getElementById("lesson-description"),
|
||||
taskInstruction: document.getElementById("task-instruction"),
|
||||
previewArea: document.getElementById("preview-area"),
|
||||
editorPrefix: document.getElementById("editor-prefix"),
|
||||
codeInput: document.getElementById("code-input"),
|
||||
editorSuffix: document.getElementById("editor-suffix"),
|
||||
prevBtn: document.getElementById("prev-btn"),
|
||||
nextBtn: document.getElementById("next-btn"),
|
||||
runBtn: document.getElementById("run-btn"),
|
||||
levelIndicator: document.getElementById("level-indicator"),
|
||||
modalContainer: document.getElementById("modal-container"),
|
||||
modalTitle: document.getElementById("modal-title"),
|
||||
modalContent: document.getElementById("modal-content"),
|
||||
modalClose: document.getElementById("modal-close"),
|
||||
moduleSelectorBtn: document.getElementById("module-selector-btn"),
|
||||
resetBtn: document.getElementById("reset-btn"),
|
||||
helpBtn: document.getElementById("help-btn"),
|
||||
lessonContainer: document.querySelector(".lesson-container"),
|
||||
editorContent: document.querySelector(".editor-content")
|
||||
};
|
||||
|
||||
// Initialize the lesson engine
|
||||
@@ -41,7 +41,7 @@ const lessonEngine = new LessonEngine();
|
||||
|
||||
// Load user progress from localStorage
|
||||
function loadUserProgress() {
|
||||
const savedProgress = localStorage.getItem('codeCrispiesProgress');
|
||||
const savedProgress = localStorage.getItem("codeCrispiesProgress");
|
||||
if (savedProgress) {
|
||||
state.userProgress = JSON.parse(savedProgress);
|
||||
}
|
||||
@@ -49,7 +49,7 @@ function loadUserProgress() {
|
||||
|
||||
// Save user progress to localStorage
|
||||
function saveUserProgress() {
|
||||
localStorage.setItem('codeCrispiesProgress', JSON.stringify(state.userProgress));
|
||||
localStorage.setItem("codeCrispiesProgress", JSON.stringify(state.userProgress));
|
||||
}
|
||||
|
||||
// Initialize the module list
|
||||
@@ -59,8 +59,8 @@ async function initializeModules() {
|
||||
renderModuleList(elements.moduleList, state.modules, selectModule);
|
||||
|
||||
// Select the first module or the last one user was on
|
||||
const lastModuleId = localStorage.getItem('lastModuleId');
|
||||
if (lastModuleId && state.modules.find(m => m.id === lastModuleId)) {
|
||||
const lastModuleId = localStorage.getItem("lastModuleId");
|
||||
if (lastModuleId && state.modules.find((m) => m.id === lastModuleId)) {
|
||||
selectModule(lastModuleId);
|
||||
} else if (state.modules.length > 0) {
|
||||
selectModule(state.modules[0].id);
|
||||
@@ -69,8 +69,8 @@ async function initializeModules() {
|
||||
// Update progress indicator on module selector button
|
||||
updateModuleSelectorButtonProgress();
|
||||
} catch (error) {
|
||||
console.error('Failed to load modules:', error);
|
||||
elements.lessonDescription.textContent = 'Failed to load modules. Please refresh the page.';
|
||||
console.error("Failed to load modules:", error);
|
||||
elements.lessonDescription.textContent = "Failed to load modules. Please refresh the page.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ function updateModuleSelectorButtonProgress() {
|
||||
let totalLessons = 0;
|
||||
let totalCompleted = 0;
|
||||
|
||||
state.modules.forEach(module => {
|
||||
state.modules.forEach((module) => {
|
||||
totalLessons += module.lessons.length;
|
||||
const progress = state.userProgress[module.id];
|
||||
if (progress && progress.completed) {
|
||||
@@ -93,8 +93,8 @@ function updateModuleSelectorButtonProgress() {
|
||||
const percentComplete = totalLessons > 0 ? Math.round((totalCompleted / totalLessons) * 100) : 0;
|
||||
|
||||
// Create progress indicator
|
||||
const progressBar = document.createElement('div');
|
||||
progressBar.className = 'progress-indicator';
|
||||
const progressBar = document.createElement("div");
|
||||
progressBar.className = "progress-indicator";
|
||||
progressBar.style.cssText = `
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
@@ -107,10 +107,10 @@ function updateModuleSelectorButtonProgress() {
|
||||
|
||||
// Add progress percentage text
|
||||
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
|
||||
const existingBar = elements.moduleSelectorBtn.querySelector('.progress-indicator');
|
||||
const existingBar = elements.moduleSelectorBtn.querySelector(".progress-indicator");
|
||||
if (existingBar) {
|
||||
existingBar.remove();
|
||||
}
|
||||
@@ -120,17 +120,17 @@ function updateModuleSelectorButtonProgress() {
|
||||
|
||||
// Select a module
|
||||
function selectModule(moduleId) {
|
||||
const selectedModule = state.modules.find(module => module.id === moduleId);
|
||||
const selectedModule = state.modules.find((module) => module.id === moduleId);
|
||||
if (!selectedModule) return;
|
||||
|
||||
state.currentModule = selectedModule;
|
||||
|
||||
// Update module list UI
|
||||
const moduleItems = elements.moduleList.querySelectorAll('.module-list-item');
|
||||
moduleItems.forEach(item => {
|
||||
item.classList.remove('active');
|
||||
const moduleItems = elements.moduleList.querySelectorAll(".module-list-item");
|
||||
moduleItems.forEach((item) => {
|
||||
item.classList.remove("active");
|
||||
if (item.dataset.moduleId === moduleId) {
|
||||
item.classList.add('active');
|
||||
item.classList.add("active");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -143,7 +143,7 @@ function selectModule(moduleId) {
|
||||
loadCurrentLesson();
|
||||
|
||||
// Save the last selected module
|
||||
localStorage.setItem('lastModuleId', moduleId);
|
||||
localStorage.setItem("lastModuleId", moduleId);
|
||||
|
||||
// Reset any success indicators
|
||||
resetSuccessIndicators();
|
||||
@@ -151,10 +151,10 @@ function selectModule(moduleId) {
|
||||
|
||||
// Reset success indicators
|
||||
function resetSuccessIndicators() {
|
||||
elements.lessonContainer.classList.remove('success-highlight');
|
||||
elements.lessonTitle.classList.remove('success-text');
|
||||
const headings = elements.lessonContainer.querySelectorAll('h2, h3, h4');
|
||||
headings.forEach(heading => heading.classList.remove('success-text'));
|
||||
elements.lessonContainer.classList.remove("success-highlight");
|
||||
elements.lessonTitle.classList.remove("success-text");
|
||||
const headings = elements.lessonContainer.querySelectorAll("h2, h3, h4");
|
||||
headings.forEach((heading) => heading.classList.remove("success-text"));
|
||||
}
|
||||
|
||||
// Load the current lesson
|
||||
@@ -189,11 +189,7 @@ function loadCurrentLesson() {
|
||||
);
|
||||
|
||||
// Update level indicator
|
||||
renderLevelIndicator(
|
||||
elements.levelIndicator,
|
||||
state.currentLessonIndex + 1,
|
||||
state.currentModule.lessons.length
|
||||
);
|
||||
renderLevelIndicator(elements.levelIndicator, state.currentLessonIndex + 1, state.currentModule.lessons.length);
|
||||
|
||||
// Update navigation buttons
|
||||
updateNavigationButtons();
|
||||
@@ -212,20 +208,19 @@ function loadCurrentLesson() {
|
||||
// Update navigation buttons state
|
||||
function updateNavigationButtons() {
|
||||
elements.prevBtn.disabled = state.currentLessonIndex === 0;
|
||||
elements.nextBtn.disabled = !state.currentModule ||
|
||||
state.currentLessonIndex === state.currentModule.lessons.length - 1;
|
||||
elements.nextBtn.disabled = !state.currentModule || state.currentLessonIndex === state.currentModule.lessons.length - 1;
|
||||
|
||||
// Style changes for disabled buttons
|
||||
if (elements.prevBtn.disabled) {
|
||||
elements.prevBtn.classList.add('btn-disabled');
|
||||
elements.prevBtn.classList.add("btn-disabled");
|
||||
} else {
|
||||
elements.prevBtn.classList.remove('btn-disabled');
|
||||
elements.prevBtn.classList.remove("btn-disabled");
|
||||
}
|
||||
|
||||
if (elements.nextBtn.disabled) {
|
||||
elements.nextBtn.classList.add('btn-disabled');
|
||||
elements.nextBtn.classList.add("btn-disabled");
|
||||
} else {
|
||||
elements.nextBtn.classList.remove('btn-disabled');
|
||||
elements.nextBtn.classList.remove("btn-disabled");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,13 +259,13 @@ function runCode() {
|
||||
}
|
||||
|
||||
// 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
|
||||
elements.lessonContainer.classList.add('success-highlight');
|
||||
elements.lessonTitle.classList.add('success-text');
|
||||
const headings = elements.lessonContainer.querySelectorAll('h3, h4');
|
||||
headings.forEach(heading => heading.classList.add('success-text'));
|
||||
elements.lessonContainer.classList.add("success-highlight");
|
||||
elements.lessonTitle.classList.add("success-text");
|
||||
const headings = elements.lessonContainer.querySelectorAll("h3, h4");
|
||||
headings.forEach((heading) => heading.classList.add("success-text"));
|
||||
|
||||
// Apply the code to see the result
|
||||
lessonEngine.applyUserCode(userCode);
|
||||
@@ -278,30 +273,30 @@ function runCode() {
|
||||
// Enable the next button if not already on the last lesson
|
||||
if (state.currentLessonIndex < state.currentModule.lessons.length - 1) {
|
||||
elements.nextBtn.disabled = false;
|
||||
elements.nextBtn.classList.remove('btn-disabled');
|
||||
elements.nextBtn.classList.remove("btn-disabled");
|
||||
}
|
||||
} else {
|
||||
// Reset any success indicators
|
||||
resetSuccessIndicators();
|
||||
|
||||
// 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
|
||||
function showModuleSelector() {
|
||||
elements.modalTitle.textContent = 'Select a Module';
|
||||
elements.modalTitle.textContent = "Select a Module";
|
||||
|
||||
// Create module buttons
|
||||
const moduleButtons = state.modules.map(module => {
|
||||
const button = document.createElement('button');
|
||||
button.classList.add('btn', 'module-button');
|
||||
button.style.display = 'block';
|
||||
button.style.width = '100%';
|
||||
button.style.marginBottom = '10px';
|
||||
button.style.padding = '15px';
|
||||
button.style.textAlign = 'left';
|
||||
const moduleButtons = state.modules.map((module) => {
|
||||
const button = document.createElement("button");
|
||||
button.classList.add("btn", "module-button");
|
||||
button.style.display = "block";
|
||||
button.style.width = "100%";
|
||||
button.style.marginBottom = "10px";
|
||||
button.style.padding = "15px";
|
||||
button.style.textAlign = "left";
|
||||
|
||||
// Add completion status
|
||||
const progress = state.userProgress[module.id];
|
||||
@@ -322,7 +317,7 @@ function showModuleSelector() {
|
||||
</div>
|
||||
`;
|
||||
|
||||
button.addEventListener('click', () => {
|
||||
button.addEventListener("click", () => {
|
||||
selectModule(module.id);
|
||||
closeModal();
|
||||
});
|
||||
@@ -331,18 +326,18 @@ function showModuleSelector() {
|
||||
});
|
||||
|
||||
// Clear and update modal content
|
||||
elements.modalContent.innerHTML = '';
|
||||
moduleButtons.forEach(button => {
|
||||
elements.modalContent.innerHTML = "";
|
||||
moduleButtons.forEach((button) => {
|
||||
elements.modalContent.appendChild(button);
|
||||
});
|
||||
|
||||
// Show the modal
|
||||
elements.modalContainer.classList.remove('hidden');
|
||||
elements.modalContainer.classList.remove("hidden");
|
||||
}
|
||||
|
||||
// Show help modal
|
||||
function showHelp() {
|
||||
elements.modalTitle.textContent = 'Help';
|
||||
elements.modalTitle.textContent = "Help";
|
||||
|
||||
elements.modalContent.innerHTML = `
|
||||
<h3>How to Use Code Crispies</h3>
|
||||
@@ -378,12 +373,12 @@ function showHelp() {
|
||||
</ul>
|
||||
`;
|
||||
|
||||
elements.modalContainer.classList.remove('hidden');
|
||||
elements.modalContainer.classList.remove("hidden");
|
||||
}
|
||||
|
||||
// Reset user progress
|
||||
function resetProgress() {
|
||||
elements.modalTitle.textContent = 'Reset Progress';
|
||||
elements.modalTitle.textContent = "Reset Progress";
|
||||
|
||||
elements.modalContent.innerHTML = `
|
||||
<p>Are you sure you want to reset all your progress? This cannot be undone.</p>
|
||||
@@ -393,10 +388,10 @@ function resetProgress() {
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.getElementById('cancel-reset').addEventListener('click', closeModal);
|
||||
document.getElementById('confirm-reset').addEventListener('click', () => {
|
||||
localStorage.removeItem('codeCrispiesProgress');
|
||||
localStorage.removeItem('lastModuleId');
|
||||
document.getElementById("cancel-reset").addEventListener("click", closeModal);
|
||||
document.getElementById("confirm-reset").addEventListener("click", () => {
|
||||
localStorage.removeItem("codeCrispiesProgress");
|
||||
localStorage.removeItem("lastModuleId");
|
||||
state.userProgress = {};
|
||||
closeModal();
|
||||
|
||||
@@ -412,12 +407,12 @@ function resetProgress() {
|
||||
updateModuleSelectorButtonProgress();
|
||||
});
|
||||
|
||||
elements.modalContainer.classList.remove('hidden');
|
||||
elements.modalContainer.classList.remove("hidden");
|
||||
}
|
||||
|
||||
// Close the modal
|
||||
function closeModal() {
|
||||
elements.modalContainer.classList.add('hidden');
|
||||
elements.modalContainer.classList.add("hidden");
|
||||
}
|
||||
|
||||
// Handle clicks in the code editor to focus the input
|
||||
@@ -425,24 +420,24 @@ function handleEditorClick() {
|
||||
elements.codeInput.focus();
|
||||
|
||||
// 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
|
||||
setTimeout(() => {
|
||||
elements.editorContent.classList.remove('editor-focused');
|
||||
elements.editorContent.classList.remove("editor-focused");
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// Handle tab key in the code editor
|
||||
function handleTabKey(e) {
|
||||
if (e.key === 'Tab') {
|
||||
if (e.key === "Tab") {
|
||||
e.preventDefault();
|
||||
|
||||
const start = e.target.selectionStart;
|
||||
const end = e.target.selectionEnd;
|
||||
|
||||
// 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
|
||||
e.target.selectionStart = e.target.selectionEnd = start + 2;
|
||||
@@ -455,27 +450,27 @@ function init() {
|
||||
initializeModules();
|
||||
|
||||
// Event listeners
|
||||
elements.prevBtn.addEventListener('click', prevLesson);
|
||||
elements.nextBtn.addEventListener('click', nextLesson);
|
||||
elements.runBtn.addEventListener('click', runCode);
|
||||
elements.modalClose.addEventListener('click', closeModal);
|
||||
elements.moduleSelectorBtn.addEventListener('click', showModuleSelector);
|
||||
elements.resetBtn.addEventListener('click', resetProgress);
|
||||
elements.helpBtn.addEventListener('click', showHelp);
|
||||
elements.codeInput.addEventListener('click', handleEditorClick);
|
||||
elements.prevBtn.addEventListener("click", prevLesson);
|
||||
elements.nextBtn.addEventListener("click", nextLesson);
|
||||
elements.runBtn.addEventListener("click", runCode);
|
||||
elements.modalClose.addEventListener("click", closeModal);
|
||||
elements.moduleSelectorBtn.addEventListener("click", showModuleSelector);
|
||||
elements.resetBtn.addEventListener("click", resetProgress);
|
||||
elements.helpBtn.addEventListener("click", showHelp);
|
||||
elements.codeInput.addEventListener("click", handleEditorClick);
|
||||
|
||||
// Also make the editor container clickable to focus the text area
|
||||
elements.editorContent.addEventListener('click', (e) => {
|
||||
elements.editorContent.addEventListener("click", (e) => {
|
||||
elements.codeInput.focus();
|
||||
});
|
||||
|
||||
// Add tab key handler for the code input
|
||||
elements.codeInput.addEventListener('keydown', handleTabKey);
|
||||
elements.codeInput.addEventListener("keydown", handleTabKey);
|
||||
|
||||
// Handle keyboard shortcuts
|
||||
document.addEventListener('keydown', (e) => {
|
||||
document.addEventListener("keydown", (e) => {
|
||||
// Ctrl+Enter to run code
|
||||
if (e.ctrlKey && e.key === 'Enter') {
|
||||
if (e.ctrlKey && e.key === "Enter") {
|
||||
runCode();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
@@ -3,18 +3,13 @@
|
||||
*/
|
||||
|
||||
// Import lesson configs
|
||||
import flexboxConfig from '../../lessons/flexbox.json';
|
||||
import gridConfig from '../../lessons/grid.json';
|
||||
import basicsConfig from '../../lessons/basics.json';
|
||||
import tailwindConfig from '../../lessons/tailwindcss.json';
|
||||
import flexboxConfig from "../../lessons/flexbox.json";
|
||||
import gridConfig from "../../lessons/grid.json";
|
||||
import basicsConfig from "../../lessons/basics.json";
|
||||
import tailwindConfig from "../../lessons/tailwindcss.json";
|
||||
|
||||
// Module store
|
||||
const moduleStore = [
|
||||
basicsConfig,
|
||||
flexboxConfig,
|
||||
gridConfig,
|
||||
tailwindConfig
|
||||
];
|
||||
const moduleStore = [basicsConfig, flexboxConfig, gridConfig, tailwindConfig];
|
||||
|
||||
/**
|
||||
* Load all available modules
|
||||
@@ -31,7 +26,7 @@ export async function loadModules() {
|
||||
* @returns {Object|null} The module object or null if not found
|
||||
*/
|
||||
export function getModuleById(moduleId) {
|
||||
return moduleStore.find(module => module.id === moduleId) || null;
|
||||
return moduleStore.find((module) => module.id === moduleId) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -51,7 +46,7 @@ export async function loadModuleFromUrl(url) {
|
||||
|
||||
return moduleConfig;
|
||||
} catch (error) {
|
||||
console.error('Error loading module from URL:', error);
|
||||
console.error("Error loading module from URL:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -84,7 +79,7 @@ export function addCustomModule(moduleConfig) {
|
||||
validateModuleConfig(moduleConfig);
|
||||
|
||||
// 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) {
|
||||
// Replace existing module
|
||||
moduleStore[existingIndex] = moduleConfig;
|
||||
@@ -95,7 +90,7 @@ export function addCustomModule(moduleConfig) {
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error adding custom module:', error);
|
||||
console.error("Error adding custom module:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -13,16 +13,16 @@ let feedbackElement = null;
|
||||
*/
|
||||
export function renderModuleList(container, modules, onSelectModule) {
|
||||
// Clear the container
|
||||
container.innerHTML = '<h3>Modules</h3>';
|
||||
container.innerHTML = "<h3>Modules</h3>";
|
||||
|
||||
// Create list items for each module
|
||||
modules.forEach(module => {
|
||||
const moduleItem = document.createElement('div');
|
||||
moduleItem.classList.add('module-list-item');
|
||||
modules.forEach((module) => {
|
||||
const moduleItem = document.createElement("div");
|
||||
moduleItem.classList.add("module-list-item");
|
||||
moduleItem.dataset.moduleId = module.id;
|
||||
moduleItem.textContent = module.title;
|
||||
|
||||
moduleItem.addEventListener('click', () => {
|
||||
moduleItem.addEventListener("click", () => {
|
||||
onSelectModule(module.id);
|
||||
});
|
||||
|
||||
@@ -41,27 +41,18 @@ export function renderModuleList(container, modules, onSelectModule) {
|
||||
* @param {HTMLElement} suffixEl - The code editor suffix element
|
||||
* @param {Object} lesson - The lesson object
|
||||
*/
|
||||
export function renderLesson(
|
||||
titleEl,
|
||||
descriptionEl,
|
||||
taskEl,
|
||||
previewEl,
|
||||
prefixEl,
|
||||
inputEl,
|
||||
suffixEl,
|
||||
lesson
|
||||
) {
|
||||
export function renderLesson(titleEl, descriptionEl, taskEl, previewEl, prefixEl, inputEl, suffixEl, lesson) {
|
||||
// Set lesson title and description
|
||||
titleEl.textContent = lesson.title || 'Untitled Lesson';
|
||||
descriptionEl.innerHTML = lesson.description || '';
|
||||
titleEl.textContent = lesson.title || "Untitled Lesson";
|
||||
descriptionEl.innerHTML = lesson.description || "";
|
||||
|
||||
// Set task instructions
|
||||
taskEl.innerHTML = lesson.task || '';
|
||||
taskEl.innerHTML = lesson.task || "";
|
||||
|
||||
// Set code editor contents
|
||||
prefixEl.textContent = lesson.codePrefix || '';
|
||||
inputEl.value = lesson.initialCode || '';
|
||||
suffixEl.textContent = lesson.codeSuffix || '';
|
||||
prefixEl.textContent = lesson.codePrefix || "";
|
||||
inputEl.value = lesson.initialCode || "";
|
||||
suffixEl.textContent = lesson.codeSuffix || "";
|
||||
|
||||
// Clear any existing feedback
|
||||
clearFeedback();
|
||||
@@ -90,12 +81,12 @@ export function showFeedback(isSuccess, message) {
|
||||
clearFeedback();
|
||||
|
||||
// Create feedback element
|
||||
feedbackElement = document.createElement('div');
|
||||
feedbackElement.classList.add(isSuccess ? 'feedback-success' : 'feedback-error');
|
||||
feedbackElement = document.createElement("div");
|
||||
feedbackElement.classList.add(isSuccess ? "feedback-success" : "feedback-error");
|
||||
feedbackElement.textContent = message;
|
||||
|
||||
// Find where to insert the feedback
|
||||
const insertAfter = document.querySelector('.code-editor');
|
||||
const insertAfter = document.querySelector(".code-editor");
|
||||
if (insertAfter && insertAfter.parentNode) {
|
||||
insertAfter.parentNode.insertBefore(feedbackElement, insertAfter.nextSibling);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
export function validateUserCode(userCode, lesson) {
|
||||
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
|
||||
@@ -19,7 +19,7 @@ export function validateUserCode(userCode, lesson) {
|
||||
// Default validation result
|
||||
let result = {
|
||||
isValid: true,
|
||||
message: 'Your code looks good!'
|
||||
message: "Your code looks good!"
|
||||
};
|
||||
|
||||
// Process each validation rule
|
||||
@@ -27,42 +27,42 @@ export function validateUserCode(userCode, lesson) {
|
||||
const { type, value, message, options } = validation;
|
||||
|
||||
switch (type) {
|
||||
case 'contains':
|
||||
case "contains":
|
||||
if (!containsValidation(userCode, value, options)) {
|
||||
return { isValid: false, message: message || `Your code should include "${value}".` };
|
||||
}
|
||||
break;
|
||||
|
||||
case 'not_contains':
|
||||
case "not_contains":
|
||||
if (containsValidation(userCode, value, options)) {
|
||||
return { isValid: false, message: message || `Your code should not include "${value}".` };
|
||||
}
|
||||
break;
|
||||
|
||||
case 'regex':
|
||||
case "regex":
|
||||
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;
|
||||
|
||||
case 'property_value':
|
||||
case "property_value":
|
||||
if (!propertyValueValidation(userCode, value, options)) {
|
||||
return { isValid: false, message: message || `The "${value.property}" property should be set to "${value.expected}".` };
|
||||
}
|
||||
break;
|
||||
|
||||
case 'syntax':
|
||||
case "syntax":
|
||||
const syntaxResult = syntaxValidation(userCode);
|
||||
if (!syntaxResult.isValid) {
|
||||
return { isValid: false, message: message || `CSS syntax error: ${syntaxResult.error}` };
|
||||
}
|
||||
break;
|
||||
|
||||
case 'custom':
|
||||
if (validation.validator && typeof validation.validator === 'function') {
|
||||
case "custom":
|
||||
if (validation.validator && typeof validation.validator === "function") {
|
||||
const customResult = validation.validator(userCode);
|
||||
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;
|
||||
@@ -94,7 +94,7 @@ function containsValidation(code, value, options = {}) {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -111,15 +111,15 @@ function containsValidation(code, value, options = {}) {
|
||||
function regexValidation(code, pattern, options = {}) {
|
||||
const { caseSensitive = true, multiline = true } = options;
|
||||
|
||||
let flags = '';
|
||||
if (!caseSensitive) flags += 'i';
|
||||
if (multiline) flags += 'm';
|
||||
let flags = "";
|
||||
if (!caseSensitive) flags += "i";
|
||||
if (multiline) flags += "m";
|
||||
|
||||
try {
|
||||
const regex = new RegExp(pattern, flags);
|
||||
return regex.test(code);
|
||||
} catch (e) {
|
||||
console.error('Invalid regex in validation:', e);
|
||||
console.error("Invalid regex in validation:", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ function propertyValueValidation(code, value, options = {}) {
|
||||
|
||||
// Create a regex to extract the property value
|
||||
// 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);
|
||||
|
||||
if (!match) {
|
||||
@@ -163,7 +163,7 @@ function propertyValueValidation(code, value, options = {}) {
|
||||
function syntaxValidation(code) {
|
||||
try {
|
||||
// Create a hidden style element to test the CSS
|
||||
const style = document.createElement('style');
|
||||
const style = document.createElement("style");
|
||||
style.textContent = code;
|
||||
document.head.appendChild(style);
|
||||
document.head.removeChild(style);
|
||||
@@ -179,5 +179,5 @@ function syntaxValidation(code) {
|
||||
* @returns {string} Escaped string
|
||||
*/
|
||||
function escapeRegExp(string) {
|
||||
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
@@ -2,13 +2,13 @@
|
||||
* LessonEngine - Core class for managing lessons and applying/testing user code
|
||||
* This file is the implementation of the LessonEngine class declaration from app.helpers
|
||||
*/
|
||||
import { validateUserCode } from '../helpers/validator.js';
|
||||
import { showFeedback } from '../helpers/renderer.js';
|
||||
import { validateUserCode } from "../helpers/validator.js";
|
||||
import { showFeedback } from "../helpers/renderer.js";
|
||||
|
||||
export class LessonEngine {
|
||||
constructor() {
|
||||
this.currentLesson = null;
|
||||
this.userCode = '';
|
||||
this.userCode = "";
|
||||
this.currentModule = null;
|
||||
this.currentLessonIndex = 0;
|
||||
}
|
||||
@@ -31,7 +31,7 @@ export class LessonEngine {
|
||||
*/
|
||||
setLesson(lesson) {
|
||||
this.currentLesson = lesson;
|
||||
this.userCode = lesson.initialCode || '';
|
||||
this.userCode = lesson.initialCode || "";
|
||||
this.renderPreview();
|
||||
}
|
||||
|
||||
@@ -90,29 +90,29 @@ export class LessonEngine {
|
||||
const { previewHTML, previewBaseCSS, previewContainer, sandboxCSS } = this.currentLesson;
|
||||
|
||||
// Create an iframe for isolated preview rendering
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.style.width = '100%';
|
||||
iframe.style.height = '100%';
|
||||
iframe.style.border = 'none';
|
||||
iframe.title = 'Preview';
|
||||
const iframe = document.createElement("iframe");
|
||||
iframe.style.width = "100%";
|
||||
iframe.style.height = "100%";
|
||||
iframe.style.border = "none";
|
||||
iframe.title = "Preview";
|
||||
|
||||
// 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
|
||||
container.innerHTML = '';
|
||||
container.innerHTML = "";
|
||||
container.appendChild(iframe);
|
||||
|
||||
// Create the complete CSS by combining base CSS with user code and sandbox CSS
|
||||
const combinedCSS = `
|
||||
/* Base CSS */
|
||||
${previewBaseCSS || ''}
|
||||
${previewBaseCSS || ""}
|
||||
|
||||
/* User Code */
|
||||
${this.userCode || ''}
|
||||
${this.userCode || ""}
|
||||
|
||||
/* Sandbox CSS (for visualizing the exercise) */
|
||||
${sandboxCSS || ''}
|
||||
${sandboxCSS || ""}
|
||||
`;
|
||||
|
||||
// Write the content to the iframe
|
||||
@@ -125,7 +125,7 @@ export class LessonEngine {
|
||||
<style>${combinedCSS}</style>
|
||||
</head>
|
||||
<body>
|
||||
${previewHTML || '<div>No preview available</div>'}
|
||||
${previewHTML || "<div>No preview available</div>"}
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
@@ -138,7 +138,7 @@ export class LessonEngine {
|
||||
*/
|
||||
validateCode() {
|
||||
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);
|
||||
@@ -176,7 +176,7 @@ export class LessonEngine {
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
|
||||
localStorage.setItem('cssQuest_progress', JSON.stringify(progressData));
|
||||
localStorage.setItem("cssQuest_progress", JSON.stringify(progressData));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -185,14 +185,14 @@ export class LessonEngine {
|
||||
* @returns {Object|null} Loaded progress data or null if not found
|
||||
*/
|
||||
loadProgress(modules) {
|
||||
const savedProgress = localStorage.getItem('cssQuest_progress');
|
||||
const savedProgress = localStorage.getItem("cssQuest_progress");
|
||||
if (!savedProgress) return null;
|
||||
|
||||
try {
|
||||
const progressData = JSON.parse(savedProgress);
|
||||
|
||||
// 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;
|
||||
|
||||
this.setModule(module);
|
||||
@@ -206,7 +206,7 @@ export class LessonEngine {
|
||||
|
||||
return progressData;
|
||||
} catch (e) {
|
||||
console.error('Error loading progress:', e);
|
||||
console.error("Error loading progress:", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -216,7 +216,7 @@ export class LessonEngine {
|
||||
*/
|
||||
reset() {
|
||||
if (this.currentLesson) {
|
||||
this.userCode = this.currentLesson.initialCode || '';
|
||||
this.userCode = this.currentLesson.initialCode || "";
|
||||
this.renderPreview();
|
||||
}
|
||||
}
|
||||
@@ -225,6 +225,6 @@ export class LessonEngine {
|
||||
* Clear all saved progress
|
||||
*/
|
||||
clearProgress() {
|
||||
localStorage.removeItem('cssQuest_progress');
|
||||
localStorage.removeItem("cssQuest_progress");
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="./public/favicon.ico" type="image/x-icon">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="./public/favicon.ico" type="image/x-icon" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CODE CRISPIES - Learn CSS Interactively</title>
|
||||
<link rel="stylesheet" href="main.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-container">
|
||||
<link rel="stylesheet" href="main.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-container">
|
||||
<header class="header">
|
||||
<div class="logo">
|
||||
<h1>🏵️ CODE CRISPIES</h1>
|
||||
@@ -35,9 +35,7 @@
|
||||
<div class="content-area">
|
||||
<div class="lesson-container">
|
||||
<h2 id="lesson-title">Loading...</h2>
|
||||
<div class="lesson-description" id="lesson-description">
|
||||
Please select a lesson to begin.
|
||||
</div>
|
||||
<div class="lesson-description" id="lesson-description">Please select a lesson to begin.</div>
|
||||
|
||||
<div class="challenge-container">
|
||||
<div class="preview-area" id="preview-area">
|
||||
@@ -83,8 +81,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
20
src/main.css
20
src/main.css
@@ -10,7 +10,7 @@
|
||||
--border-color: #e0e0e0;
|
||||
--success-color: #2ecc71;
|
||||
--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);
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ body {
|
||||
color: #d4d4d4;
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
cursor: text; /* Add text cursor to indicate it's editable */
|
||||
@@ -211,13 +211,19 @@ body {
|
||||
|
||||
/* Pulse animation */
|
||||
@keyframes focus-pulse {
|
||||
0% { background-color: #1e1e1e; }
|
||||
50% { background-color: #303030; }
|
||||
100% { background-color: #1e1e1e; }
|
||||
0% {
|
||||
background-color: #1e1e1e;
|
||||
}
|
||||
50% {
|
||||
background-color: #303030;
|
||||
}
|
||||
100% {
|
||||
background-color: #1e1e1e;
|
||||
}
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||
}
|
||||
|
||||
.code-input {
|
||||
@@ -226,7 +232,7 @@ code {
|
||||
border: none;
|
||||
width: 100%;
|
||||
min-height: 100px;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', monospace;
|
||||
font-family: "JetBrains Mono", "Fira Code", monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
padding: 0.5rem 0;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach } from 'vitest';
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { afterEach } from "vitest";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
// import 'whatwg-fetch';
|
||||
|
||||
// Setup mock for localStorage
|
||||
@@ -19,7 +19,9 @@ const localStorageMock = (() => {
|
||||
store = {};
|
||||
},
|
||||
length: 0,
|
||||
key() { return null; }
|
||||
key() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -84,9 +86,9 @@ if (!window.document.createRange) {
|
||||
setStart: () => {},
|
||||
setEnd: () => {},
|
||||
commonAncestorContainer: {
|
||||
nodeName: 'BODY',
|
||||
ownerDocument: document,
|
||||
},
|
||||
nodeName: "BODY",
|
||||
ownerDocument: document
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,62 +1,60 @@
|
||||
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||
import { loadModules, getModuleById, loadModuleFromUrl, addCustomModule } from '../../src/config/lessons.js';
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
import { loadModules, getModuleById, loadModuleFromUrl, addCustomModule } from "../../src/config/lessons.js";
|
||||
|
||||
// Mock the module store for testing
|
||||
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/basics.json', () => ({ default: { id: 'basics', title: 'CSS Basics', lessons: [] }}));
|
||||
vi.mock('../../lessons/tailwindcss.json', () => ({ default: { id: 'tailwind', title: 'Tailwind CSS', 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/basics.json", () => ({ default: { id: "basics", title: "CSS Basics", lessons: [] } }));
|
||||
vi.mock("../../lessons/tailwindcss.json", () => ({ default: { id: "tailwind", title: "Tailwind CSS", lessons: [] } }));
|
||||
|
||||
describe('Lessons Config Module', () => {
|
||||
describe('loadModules', () => {
|
||||
test('should return an array of modules', async () => {
|
||||
describe("Lessons Config Module", () => {
|
||||
describe("loadModules", () => {
|
||||
test("should return an array of modules", async () => {
|
||||
const modules = await loadModules();
|
||||
|
||||
expect(Array.isArray(modules)).toBe(true);
|
||||
expect(modules.length).toBe(4);
|
||||
|
||||
// Check if modules have the right structure
|
||||
const moduleIds = modules.map(m => m.id);
|
||||
expect(moduleIds).toContain('basics');
|
||||
expect(moduleIds).toContain('flexbox');
|
||||
expect(moduleIds).toContain('grid');
|
||||
expect(moduleIds).toContain('tailwind');
|
||||
const moduleIds = modules.map((m) => m.id);
|
||||
expect(moduleIds).toContain("basics");
|
||||
expect(moduleIds).toContain("flexbox");
|
||||
expect(moduleIds).toContain("grid");
|
||||
expect(moduleIds).toContain("tailwind");
|
||||
});
|
||||
});
|
||||
|
||||
describe('getModuleById', () => {
|
||||
test('should return a module by ID', async () => {
|
||||
describe("getModuleById", () => {
|
||||
test("should return a module by ID", async () => {
|
||||
// Load modules first to populate the module store
|
||||
await loadModules();
|
||||
|
||||
const flexboxModule = getModuleById('flexbox');
|
||||
const flexboxModule = getModuleById("flexbox");
|
||||
expect(flexboxModule).not.toBeNull();
|
||||
expect(flexboxModule.id).toBe('flexbox');
|
||||
expect(flexboxModule.title).toBe('Flexbox');
|
||||
expect(flexboxModule.id).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
|
||||
await loadModules();
|
||||
|
||||
const nonExistentModule = getModuleById('non-existent');
|
||||
const nonExistentModule = getModuleById("non-existent");
|
||||
expect(nonExistentModule).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadModuleFromUrl', () => {
|
||||
describe("loadModuleFromUrl", () => {
|
||||
beforeEach(() => {
|
||||
// Reset fetch mock
|
||||
fetch.mockReset();
|
||||
});
|
||||
|
||||
test('should load a module from a URL', async () => {
|
||||
test("should load a module from a URL", async () => {
|
||||
const mockModule = {
|
||||
id: 'remote-module',
|
||||
title: 'Remote Module',
|
||||
lessons: [
|
||||
{ title: 'Lesson 1', previewHTML: '<div>Preview</div>' }
|
||||
]
|
||||
id: "remote-module",
|
||||
title: "Remote Module",
|
||||
lessons: [{ title: "Lesson 1", previewHTML: "<div>Preview</div>" }]
|
||||
};
|
||||
|
||||
// Mock the fetch response
|
||||
@@ -65,29 +63,27 @@ describe('Lessons Config Module', () => {
|
||||
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);
|
||||
});
|
||||
|
||||
test('should throw an error for failed fetch', async () => {
|
||||
test("should throw an error for failed fetch", async () => {
|
||||
fetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 404,
|
||||
statusText: 'Not Found'
|
||||
statusText: "Not Found"
|
||||
});
|
||||
|
||||
await expect(loadModuleFromUrl('https://example.com/not-found.json'))
|
||||
.rejects
|
||||
.toThrow('Failed to load module: 404 Not Found');
|
||||
await expect(loadModuleFromUrl("https://example.com/not-found.json")).rejects.toThrow("Failed to load module: 404 Not Found");
|
||||
});
|
||||
|
||||
test('should validate module structure', async () => {
|
||||
test("should validate module structure", async () => {
|
||||
// Missing required fields
|
||||
const invalidModule = {
|
||||
// Missing id
|
||||
title: 'Invalid Module'
|
||||
title: "Invalid Module"
|
||||
// Missing lessons array
|
||||
};
|
||||
|
||||
@@ -96,17 +92,13 @@ describe('Lessons Config Module', () => {
|
||||
json: async () => invalidModule
|
||||
});
|
||||
|
||||
await expect(loadModuleFromUrl('https://example.com/invalid.json'))
|
||||
.rejects
|
||||
.toThrow('Module config missing "id"');
|
||||
await expect(loadModuleFromUrl("https://example.com/invalid.json")).rejects.toThrow('Module config missing "id"');
|
||||
|
||||
// Invalid lessons structure
|
||||
const moduleWithInvalidLessons = {
|
||||
id: 'invalid-lessons',
|
||||
title: 'Invalid Lessons',
|
||||
lessons: [
|
||||
{ /* Missing title */ previewHTML: '<div>Preview</div>' }
|
||||
]
|
||||
id: "invalid-lessons",
|
||||
title: "Invalid Lessons",
|
||||
lessons: [{ /* Missing title */ previewHTML: "<div>Preview</div>" }]
|
||||
};
|
||||
|
||||
fetch.mockResolvedValueOnce({
|
||||
@@ -114,24 +106,20 @@ describe('Lessons Config Module', () => {
|
||||
json: async () => moduleWithInvalidLessons
|
||||
});
|
||||
|
||||
await expect(loadModuleFromUrl('https://example.com/invalid-lessons.json'))
|
||||
.rejects
|
||||
.toThrow('Lesson 0 missing "title"');
|
||||
await expect(loadModuleFromUrl("https://example.com/invalid-lessons.json")).rejects.toThrow('Lesson 0 missing "title"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('addCustomModule', () => {
|
||||
test('should add a new module to the store', async () => {
|
||||
describe("addCustomModule", () => {
|
||||
test("should add a new module to the store", async () => {
|
||||
// Load modules first to get current count
|
||||
const initialModules = await loadModules();
|
||||
const initialCount = initialModules.length;
|
||||
|
||||
const customModule = {
|
||||
id: 'custom-module',
|
||||
title: 'Custom Module',
|
||||
lessons: [
|
||||
{ title: 'Custom Lesson', previewHTML: '<div>Preview</div>' }
|
||||
]
|
||||
id: "custom-module",
|
||||
title: "Custom Module",
|
||||
lessons: [{ title: "Custom Lesson", previewHTML: "<div>Preview</div>" }]
|
||||
};
|
||||
|
||||
const result = addCustomModule(customModule);
|
||||
@@ -141,40 +129,40 @@ describe('Lessons Config Module', () => {
|
||||
const updatedModules = await loadModules();
|
||||
expect(updatedModules.length).toBe(initialCount + 1);
|
||||
|
||||
const addedModule = getModuleById('custom-module');
|
||||
const addedModule = getModuleById("custom-module");
|
||||
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
|
||||
const customModule = {
|
||||
id: 'replace-test',
|
||||
title: 'Original Module',
|
||||
lessons: [{ title: 'Original Lesson', previewHTML: '<div>Preview</div>' }]
|
||||
id: "replace-test",
|
||||
title: "Original Module",
|
||||
lessons: [{ title: "Original Lesson", previewHTML: "<div>Preview</div>" }]
|
||||
};
|
||||
|
||||
addCustomModule(customModule);
|
||||
|
||||
// Now replace it
|
||||
const replacementModule = {
|
||||
id: 'replace-test',
|
||||
title: 'Replacement Module',
|
||||
lessons: [{ title: 'New Lesson', previewHTML: '<div>New Preview</div>' }]
|
||||
id: "replace-test",
|
||||
title: "Replacement Module",
|
||||
lessons: [{ title: "New Lesson", previewHTML: "<div>New Preview</div>" }]
|
||||
};
|
||||
|
||||
const result = addCustomModule(replacementModule);
|
||||
expect(result).toBe(true);
|
||||
|
||||
// Check if module was replaced
|
||||
const updatedModule = getModuleById('replace-test');
|
||||
expect(updatedModule.title).toBe('Replacement Module');
|
||||
const updatedModule = getModuleById("replace-test");
|
||||
expect(updatedModule.title).toBe("Replacement Module");
|
||||
});
|
||||
|
||||
test('should validate module before adding', () => {
|
||||
test("should validate module before adding", () => {
|
||||
const invalidModule = {
|
||||
// Missing required fields
|
||||
title: 'Invalid Module'
|
||||
title: "Invalid Module"
|
||||
};
|
||||
|
||||
const result = addCustomModule(invalidModule);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderModuleList, renderLesson, renderLevelIndicator, showFeedback, clearFeedback } from '../../src/helpers/renderer.js';
|
||||
import { describe, test, expect, vi, beforeEach } from "vitest";
|
||||
import { renderModuleList, renderLesson, renderLevelIndicator, showFeedback, clearFeedback } from "../../src/helpers/renderer.js";
|
||||
|
||||
describe('Renderer Module', () => {
|
||||
describe("Renderer Module", () => {
|
||||
beforeEach(() => {
|
||||
// Reset the DOM between tests
|
||||
document.body.innerHTML = `
|
||||
@@ -18,158 +18,140 @@ describe('Renderer Module', () => {
|
||||
`;
|
||||
});
|
||||
|
||||
describe('renderModuleList', () => {
|
||||
test('should render a list of modules', () => {
|
||||
const container = document.getElementById('module-list');
|
||||
describe("renderModuleList", () => {
|
||||
test("should render a list of modules", () => {
|
||||
const container = document.getElementById("module-list");
|
||||
const modules = [
|
||||
{ id: 'mod1', title: 'Module 1' },
|
||||
{ id: 'mod2', title: 'Module 2' }
|
||||
{ id: "mod1", title: "Module 1" },
|
||||
{ id: "mod2", title: "Module 2" }
|
||||
];
|
||||
const onSelectModule = vi.fn();
|
||||
|
||||
renderModuleList(container, modules, onSelectModule);
|
||||
|
||||
// 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
|
||||
const moduleItems = container.querySelectorAll('.module-list-item');
|
||||
const moduleItems = container.querySelectorAll(".module-list-item");
|
||||
expect(moduleItems.length).toBe(2);
|
||||
expect(moduleItems[0].textContent).toBe('Module 1');
|
||||
expect(moduleItems[1].textContent).toBe('Module 2');
|
||||
expect(moduleItems[0].textContent).toBe("Module 1");
|
||||
expect(moduleItems[1].textContent).toBe("Module 2");
|
||||
|
||||
// Test click event
|
||||
moduleItems[0].click();
|
||||
expect(onSelectModule).toHaveBeenCalledWith('mod1');
|
||||
expect(onSelectModule).toHaveBeenCalledWith("mod1");
|
||||
});
|
||||
|
||||
test('should handle empty module list', () => {
|
||||
const container = document.getElementById('module-list');
|
||||
test("should handle empty module list", () => {
|
||||
const container = document.getElementById("module-list");
|
||||
renderModuleList(container, [], vi.fn());
|
||||
|
||||
expect(container.innerHTML).toContain('<h3>Modules</h3>');
|
||||
expect(container.querySelectorAll('.module-list-item').length).toBe(0);
|
||||
expect(container.innerHTML).toContain("<h3>Modules</h3>");
|
||||
expect(container.querySelectorAll(".module-list-item").length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderLesson', () => {
|
||||
test('should render lesson content correctly', () => {
|
||||
const titleEl = document.getElementById('title');
|
||||
const descriptionEl = document.getElementById('description');
|
||||
const taskEl = document.getElementById('task');
|
||||
const previewEl = document.getElementById('preview');
|
||||
const prefixEl = document.getElementById('prefix');
|
||||
const inputEl = document.getElementById('input');
|
||||
const suffixEl = document.getElementById('suffix');
|
||||
describe("renderLesson", () => {
|
||||
test("should render lesson content correctly", () => {
|
||||
const titleEl = document.getElementById("title");
|
||||
const descriptionEl = document.getElementById("description");
|
||||
const taskEl = document.getElementById("task");
|
||||
const previewEl = document.getElementById("preview");
|
||||
const prefixEl = document.getElementById("prefix");
|
||||
const inputEl = document.getElementById("input");
|
||||
const suffixEl = document.getElementById("suffix");
|
||||
|
||||
const lesson = {
|
||||
title: 'Test Lesson',
|
||||
description: '<p>Description text</p>',
|
||||
task: '<p>Task instructions</p>',
|
||||
codePrefix: 'body {',
|
||||
initialCode: ' color: red;',
|
||||
codeSuffix: '}'
|
||||
title: "Test Lesson",
|
||||
description: "<p>Description text</p>",
|
||||
task: "<p>Task instructions</p>",
|
||||
codePrefix: "body {",
|
||||
initialCode: " color: red;",
|
||||
codeSuffix: "}"
|
||||
};
|
||||
|
||||
renderLesson(
|
||||
titleEl,
|
||||
descriptionEl,
|
||||
taskEl,
|
||||
previewEl,
|
||||
prefixEl,
|
||||
inputEl,
|
||||
suffixEl,
|
||||
lesson
|
||||
);
|
||||
renderLesson(titleEl, descriptionEl, taskEl, previewEl, prefixEl, inputEl, suffixEl, lesson);
|
||||
|
||||
expect(titleEl.textContent).toBe('Test Lesson');
|
||||
expect(descriptionEl.innerHTML).toBe('<p>Description text</p>');
|
||||
expect(taskEl.innerHTML).toBe('<p>Task instructions</p>');
|
||||
expect(prefixEl.textContent).toBe('body {');
|
||||
expect(inputEl.value).toBe(' color: red;');
|
||||
expect(suffixEl.textContent).toBe('}');
|
||||
expect(titleEl.textContent).toBe("Test Lesson");
|
||||
expect(descriptionEl.innerHTML).toBe("<p>Description text</p>");
|
||||
expect(taskEl.innerHTML).toBe("<p>Task instructions</p>");
|
||||
expect(prefixEl.textContent).toBe("body {");
|
||||
expect(inputEl.value).toBe(" color: red;");
|
||||
expect(suffixEl.textContent).toBe("}");
|
||||
});
|
||||
|
||||
test('should handle missing lesson data with defaults', () => {
|
||||
const titleEl = document.getElementById('title');
|
||||
const descriptionEl = document.getElementById('description');
|
||||
const taskEl = document.getElementById('task');
|
||||
const prefixEl = document.getElementById('prefix');
|
||||
const inputEl = document.getElementById('input');
|
||||
const suffixEl = document.getElementById('suffix');
|
||||
test("should handle missing lesson data with defaults", () => {
|
||||
const titleEl = document.getElementById("title");
|
||||
const descriptionEl = document.getElementById("description");
|
||||
const taskEl = document.getElementById("task");
|
||||
const prefixEl = document.getElementById("prefix");
|
||||
const inputEl = document.getElementById("input");
|
||||
const suffixEl = document.getElementById("suffix");
|
||||
|
||||
// Empty lesson object
|
||||
const lesson = {};
|
||||
|
||||
renderLesson(
|
||||
titleEl,
|
||||
descriptionEl,
|
||||
taskEl,
|
||||
document.getElementById('preview'),
|
||||
prefixEl,
|
||||
inputEl,
|
||||
suffixEl,
|
||||
lesson
|
||||
);
|
||||
renderLesson(titleEl, descriptionEl, taskEl, document.getElementById("preview"), prefixEl, inputEl, suffixEl, lesson);
|
||||
|
||||
expect(titleEl.textContent).toBe('Untitled Lesson');
|
||||
expect(descriptionEl.innerHTML).toBe('');
|
||||
expect(taskEl.innerHTML).toBe('');
|
||||
expect(prefixEl.textContent).toBe('');
|
||||
expect(inputEl.value).toBe('');
|
||||
expect(suffixEl.textContent).toBe('');
|
||||
expect(titleEl.textContent).toBe("Untitled Lesson");
|
||||
expect(descriptionEl.innerHTML).toBe("");
|
||||
expect(taskEl.innerHTML).toBe("");
|
||||
expect(prefixEl.textContent).toBe("");
|
||||
expect(inputEl.value).toBe("");
|
||||
expect(suffixEl.textContent).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderLevelIndicator', () => {
|
||||
test('should update level indicator text', () => {
|
||||
const element = document.getElementById('level-indicator');
|
||||
describe("renderLevelIndicator", () => {
|
||||
test("should update level indicator text", () => {
|
||||
const element = document.getElementById("level-indicator");
|
||||
|
||||
renderLevelIndicator(element, 3, 10);
|
||||
expect(element.textContent).toBe('Lesson 3 of 10');
|
||||
expect(element.textContent).toBe("Lesson 3 of 10");
|
||||
|
||||
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', () => {
|
||||
test('should create success feedback element', () => {
|
||||
const editor = document.getElementById('code-editor');
|
||||
showFeedback(true, 'Great job!');
|
||||
describe.skip("showFeedback and clearFeedback", () => {
|
||||
test("should create success feedback element", () => {
|
||||
const editor = document.getElementById("code-editor");
|
||||
showFeedback(true, "Great job!");
|
||||
|
||||
const feedback = document.querySelector('.feedback-success');
|
||||
const feedback = document.querySelector(".feedback-success");
|
||||
expect(feedback).not.toBeNull();
|
||||
expect(feedback.textContent).toBe('Great job!');
|
||||
expect(feedback.textContent).toBe("Great job!");
|
||||
|
||||
// Test auto clearing with setTimeout
|
||||
vi.useFakeTimers();
|
||||
showFeedback(true, 'Auto clear test');
|
||||
showFeedback(true, "Auto clear test");
|
||||
vi.advanceTimersByTime(5001);
|
||||
expect(document.querySelector('.feedback-success')).toBeNull();
|
||||
expect(document.querySelector(".feedback-success")).toBeNull();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('should create error feedback element', () => {
|
||||
showFeedback(false, 'Try again');
|
||||
test("should create error feedback element", () => {
|
||||
showFeedback(false, "Try again");
|
||||
|
||||
const feedback = document.querySelector('.feedback-error');
|
||||
const feedback = document.querySelector(".feedback-error");
|
||||
expect(feedback).not.toBeNull();
|
||||
expect(feedback.textContent).toBe('Try again');
|
||||
expect(feedback.textContent).toBe("Try again");
|
||||
|
||||
// Error feedback should not auto-clear
|
||||
vi.useFakeTimers();
|
||||
vi.advanceTimersByTime(5001);
|
||||
expect(document.querySelector('.feedback-error')).not.toBeNull();
|
||||
expect(document.querySelector(".feedback-error")).not.toBeNull();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('should clear existing feedback', () => {
|
||||
showFeedback(false, 'Error message');
|
||||
expect(document.querySelector('.feedback-error')).not.toBeNull();
|
||||
test("should clear existing feedback", () => {
|
||||
showFeedback(false, "Error message");
|
||||
expect(document.querySelector(".feedback-error")).not.toBeNull();
|
||||
|
||||
clearFeedback();
|
||||
expect(document.querySelector('.feedback-error')).toBeNull();
|
||||
expect(document.querySelector(".feedback-error")).toBeNull();
|
||||
|
||||
// Should work when called multiple times
|
||||
clearFeedback();
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { validateUserCode } from '../../src/helpers/validator.js';
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { validateUserCode } from "../../src/helpers/validator.js";
|
||||
|
||||
describe('CSS Validator', () => {
|
||||
describe("CSS Validator", () => {
|
||||
// Mock document functions since we're not in a browser
|
||||
document.createElement = vi.fn().mockImplementation(() => {
|
||||
return {
|
||||
textContent: '',
|
||||
textContent: "",
|
||||
parentNode: { removeChild: vi.fn() }
|
||||
};
|
||||
});
|
||||
@@ -15,104 +15,92 @@ describe('CSS Validator', () => {
|
||||
// removeChild: vi.fn()
|
||||
// };
|
||||
|
||||
describe('validateUserCode', () => {
|
||||
it('should pass when no validations are specified', () => {
|
||||
const userCode = 'div { color: red; }';
|
||||
const lesson = { title: 'Test Lesson' };
|
||||
describe("validateUserCode", () => {
|
||||
it("should pass when no validations are specified", () => {
|
||||
const userCode = "div { color: red; }";
|
||||
const lesson = { title: "Test Lesson" };
|
||||
|
||||
const result = validateUserCode(userCode, lesson);
|
||||
|
||||
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', () => {
|
||||
const userCode = 'div { color: red; }';
|
||||
it("should pass with empty validations array", () => {
|
||||
const userCode = "div { color: red; }";
|
||||
const lesson = {
|
||||
title: 'Test Lesson',
|
||||
title: "Test Lesson",
|
||||
validations: []
|
||||
};
|
||||
|
||||
const result = validateUserCode(userCode, lesson);
|
||||
|
||||
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', () => {
|
||||
const userCode = 'div { color: red; }';
|
||||
const userCode = "div { color: red; }";
|
||||
const lesson = {
|
||||
validations: [
|
||||
{ type: 'contains', value: 'color: red', message: 'Should use red color' }
|
||||
]
|
||||
validations: [{ type: "contains", value: "color: red", message: "Should use red color" }]
|
||||
};
|
||||
|
||||
const result = validateUserCode(userCode, lesson);
|
||||
expect(result.isValid).toBe(true);
|
||||
|
||||
const failLesson = {
|
||||
validations: [
|
||||
{ type: 'contains', value: 'color: blue', message: 'Should use blue color' }
|
||||
]
|
||||
validations: [{ type: "contains", value: "color: blue", message: "Should use blue color" }]
|
||||
};
|
||||
|
||||
const failResult = validateUserCode(userCode, failLesson);
|
||||
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', () => {
|
||||
const userCode = 'div { color: red; }';
|
||||
const userCode = "div { color: red; }";
|
||||
const lesson = {
|
||||
validations: [
|
||||
{ type: 'not_contains', value: 'color: blue', message: 'Should not use blue color' }
|
||||
]
|
||||
validations: [{ type: "not_contains", value: "color: blue", message: "Should not use blue color" }]
|
||||
};
|
||||
|
||||
const result = validateUserCode(userCode, lesson);
|
||||
expect(result.isValid).toBe(true);
|
||||
|
||||
const failLesson = {
|
||||
validations: [
|
||||
{ type: 'not_contains', value: 'color: red', message: 'Should not use red color' }
|
||||
]
|
||||
validations: [{ type: "not_contains", value: "color: red", message: "Should not use red color" }]
|
||||
};
|
||||
|
||||
const failResult = validateUserCode(userCode, failLesson);
|
||||
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', () => {
|
||||
const userCode = 'div { color: #ff0000; }';
|
||||
const userCode = "div { color: #ff0000; }";
|
||||
const lesson = {
|
||||
validations: [
|
||||
{ type: 'regex', value: '#[a-f0-9]{6}', message: 'Should use hex color' }
|
||||
]
|
||||
validations: [{ type: "regex", value: "#[a-f0-9]{6}", message: "Should use hex color" }]
|
||||
};
|
||||
|
||||
const result = validateUserCode(userCode, lesson);
|
||||
expect(result.isValid).toBe(true);
|
||||
|
||||
const failLesson = {
|
||||
validations: [
|
||||
{ type: 'regex', value: 'rgb\\(\\d+,\\s*\\d+,\\s*\\d+\\)', message: 'Should use RGB color' }
|
||||
]
|
||||
validations: [{ type: "regex", value: "rgb\\(\\d+,\\s*\\d+,\\s*\\d+\\)", message: "Should use RGB color" }]
|
||||
};
|
||||
|
||||
const failResult = validateUserCode(userCode, failLesson);
|
||||
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', () => {
|
||||
const userCode = 'div { display: flex; }';
|
||||
const userCode = "div { display: flex; }";
|
||||
const lesson = {
|
||||
validations: [
|
||||
{
|
||||
type: 'property_value',
|
||||
value: { property: 'display', expected: 'flex' },
|
||||
message: 'Should use display: flex'
|
||||
type: "property_value",
|
||||
value: { property: "display", expected: "flex" },
|
||||
message: "Should use display: flex"
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -123,25 +111,25 @@ describe('CSS Validator', () => {
|
||||
const failLesson = {
|
||||
validations: [
|
||||
{
|
||||
type: 'property_value',
|
||||
value: { property: 'display', expected: 'grid' },
|
||||
message: 'Should use display: grid'
|
||||
type: "property_value",
|
||||
value: { property: "display", expected: "grid" },
|
||||
message: "Should use display: grid"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const failResult = validateUserCode(userCode, failLesson);
|
||||
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', () => {
|
||||
const userCode = 'div { display: flex; color: red; }';
|
||||
it("should handle complex validation chains", () => {
|
||||
const userCode = "div { display: flex; color: red; }";
|
||||
const lesson = {
|
||||
validations: [
|
||||
{ type: 'contains', value: 'display: flex' },
|
||||
{ type: 'contains', value: 'color: red' },
|
||||
{ type: 'not_contains', value: 'float:' }
|
||||
{ type: "contains", value: "display: flex" },
|
||||
{ type: "contains", value: "color: red" },
|
||||
{ type: "not_contains", value: "float:" }
|
||||
]
|
||||
};
|
||||
|
||||
@@ -151,30 +139,30 @@ describe('CSS Validator', () => {
|
||||
// First failing validation should cause early return
|
||||
const failLesson = {
|
||||
validations: [
|
||||
{ type: 'contains', value: 'display: flex' },
|
||||
{ type: 'contains', value: 'border: 1px solid black', message: 'Missing border' },
|
||||
{ type: 'not_contains', value: 'color: green' }
|
||||
{ type: "contains", value: "display: flex" },
|
||||
{ type: "contains", value: "border: 1px solid black", message: "Missing border" },
|
||||
{ type: "not_contains", value: "color: green" }
|
||||
]
|
||||
};
|
||||
|
||||
const failResult = validateUserCode(userCode, failLesson);
|
||||
expect(failResult.isValid).toBe(false);
|
||||
expect(failResult.message).toBe('Missing border');
|
||||
expect(failResult.message).toBe("Missing border");
|
||||
});
|
||||
|
||||
it('should validate "custom" rule correctly', () => {
|
||||
const userCode = 'div { margin: 10px; }';
|
||||
const userCode = "div { margin: 10px; }";
|
||||
const customValidator = (code) => {
|
||||
return {
|
||||
isValid: code.includes('margin'),
|
||||
message: 'Should include margin property'
|
||||
isValid: code.includes("margin"),
|
||||
message: "Should include margin property"
|
||||
};
|
||||
};
|
||||
|
||||
const lesson = {
|
||||
validations: [
|
||||
{
|
||||
type: 'custom',
|
||||
type: "custom",
|
||||
validator: customValidator
|
||||
}
|
||||
]
|
||||
@@ -185,34 +173,34 @@ describe('CSS Validator', () => {
|
||||
|
||||
const failValidator = (code) => {
|
||||
return {
|
||||
isValid: code.includes('padding'),
|
||||
message: 'Should include padding property'
|
||||
isValid: code.includes("padding"),
|
||||
message: "Should include padding property"
|
||||
};
|
||||
};
|
||||
|
||||
const failLesson = {
|
||||
validations: [
|
||||
{
|
||||
type: 'custom',
|
||||
type: "custom",
|
||||
validator: failValidator,
|
||||
message: 'Custom validation failed'
|
||||
message: "Custom validation failed"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const failResult = validateUserCode(userCode, failLesson);
|
||||
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
|
||||
const userCode = 'div { COLOR: Red; }';
|
||||
const userCode = "div { COLOR: Red; }";
|
||||
const lesson = {
|
||||
validations: [
|
||||
{
|
||||
type: 'contains',
|
||||
value: 'color: red',
|
||||
type: "contains",
|
||||
value: "color: red",
|
||||
options: { caseSensitive: false }
|
||||
}
|
||||
]
|
||||
@@ -225,14 +213,14 @@ describe('CSS Validator', () => {
|
||||
const exactLesson = {
|
||||
validations: [
|
||||
{
|
||||
type: 'property_value',
|
||||
value: { property: 'color', expected: 'red' },
|
||||
type: "property_value",
|
||||
value: { property: "color", expected: "red" },
|
||||
options: { exact: true }
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const failExactResult = validateUserCode('div { color: RED; }', exactLesson);
|
||||
const failExactResult = validateUserCode("div { color: RED; }", exactLesson);
|
||||
expect(failExactResult.isValid).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
export default defineConfig({
|
||||
root: './src',
|
||||
publicDir: './public',
|
||||
root: "./src",
|
||||
publicDir: "./public",
|
||||
build: {
|
||||
outDir: '../dist',
|
||||
outDir: "../dist",
|
||||
emptyOutDir: true,
|
||||
sourcemap: true
|
||||
},
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
// vitest.config.js
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./tests/setup.js'],
|
||||
include: ['tests/**/*.{test,spec}.js'],
|
||||
environment: "jsdom",
|
||||
setupFiles: ["./tests/setup.js"],
|
||||
include: ["tests/**/*.{test,spec}.js"],
|
||||
coverage: {
|
||||
reporter: ['text', 'json', 'html'],
|
||||
exclude: ['node_modules/', 'tests/setup.js']
|
||||
reporter: ["text", "json", "html"],
|
||||
exclude: ["node_modules/", "tests/setup.js"]
|
||||
},
|
||||
server: {
|
||||
deps: {
|
||||
|
||||
Reference in New Issue
Block a user