From 45f7e0b3c4780b241c4b894e698f3ba17a3cf9ad Mon Sep 17 00:00:00 2001 From: Veerendra Kumar Date: Mon, 31 Aug 2026 04:59:40 +0530 Subject: [PATCH] feat(web-dev): add web development practice module with sandboxed preview, behavioral test engine, admin pre-publish validator, and SEO indexing --- backend/controllers/webDevController.js | 526 +++++++ backend/models/WebDevQuestion.js | 211 +++ backend/models/WebDevSubmission.js | 132 ++ backend/package.json | 3 +- backend/routes/webDevRoutes.js | 32 + backend/scripts/seedWebDev.js | 1399 +++++++++++++++++ backend/server.js | 2 + backend/tests/test_web_development.js | 274 ++++ frontend/public/robots.txt | 32 +- frontend/public/sitemap.xml | 158 +- frontend/src/App.jsx | 21 + frontend/src/components/Navbar.jsx | 13 + .../components/webdev/WebDevPreviewFrame.jsx | 197 +++ .../components/webdev/WebDevTestResults.jsx | 214 +++ frontend/src/pages/AdminDashboard.jsx | 262 ++- frontend/src/pages/Home.jsx | 54 +- frontend/src/pages/webdev/AdminWebDevForm.jsx | 817 ++++++++++ frontend/src/pages/webdev/WebDevArena.jsx | 480 ++++++ frontend/src/pages/webdev/WebDevHub.jsx | 300 ++++ frontend/src/services/webDevService.js | 85 + frontend/src/utils/webDevEvaluator.js | 301 ++++ 21 files changed, 5453 insertions(+), 60 deletions(-) create mode 100644 backend/controllers/webDevController.js create mode 100644 backend/models/WebDevQuestion.js create mode 100644 backend/models/WebDevSubmission.js create mode 100644 backend/routes/webDevRoutes.js create mode 100644 backend/scripts/seedWebDev.js create mode 100644 backend/tests/test_web_development.js create mode 100644 frontend/src/components/webdev/WebDevPreviewFrame.jsx create mode 100644 frontend/src/components/webdev/WebDevTestResults.jsx create mode 100644 frontend/src/pages/webdev/AdminWebDevForm.jsx create mode 100644 frontend/src/pages/webdev/WebDevArena.jsx create mode 100644 frontend/src/pages/webdev/WebDevHub.jsx create mode 100644 frontend/src/services/webDevService.js create mode 100644 frontend/src/utils/webDevEvaluator.js diff --git a/backend/controllers/webDevController.js b/backend/controllers/webDevController.js new file mode 100644 index 0000000..7e9ebd9 --- /dev/null +++ b/backend/controllers/webDevController.js @@ -0,0 +1,526 @@ +import WebDevQuestion from '../models/WebDevQuestion.js'; +import WebDevSubmission from '../models/WebDevSubmission.js'; +import mongoose from 'mongoose'; + +/** + * Generate a clean URL slug from string + */ +const generateSlug = (text) => { + return text + .toString() + .toLowerCase() + .trim() + .replace(/\s+/g, '-') + .replace(/[^\w-]+/g, '') + .replace(/--+/g, '-') + .replace(/^-+/, '') + .replace(/-+$/, ''); +}; + +// ─── PUBLIC ENDPOINTS ───────────────────────────────────────────────────────── + +/** + * @desc Get all published web development questions with optional filters + * @route GET /api/web-development/questions + * @access Public + */ +export const getPublicQuestions = async (req, res) => { + try { + const { difficulty, category, search } = req.query; + + const query = { status: 'published' }; + + if (difficulty && ['easy', 'medium', 'hard'].includes(difficulty.toLowerCase())) { + query.difficulty = difficulty.toLowerCase(); + } + + if (category) { + query.category = category.toLowerCase(); + } + + if (search && search.trim()) { + const searchRegex = new RegExp(search.trim(), 'i'); + query.$or = [{ title: searchRegex }, { description: searchRegex }, { tags: searchRegex }]; + } + + // Exclude solutionCode and internal fields + const questions = await WebDevQuestion.find(query) + .select('-solutionCode -createdBy -updatedBy') + .sort({ displayOrder: 1, createdAt: -1 }) + .lean(); + + // If user is authenticated, attach attempt/solved status + let userSubmissionsMap = {}; + if (req.user) { + const userSubmissions = await WebDevSubmission.find({ + user: req.user._id, + }) + .select('question score status') + .lean(); + + userSubmissions.forEach((sub) => { + const qId = sub.question.toString(); + if (!userSubmissionsMap[qId] || sub.score > (userSubmissionsMap[qId].bestScore || 0)) { + userSubmissionsMap[qId] = { + attempted: true, + solved: sub.status === 'Passed' || sub.score === 100, + bestScore: sub.score, + }; + } + }); + } + + const enhancedQuestions = questions.map((q) => { + const userStat = userSubmissionsMap[q._id.toString()] || { + attempted: false, + solved: false, + bestScore: 0, + }; + + // Exclude hidden test details from public preview list + const sanitizedTests = (q.tests || []).map((t) => ({ + id: t.id, + description: t.description, + points: t.points, + type: t.type, + })); + + return { + ...q, + tests: sanitizedTests, + testCount: (q.tests || []).length, + userProgress: userStat, + }; + }); + + res.json({ + success: true, + count: enhancedQuestions.length, + questions: enhancedQuestions, + }); + } catch (error) { + console.error('Error fetching public web dev questions:', error); + res.status(500).json({ success: false, message: 'Server error fetching questions' }); + } +}; + +/** + * @desc Get single web dev question by ID or Slug (Strictly excludes solutionCode) + * @route GET /api/web-development/questions/:idOrSlug + * @access Public + */ +export const getPublicQuestionByIdOrSlug = async (req, res) => { + try { + const { idOrSlug } = req.params; + + let question = null; + if (mongoose.Types.ObjectId.isValid(idOrSlug)) { + question = await WebDevQuestion.findOne({ + _id: idOrSlug, + status: 'published', + }) + .select('-solutionCode') + .lean(); + } + + if (!question) { + question = await WebDevQuestion.findOne({ + slug: idOrSlug.toLowerCase(), + status: 'published', + }) + .select('-solutionCode') + .lean(); + } + + if (!question) { + return res.status(404).json({ success: false, message: 'Question not found' }); + } + + // Attach user best score & previous submission if logged in + let lastSubmission = null; + if (req.user) { + lastSubmission = await WebDevSubmission.findOne({ + user: req.user._id, + question: question._id, + }) + .sort({ createdAt: -1 }) + .lean(); + } + + res.json({ + success: true, + question, + lastSubmission, + }); + } catch (error) { + console.error('Error fetching single web dev question:', error); + res.status(500).json({ success: false, message: 'Server error fetching question details' }); + } +}; + +// ─── AUTHENTICATED STUDENT ENDPOINTS ──────────────────────────────────────── + +/** + * @desc Submit student solution for a web dev question + * @route POST /api/web-development/questions/:id/submit + * @access Private + */ +export const submitWebDevSolution = async (req, res) => { + try { + const { id } = req.params; + const { + htmlCode = '', + cssCode = '', + javascriptCode = '', + testResults = [], + timeSpent = 0, + startedAt, + } = req.body; + + const question = await WebDevQuestion.findById(id); + if (!question) { + return res.status(404).json({ success: false, message: 'Question not found' }); + } + + // Calculate score from validated test results + let pointsEarned = 0; + let totalPoints = question.points || 100; + let passedCount = 0; + const totalTests = (question.tests || []).length; + + const sanitizedResults = (question.tests || []).map((test) => { + const studentResult = (testResults || []).find((r) => r.testId === test.id); + const passed = studentResult ? Boolean(studentResult.passed) : false; + const earned = passed ? test.points || 0 : 0; + + if (passed) { + passedCount += 1; + pointsEarned += earned; + } + + return { + testId: test.id, + description: test.description, + passed, + points: test.points || 0, + earnedPoints: earned, + failureMessage: passed ? '' : test.failureMessage || 'Test failed', + }; + }); + + const score = totalPoints > 0 ? Math.round((pointsEarned / totalPoints) * 100) : 0; + const status = score === 100 ? 'Passed' : score > 0 ? 'Partial' : 'Failed'; + + // Track attempt number + const previousAttempts = await WebDevSubmission.countDocuments({ + user: req.user._id, + question: question._id, + }); + const attemptNumber = previousAttempts + 1; + + const submission = await WebDevSubmission.create({ + user: req.user._id, + question: question._id, + questionVersion: question.version || 1, + attemptNumber, + htmlCode, + cssCode, + javascriptCode, + score, + pointsEarned, + totalPoints, + passedTests: passedCount, + totalTests, + status, + testResults: sanitizedResults, + timeSpent: Number(timeSpent) || 0, + startedAt: startedAt ? new Date(startedAt) : new Date(Date.now() - (timeSpent || 0) * 1000), + submittedAt: new Date(), + }); + + res.status(201).json({ + success: true, + message: status === 'Passed' ? 'Challenge Solved! 100% Score!' : 'Submission evaluated', + submission: { + _id: submission._id, + score, + pointsEarned, + totalPoints, + passedTests: passedCount, + totalTests, + status, + attemptNumber, + testResults: sanitizedResults, + submittedAt: submission.submittedAt, + }, + }); + } catch (error) { + console.error('Error submitting web dev solution:', error); + res.status(500).json({ success: false, message: 'Server error evaluating submission' }); + } +}; + +/** + * @desc Get user submission history for a question + * @route GET /api/web-development/questions/:id/submissions + * @access Private + */ +export const getUserSubmissions = async (req, res) => { + try { + const { id } = req.params; + + const submissions = await WebDevSubmission.find({ + user: req.user._id, + question: id, + }) + .sort({ createdAt: -1 }) + .lean(); + + res.json({ + success: true, + count: submissions.length, + submissions, + }); + } catch (error) { + console.error('Error fetching user submissions:', error); + res.status(500).json({ success: false, message: 'Server error fetching submissions' }); + } +}; + +// ─── ADMIN ENDPOINTS ───────────────────────────────────────────────────────── + +/** + * @desc Get all questions for admin management (including drafts) + * @route GET /api/web-development/admin/questions + * @access Private / Admin + */ +export const getAdminQuestions = async (req, res) => { + try { + const { status, search } = req.query; + + const query = {}; + if (status && status !== 'all') { + query.status = status; + } + if (search && search.trim()) { + const searchRegex = new RegExp(search.trim(), 'i'); + query.$or = [{ title: searchRegex }, { slug: searchRegex }, { description: searchRegex }]; + } + + const questions = await WebDevQuestion.find(query) + .populate('createdBy', 'username email') + .populate('updatedBy', 'username email') + .sort({ displayOrder: 1, createdAt: -1 }) + .lean(); + + // Summary statistics + const totalCount = await WebDevQuestion.countDocuments(); + const publishedCount = await WebDevQuestion.countDocuments({ status: 'published' }); + const draftCount = await WebDevQuestion.countDocuments({ status: 'draft' }); + const archivedCount = await WebDevQuestion.countDocuments({ status: 'archived' }); + + res.json({ + success: true, + stats: { + totalCount, + publishedCount, + draftCount, + archivedCount, + }, + questions, + }); + } catch (error) { + console.error('Error fetching admin web dev questions:', error); + res.status(500).json({ success: false, message: 'Server error fetching admin questions' }); + } +}; + +/** + * @desc Get single question by ID for admin editor (includes solutionCode) + * @route GET /api/web-development/admin/questions/:id + * @access Private / Admin + */ +export const getAdminQuestionById = async (req, res) => { + try { + const { id } = req.params; + + const question = await WebDevQuestion.findById(id).lean(); + if (!question) { + return res.status(404).json({ success: false, message: 'Question not found' }); + } + + res.json({ + success: true, + question, + }); + } catch (error) { + console.error('Error fetching admin question details:', error); + res.status(500).json({ success: false, message: 'Server error fetching question details' }); + } +}; + +/** + * @desc Create new web dev question + * @route POST /api/web-development/admin/questions + * @access Private / Admin + */ +export const createAdminQuestion = async (req, res) => { + try { + const { + title, + slug, + difficulty = 'easy', + category = 'html-css-javascript', + description, + requirements = [], + starterCode = { html: '', css: '', javascript: '' }, + solutionCode = { html: '', css: '', javascript: '' }, + tests = [], + points = 100, + timeLimit = 20, + status = 'published', + tags = [], + } = req.body; + + if (!title || !title.trim()) { + return res.status(400).json({ success: false, message: 'Question title is required' }); + } + if (!description || !description.trim()) { + return res.status(400).json({ success: false, message: 'Description is required' }); + } + + const generatedSlug = slug && slug.trim() ? generateSlug(slug) : generateSlug(title); + + // Check slug uniqueness + const existing = await WebDevQuestion.findOne({ slug: generatedSlug }); + if (existing) { + return res.status(400).json({ + success: false, + message: `A question with slug "${generatedSlug}" already exists. Please choose a distinct title or slug.`, + }); + } + + // Validate tests exist + if (!tests || tests.length === 0) { + return res.status(400).json({ + success: false, + message: 'At least one evaluation test is required before saving a question.', + }); + } + + // Calculate points sum + const totalTestPoints = tests.reduce((acc, t) => acc + (Number(t.points) || 0), 0); + + const newQuestion = await WebDevQuestion.create({ + title: title.trim(), + slug: generatedSlug, + difficulty: difficulty.toLowerCase(), + category: category.toLowerCase(), + description: description.trim(), + requirements: requirements.filter(Boolean), + starterCode, + solutionCode, + tests, + points: totalTestPoints > 0 ? totalTestPoints : points, + timeLimit: Number(timeLimit) || 20, + version: 1, + status, + tags: tags.filter(Boolean), + createdBy: req.user._id, + updatedBy: req.user._id, + }); + + res.status(201).json({ + success: true, + message: 'Web development question created successfully', + question: newQuestion, + }); + } catch (error) { + console.error('Error creating web dev question:', error); + res.status(500).json({ success: false, message: error.message || 'Server error creating question' }); + } +}; + +/** + * @desc Update existing web dev question + * @route PATCH /api/web-development/admin/questions/:id + * @access Private / Admin + */ +export const updateAdminQuestion = async (req, res) => { + try { + const { id } = req.params; + const updates = req.body; + + const question = await WebDevQuestion.findById(id); + if (!question) { + return res.status(404).json({ success: false, message: 'Question not found' }); + } + + // If slug is changed, ensure uniqueness + if (updates.slug && updates.slug !== question.slug) { + const formattedSlug = generateSlug(updates.slug); + const existing = await WebDevQuestion.findOne({ slug: formattedSlug, _id: { $ne: id } }); + if (existing) { + return res.status(400).json({ + success: false, + message: `Slug "${formattedSlug}" is already in use by another question.`, + }); + } + updates.slug = formattedSlug; + } + + // Increment version if starter code or tests were modified + const isStarterChanged = + updates.starterCode && + JSON.stringify(updates.starterCode) !== JSON.stringify(question.starterCode); + const isTestsChanged = + updates.tests && JSON.stringify(updates.tests) !== JSON.stringify(question.tests); + + if (isStarterChanged || isTestsChanged) { + updates.version = (question.version || 1) + 1; + } + + updates.updatedBy = req.user._id; + + const updatedQuestion = await WebDevQuestion.findByIdAndUpdate(id, updates, { + new: true, + runValidators: true, + }); + + res.json({ + success: true, + message: 'Question updated successfully', + question: updatedQuestion, + }); + } catch (error) { + console.error('Error updating web dev question:', error); + res.status(500).json({ success: false, message: error.message || 'Server error updating question' }); + } +}; + +/** + * @desc Delete a web dev question + * @route DELETE /api/web-development/admin/questions/:id + * @access Private / Admin + */ +export const deleteAdminQuestion = async (req, res) => { + try { + const { id } = req.params; + + const question = await WebDevQuestion.findById(id); + if (!question) { + return res.status(404).json({ success: false, message: 'Question not found' }); + } + + await WebDevQuestion.findByIdAndDelete(id); + await WebDevSubmission.deleteMany({ question: id }); + + res.json({ + success: true, + message: 'Question and associated submission logs deleted successfully', + }); + } catch (error) { + console.error('Error deleting web dev question:', error); + res.status(500).json({ success: false, message: 'Server error deleting question' }); + } +}; diff --git a/backend/models/WebDevQuestion.js b/backend/models/WebDevQuestion.js new file mode 100644 index 0000000..f2add21 --- /dev/null +++ b/backend/models/WebDevQuestion.js @@ -0,0 +1,211 @@ +import mongoose from 'mongoose'; + +const testSpecSchema = new mongoose.Schema( + { + id: { + type: String, + required: true, + }, + description: { + type: String, + required: true, + trim: true, + }, + failureMessage: { + type: String, + required: true, + trim: true, + }, + points: { + type: Number, + required: true, + min: 1, + default: 20, + }, + type: { + type: String, + required: true, + enum: [ + 'dom', + 'css', + 'click', + 'input', + 'change', + 'submit', + 'keyboard', + 'attribute', + 'count', + 'visibility', + 'responsive', + 'custom', + ], + default: 'dom', + }, + target: { + type: String, // CSS selector (e.g. '#count', '.card', 'button') + trim: true, + }, + action: { + type: { + type: String, // 'click', 'type', 'key', 'viewport', etc. + }, + value: mongoose.Schema.Types.Mixed, + key: String, + width: Number, + height: Number, + }, + assertion: { + type: { + type: String, // 'exists', 'textEquals', 'textContains', 'computedCss', 'cssRange', 'cssGreaterThan', 'attributeEquals', 'countEquals', 'hasClass', 'isVisible' + required: true, + }, + expected: mongoose.Schema.Types.Mixed, + property: String, // for computed CSS (e.g. 'border-radius', 'background-color') + attribute: String, // for attributes (e.g. 'type', 'placeholder') + className: String, // for class checks + min: Number, // for ranges + max: Number, + operator: String, // 'greaterThan', 'lessThan', 'equals' + }, + isHidden: { + type: Boolean, + default: false, + }, + }, + { _id: false } +); + +const webDevQuestionSchema = new mongoose.Schema( + { + title: { + type: String, + required: [true, 'Question title is required'], + trim: true, + }, + slug: { + type: String, + required: [true, 'Slug is required'], + unique: true, + trim: true, + lowercase: true, + index: true, + }, + difficulty: { + type: String, + required: [true, 'Difficulty is required'], + enum: ['easy', 'medium', 'hard'], + default: 'easy', + index: true, + }, + category: { + type: String, + required: [true, 'Category is required'], + enum: ['html', 'css', 'javascript', 'html-css', 'html-css-javascript'], + default: 'html-css-javascript', + index: true, + }, + description: { + type: String, + required: [true, 'Problem description is required'], + trim: true, + }, + requirements: [ + { + type: String, + trim: true, + }, + ], + starterCode: { + html: { + type: String, + default: '', + }, + css: { + type: String, + default: '', + }, + javascript: { + type: String, + default: '', + }, + }, + solutionCode: { + html: { + type: String, + default: '', + }, + css: { + type: String, + default: '', + }, + javascript: { + type: String, + default: '', + }, + }, + tests: { + type: [testSpecSchema], + default: [], + }, + points: { + type: Number, + default: 100, + min: 1, + }, + timeLimit: { + type: Number, + default: 20, // in minutes + min: 1, + }, + version: { + type: Number, + default: 1, + min: 1, + }, + status: { + type: String, + enum: ['draft', 'published', 'archived'], + default: 'published', + index: true, + }, + tags: [ + { + type: String, + trim: true, + lowercase: true, + }, + ], + displayOrder: { + type: Number, + default: 0, + index: true, + }, + createdBy: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + }, + updatedBy: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + }, + }, + { + timestamps: true, + } +); + +// Auto-sync question points with test points if tests exist +webDevQuestionSchema.pre('save', function (next) { + if (this.tests && this.tests.length > 0) { + const totalTestPoints = this.tests.reduce((acc, t) => acc + (t.points || 0), 0); + if (totalTestPoints > 0) { + this.points = totalTestPoints; + } + } + next(); +}); + +const WebDevQuestion = + mongoose.models.WebDevQuestion || mongoose.model('WebDevQuestion', webDevQuestionSchema); + +export default WebDevQuestion; diff --git a/backend/models/WebDevSubmission.js b/backend/models/WebDevSubmission.js new file mode 100644 index 0000000..e3eb83f --- /dev/null +++ b/backend/models/WebDevSubmission.js @@ -0,0 +1,132 @@ +import mongoose from 'mongoose'; + +const testResultSchema = new mongoose.Schema( + { + testId: { + type: String, + required: true, + }, + description: { + type: String, + required: true, + }, + passed: { + type: Boolean, + required: true, + }, + points: { + type: Number, + required: true, + default: 0, + }, + earnedPoints: { + type: Number, + required: true, + default: 0, + }, + failureMessage: { + type: String, + default: '', + }, + }, + { _id: false } +); + +const webDevSubmissionSchema = new mongoose.Schema( + { + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true, + index: true, + }, + question: { + type: mongoose.Schema.Types.ObjectId, + ref: 'WebDevQuestion', + required: true, + index: true, + }, + questionVersion: { + type: Number, + default: 1, + }, + attemptNumber: { + type: Number, + default: 1, + }, + htmlCode: { + type: String, + default: '', + }, + cssCode: { + type: String, + default: '', + }, + javascriptCode: { + type: String, + default: '', + }, + score: { + type: Number, // Percentage 0 - 100 + required: true, + default: 0, + min: 0, + max: 100, + }, + pointsEarned: { + type: Number, + required: true, + default: 0, + min: 0, + }, + totalPoints: { + type: Number, + required: true, + default: 100, + min: 1, + }, + passedTests: { + type: Number, + default: 0, + min: 0, + }, + totalTests: { + type: Number, + default: 0, + min: 0, + }, + status: { + type: String, + enum: ['Passed', 'Partial', 'Failed'], + default: 'Failed', + index: true, + }, + testResults: { + type: [testResultSchema], + default: [], + }, + timeSpent: { + type: Number, // seconds + default: 0, + }, + startedAt: { + type: Date, + default: Date.now, + }, + submittedAt: { + type: Date, + default: Date.now, + }, + }, + { + timestamps: true, + } +); + +// Compound index for quick lookup of user attempts on a question +webDevSubmissionSchema.index({ user: 1, question: 1, createdAt: -1 }); + +const WebDevSubmission = + mongoose.models.WebDevSubmission || mongoose.model('WebDevSubmission', webDevSubmissionSchema); + +export default WebDevSubmission; diff --git a/backend/package.json b/backend/package.json index 382e943..566f77f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -21,7 +21,8 @@ "test:forgot-password": "node tests/test_forgot_password.js", "test:validation": "node tests/test_validation.js", "test:google-linking": "node tests/test_google_linking.js", - "test:public-access": "node tests/test_public_access.js" + "test:public-access": "node tests/test_public_access.js", + "seed:webdev": "node scripts/seedWebDev.js" }, "dependencies": { "@google/generative-ai": "^0.24.1", diff --git a/backend/routes/webDevRoutes.js b/backend/routes/webDevRoutes.js new file mode 100644 index 0000000..b3db2e2 --- /dev/null +++ b/backend/routes/webDevRoutes.js @@ -0,0 +1,32 @@ +import express from 'express'; +import { + getPublicQuestions, + getPublicQuestionByIdOrSlug, + submitWebDevSolution, + getUserSubmissions, + getAdminQuestions, + getAdminQuestionById, + createAdminQuestion, + updateAdminQuestion, + deleteAdminQuestion, +} from '../controllers/webDevController.js'; +import { protect, admin, optionalProtect } from '../middleware/authMiddleware.js'; + +const router = express.Router(); + +// Public routes (with optional user context for progress tracking) +router.get('/questions', optionalProtect, getPublicQuestions); +router.get('/questions/:idOrSlug', optionalProtect, getPublicQuestionByIdOrSlug); + +// Authenticated student routes +router.post('/questions/:id/submit', protect, submitWebDevSolution); +router.get('/questions/:id/submissions', protect, getUserSubmissions); + +// Admin routes +router.get('/admin/questions', protect, admin, getAdminQuestions); +router.get('/admin/questions/:id', protect, admin, getAdminQuestionById); +router.post('/admin/questions', protect, admin, createAdminQuestion); +router.patch('/admin/questions/:id', protect, admin, updateAdminQuestion); +router.delete('/admin/questions/:id', protect, admin, deleteAdminQuestion); + +export default router; diff --git a/backend/scripts/seedWebDev.js b/backend/scripts/seedWebDev.js new file mode 100644 index 0000000..7883a5b --- /dev/null +++ b/backend/scripts/seedWebDev.js @@ -0,0 +1,1399 @@ +import mongoose from 'mongoose'; +import dotenv from 'dotenv'; +import WebDevQuestion from '../models/WebDevQuestion.js'; + +dotenv.config(); + +const webDevSeedData = [ + { + title: 'Interactive Counter Card', + slug: 'interactive-counter-card', + difficulty: 'easy', + category: 'javascript', + description: `Build an interactive counter component that allows students to increment, decrement, and reset numeric values. The counter must initialize at 0 and must never decrease below 0.`, + requirements: [ + 'Render a counter display element with id "count" initializing at 0.', + 'An increment button with id "incrementBtn" that increases the counter by 1 upon clicking.', + 'A decrement button with id "decrementBtn" that decreases the counter by 1.', + 'Prevent the counter from decreasing below 0 (non-negative constraint).', + 'A reset button with id "resetBtn" that returns the count back to 0.', + ], + starterCode: { + html: ` + + + + Counter Card + + +
+

Student Counter

+
0
+ +
+ + + +
+
+ +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: #f8fafc; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.counter-card { + background: #1e293b; + padding: 2rem; + border-radius: 12px; + text-align: center; + box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3); + width: 320px; +} + +.count-display { + font-size: 3.5rem; + font-weight: bold; + color: #38bdf8; + margin: 1.5rem 0; +} + +.btn-group { + display: flex; + gap: 0.75rem; + justify-content: center; +} + +.btn { + padding: 0.6rem 1.2rem; + font-size: 1.1rem; + font-weight: bold; + border: none; + border-radius: 8px; + cursor: pointer; + transition: opacity 0.2s; +} + +.btn:hover { + opacity: 0.9; +} + +.btn-dec { + background: #f43f5e; + color: white; +} + +.btn-reset { + background: #64748b; + color: white; +} + +.btn-inc { + background: #10b981; + color: white; +}`, + javascript: `// Write your interactive counter logic below +const countDisplay = document.getElementById('count'); +const incrementBtn = document.getElementById('incrementBtn'); +const decrementBtn = document.getElementById('decrementBtn'); +const resetBtn = document.getElementById('resetBtn'); + +let count = 0; + +// Implement click handlers for increment, decrement, and reset: +`, + }, + solutionCode: { + html: ` + + + + Counter Card + + +
+

Student Counter

+
0
+ +
+ + + +
+
+ +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: #f8fafc; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.counter-card { + background: #1e293b; + padding: 2rem; + border-radius: 12px; + text-align: center; + box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3); + width: 320px; +} + +.count-display { + font-size: 3.5rem; + font-weight: bold; + color: #38bdf8; + margin: 1.5rem 0; +} + +.btn-group { + display: flex; + gap: 0.75rem; + justify-content: center; +} + +.btn { + padding: 0.6rem 1.2rem; + font-size: 1.1rem; + font-weight: bold; + border: none; + border-radius: 8px; + cursor: pointer; + transition: opacity 0.2s; +} + +.btn-dec { + background: #f43f5e; + color: white; +} + +.btn-reset { + background: #64748b; + color: white; +} + +.btn-inc { + background: #10b981; + color: white; +}`, + javascript: `const countDisplay = document.getElementById('count'); +const incrementBtn = document.getElementById('incrementBtn'); +const decrementBtn = document.getElementById('decrementBtn'); +const resetBtn = document.getElementById('resetBtn'); + +let count = 0; + +function updateDisplay() { + countDisplay.textContent = count; +} + +incrementBtn.addEventListener('click', () => { + count += 1; + updateDisplay(); +}); + +decrementBtn.addEventListener('click', () => { + if (count > 0) { + count -= 1; + updateDisplay(); + } +}); + +resetBtn.addEventListener('click', () => { + count = 0; + updateDisplay(); +});`, + }, + tests: [ + { + id: 'cnt_1', + description: 'Counter element exists with initial value 0', + failureMessage: 'Element #count was not found or did not initialize with "0"', + points: 20, + type: 'dom', + target: '#count', + assertion: { + type: 'textEquals', + expected: '0', + }, + }, + { + id: 'cnt_2', + description: 'Clicking increment button increases count to 1 and 2', + failureMessage: 'Clicking #incrementBtn did not increase the counter to 1', + points: 25, + type: 'click', + target: '#incrementBtn', + action: { type: 'click' }, + assertion: { + type: 'textEquals', + expected: '1', + }, + }, + { + id: 'cnt_3', + description: 'Clicking decrement button reduces count by 1', + failureMessage: 'Clicking #decrementBtn did not decrease the counter', + points: 25, + type: 'click', + target: '#decrementBtn', + action: { type: 'click' }, + assertion: { + type: 'textEquals', + expected: '0', + }, + }, + { + id: 'cnt_4', + description: 'Counter cannot decrease below zero (boundary check)', + failureMessage: 'Counter decreased below 0 when decrement was clicked at 0', + points: 20, + type: 'click', + target: '#decrementBtn', + action: { type: 'click' }, + assertion: { + type: 'textEquals', + expected: '0', + }, + }, + { + id: 'cnt_5', + description: 'Reset button returns count to 0', + failureMessage: '#resetBtn did not reset the counter back to 0', + points: 10, + type: 'click', + target: '#resetBtn', + action: { type: 'click' }, + assertion: { + type: 'textEquals', + expected: '0', + }, + }, + ], + points: 100, + timeLimit: 15, + version: 1, + status: 'published', + tags: ['dom', 'javascript', 'events', 'counter'], + displayOrder: 1, + }, + { + title: 'Responsive Login Form with Validation', + slug: 'responsive-login-form-validation', + difficulty: 'medium', + category: 'html-css-javascript', + description: `Construct a responsive authentication card with an email field, password field, and submit button. Implement client-side validation that alerts the student if the email is invalid or fields are empty upon clicking the login button.`, + requirements: [ + 'Email input with id "email" and type="email".', + 'Password input with id "password" and type="password".', + 'A button with id "loginBtn" or type="submit".', + 'A status container with id "statusMessage" for showing validation verdicts.', + 'Clicking login with empty fields displays "Please fill in all fields" in #statusMessage.', + 'Clicking login with an invalid email address format displays "Invalid email address".', + 'Submitting with valid credentials displays "Login successful".', + ], + starterCode: { + html: ` + + + + Login Card + + +
+

NQTCoder Login

+
+
+ + +
+ +
+ + +
+ + +
+
+
+ +`, + css: `body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #0b0f19; + color: #e2e8f0; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.login-box { + background: #1e293b; + padding: 2.5rem; + border-radius: 16px; + width: 340px; + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5); +} + +.login-box h2 { + margin-top: 0; + margin-bottom: 1.5rem; + color: #38bdf8; + text-align: center; +} + +.input-group { + margin-bottom: 1.2rem; +} + +.input-group label { + display: block; + font-size: 0.85rem; + font-weight: 600; + margin-bottom: 0.4rem; + color: #94a3b8; +} + +.input-group input { + width: 100%; + padding: 0.75rem; + background: #0f172a; + border: 1px solid #334155; + border-radius: 8px; + color: white; + box-sizing: border-box; + font-size: 0.95rem; +} + +.input-group input:focus { + outline: none; + border-color: #38bdf8; +} + +button { + width: 100%; + padding: 0.8rem; + background: #0284c7; + color: white; + border: none; + border-radius: 8px; + font-weight: bold; + cursor: pointer; + font-size: 1rem; + margin-top: 0.5rem; + transition: background 0.2s; +} + +button:hover { + background: #0369a1; +} + +.status-msg { + margin-top: 1rem; + font-size: 0.85rem; + text-align: center; + min-height: 1.2rem; +}`, + javascript: `// Implement form validation logic here +const emailInput = document.getElementById('email'); +const passwordInput = document.getElementById('password'); +const loginBtn = document.getElementById('loginBtn'); +const statusMessage = document.getElementById('statusMessage'); + +// Add event listener to validate inputs upon login submission +`, + }, + solutionCode: { + html: ` + + + + Login Card + + +
+

NQTCoder Login

+
+
+ + +
+ +
+ + +
+ + +
+
+
+ +`, + css: `body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #0b0f19; + color: #e2e8f0; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.login-box { + background: #1e293b; + padding: 2.5rem; + border-radius: 16px; + width: 340px; + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5); +} + +.input-group { + margin-bottom: 1.2rem; +} + +.input-group label { + display: block; + font-size: 0.85rem; + margin-bottom: 0.4rem; + color: #94a3b8; +} + +.input-group input { + width: 100%; + padding: 0.75rem; + background: #0f172a; + border: 1px solid #334155; + border-radius: 8px; + color: white; + box-sizing: border-box; +} + +button { + width: 100%; + padding: 0.8rem; + background: #0284c7; + color: white; + border: none; + border-radius: 8px; + font-weight: bold; + cursor: pointer; +} + +.status-msg { + margin-top: 1rem; + font-size: 0.85rem; + text-align: center; +}`, + javascript: `const emailInput = document.getElementById('email'); +const passwordInput = document.getElementById('password'); +const loginBtn = document.getElementById('loginBtn'); +const statusMessage = document.getElementById('statusMessage'); + +function validateEmail(email) { + const re = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/; + return re.test(email); +} + +loginBtn.addEventListener('click', (e) => { + e.preventDefault(); + const email = emailInput.value.trim(); + const password = passwordInput.value.trim(); + + if (!email || !password) { + statusMessage.textContent = 'Please fill in all fields'; + statusMessage.style.color = '#f43f5e'; + return; + } + + if (!validateEmail(email)) { + statusMessage.textContent = 'Invalid email address'; + statusMessage.style.color = '#f43f5e'; + return; + } + + statusMessage.textContent = 'Login successful'; + statusMessage.style.color = '#10b981'; +});`, + }, + tests: [ + { + id: 'log_1', + description: 'Input elements and button exist with required attributes', + failureMessage: 'Form must contain #email with type="email" and #password with type="password"', + points: 20, + type: 'dom', + target: '#email', + assertion: { + type: 'attributeEquals', + attribute: 'type', + expected: 'email', + }, + }, + { + id: 'log_2', + description: 'Submitting with empty fields shows "Please fill in all fields"', + failureMessage: 'Clicking login with empty inputs did not show error message in #statusMessage', + points: 30, + type: 'click', + target: '#loginBtn', + action: { type: 'click' }, + assertion: { + type: 'textContains', + expected: 'Please fill in all fields', + }, + }, + { + id: 'log_3', + description: 'Submitting with invalid email format shows "Invalid email address"', + failureMessage: 'Entering invalid email format did not trigger email validation message', + points: 25, + type: 'input', + target: '#email', + action: { type: 'type', value: 'not-an-email' }, + assertion: { + type: 'exists', + }, + }, + { + id: 'log_4', + description: 'Submitting valid credentials produces "Login successful"', + failureMessage: 'Valid email and password did not produce "Login successful"', + points: 25, + type: 'click', + target: '#loginBtn', + action: { type: 'click' }, + assertion: { + type: 'textContains', + expected: 'Login successful', + }, + }, + ], + points: 100, + timeLimit: 20, + version: 1, + status: 'published', + tags: ['forms', 'validation', 'html-css-js', 'login'], + displayOrder: 2, + }, + { + title: 'Interactive Task / Todo List', + slug: 'interactive-task-todo-list', + difficulty: 'medium', + category: 'javascript', + description: `Build a clean vanilla JavaScript task manager where candidates can add new tasks via input and button, toggle completion styles, and delete completed items dynamically.`, + requirements: [ + 'Text input with id "taskInput" for typing a new task.', + 'Add button with id "addTaskBtn" that appends a new item into the unordered list with id "taskList".', + 'Pressing Enter inside #taskInput also appends the new task item.', + 'Clears the text input after adding a task.', + 'Clicking a task text toggles the ".completed" CSS class on the task item.', + 'Clicking the delete button inside a task removes that specific item from the DOM.', + ], + starterCode: { + html: ` + + + + Task Manager + + +
+

My Placement Tasks

+ +
+ + +
+ + +
+ +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: #f8fafc; + display: flex; + justify-content: center; + padding-top: 3rem; + margin: 0; +} + +.todo-app { + background: #1e293b; + padding: 2rem; + border-radius: 12px; + width: 380px; + box-shadow: 0 10px 25px rgba(0,0,0,0.3); +} + +.input-row { + display: flex; + gap: 0.5rem; + margin-bottom: 1.5rem; +} + +#taskInput { + flex: 1; + padding: 0.6rem; + border-radius: 6px; + border: 1px solid #334155; + background: #0f172a; + color: white; +} + +#addTaskBtn { + background: #38bdf8; + color: #0f172a; + border: none; + border-radius: 6px; + font-weight: bold; + padding: 0.6rem 1rem; + cursor: pointer; +} + +#taskList { + list-style: none; + padding: 0; + margin: 0; +} + +#taskList li { + display: flex; + justify-content: space-between; + align-items: center; + background: #0f172a; + padding: 0.75rem; + border-radius: 6px; + margin-bottom: 0.5rem; +} + +#taskList li.completed span { + text-decoration: line-through; + color: #64748b; +} + +.delete-btn { + background: #f43f5e; + color: white; + border: none; + border-radius: 4px; + padding: 0.3rem 0.6rem; + font-size: 0.8rem; + cursor: pointer; +}`, + javascript: `const taskInput = document.getElementById('taskInput'); +const addTaskBtn = document.getElementById('addTaskBtn'); +const taskList = document.getElementById('taskList'); + +// Implement dynamic task insertion, completion toggle, and deletion +`, + }, + solutionCode: { + html: ` + + + + Task Manager + + +
+

My Placement Tasks

+ +
+ + +
+ + +
+ +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: #f8fafc; + display: flex; + justify-content: center; + padding-top: 3rem; + margin: 0; +} + +.todo-app { + background: #1e293b; + padding: 2rem; + border-radius: 12px; + width: 380px; +} + +.input-row { + display: flex; + gap: 0.5rem; + margin-bottom: 1.5rem; +} + +#taskInput { + flex: 1; + padding: 0.6rem; + border-radius: 6px; + border: 1px solid #334155; + background: #0f172a; + color: white; +} + +#addTaskBtn { + background: #38bdf8; + color: #0f172a; + border: none; + border-radius: 6px; + font-weight: bold; + padding: 0.6rem 1rem; + cursor: pointer; +} + +#taskList { + list-style: none; + padding: 0; + margin: 0; +} + +#taskList li { + display: flex; + justify-content: space-between; + align-items: center; + background: #0f172a; + padding: 0.75rem; + border-radius: 6px; + margin-bottom: 0.5rem; +} + +#taskList li.completed span { + text-decoration: line-through; + color: #64748b; +} + +.delete-btn { + background: #f43f5e; + color: white; + border: none; + border-radius: 4px; + padding: 0.3rem 0.6rem; + font-size: 0.8rem; + cursor: pointer; +}`, + javascript: `const taskInput = document.getElementById('taskInput'); +const addTaskBtn = document.getElementById('addTaskBtn'); +const taskList = document.getElementById('taskList'); + +function addTask() { + const text = taskInput.value.trim(); + if (!text) return; + + const li = document.createElement('li'); + const span = document.createElement('span'); + span.textContent = text; + span.addEventListener('click', () => { + li.classList.toggle('completed'); + }); + + const delBtn = document.createElement('button'); + delBtn.textContent = 'Delete'; + delBtn.className = 'delete-btn'; + delBtn.addEventListener('click', (e) => { + e.stopPropagation(); + li.remove(); + }); + + li.appendChild(span); + li.appendChild(delBtn); + taskList.appendChild(li); + + taskInput.value = ''; +} + +addTaskBtn.addEventListener('click', addTask); +taskInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + addTask(); + } +});`, + }, + tests: [ + { + id: 'todo_1', + description: 'Input element and add button exist in DOM', + failureMessage: 'Required elements #taskInput or #addTaskBtn were not found', + points: 20, + type: 'dom', + target: '#taskInput', + assertion: { + type: 'exists', + }, + }, + { + id: 'todo_2', + description: 'Adding a task appends an item to #taskList', + failureMessage: 'Clicking #addTaskBtn with input text did not add an
  • to #taskList', + points: 30, + type: 'input', + target: '#taskInput', + action: { type: 'type', value: 'Practice TCS NQT Coding' }, + assertion: { + type: 'exists', + }, + }, + { + id: 'todo_3', + description: 'Task item can be toggled as completed', + failureMessage: 'Clicking the task item did not toggle the "completed" class', + points: 25, + type: 'dom', + target: '#taskList li', + assertion: { + type: 'exists', + }, + }, + { + id: 'todo_4', + description: 'Delete button removes task from DOM', + failureMessage: 'Clicking delete button did not remove the task item from list', + points: 25, + type: 'dom', + target: '#taskList', + assertion: { + type: 'exists', + }, + }, + ], + points: 100, + timeLimit: 25, + version: 1, + status: 'published', + tags: ['dom', 'javascript', 'todo', 'lists'], + displayOrder: 3, + }, + { + title: 'Dynamic Color Palette Generator', + slug: 'dynamic-color-palette-generator', + difficulty: 'easy', + category: 'css', + description: `Build a dynamic color palette card. Clicking the "Generate Colors" button generates random hex colors for 4 color cards and updates the hex labels underneath each swatch.`, + requirements: [ + 'Four color box containers with class ".color-box".', + 'Hex code label inside each color box with class ".hex-code".', + 'Generate button with id "generateBtn".', + 'Clicking generate button assigns new background colors to all color boxes.', + 'Hex codes match format "#XXXXXX".', + ], + starterCode: { + html: ` + + + + Color Palette + + +
    +

    Palette Generator

    + +
    +
    #38bdf8
    +
    #818cf8
    +
    #c084fc
    +
    #f472b6
    +
    + + +
    + +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: white; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.palette-container { + background: #1e293b; + padding: 2rem; + border-radius: 16px; + text-align: center; + box-shadow: 0 10px 25px rgba(0,0,0,0.3); +} + +.palette-grid { + display: flex; + gap: 1rem; + margin: 2rem 0; +} + +.color-box { + width: 90px; + height: 140px; + border-radius: 12px; + display: flex; + align-items: flex-end; + justify-content: center; + padding-bottom: 0.75rem; + box-shadow: 0 4px 6px rgba(0,0,0,0.2); + transition: transform 0.2s; +} + +.color-box:hover { + transform: translateY(-4px); +} + +.hex-code { + background: rgba(0,0,0,0.6); + padding: 0.3rem 0.5rem; + border-radius: 6px; + font-size: 0.75rem; + font-family: monospace; + font-weight: bold; +} + +#generateBtn { + background: #38bdf8; + color: #0f172a; + font-weight: bold; + border: none; + padding: 0.75rem 1.5rem; + border-radius: 8px; + cursor: pointer; + font-size: 1rem; +}`, + javascript: `const generateBtn = document.getElementById('generateBtn'); +const colorBoxes = document.querySelectorAll('.color-box'); + +// Implement random hex color generator logic on click +`, + }, + solutionCode: { + html: ` + + + + Color Palette + + +
    +

    Palette Generator

    + +
    +
    #38bdf8
    +
    #818cf8
    +
    #c084fc
    +
    #f472b6
    +
    + + +
    + +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: white; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.palette-container { + background: #1e293b; + padding: 2rem; + border-radius: 16px; + text-align: center; +} + +.palette-grid { + display: flex; + gap: 1rem; + margin: 2rem 0; +} + +.color-box { + width: 90px; + height: 140px; + border-radius: 12px; + display: flex; + align-items: flex-end; + justify-content: center; + padding-bottom: 0.75rem; +} + +.hex-code { + background: rgba(0,0,0,0.6); + padding: 0.3rem 0.5rem; + border-radius: 6px; + font-size: 0.75rem; + font-family: monospace; + font-weight: bold; +} + +#generateBtn { + background: #38bdf8; + color: #0f172a; + font-weight: bold; + border: none; + padding: 0.75rem 1.5rem; + border-radius: 8px; + cursor: pointer; +}`, + javascript: `const generateBtn = document.getElementById('generateBtn'); +const colorBoxes = document.querySelectorAll('.color-box'); + +function getRandomHex() { + const chars = '0123456789ABCDEF'; + let color = '#'; + for (let i = 0; i < 6; i++) { + color += chars[Math.floor(Math.random() * 16)]; + } + return color; +} + +function updatePalette() { + colorBoxes.forEach((box) => { + const hex = getRandomHex(); + box.style.backgroundColor = hex; + const hexSpan = box.querySelector('.hex-code'); + if (hexSpan) hexSpan.textContent = hex; + }); +} + +generateBtn.addEventListener('click', updatePalette); +updatePalette();`, + }, + tests: [ + { + id: 'pal_1', + description: 'Palette grid has 4 color boxes with hex labels', + failureMessage: 'Must render exactly 4 .color-box elements', + points: 30, + type: 'count', + target: '.color-box', + assertion: { + type: 'countEquals', + expected: 4, + }, + }, + { + id: 'pal_2', + description: 'Generate button with id #generateBtn exists', + failureMessage: 'Element #generateBtn was not found', + points: 20, + type: 'dom', + target: '#generateBtn', + assertion: { + type: 'exists', + }, + }, + { + id: 'pal_3', + description: 'Clicking generate button triggers color update', + failureMessage: 'Clicking #generateBtn did not update color box styles', + points: 50, + type: 'click', + target: '#generateBtn', + action: { type: 'click' }, + assertion: { + type: 'exists', + }, + }, + ], + points: 100, + timeLimit: 15, + version: 1, + status: 'published', + tags: ['css', 'javascript', 'colors', 'styling'], + displayOrder: 4, + }, + { + title: '5-Star Interactive Rating Widget', + slug: '5-star-interactive-rating-widget', + difficulty: 'medium', + category: 'html-css-javascript', + description: `Build an interactive 5-star rating widget. When the student hovers or clicks on a star, all stars up to that rating highlight in golden color, and a feedback label updates to show the selected rating (e.g., "5 of 5 Stars").`, + requirements: [ + 'Rating container with 5 star elements carrying class ".star".', + 'Feedback text container with id "ratingFeedback".', + 'Clicking the 4th star highlights 4 stars with the ".active" class.', + 'Updates #ratingFeedback text to display "4 of 5 Stars".', + 'Preserves selected rating state on subsequent interactions.', + ], + starterCode: { + html: ` + + + + Rating Widget + + +
    +

    Rate Your Assessment

    +
    + ★ + ★ + ★ + ★ + ★ +
    + +
    + +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: white; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.rating-card { + background: #1e293b; + padding: 2.5rem; + border-radius: 16px; + text-align: center; + box-shadow: 0 10px 25px rgba(0,0,0,0.3); +} + +.star-group { + display: flex; + gap: 0.5rem; + justify-content: center; + margin: 1.5rem 0; +} + +.star { + font-size: 2.5rem; + color: #475569; + cursor: pointer; + transition: color 0.2s, transform 0.1s; +} + +.star:hover { + transform: scale(1.15); +} + +.star.active { + color: #fbbf24; +} + +.feedback-text { + font-size: 0.95rem; + color: #94a3b8; + font-weight: bold; +}`, + javascript: `const stars = document.querySelectorAll('.star'); +const feedback = document.getElementById('ratingFeedback'); + +// Implement hover & click rating selection logic +`, + }, + solutionCode: { + html: ` + + + + Rating Widget + + +
    +

    Rate Your Assessment

    +
    + ★ + ★ + ★ + ★ + ★ +
    + +
    + +`, + css: `body { + font-family: Arial, sans-serif; + background-color: #0f172a; + color: white; + display: flex; + justify-content: center; + align-items: center; + min-height: 100vh; + margin: 0; +} + +.rating-card { + background: #1e293b; + padding: 2.5rem; + border-radius: 16px; + text-align: center; +} + +.star-group { + display: flex; + gap: 0.5rem; + justify-content: center; + margin: 1.5rem 0; +} + +.star { + font-size: 2.5rem; + color: #475569; + cursor: pointer; +} + +.star.active { + color: #fbbf24; +} + +.feedback-text { + font-size: 0.95rem; + color: #94a3b8; + font-weight: bold; +}`, + javascript: `const stars = document.querySelectorAll('.star'); +const feedback = document.getElementById('ratingFeedback'); + +let selectedRating = 0; + +function highlightStars(rating) { + stars.forEach((star) => { + const val = parseInt(star.getAttribute('data-value'), 10); + if (val <= rating) { + star.classList.add('active'); + } else { + star.classList.remove('active'); + } + }); +} + +stars.forEach((star) => { + star.addEventListener('click', () => { + selectedRating = parseInt(star.getAttribute('data-value'), 10); + highlightStars(selectedRating); + feedback.textContent = \`\${selectedRating} of 5 Stars\`; + }); +});`, + }, + tests: [ + { + id: 'star_1', + description: 'Contains 5 star elements with .star class', + failureMessage: 'Widget must contain 5 .star elements', + points: 20, + type: 'count', + target: '.star', + assertion: { + type: 'countEquals', + expected: 5, + }, + }, + { + id: 'star_2', + description: 'Initial feedback text prompts selection', + failureMessage: '#ratingFeedback must contain initial text', + points: 20, + type: 'dom', + target: '#ratingFeedback', + assertion: { + type: 'exists', + }, + }, + { + id: 'star_3', + description: 'Clicking star applies .active class to stars', + failureMessage: 'Clicking star did not apply active highlight class', + points: 30, + type: 'click', + target: '.star[data-value="4"]', + action: { type: 'click' }, + assertion: { + type: 'hasClass', + className: 'active', + }, + }, + { + id: 'star_4', + description: 'Feedback text updates to show "4 of 5 Stars"', + failureMessage: '#ratingFeedback did not update to "4 of 5 Stars" after clicking 4th star', + points: 30, + type: 'dom', + target: '#ratingFeedback', + assertion: { + type: 'textContains', + expected: '4 of 5 Stars', + }, + }, + ], + points: 100, + timeLimit: 20, + version: 1, + status: 'published', + tags: ['stars', 'ratings', 'events', 'ui'], + displayOrder: 5, + }, +]; + +async function seedWebDev() { + try { + const mongoUri = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/nqtcoder'; + console.log('Connecting to MongoDB...'); + try { + await mongoose.connect(mongoUri, { serverSelectionTimeoutMS: 10000 }); + } catch { + await mongoose.connect('mongodb://127.0.0.1:27017/nqtcoder'); + } + console.log('✅ Connected to MongoDB.'); + + console.log(`🌱 Seeding ${webDevSeedData.length} Web Development practical challenges...`); + + for (const qData of webDevSeedData) { + await WebDevQuestion.findOneAndUpdate({ slug: qData.slug }, qData, { + upsert: true, + new: true, + setDefaultsOnInsert: true, + }); + console.log(` ✓ Seeded / Verified: ${qData.title} (${qData.difficulty})`); + } + + console.log('🌟 Web Development Practice challenges successfully seeded! 🌟'); + } catch (error) { + console.error('❌ Seeding error:', error); + } finally { + await mongoose.disconnect(); + console.log('🔌 Disconnected from MongoDB.'); + } +} + +// Execute if run directly via CLI +seedWebDev(); diff --git a/backend/server.js b/backend/server.js index aee9ed9..b533d45 100644 --- a/backend/server.js +++ b/backend/server.js @@ -18,6 +18,7 @@ import companyGuideRoutes from './routes/companyGuideRoutes.js'; import adminCompanyGuideRoutes from './routes/adminCompanyGuideRoutes.js'; import testimonialRoutes from './routes/testimonialRoutes.js'; import gameRoutes from './routes/gameRoutes.js'; +import webDevRoutes from './routes/webDevRoutes.js'; import { notFound, errorHandler } from './middleware/errorMiddleware.js'; // Connect to database & auto-seed cognitive games if empty @@ -87,6 +88,7 @@ app.use('/api/company-guides', companyGuideRoutes); app.use('/api/admin', adminCompanyGuideRoutes); app.use('/api/testimonials', testimonialRoutes); app.use('/api/games', gameRoutes); +app.use('/api/web-development', webDevRoutes); // Error Middlewares app.use(notFound); diff --git a/backend/tests/test_web_development.js b/backend/tests/test_web_development.js new file mode 100644 index 0000000..4bbe229 --- /dev/null +++ b/backend/tests/test_web_development.js @@ -0,0 +1,274 @@ +import axios from 'axios'; +import mongoose from 'mongoose'; +import dotenv from 'dotenv'; +import User from '../models/User.js'; +import WebDevQuestion from '../models/WebDevQuestion.js'; +import WebDevSubmission from '../models/WebDevSubmission.js'; + +dotenv.config(); + +const BASE_URL = 'http://localhost:5000/api'; +const testUsername = `wd_u_${Math.floor(100000 + Math.random() * 900000)}`; +const testEmail = `${testUsername}@example.com`; +const testPassword = 'Password@123'; + +const adminEmail = process.env.ADMIN_EMAIL || 'admin@nqtcoder.com'; +const adminPassword = process.env.ADMIN_PASSWORD || 'Admin@123'; + +async function runWebDevTests() { + console.log('🚀 Starting Web Development Module Integration Test...'); + + let adminToken = ''; + let adminHeader = {}; + let userToken = ''; + let userHeader = {}; + let tempUserId = ''; + let createdQuestionId = ''; + + try { + try { + await mongoose.connect(process.env.MONGO_URI, { serverSelectionTimeoutMS: 10000 }); + console.log('✅ Connected to Primary MongoDB Atlas.'); + } catch { + await mongoose.connect('mongodb://127.0.0.1:27017/nqtcoder'); + console.log('✅ Connected to Local Fallback MongoDB.'); + } + + // Ensure Admin user exists + let adminUser = await User.findOne({ email: adminEmail }); + if (!adminUser) { + adminUser = await User.create({ + username: 'wd_admin_test', + email: adminEmail, + password: adminPassword, + role: 'admin', + isVerified: true, + }); + await new Promise((r) => setTimeout(r, 400)); + } + + // 1. Admin Login + const adminLoginRes = await axios.post(`${BASE_URL}/auth/login`, { + email: adminEmail, + password: adminPassword, + }); + adminToken = adminLoginRes.data.token; + adminHeader = { headers: { Authorization: `Bearer ${adminToken}` } }; + console.log('✅ Admin login successful.'); + + // 2. Register & Verify Student User + await axios.post(`${BASE_URL}/auth/register`, { + username: testUsername, + email: testEmail.toLowerCase(), + password: testPassword, + confirmPassword: testPassword, + }); + let user1InDb = null; + for (let i = 0; i < 10; i++) { + user1InDb = await User.findOne({ email: testEmail.toLowerCase() }); + if (user1InDb && user1InDb.verificationCode) break; + await new Promise((r) => setTimeout(r, 350)); + } + if (!user1InDb) throw new Error('Student user not found in DB'); + tempUserId = user1InDb._id.toString(); + + await axios.post(`${BASE_URL}/auth/verify`, { + email: testEmail.toLowerCase(), + code: user1InDb.verificationCode, + }); + const userLoginRes = await axios.post(`${BASE_URL}/auth/login`, { + email: testEmail.toLowerCase(), + password: testPassword, + }); + userToken = userLoginRes.data.token; + userHeader = { headers: { Authorization: `Bearer ${userToken}` } }; + console.log('✅ Student user registered & logged in.'); + + // ── Test 1: Public Question Retrieval & Privacy Sanitization ── + console.log('\n--- Test 1: Public Question Retrieval & Privacy Check ---'); + const publicRes = await axios.get(`${BASE_URL}/web-development/questions`); + if (publicRes.status !== 200 || !publicRes.data.questions.length) { + throw new Error('Failed to retrieve public questions'); + } + const sample = publicRes.data.questions[0]; + if (sample.solutionCode !== undefined) { + throw new Error('CRITICAL: solutionCode was exposed in public questions list!'); + } + console.log(`✅ PASS: Retrieved ${publicRes.data.count} public questions. Zero solutionCode leaked.`); + + // ── Test 2: Single Question by Slug ── + console.log('\n--- Test 2: Single Question Retrieval by Slug ---'); + const singleRes = await axios.get(`${BASE_URL}/web-development/questions/interactive-counter-card`); + if (singleRes.status !== 200 || !singleRes.data.question) { + throw new Error('Failed to retrieve single question by slug'); + } + if (singleRes.data.question.solutionCode !== undefined) { + throw new Error('CRITICAL: solutionCode was exposed in single question endpoint!'); + } + console.log(`✅ PASS: Question "${singleRes.data.question.title}" retrieved cleanly with starterCode.`); + + // ── Test 3: Admin RBAC Protection ── + console.log('\n--- Test 3: Admin RBAC Protection ---'); + try { + await axios.get(`${BASE_URL}/web-development/admin/questions`); + throw new Error('Guest was allowed to access admin questions!'); + } catch (err) { + if (err.response && err.response.status === 401) { + console.log('✅ PASS: Guest blocked with 401 Unauthorized.'); + } else { + throw err; + } + } + + try { + await axios.get(`${BASE_URL}/web-development/admin/questions`, userHeader); + throw new Error('Regular student was allowed to access admin questions!'); + } catch (err) { + if (err.response && err.response.status === 403) { + console.log('✅ PASS: Regular student blocked with 403 Forbidden.'); + } else { + throw err; + } + } + + // ── Test 4: Admin Create Question ── + console.log('\n--- Test 4: Admin Create Question ---'); + const customQPayload = { + title: 'Dynamic Toggle Button Test', + slug: `dynamic-toggle-${Math.floor(1000 + Math.random() * 9000)}`, + difficulty: 'easy', + category: 'javascript', + description: 'Create a toggle button that toggles active class on click.', + requirements: ['Button with id #toggleBtn', 'Toggles .active class'], + starterCode: { + html: '', + css: '.active { background: blue; }', + javascript: '// logic', + }, + solutionCode: { + html: '', + css: '.active { background: blue; }', + javascript: 'document.getElementById("toggleBtn").onclick = (e) => e.target.classList.toggle("active");', + }, + tests: [ + { + id: 'tog_1', + description: 'Toggle button exists', + failureMessage: 'Missing #toggleBtn', + points: 50, + type: 'dom', + target: '#toggleBtn', + assertion: { type: 'exists' }, + }, + { + id: 'tog_2', + description: 'Clicking button toggles active class', + failureMessage: 'Button did not gain active class', + points: 50, + type: 'click', + target: '#toggleBtn', + action: { type: 'click' }, + assertion: { type: 'hasClass', className: 'active' }, + }, + ], + points: 100, + }; + + const createRes = await axios.post(`${BASE_URL}/web-development/admin/questions`, customQPayload, adminHeader); + if (createRes.status !== 201 || !createRes.data.question) { + throw new Error('Failed to create question via admin endpoint'); + } + createdQuestionId = createRes.data.question._id; + console.log(`✅ PASS: Admin created question "${createRes.data.question.title}" (ID: ${createdQuestionId}, Version: ${createRes.data.question.version}).`); + + // ── Test 5: Admin Update Question & Version Increment ── + console.log('\n--- Test 5: Admin Update Question & Versioning ---'); + const updateRes = await axios.patch( + `${BASE_URL}/web-development/admin/questions/${createdQuestionId}`, + { + starterCode: { + html: '', + css: '.btn { color: white; } .active { background: blue; }', + javascript: '// updated starter code', + }, + }, + adminHeader + ); + if (updateRes.data.question.version !== 2) { + throw new Error(`Expected question version 2 after starterCode update, got ${updateRes.data.question.version}`); + } + console.log(`✅ PASS: Updated starter code and version auto-incremented to ${updateRes.data.question.version}.`); + + // ── Test 6: Student Submission & Attempt Tracking ── + console.log('\n--- Test 6: Student Submission & Attempt Tracking ---'); + // Attempt 1: 50% partial + const submitRes1 = await axios.post( + `${BASE_URL}/web-development/questions/${createdQuestionId}/submit`, + { + htmlCode: '', + cssCode: '', + javascriptCode: '', + testResults: [ + { testId: 'tog_1', passed: true }, + { testId: 'tog_2', passed: false }, + ], + timeSpent: 45, + }, + userHeader + ); + if (submitRes1.data.submission.score !== 50 || submitRes1.data.submission.attemptNumber !== 1) { + throw new Error(`Attempt 1 failed expected score 50 and attempt 1: ${JSON.stringify(submitRes1.data)}`); + } + console.log(`✅ PASS: Attempt 1 saved (Score: 50%, Attempt #: 1, Status: Partial).`); + + // Attempt 2: 100% passed + const submitRes2 = await axios.post( + `${BASE_URL}/web-development/questions/${createdQuestionId}/submit`, + { + htmlCode: '', + cssCode: '.active { background: blue; }', + javascriptCode: 'document.getElementById("toggleBtn").onclick = (e) => e.target.classList.toggle("active");', + testResults: [ + { testId: 'tog_1', passed: true }, + { testId: 'tog_2', passed: true }, + ], + timeSpent: 75, + }, + userHeader + ); + if (submitRes2.data.submission.score !== 100 || submitRes2.data.submission.attemptNumber !== 2) { + throw new Error(`Attempt 2 failed expected score 100 and attempt 2: ${JSON.stringify(submitRes2.data)}`); + } + console.log(`✅ PASS: Attempt 2 saved (Score: 100%, Attempt #: 2, Status: Passed).`); + + // ── Test 7: Fetch Student Submission History ── + console.log('\n--- Test 7: Fetch Student Submissions History ---'); + const historyRes = await axios.get(`${BASE_URL}/web-development/questions/${createdQuestionId}/submissions`, userHeader); + if (historyRes.data.count !== 2) { + throw new Error(`Expected 2 submissions in history, got ${historyRes.data.count}`); + } + console.log(`✅ PASS: Successfully retrieved ${historyRes.data.count} submissions for student.`); + + // ── Test 8: Admin Delete Clean Up ── + console.log('\n--- Test 8: Admin Delete & Cleanup ---'); + await axios.delete(`${BASE_URL}/web-development/admin/questions/${createdQuestionId}`, adminHeader); + const verifyDel = await WebDevQuestion.findById(createdQuestionId); + if (verifyDel) throw new Error('Deleted question still found in DB'); + console.log('✅ PASS: Temporary question and submissions cleaned up.'); + + console.log('\n🧹 Cleaning up test user...'); + await User.deleteMany({ email: testEmail.toLowerCase() }); + console.log('✅ Test student user cleaned up.'); + + console.log('\n🌟 ALL WEB DEVELOPMENT BACKEND INTEGRATION TESTS PASSED! 🌟'); + } catch (err) { + console.error('\n❌ Web Dev Test failed:', err.response?.data || err.message); + process.exit(1); + } finally { + await mongoose.disconnect(); + console.log('🔌 Disconnected from MongoDB.'); + console.log('🏁 Web Development Test complete.'); + } +} + +runWebDevTests(); diff --git a/frontend/public/robots.txt b/frontend/public/robots.txt index f15cdbd..b0480a7 100644 --- a/frontend/public/robots.txt +++ b/frontend/public/robots.txt @@ -1,12 +1,20 @@ # https://www.robotstxt.org/robotstxt.html User-agent: * -# Allow indexing of public marketing and learning routes +# Allow indexing of all public marketing, learning, practice, games & web dev routes Allow: /$ Allow: /practice$ Allow: /practice?* -Allow: /leaderboard$ +Allow: /web-development$ +Allow: /web-development/* +Allow: /games$ +Allow: /games/* +Allow: /companies$ +Allow: /companies/* +Allow: /aptitude$ +Allow: /aptitude/* Allow: /tracks$ +Allow: /leaderboard$ Allow: /resources$ Allow: /compiler-setup$ Allow: /about$ @@ -14,27 +22,23 @@ Allow: /contact$ Allow: /privacy$ Allow: /terms$ -# Disallow indexing of authentication / verification pages -Disallow: /login -Disallow: /register -Disallow: /verify-email -Disallow: /forgot-password - # Disallow indexing of private dashboards and administrative interfaces Disallow: /admin Disallow: /admin/* Disallow: /profile Disallow: /profile/* -# Disallow indexing of dynamic interactive coding arena sessions (require auth/state) -Disallow: /problem/ -Disallow: /problem/* +# Disallow indexing of active mock test proctored runtime sessions (require auth/state) Disallow: /mocktest/arena/ Disallow: /mocktest/arena/* Disallow: /mocktest/result/ Disallow: /mocktest/result/* -Disallow: /tracks/ -Disallow: /tracks/* -# Sitemap directive using the official custom production domain +# Disallow indexing of authentication / verification action pages +Disallow: /login +Disallow: /register +Disallow: /verify-email +Disallow: /forgot-password + +# Sitemap directive using official production domain Sitemap: https://www.nqtcoder.dev/sitemap.xml diff --git a/frontend/public/sitemap.xml b/frontend/public/sitemap.xml index 4909f69..81698c0 100644 --- a/frontend/public/sitemap.xml +++ b/frontend/public/sitemap.xml @@ -4,85 +4,181 @@ https://www.nqtcoder.dev/ - 2026-07-01 + 2026-08-31 daily 1.0 - + + + https://www.nqtcoder.dev/web-development + 2026-08-31 + daily + 0.95 + + + https://www.nqtcoder.dev/web-development/interactive-counter-card + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/web-development/responsive-login-form-validation + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/web-development/interactive-task-todo-list + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/web-development/dynamic-color-palette-generator + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/web-development/5-star-interactive-rating-widget + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/practice - 2026-07-01 + 2026-08-31 + daily + 0.9 + + + + + https://www.nqtcoder.dev/games + 2026-08-31 daily 0.9 + + https://www.nqtcoder.dev/games/geo-sudo + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/games/switch-challenge + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/games/motion-challenge + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/games/inductive-challenge + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/games/grid-memory-challenge + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/games/digit-challenge + 2026-08-31 + weekly + 0.85 + + + https://www.nqtcoder.dev/games/deductive-logic-challenge + 2026-08-31 + weekly + 0.85 + - + https://www.nqtcoder.dev/companies - 2026-07-28 + 2026-08-31 daily 0.9 https://www.nqtcoder.dev/companies/tcs-nqt - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/cognizant-2027 - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/ltimindtree-2027 - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/infosys-2027 - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/itc-infotech-2027 - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/ey-2027 - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/pwc-2027 - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/cloudkaptan-2027 - 2026-07-28 + 2026-08-31 weekly 0.85 https://www.nqtcoder.dev/companies/streebo-2027 - 2026-08-03 + 2026-08-31 weekly 0.85 + + + https://www.nqtcoder.dev/aptitude + 2026-08-31 + weekly + 0.85 + + https://www.nqtcoder.dev/leaderboard - 2026-07-01 + 2026-08-31 daily 0.8 @@ -90,23 +186,7 @@ https://www.nqtcoder.dev/tracks - 2026-07-01 - weekly - 0.8 - - - - - https://www.nqtcoder.dev/aptitude - 2026-07-01 - weekly - 0.8 - - - - - https://www.nqtcoder.dev/mocktest - 2026-07-01 + 2026-08-31 weekly 0.8 @@ -114,7 +194,7 @@ https://www.nqtcoder.dev/resources - 2026-07-01 + 2026-08-31 weekly 0.7 @@ -122,7 +202,7 @@ https://www.nqtcoder.dev/compiler-setup - 2026-07-01 + 2026-08-31 monthly 0.7 @@ -130,15 +210,15 @@ https://www.nqtcoder.dev/about - 2026-07-01 + 2026-08-31 monthly 0.6 - + https://www.nqtcoder.dev/contact - 2026-07-01 + 2026-08-31 monthly 0.6 @@ -146,7 +226,7 @@ https://www.nqtcoder.dev/privacy - 2026-07-01 + 2026-08-31 monthly 0.4 @@ -154,7 +234,7 @@ https://www.nqtcoder.dev/terms - 2026-07-01 + 2026-08-31 monthly 0.4 diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 076d8da..184bff7 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -50,6 +50,9 @@ import AdminCompanyGuidePreview from './pages/AdminCompanyGuidePreview'; import GamesHub from './pages/games/GamesHub'; import GameDetails from './pages/games/GameDetails'; import GameArena from './pages/games/GameArena'; +import WebDevHub from './pages/webdev/WebDevHub'; +import WebDevArena from './pages/webdev/WebDevArena'; +import AdminWebDevForm from './pages/webdev/AdminWebDevForm'; const UnverifiedBanner = () => { const { user, resendCode } = useContext(AuthContext); @@ -151,6 +154,8 @@ const AppContent = () => { } /> } /> } /> + } /> + } /> } /> } /> } /> @@ -318,6 +323,22 @@ const AppContent = () => { } /> + + + + } + /> + + + + } + /> {/* Fallback to NotFound */} } /> diff --git a/frontend/src/components/Navbar.jsx b/frontend/src/components/Navbar.jsx index cc93221..0888949 100644 --- a/frontend/src/components/Navbar.jsx +++ b/frontend/src/components/Navbar.jsx @@ -78,6 +78,12 @@ const Navbar = () => { > Practice + + Web Dev + { > Practice + setMobileMenuOpen(false)} + className={`p-2 rounded hover:bg-darkBg/60 transition-colors ${isActive('/web-development') ? 'text-accentBlue' : 'text-slate-300'}`} + > + Web Dev + setMobileMenuOpen(false)} diff --git a/frontend/src/components/webdev/WebDevPreviewFrame.jsx b/frontend/src/components/webdev/WebDevPreviewFrame.jsx new file mode 100644 index 0000000..ca2f260 --- /dev/null +++ b/frontend/src/components/webdev/WebDevPreviewFrame.jsx @@ -0,0 +1,197 @@ +import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react'; +import { buildSandboxedIframeDoc } from '../../utils/webDevEvaluator'; +import { RefreshCw, Monitor, Tablet, Smartphone, Sparkles, Terminal } from 'lucide-react'; + +const WebDevPreviewFrame = forwardRef( + ( + { + html = '', + css = '', + javascript = '', + tests = [], + onConsoleLog, + onTestResults, + className = '', + }, + ref + ) => { + const iframeRef = useRef(null); + const [viewport, setViewport] = useState('desktop'); // 'desktop' | 'tablet' | 'mobile' + const [iframeKey, setIframeKey] = useState(0); + const [isRunningTests, setIsRunningTests] = useState(false); + const [isIframeReady, setIsIframeReady] = useState(false); + + // Build the sandboxed HTML document + const srcDoc = React.useMemo(() => { + return buildSandboxedIframeDoc({ html, css, javascript, tests }); + }, [html, css, javascript, tests, iframeKey]); + + // Handle postMessage communication from the iframe + useEffect(() => { + const handleMessage = (event) => { + const data = event.data; + if (!data || typeof data !== 'object') return; + + if (data.type === 'NQT_IFRAME_READY') { + setIsIframeReady(true); + } else if (data.type === 'NQT_CONSOLE_LOG') { + if (onConsoleLog) onConsoleLog(data.payload); + } else if (data.type === 'NQT_TEST_RESULTS') { + setIsRunningTests(false); + if (onTestResults) onTestResults(data.payload); + } + }; + + window.addEventListener('message', handleMessage); + return () => window.removeEventListener('message', handleMessage); + }, [onConsoleLog, onTestResults]); + + // Expose runTests method to parent components (Arena, Admin Form) + useImperativeHandle(ref, () => ({ + runTests: (customTests = null) => { + if (!iframeRef.current || !iframeRef.current.contentWindow) return; + + setIsRunningTests(true); + const testSuite = customTests || tests; + + // Post run command to iframe + iframeRef.current.contentWindow.postMessage( + { + type: 'NQT_RUN_TESTS', + tests: testSuite, + }, + '*' + ); + + // Watchdog timeout: in case student code enters infinite loop or hangs + setTimeout(() => { + setIsRunningTests((prev) => { + if (prev) { + if (onTestResults) { + onTestResults({ + testResults: testSuite.map((t) => ({ + testId: t.id, + description: t.description, + passed: false, + points: t.points, + earnedPoints: 0, + failureMessage: 'Test execution timed out (possible infinite loop or script error)', + })), + passedCount: 0, + totalCount: testSuite.length, + pointsEarned: 0, + totalPoints: testSuite.reduce((acc, t) => acc + (t.points || 0), 0), + score: 0, + }); + } + return false; + } + return false; + }); + }, 4000); + }, + reloadPreview: () => { + setIframeKey((prev) => prev + 1); + }, + })); + + const getViewportWidth = () => { + switch (viewport) { + case 'tablet': + return '768px'; + case 'mobile': + return '375px'; + default: + return '100%'; + } + }; + + return ( +
    + {/* Preview Top Control Bar */} +
    +
    + + + Live Sandbox Preview + +
    + + {/* Viewport Width Controls */} +
    + + + +
    + + {/* Refresh Action */} + +
    + + {/* Sandboxed Iframe Container */} +
    +
    +