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
+
+
+ -
+ Reset
+ +
+
+
+
+`,
+ 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
+
+
+ -
+ Reset
+ +
+
+
+
+`,
+ 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
+
+
+
+
+`,
+ 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
+
+
+
+
+`,
+ 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
+
+
+
+ Add Task
+
+
+
+
+
+`,
+ 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
+
+
+
+ Add Task
+
+
+
+
+
+`,
+ 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
+
+
+
Generate New Palette
+
+
+`,
+ 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
+
+
+
Generate New Palette
+
+
+`,
+ 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
+
+ ★
+ ★
+ ★
+ ★
+ ★
+
+
Select a rating
+
+
+`,
+ 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
+
+ ★
+ ★
+ ★
+ ★
+ ★
+
+
Select a rating
+
+
+`,
+ 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: 'Toggle ',
+ css: '.active { background: blue; }',
+ javascript: '// logic',
+ },
+ solutionCode: {
+ html: 'Toggle ',
+ 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: 'Toggle Me ',
+ 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: 'Toggle ',
+ 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: 'Toggle ',
+ 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 */}
+
+
setViewport('desktop')}
+ title="Desktop (100%)"
+ className={`p-1.5 rounded-lg transition-colors cursor-pointer ${
+ viewport === 'desktop'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+
+
setViewport('tablet')}
+ title="Tablet (768px)"
+ className={`p-1.5 rounded-lg transition-colors cursor-pointer ${
+ viewport === 'tablet'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+
+
setViewport('mobile')}
+ title="Mobile (375px)"
+ className={`p-1.5 rounded-lg transition-colors cursor-pointer ${
+ viewport === 'mobile'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+
+
+
+ {/* Refresh Action */}
+
setIframeKey((k) => k + 1)}
+ title="Reload Preview"
+ className="p-1.5 rounded-xl border border-darkBorder hover:border-slate-600 text-slate-400 hover:text-white transition-colors cursor-pointer"
+ >
+
+
+
+
+ {/* Sandboxed Iframe Container */}
+
+
+ );
+ }
+);
+
+WebDevPreviewFrame.displayName = 'WebDevPreviewFrame';
+
+export default WebDevPreviewFrame;
diff --git a/frontend/src/components/webdev/WebDevTestResults.jsx b/frontend/src/components/webdev/WebDevTestResults.jsx
new file mode 100644
index 0000000..1ce0a36
--- /dev/null
+++ b/frontend/src/components/webdev/WebDevTestResults.jsx
@@ -0,0 +1,214 @@
+import React, { useState } from 'react';
+import { CheckCircle2, XCircle, Terminal, Award, AlertCircle, ShieldCheck, Sparkles } from 'lucide-react';
+
+const WebDevTestResults = ({ results, consoleLogs = [], isRunning = false, onRunAgain }) => {
+ const [activeTab, setActiveTab] = useState('tests'); // 'tests' | 'console'
+
+ if (isRunning) {
+ return (
+
+
+
+
+
Evaluating Behavioral Tests...
+
+ Simulating user clicks, inputs, and validating computed DOM styles inside the sandbox.
+
+
+ );
+ }
+
+ if (!results) {
+ return (
+
+
+
+
+
No Tests Run Yet
+
+ Click Run Tests to evaluate your HTML, CSS, and JavaScript implementation against the behavioral test suite.
+
+ {onRunAgain && (
+
+ Run Tests Now
+
+ )}
+
+ );
+ }
+
+ const {
+ testResults = [],
+ passedCount = 0,
+ totalCount = 0,
+ pointsEarned = 0,
+ totalPoints = 100,
+ score = 0,
+ } = results;
+
+ const isAllPassed = score === 100;
+
+ return (
+
+ {/* Header Tabs */}
+
+
+ setActiveTab('tests')}
+ className={`px-3 py-1.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer ${
+ activeTab === 'tests'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+ Test Results ({passedCount}/{totalCount})
+
+ setActiveTab('console')}
+ className={`px-3 py-1.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer flex items-center space-x-1.5 ${
+ activeTab === 'console'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+ Console Logs ({consoleLogs.length})
+
+
+
+ {/* Score Pill */}
+
0
+ ? 'bg-amber-500/10 text-amber-300 border-amber-500/20'
+ : 'bg-rose-500/10 text-rose-400 border-rose-500/20'
+ }`}
+ >
+
+
+ {score}% ({pointsEarned}/{totalPoints} pts)
+
+
+
+
+ {/* Main Tab Content */}
+
+ {activeTab === 'tests' ? (
+ <>
+ {/* Top Score Banner */}
+
0
+ ? 'bg-amber-500/10 border-amber-500/25 text-amber-300'
+ : 'bg-rose-500/10 border-rose-500/25 text-rose-300'
+ }`}
+ >
+
+ {isAllPassed ? (
+
+ ) : (
+
+ )}
+
+
+ {isAllPassed
+ ? 'All Behavioral Tests Passed!'
+ : `${passedCount} of ${totalCount} Tests Passed`}
+
+
+ {isAllPassed
+ ? 'Your implementation satisfies all functional requirements.'
+ : 'Review the failed test descriptions below to complete your solution.'}
+
+
+
+
+
+ {score}
+ / 100
+
+
+
+ {/* Test Cards List */}
+
+ {testResults.map((test, idx) => (
+
+
+
+ {test.passed ? (
+
+ ) : (
+
+ )}
+
+ {test.description}
+
+
+
+
+ {test.passed ? `+${test.points} pts` : `0/${test.points} pts`}
+
+
+
+ {!test.passed && test.failureMessage && (
+
+ {test.failureMessage}
+
+ )}
+
+ ))}
+
+ >
+ ) : (
+ /* Console Tab */
+
+ {consoleLogs.length === 0 ? (
+
No console outputs recorded. Use console.log() in your code to debug.
+ ) : (
+ consoleLogs.map((log, i) => (
+
+ [{log.level.toUpperCase()}]
+ {log.message}
+
+ ))
+ )}
+
+ )}
+
+
+ );
+};
+
+export default WebDevTestResults;
diff --git a/frontend/src/pages/AdminDashboard.jsx b/frontend/src/pages/AdminDashboard.jsx
index 3920fce..60c674f 100644
--- a/frontend/src/pages/AdminDashboard.jsx
+++ b/frontend/src/pages/AdminDashboard.jsx
@@ -5,13 +5,14 @@ import * as trackService from '../services/trackService';
import * as feedbackService from '../services/feedbackService';
import * as resourceService from '../services/resourceService';
import * as testimonialService from '../services/testimonialService';
+import * as webDevService from '../services/webDevService';
import AdminQuestionForm from './AdminQuestionForm';
import {
Plus, Edit2, Trash2, ShieldAlert, Award, Tag, Settings,
Users, BookOpen, Send, Activity, LayoutDashboard, ChevronRight,
Compass, Calendar, ExternalLink, MessageSquare, Bug, Check,
Database, Server, Network, Layers, FileText, FolderOpen, Link2, Building2,
- Star, ThumbsUp, Eye, EyeOff, ShieldCheck, Filter, Search
+ Star, ThumbsUp, Eye, EyeOff, ShieldCheck, Filter, Search, Code, Globe
} from 'lucide-react';
import SEO from '../components/SEO';
@@ -20,7 +21,7 @@ const AdminDashboard = () => {
const [questions, setQuestions] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
- const [activeTab, setActiveTab] = useState('overview'); // 'overview', 'questions', 'add_question', 'manage_tracks', 'feedback', 'testimonials'
+ const [activeTab, setActiveTab] = useState('overview'); // 'overview', 'questions', 'add_question', 'manage_tracks', 'feedback', 'testimonials', 'web_dev'
const [editQuestionId, setEditQuestionId] = useState(null);
// Feedback Management States
@@ -37,6 +38,14 @@ const AdminDashboard = () => {
const [testimonialFilter, setTestimonialFilter] = useState('all'); // 'all', 'pending', 'approved', 'rejected', 'hidden'
const [testimonialSearch, setTestimonialSearch] = useState('');
const [adminNotes, setAdminNotes] = useState({});
+
+ // Web Development Management States
+ const [webDevQuestions, setWebDevQuestions] = useState([]);
+ const [webDevStats, setWebDevStats] = useState({ totalCount: 0, publishedCount: 0, draftCount: 0, archivedCount: 0 });
+ const [webDevLoading, setWebDevLoading] = useState(false);
+ const [webDevError, setWebDevError] = useState('');
+ const [webDevFilter, setWebDevFilter] = useState('all');
+ const [webDevSearch, setWebDevSearch] = useState('');
// Track Management States
const [tracks, setTracks] = useState([]);
@@ -249,6 +258,43 @@ const AdminDashboard = () => {
}
};
+ const fetchAdminWebDevQuestions = async (status = webDevFilter, search = webDevSearch) => {
+ setWebDevLoading(true);
+ setWebDevError('');
+ try {
+ const data = await webDevService.getAdminWebDevQuestions({ status, search });
+ setWebDevQuestions(data.questions || []);
+ if (data.stats) setWebDevStats(data.stats);
+ } catch (err) {
+ console.error(err);
+ setWebDevError('Could not retrieve web development challenges.');
+ } finally {
+ setWebDevLoading(false);
+ }
+ };
+
+ const handleToggleWebDevStatus = async (id, newStatus) => {
+ try {
+ await webDevService.updateAdminWebDevQuestion(id, { status: newStatus });
+ fetchAdminWebDevQuestions(webDevFilter, webDevSearch);
+ } catch (err) {
+ console.error(err);
+ alert('Failed to update challenge status.');
+ }
+ };
+
+ const handleDeleteWebDevQuestion = async (id) => {
+ if (window.confirm('Are you sure you want to delete this Web Dev Challenge and all student submissions?')) {
+ try {
+ await webDevService.deleteAdminWebDevQuestion(id);
+ fetchAdminWebDevQuestions(webDevFilter, webDevSearch);
+ } catch (err) {
+ console.error(err);
+ alert('Failed to delete challenge.');
+ }
+ }
+ };
+
const renderAreaChart = () => {
const trend = stats.userRegistrationTrend || [];
if (!trend.length) {
@@ -678,6 +724,25 @@ const AdminDashboard = () => {
+ {
+ setEditQuestionId(null);
+ setActiveTab('web_dev');
+ fetchAdminWebDevQuestions();
+ }}
+ className={`w-full flex items-center justify-between px-4 py-3 rounded-xl text-xs font-black tracking-wider uppercase transition-all border ${
+ activeTab === 'web_dev'
+ ? 'bg-accentBlue border-accentBlue text-white shadow-lg shadow-accentBlue/20'
+ : 'bg-transparent border-transparent text-slate-400 hover:text-slate-200 hover:bg-darkBg/60'
+ }`}
+ >
+
+
+ Web Development
+
+
+
+
{
setEditQuestionId(null);
@@ -1720,6 +1785,199 @@ const AdminDashboard = () => {
)}
+ {/* VIEW 5.7: Web Development Practical Challenges */}
+ {activeTab === 'web_dev' && (
+
+ {/* Header */}
+
+
+
Web Development Challenges
+
Manage HTML, CSS & JavaScript practical tasks, starter templates, and test suites
+
+
+
navigate('/admin/web-dev/new')}
+ className="bg-accentBtn hover:bg-accentBtnHover text-white px-5 py-2.5 rounded-xl text-xs font-black uppercase tracking-wider flex items-center space-x-2 shadow-lg shadow-accentBtn/20 transition-all self-start md:self-auto cursor-pointer"
+ >
+
+ Add Web Dev Challenge
+
+
+
+ {/* Quick Metrics */}
+
+
+ Total Challenges
+ {webDevStats.totalCount}
+
+
+ Published Live
+ {webDevStats.publishedCount}
+
+
+ Drafts
+ {webDevStats.draftCount}
+
+
+ Archived
+ {webDevStats.archivedCount}
+
+
+
+ {/* Filter Bar & Search */}
+
+
+
+ Filter:
+
+ {['all', 'published', 'draft', 'archived'].map((f) => (
+ {
+ setWebDevFilter(f);
+ fetchAdminWebDevQuestions(f, webDevSearch);
+ }}
+ className={`px-3 py-1.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-all cursor-pointer ${
+ webDevFilter === f
+ ? 'bg-accentBlue text-white shadow-md shadow-accentBlue/20'
+ : 'bg-darkBg text-slate-400 hover:text-slate-200 border border-darkBorder'
+ }`}
+ >
+ {f}
+
+ ))}
+
+
+
+ {
+ setWebDevSearch(e.target.value);
+ fetchAdminWebDevQuestions(webDevFilter, e.target.value);
+ }}
+ className="w-full bg-darkBg border border-darkBorder px-3.5 py-1.5 pl-8 rounded-xl text-xs focus:outline-none focus:border-accentBlue text-slate-200"
+ />
+
+
+
+
+ {webDevError && (
+
+ {webDevError}
+
+ )}
+
+ {webDevLoading ? (
+
+
+
Loading challenges...
+
+ ) : webDevQuestions.length === 0 ? (
+
+
+
No Web Dev Challenges Found
+
Click "Add Web Dev Challenge" to create your first practical task.
+
+ ) : (
+
+ {webDevQuestions.map((q) => (
+
+
+
+
+ {q.difficulty}
+
+
+
+ {q.category}
+
+
+
v{q.version || 1}
+
+
+ handleToggleWebDevStatus(q._id, e.target.value)}
+ className={`text-[9px] font-black uppercase tracking-widest px-2.5 py-0.5 rounded border cursor-pointer focus:outline-none appearance-none pr-5 ${
+ q.status === 'published'
+ ? 'text-emerald-400 border-emerald-500/25 bg-emerald-500/10'
+ : q.status === 'draft'
+ ? 'text-amber-400 border-amber-500/25 bg-amber-500/10'
+ : 'text-slate-400 border-slate-500/25 bg-slate-500/10'
+ }`}
+ >
+ Published
+ Draft
+ Archived
+
+ ▾
+
+
+
+
+
{q.title}
+
slug: {q.slug}
+
+
+
+ {q.tests?.length || 0} Tests
+ •
+ {q.points || 100} Points
+ •
+ {q.requirements?.length || 0} Requirements
+
+
+
+ {/* Actions */}
+
+
+
+ Preview
+
+
+ navigate(`/admin/web-dev/edit/${q._id}`)}
+ className="px-3 py-1.5 bg-accentBlue/10 hover:bg-accentBlue/20 text-accentBlue border border-accentBlue/20 rounded-xl text-xs font-bold uppercase tracking-wider flex items-center space-x-1 transition-all cursor-pointer"
+ >
+
+ Edit
+
+
+ handleDeleteWebDevQuestion(q._id)}
+ className="p-2 text-rose-400 hover:bg-rose-500/10 rounded-xl border border-transparent hover:border-rose-500/20 transition-all cursor-pointer"
+ title="Delete Challenge"
+ >
+
+
+
+
+ ))}
+
+ )}
+
+ )}
+
{/* VIEW 6: Manage Resources */}
{activeTab === 'manage_resources' && (
diff --git a/frontend/src/pages/Home.jsx b/frontend/src/pages/Home.jsx
index 1f1a52d..8149db8 100644
--- a/frontend/src/pages/Home.jsx
+++ b/frontend/src/pages/Home.jsx
@@ -73,6 +73,24 @@ const faqs = [
}
]
},
+ {
+ category: 'Web Development Practice',
+ color: 'text-accentBlue',
+ items: [
+ {
+ q: 'Does NQTCoder offer HTML, CSS, and JavaScript practical assessments?',
+ a: 'Yes! Our Web Development Practice Arena offers interactive, multi-file frontend coding challenges designed specifically for Cognizant, TCS, and product company practical assessments. You can write HTML, CSS, and JavaScript in dedicated Monaco editors with real-time sandbox preview.'
+ },
+ {
+ q: 'How are Web Development coding challenges evaluated?',
+ a: 'Evaluations are behavioral and test-driven. Our engine simulates genuine user clicks, form submissions, and keyboard events inside an isolated sandbox, checking DOM structure and computed styles to award instant, automated scores.'
+ },
+ {
+ q: 'Do I need to manually attach CSS and JS files in HTML?',
+ a: 'No. The platform automatically injects your CSS into the and your JavaScript at the end of the inside the sandboxed preview, so you can focus purely on coding UI components.'
+ }
+ ]
+ },
{
category: 'Code Execution',
color: 'text-accentBlue',
@@ -582,10 +600,10 @@ const Home = () => {
{/* ── SEO ──────────────────────────────────────────────────────────── */}
{
-
+
{/* Card 1: All Roadmaps */}
@@ -870,6 +888,34 @@ const Home = () => {
+
+ {/* Card 4: Web Dev Practice Arena */}
+
+
+
+
+
+
+
Web Development
+
+ Solve HTML, CSS & JavaScript practical assessments with live sandbox preview & behavioral tests.
+
+
+
+ ⚡ Frontend Sandbox
+
+
+
+
+
+
+ Practice Web Dev
+
+
+
diff --git a/frontend/src/pages/webdev/AdminWebDevForm.jsx b/frontend/src/pages/webdev/AdminWebDevForm.jsx
new file mode 100644
index 0000000..2c4729f
--- /dev/null
+++ b/frontend/src/pages/webdev/AdminWebDevForm.jsx
@@ -0,0 +1,817 @@
+import React, { useState, useEffect, useRef } from 'react';
+import { useParams, useNavigate, Link } from 'react-router-dom';
+import Editor from '@monaco-editor/react';
+import {
+ getAdminWebDevQuestion,
+ createAdminWebDevQuestion,
+ updateAdminWebDevQuestion,
+} from '../../services/webDevService';
+import WebDevPreviewFrame from '../../components/webdev/WebDevPreviewFrame';
+import {
+ ChevronLeft,
+ Plus,
+ Trash2,
+ Save,
+ CheckCircle2,
+ AlertCircle,
+ Play,
+ Award,
+ Sparkles,
+ Layers,
+ Code,
+ ShieldAlert,
+} from 'lucide-react';
+import SEO from '../../components/SEO';
+
+const AdminWebDevForm = () => {
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const isEdit = Boolean(id);
+
+ // Metadata
+ const [title, setTitle] = useState('');
+ const [slug, setSlug] = useState('');
+ const [difficulty, setDifficulty] = useState('easy');
+ const [category, setCategory] = useState('javascript');
+ const [description, setDescription] = useState('');
+ const [timeLimit, setTimeLimit] = useState(20);
+ const [status, setStatus] = useState('published');
+ const [tags, setTags] = useState('');
+ const [requirements, setRequirements] = useState(['']);
+
+ // Starter Code
+ const [starterHtml, setStarterHtml] = useState('');
+ const [starterCss, setStarterCss] = useState('');
+ const [starterJs, setStarterJs] = useState('');
+ const [activeStarterTab, setActiveStarterTab] = useState('javascript');
+
+ // Solution Code
+ const [solutionHtml, setSolutionHtml] = useState('');
+ const [solutionCss, setSolutionCss] = useState('');
+ const [solutionJs, setSolutionJs] = useState('');
+ const [activeSolutionTab, setActiveSolutionTab] = useState('javascript');
+
+ // Tests
+ const [tests, setTests] = useState([
+ {
+ id: 'test_1',
+ description: 'Element exists in DOM',
+ failureMessage: 'Target element was not found in DOM',
+ points: 50,
+ type: 'dom',
+ target: '#root',
+ assertion: { type: 'exists', expected: '' },
+ },
+ ]);
+
+ // Validation / Test runner state
+ const [isValidating, setIsValidating] = useState(false);
+ const [validationResults, setValidationResults] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState('');
+ const [success, setSuccess] = useState('');
+
+ const validatorPreviewRef = useRef(null);
+
+ useEffect(() => {
+ if (isEdit) {
+ fetchQuestionDetails();
+ }
+ }, [id]);
+
+ const fetchQuestionDetails = async () => {
+ setLoading(true);
+ setError('');
+ try {
+ const res = await getAdminWebDevQuestion(id);
+ const q = res.question;
+ setTitle(q.title || '');
+ setSlug(q.slug || '');
+ setDifficulty(q.difficulty || 'easy');
+ setCategory(q.category || 'javascript');
+ setDescription(q.description || '');
+ setTimeLimit(q.timeLimit || 20);
+ setStatus(q.status || 'published');
+ setTags((q.tags || []).join(', '));
+ setRequirements(q.requirements?.length ? q.requirements : ['']);
+
+ setStarterHtml(q.starterCode?.html || '');
+ setStarterCss(q.starterCode?.css || '');
+ setStarterJs(q.starterCode?.javascript || '');
+
+ setSolutionHtml(q.solutionCode?.html || '');
+ setSolutionCss(q.solutionCode?.css || '');
+ setSolutionJs(q.solutionCode?.javascript || '');
+
+ setTests(q.tests?.length ? q.tests : []);
+ } catch (err) {
+ console.error(err);
+ setError('Failed to fetch question details for editing.');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleAddRequirement = () => {
+ setRequirements((prev) => [...prev, '']);
+ };
+
+ const handleUpdateRequirement = (index, value) => {
+ setRequirements((prev) => {
+ const copy = [...prev];
+ copy[index] = value;
+ return copy;
+ });
+ };
+
+ const handleRemoveRequirement = (index) => {
+ setRequirements((prev) => prev.filter((_, i) => i !== index));
+ };
+
+ const handleAddTest = () => {
+ const newId = `test_${Date.now()}`;
+ setTests((prev) => [
+ ...prev,
+ {
+ id: newId,
+ description: 'New behavioral check',
+ failureMessage: 'Check failed',
+ points: 25,
+ type: 'dom',
+ target: '#target',
+ assertion: { type: 'exists', expected: '' },
+ },
+ ]);
+ };
+
+ const handleUpdateTest = (index, field, value) => {
+ setTests((prev) => {
+ const copy = [...prev];
+ copy[index] = { ...copy[index], [field]: value };
+ return copy;
+ });
+ };
+
+ const handleUpdateTestAssertion = (index, field, value) => {
+ setTests((prev) => {
+ const copy = [...prev];
+ copy[index] = {
+ ...copy[index],
+ assertion: { ...(copy[index].assertion || {}), [field]: value },
+ };
+ return copy;
+ });
+ };
+
+ const handleRemoveTest = (index) => {
+ setTests((prev) => prev.filter((_, i) => i !== index));
+ };
+
+ // Run the Reference Solution through the Test Evaluator inside the preview frame
+ const handleValidateChallenge = () => {
+ if (!validatorPreviewRef.current) return;
+ setIsValidating(true);
+ setValidationResults(null);
+ validatorPreviewRef.current.runTests(tests);
+ };
+
+ const handleValidationResults = (results) => {
+ setIsValidating(false);
+ setValidationResults(results);
+ };
+
+ const totalTestPoints = tests.reduce((acc, t) => acc + (Number(t.points) || 0), 0);
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ if (!title.trim()) {
+ setError('Title is required');
+ return;
+ }
+ if (!description.trim()) {
+ setError('Description is required');
+ return;
+ }
+ if (!tests.length) {
+ setError('At least one evaluation test is required');
+ return;
+ }
+
+ setLoading(true);
+ setError('');
+ setSuccess('');
+
+ try {
+ const payload = {
+ title: title.trim(),
+ slug: slug.trim() || undefined,
+ difficulty,
+ category,
+ description: description.trim(),
+ requirements: requirements.filter(Boolean),
+ starterCode: {
+ html: starterHtml,
+ css: starterCss,
+ javascript: starterJs,
+ },
+ solutionCode: {
+ html: solutionHtml,
+ css: solutionCss,
+ javascript: solutionJs,
+ },
+ tests,
+ points: totalTestPoints || 100,
+ timeLimit: Number(timeLimit) || 20,
+ status,
+ tags: tags
+ .split(',')
+ .map((t) => t.trim().toLowerCase())
+ .filter(Boolean),
+ };
+
+ if (isEdit) {
+ await updateAdminWebDevQuestion(id, payload);
+ setSuccess('Question updated successfully!');
+ } else {
+ await createAdminWebDevQuestion(payload);
+ setSuccess('Question created successfully!');
+ }
+
+ setTimeout(() => {
+ navigate('/admin');
+ }, 1200);
+ } catch (err) {
+ console.error(err);
+ setError(err.response?.data?.message || 'Error saving question.');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+
+
+
+
+ {/* Top Header */}
+
+
+
+
+
+
+
+ {isEdit ? 'Edit Web Dev Challenge' : 'Create Web Dev Challenge'}
+
+
+ Configure starter code, solution code, and behavioral test assertions
+
+
+
+
+
+
+ {loading ? 'Saving...' : isEdit ? 'Update Challenge' : 'Publish Challenge'}
+
+
+
+ {error && (
+
+ )}
+
+ {success && (
+
+
+ {success}
+
+ )}
+
+ {/* ── Section 1: Challenge Metadata ───────────────────────────────────── */}
+
+
+
+ Challenge Metadata
+
+
+
+
+
+
+
+ Difficulty
+
+ setDifficulty(e.target.value)}
+ className="w-full bg-darkBg border border-darkBorder px-3.5 py-2.5 rounded-xl text-xs focus:outline-none focus:border-accentBlue text-slate-200"
+ >
+ Easy
+ Medium
+ Hard
+
+
+
+
+
+ Category
+
+ setCategory(e.target.value)}
+ className="w-full bg-darkBg border border-darkBorder px-3.5 py-2.5 rounded-xl text-xs focus:outline-none focus:border-accentBlue text-slate-200"
+ >
+ JavaScript
+ HTML & CSS
+ Full Stack Frontend
+ HTML Only
+ CSS Only
+
+
+
+
+
+ Time Limit (Mins)
+
+ setTimeLimit(e.target.value)}
+ className="w-full bg-darkBg border border-darkBorder px-3.5 py-2.5 rounded-xl text-xs focus:outline-none focus:border-accentBlue text-slate-200"
+ />
+
+
+
+
+ Status
+
+ setStatus(e.target.value)}
+ className="w-full bg-darkBg border border-darkBorder px-3.5 py-2.5 rounded-xl text-xs focus:outline-none focus:border-accentBlue text-slate-200"
+ >
+ Published
+ Draft
+ Archived
+
+
+
+
+
+
+ Problem Description *
+
+
+
+
+
+ Tags (Comma separated)
+
+ setTags(e.target.value)}
+ placeholder="dom, events, forms, validation"
+ className="w-full bg-darkBg border border-darkBorder px-3.5 py-2.5 rounded-xl text-xs focus:outline-none focus:border-accentBlue text-slate-200"
+ />
+
+
+
+ {/* ── Section 2: Requirements Checklist Builder ───────────────────────── */}
+
+
+
+ Student Requirements Checklist
+
+
+
+ Add Requirement
+
+
+
+
+ {requirements.map((req, idx) => (
+
+ handleUpdateRequirement(idx, e.target.value)}
+ placeholder={`Requirement #${idx + 1} (e.g. Counter must start at 0)`}
+ className="flex-1 bg-darkBg border border-darkBorder px-3.5 py-2 rounded-xl text-xs focus:outline-none focus:border-accentBlue text-slate-200"
+ />
+ handleRemoveRequirement(idx)}
+ className="p-2 text-rose-400 hover:bg-rose-500/10 rounded-xl transition-colors cursor-pointer"
+ >
+
+
+
+ ))}
+
+
+
+ {/* ── Section 3: Starter Code (3 Files) ────────────────────────────────── */}
+
+
+
+
+ Starter Code (Given to Students)
+
+
+ Define the starter templates for HTML, CSS, and JavaScript
+
+
+
+
+ {['html', 'css', 'javascript'].map((tab) => (
+ setActiveStarterTab(tab)}
+ className={`px-3 py-1 rounded-lg text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer ${
+ activeStarterTab === tab
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+ {tab.toUpperCase()}
+
+ ))}
+
+
+
+
+ {
+ if (activeStarterTab === 'javascript') setStarterJs(val || '');
+ else if (activeStarterTab === 'css') setStarterCss(val || '');
+ else setStarterHtml(val || '');
+ }}
+ options={{
+ fontSize: 13,
+ fontFamily: 'JetBrains Mono, monospace',
+ minimap: { enabled: false },
+ automaticLayout: true,
+ tabSize: 2,
+ }}
+ />
+
+
+
+ {/* ── Section 4: Reference Solution Code (Private for Validation) ─────── */}
+
+
+
+
+
+ Reference Solution Code (Hidden from Students)
+
+
+ Used by the pre-publish validator to verify tests pass 100%
+
+
+
+
+ {['html', 'css', 'javascript'].map((tab) => (
+ setActiveSolutionTab(tab)}
+ className={`px-3 py-1 rounded-lg text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer ${
+ activeSolutionTab === tab
+ ? 'bg-emerald-600 text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+ {tab.toUpperCase()}
+
+ ))}
+
+
+
+
+ {
+ if (activeSolutionTab === 'javascript') setSolutionJs(val || '');
+ else if (activeSolutionTab === 'css') setSolutionCss(val || '');
+ else setSolutionHtml(val || '');
+ }}
+ options={{
+ fontSize: 13,
+ fontFamily: 'JetBrains Mono, monospace',
+ minimap: { enabled: false },
+ automaticLayout: true,
+ tabSize: 2,
+ }}
+ />
+
+
+
+ {/* ── Section 5: Behavioral Test Suite Builder ────────────────────────── */}
+
+
+
+
+ Behavioral Test Suite (Total Points: {totalTestPoints})
+
+
+ Define DOM checks, user clicks, input events, and computed CSS assertions
+
+
+
+
+
+ Add Test
+
+
+
+
+ {tests.map((t, idx) => (
+
+
+
+ Test #{idx + 1} ({t.points || 20} pts)
+
+ handleRemoveTest(idx)}
+ className="text-rose-400 hover:text-rose-300 transition-colors cursor-pointer"
+ >
+
+
+
+
+
+
+
+ Description (Shown to Student)
+
+ handleUpdateTest(idx, 'description', e.target.value)}
+ placeholder="e.g. Counter starts at 0"
+ className="w-full bg-darkCard border border-darkBorder px-3 py-1.5 rounded-lg text-xs text-slate-200"
+ />
+
+
+
+
+ Test Type
+
+ handleUpdateTest(idx, 'type', e.target.value)}
+ className="w-full bg-darkCard border border-darkBorder px-3 py-1.5 rounded-lg text-xs text-slate-200"
+ >
+ DOM Check
+ User Click
+ User Input
+ Keyboard Press
+ Computed CSS
+ Element Count
+
+
+
+
+ Points
+ handleUpdateTest(idx, 'points', Number(e.target.value))}
+ className="w-full bg-darkCard border border-darkBorder px-3 py-1.5 rounded-lg text-xs text-slate-200"
+ />
+
+
+
+
+
+
+ Target Selector
+
+ handleUpdateTest(idx, 'target', e.target.value)}
+ placeholder="#count, button:contains('Add')"
+ className="w-full bg-darkCard border border-darkBorder px-3 py-1.5 rounded-lg text-xs text-slate-200 font-mono"
+ />
+
+
+
+
+ Assertion Type
+
+ handleUpdateTestAssertion(idx, 'type', e.target.value)}
+ className="w-full bg-darkCard border border-darkBorder px-3 py-1.5 rounded-lg text-xs text-slate-200"
+ >
+ Element Exists
+ Text Exactly Matches
+ Text Contains Snippet
+ Attribute Matches
+ Count Matches Number
+ Has CSS Class
+ Computed CSS Value
+
+
+
+
+
+ Expected Value
+
+ handleUpdateTestAssertion(idx, 'expected', e.target.value)}
+ placeholder="0, true, #38bdf8"
+ className="w-full bg-darkCard border border-darkBorder px-3 py-1.5 rounded-lg text-xs text-slate-200 font-mono"
+ />
+
+
+
+
+
+ Failure Message (Shown to student if failed)
+
+ handleUpdateTest(idx, 'failureMessage', e.target.value)}
+ placeholder="e.g. Counter did not start at 0"
+ className="w-full bg-darkCard border border-darkBorder px-3 py-1.5 rounded-lg text-xs text-slate-200"
+ />
+
+
+ ))}
+
+
+
+ {/* ── Section 6: "Validate Challenge" Pre-Publish Gate ───────────────── */}
+
+
+
+
+
+ Pre-Publish Challenge Validator
+
+
+ Test your reference solution against all tests before publishing to ensure 100% correctness
+
+
+
+
+
+ {isValidating ? 'Validating...' : 'Validate Challenge'}
+
+
+
+ {/* Validation Verdict Box */}
+ {validationResults && (
+
+
+ {validationResults.score === 100 ? (
+
+ ) : (
+
+ )}
+
+
+ {validationResults.score === 100
+ ? '✓ All Tests Passed! Ready to Publish.'
+ : `❌ Validation Failed: ${validationResults.passedCount}/${validationResults.totalCount} Tests Passed`}
+
+
+ {validationResults.score === 100
+ ? 'Reference solution satisfies all behavioral test assertions.'
+ : 'Fix failing tests or adjust reference solution before publishing.'}
+
+
+
+
{validationResults.score}%
+
+ )}
+
+ {/* Embedded Sandbox Runner Frame (For Reference Solution) */}
+
+
+
+
+
+
+ );
+};
+
+export default AdminWebDevForm;
diff --git a/frontend/src/pages/webdev/WebDevArena.jsx b/frontend/src/pages/webdev/WebDevArena.jsx
new file mode 100644
index 0000000..1f3500a
--- /dev/null
+++ b/frontend/src/pages/webdev/WebDevArena.jsx
@@ -0,0 +1,480 @@
+import React, { useState, useEffect, useContext, useRef } from 'react';
+import { useParams, useNavigate, Link } from 'react-router-dom';
+import Editor from '@monaco-editor/react';
+import { getPublicQuestionByIdOrSlug, submitWebDevSolution } from '../../services/webDevService';
+import { AuthContext } from '../../context/AuthContext';
+import WebDevPreviewFrame from '../../components/webdev/WebDevPreviewFrame';
+import WebDevTestResults from '../../components/webdev/WebDevTestResults';
+import AuthModal from '../../components/AuthModal';
+import {
+ Play,
+ Send,
+ ChevronLeft,
+ RotateCcw,
+ CheckCircle2,
+ Clock,
+ Code,
+ Layout,
+ Award,
+ Sparkles,
+ FileCode,
+ Check,
+ AlertCircle,
+ Eye,
+} from 'lucide-react';
+import SEO from '../../components/SEO';
+
+const WebDevArena = () => {
+ const { idOrSlug } = useParams();
+ const navigate = useNavigate();
+ const { user } = useContext(AuthContext);
+
+ const [question, setQuestion] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState('');
+
+ // Code state for 3 files
+ const [htmlCode, setHtmlCode] = useState('');
+ const [cssCode, setCssCode] = useState('');
+ const [javascriptCode, setJavascriptCode] = useState('');
+ const [activeFile, setActiveFile] = useState('javascript'); // 'html' | 'css' | 'javascript'
+
+ // Arena tabs
+ const [leftTab, setLeftTab] = useState('editor'); // 'description' | 'editor'
+ const [rightTab, setRightTab] = useState('preview'); // 'preview' | 'results'
+
+ // Evaluation & Results
+ const [testResults, setTestResults] = useState(null);
+ const [isEvaluating, setIsEvaluating] = useState(false);
+ const [consoleLogs, setConsoleLogs] = useState([]);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [submissionVerdict, setSubmissionVerdict] = useState(null);
+ const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
+
+ // Timer state
+ const [timeSpent, setTimeSpent] = useState(0);
+ const startTimeRef = useRef(Date.now());
+ const previewRef = useRef(null);
+
+ useEffect(() => {
+ fetchQuestion();
+ }, [idOrSlug]);
+
+ // Track time spent in arena
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setTimeSpent(Math.floor((Date.now() - startTimeRef.current) / 1000));
+ }, 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ const fetchQuestion = async () => {
+ setLoading(true);
+ setError('');
+ try {
+ const res = await getPublicQuestionByIdOrSlug(idOrSlug);
+ const q = res.question;
+ setQuestion(q);
+
+ // Load previous submission if user has one, otherwise load starter code
+ if (res.lastSubmission) {
+ setHtmlCode(res.lastSubmission.htmlCode || q.starterCode?.html || '');
+ setCssCode(res.lastSubmission.cssCode || q.starterCode?.css || '');
+ setJavascriptCode(res.lastSubmission.javascriptCode || q.starterCode?.javascript || '');
+ } else {
+ setHtmlCode(q.starterCode?.html || '');
+ setCssCode(q.starterCode?.css || '');
+ setJavascriptCode(q.starterCode?.javascript || '');
+ }
+
+ // Default active file
+ if (q.category === 'css') {
+ setActiveFile('css');
+ } else if (q.category === 'html') {
+ setActiveFile('html');
+ } else {
+ setActiveFile('javascript');
+ }
+ } catch (err) {
+ console.error('Error fetching question:', err);
+ setError('Could not load challenge details.');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleResetStarterCode = () => {
+ if (
+ window.confirm(
+ 'Are you sure you want to reset your code to the default starter template? All current changes will be overwritten.'
+ )
+ ) {
+ if (question?.starterCode) {
+ setHtmlCode(question.starterCode.html || '');
+ setCssCode(question.starterCode.css || '');
+ setJavascriptCode(question.starterCode.javascript || '');
+ }
+ setTestResults(null);
+ setConsoleLogs([]);
+ }
+ };
+
+ const handleConsoleLog = (log) => {
+ setConsoleLogs((prev) => [...prev.slice(-40), log]);
+ };
+
+ const handleRunTests = () => {
+ if (!previewRef.current) return;
+ setIsEvaluating(true);
+ setRightTab('results');
+ previewRef.current.runTests();
+ };
+
+ const handleTestResults = (results) => {
+ setIsEvaluating(false);
+ setTestResults(results);
+ };
+
+ const handleSubmitSolution = async () => {
+ if (!user) {
+ setIsAuthModalOpen(true);
+ return;
+ }
+
+ if (!previewRef.current) return;
+
+ setIsSubmitting(true);
+ setIsEvaluating(true);
+ setRightTab('results');
+
+ // Execute tests inside preview iframe
+ previewRef.current.runTests();
+
+ // Small delay to capture final test results payload
+ setTimeout(async () => {
+ try {
+ const payload = {
+ htmlCode,
+ cssCode,
+ javascriptCode,
+ testResults: testResults?.testResults || [],
+ timeSpent,
+ startedAt: new Date(startTimeRef.current),
+ };
+
+ const res = await submitWebDevSolution(question._id, payload);
+ setSubmissionVerdict(res.submission);
+ } catch (err) {
+ console.error('Error submitting solution:', err);
+ } finally {
+ setIsSubmitting(false);
+ setIsEvaluating(false);
+ }
+ }, 450);
+ };
+
+ const formatTimer = (seconds) => {
+ const mins = Math.floor(seconds / 60);
+ const secs = seconds % 60;
+ return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
+ };
+
+ if (loading) {
+ return (
+
+
+
+
Loading workspace...
+
+
+ );
+ }
+
+ if (error || !question) {
+ return (
+
+
+
+
Challenge Not Found
+
{error || 'Unable to locate this question.'}
+
+ Back to Arena
+
+
+
+ );
+ }
+
+ const currentCode =
+ activeFile === 'html' ? htmlCode : activeFile === 'css' ? cssCode : javascriptCode;
+ const currentLanguage =
+ activeFile === 'html' ? 'html' : activeFile === 'css' ? 'css' : 'javascript';
+
+ const handleEditorChange = (value) => {
+ if (activeFile === 'html') setHtmlCode(value || '');
+ else if (activeFile === 'css') setCssCode(value || '');
+ else setJavascriptCode(value || '');
+ };
+
+ return (
+
+
+
+ {/* ── Top Bar ────────────────────────────────────────────────────────── */}
+
+
+ {/* ── Main Two-Column Workspace ───────────────────────────────────────── */}
+
+ {/* ── Left Column: Problem & Monaco Editor ───────────────────────────── */}
+
+ {/* Top Panel Controls */}
+
+ {/* Left Tab Switcher (Problem vs Editor) */}
+
+ setLeftTab('editor')}
+ className={`px-3 py-1 rounded-lg text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer flex items-center space-x-1.5 ${
+ leftTab === 'editor'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+ Code Editor
+
+ setLeftTab('description')}
+ className={`px-3 py-1 rounded-lg text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer flex items-center space-x-1.5 ${
+ leftTab === 'description'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+ Requirements
+
+
+
+ {/* File Switcher (Only shown when Editor tab active) */}
+ {leftTab === 'editor' && (
+
+ {[
+ { id: 'html', label: 'HTML', color: 'text-orange-400' },
+ { id: 'css', label: 'CSS', color: 'text-sky-400' },
+ { id: 'javascript', label: 'JS', color: 'text-amber-400' },
+ ].map((f) => (
+ setActiveFile(f.id)}
+ className={`px-2.5 py-1 rounded-lg text-[11px] font-bold uppercase tracking-wider transition-colors cursor-pointer flex items-center space-x-1 ${
+ activeFile === f.id
+ ? 'bg-slate-700 text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+ ●
+ {f.label}
+
+ ))}
+
+ )}
+
+ {/* Reset Starter Code Action */}
+
+
+
+
+
+ {/* Body Content */}
+
+ {leftTab === 'editor' ? (
+
+ ) : (
+ /* Requirements Checklist & Problem Description */
+
+
+
Problem Statement
+
+ {question.description}
+
+
+
+ {/* Requirements Checklist */}
+ {question.requirements && question.requirements.length > 0 && (
+
+
+ Requirements Checklist
+
+
+ {question.requirements.map((req, idx) => (
+
+
+ {req}
+
+ ))}
+
+
+ )}
+
+ )}
+
+
+
+ {/* ── Right Column: Live Preview & Test Results ──────────────────────── */}
+
+ {/* Top Panel Controls */}
+
+ {/* Right Tab Switcher (Preview vs Results) */}
+
+
setRightTab('preview')}
+ className={`px-3 py-1 rounded-lg text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer flex items-center space-x-1.5 ${
+ rightTab === 'preview'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+ Live Preview
+
+
setRightTab('results')}
+ className={`px-3 py-1 rounded-lg text-xs font-bold uppercase tracking-wider transition-colors cursor-pointer flex items-center space-x-1.5 ${
+ rightTab === 'results'
+ ? 'bg-accentBlue text-white shadow-sm'
+ : 'text-slate-400 hover:text-slate-200'
+ }`}
+ >
+
+ Test Results {testResults ? `(${testResults.score}%)` : ''}
+
+
+
+
+ {/* Body Content */}
+
+
+
+
+ {/* Auth Modal Guard */}
+
setIsAuthModalOpen(false)}
+ mode="submit"
+ />
+
+ );
+};
+
+export default WebDevArena;
diff --git a/frontend/src/pages/webdev/WebDevHub.jsx b/frontend/src/pages/webdev/WebDevHub.jsx
new file mode 100644
index 0000000..75df856
--- /dev/null
+++ b/frontend/src/pages/webdev/WebDevHub.jsx
@@ -0,0 +1,300 @@
+import React, { useState, useEffect, useContext } from 'react';
+import { Link } from 'react-router-dom';
+import { getWebDevQuestions } from '../../services/webDevService';
+import { AuthContext } from '../../context/AuthContext';
+import {
+ Code, Layout, Sparkles, CheckCircle2, Clock,
+ ArrowRight, Search, Filter, Layers, Award, Terminal, Compass
+} from 'lucide-react';
+import SEO from '../../components/SEO';
+
+const CATEGORY_MAP = {
+ all: 'All Categories',
+ html: 'HTML',
+ css: 'CSS',
+ javascript: 'JavaScript',
+ 'html-css': 'HTML & CSS',
+ 'html-css-javascript': 'Full Stack Frontend',
+};
+
+const WebDevHub = () => {
+ const { user } = useContext(AuthContext);
+ const [questions, setQuestions] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState('');
+
+ // Filter States
+ const [search, setSearch] = useState('');
+ const [selectedCategory, setSelectedCategory] = useState('all');
+ const [selectedDifficulty, setSelectedDifficulty] = useState('all');
+
+ useEffect(() => {
+ fetchQuestions();
+ }, [selectedCategory, selectedDifficulty]);
+
+ const fetchQuestions = async () => {
+ setLoading(true);
+ setError('');
+ try {
+ const params = {};
+ if (selectedCategory !== 'all') params.category = selectedCategory;
+ if (selectedDifficulty !== 'all') params.difficulty = selectedDifficulty;
+ if (search.trim()) params.search = search.trim();
+
+ const res = await getWebDevQuestions(params);
+ setQuestions(res.questions || []);
+ } catch (err) {
+ console.error('Error fetching web dev questions:', err);
+ setError('Could not load web development challenges. Please try again.');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleSearchSubmit = (e) => {
+ e.preventDefault();
+ fetchQuestions();
+ };
+
+ // Filter questions on client side for responsive search
+ const filteredQuestions = questions.filter((q) => {
+ if (!search.trim()) return true;
+ const query = search.toLowerCase();
+ return (
+ q.title.toLowerCase().includes(query) ||
+ q.description.toLowerCase().includes(query) ||
+ (q.tags || []).some((t) => t.toLowerCase().includes(query))
+ );
+ });
+
+ const totalSolved = filteredQuestions.filter((q) => q.userProgress?.solved).length;
+
+ return (
+
+
+
+ {/* Hero Header */}
+
+
+
+
+ Targeting TCS & Cognizant Practical Assessments 2026-27
+
+
+
+
+
+ Web Development Practice Arena
+
+
+ Build real UI components with HTML, CSS, and vanilla JavaScript. Test your code against real-time behavioral user interactions in an isolated sandbox.
+
+
+
+ {/* User Stats Card */}
+ {user && (
+
+
+
+
+
+ Solved Progress
+
+ {totalSolved} / {filteredQuestions.length} Completed
+
+
+
+ )}
+
+
+
+
+ {/* Filters and Catalog Grid */}
+
+ {/* Filter Controls Bar */}
+
+ {/* Category Tabs */}
+
+ {['all', 'javascript', 'html-css', 'html-css-javascript'].map((cat) => (
+ setSelectedCategory(cat)}
+ className={`px-3.5 py-1.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-all cursor-pointer ${
+ selectedCategory === cat
+ ? 'bg-accentBlue text-white shadow-md shadow-accentBlue/20'
+ : 'bg-darkBg text-slate-400 hover:text-slate-200 border border-darkBorder'
+ }`}
+ >
+ {CATEGORY_MAP[cat] || cat}
+
+ ))}
+
+
+ {/* Difficulty and Search */}
+
+ {/* Difficulty Selector */}
+
+ {['all', 'easy', 'medium', 'hard'].map((diff) => (
+ setSelectedDifficulty(diff)}
+ className={`px-3 py-1.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-all cursor-pointer ${
+ selectedDifficulty === diff
+ ? 'bg-slate-700 text-white border border-slate-500'
+ : 'bg-darkBg text-slate-400 hover:text-slate-200 border border-darkBorder'
+ }`}
+ >
+ {diff}
+
+ ))}
+
+
+ {/* Search Input */}
+
+
+
+
+ {error && (
+
+ {error}
+
+ )}
+
+ {/* Loading Spinner */}
+ {loading ? (
+
+
+
+ Loading challenges...
+
+
+ ) : filteredQuestions.length === 0 ? (
+ /* Empty Catalog State */
+
+
+
No Challenges Found
+
+ No practical coding tasks matched your selected filter criteria.
+
+
+ ) : (
+ /* Questions Grid */
+
+ {filteredQuestions.map((q) => {
+ const isSolved = q.userProgress?.solved;
+ const isAttempted = q.userProgress?.attempted && !isSolved;
+
+ return (
+
+
+
+
+ {/* Top Row: Category & Difficulty Badges */}
+
+
+ {q.difficulty}
+
+
+ {/* Status / Solved Badge */}
+ {isSolved ? (
+
+
+ Solved
+
+ ) : isAttempted ? (
+
+ Attempted ({q.userProgress?.bestScore}%)
+
+ ) : (
+
+ {q.points || 100} pts
+
+ )}
+
+
+ {/* Challenge Title & Snippet */}
+
+
+ {q.title}
+
+
+ {q.description}
+
+
+
+ {/* Requirements Count & Tags */}
+
+
+
+
+ {q.requirements?.length || 0} Requirements
+
+
+
+ ~{q.timeLimit || 20}m
+
+
+
+ {q.tags && q.tags.length > 0 && (
+
+ {q.tags.slice(0, 3).map((tag) => (
+
+ {tag}
+
+ ))}
+
+ )}
+
+
+
+ {/* Card Action Button */}
+
+
+
{isSolved ? 'Review Solution' : 'Solve Challenge'}
+
+
+
+
+ );
+ })}
+
+ )}
+
+
+ );
+};
+
+export default WebDevHub;
diff --git a/frontend/src/services/webDevService.js b/frontend/src/services/webDevService.js
new file mode 100644
index 0000000..31be678
--- /dev/null
+++ b/frontend/src/services/webDevService.js
@@ -0,0 +1,85 @@
+import api from './api';
+
+/**
+ * Fetch all published web development questions with optional filters
+ * @param {Object} params { difficulty, category, search }
+ */
+export const getWebDevQuestions = async (params = {}) => {
+ const response = await api.get('/api/web-development/questions', { params });
+ return response.data;
+};
+
+/**
+ * Fetch single web dev question by ID or Slug
+ * @param {string} idOrSlug
+ */
+export const getWebDevQuestion = async (idOrSlug) => {
+ const response = await api.get(`/api/web-development/questions/${idOrSlug}`);
+ return response.data;
+};
+export const getPublicQuestionByIdOrSlug = getWebDevQuestion;
+
+/**
+ * Submit student solution for a web dev question
+ * @param {string} questionId
+ * @param {Object} payload { htmlCode, cssCode, javascriptCode, testResults, timeSpent, startedAt }
+ */
+export const submitWebDevSolution = async (questionId, payload) => {
+ const response = await api.post(`/api/web-development/questions/${questionId}/submit`, payload);
+ return response.data;
+};
+
+/**
+ * Get user submission history for a web dev question
+ * @param {string} questionId
+ */
+export const getWebDevSubmissions = async (questionId) => {
+ const response = await api.get(`/api/web-development/questions/${questionId}/submissions`);
+ return response.data;
+};
+
+/**
+ * Admin: Get all web dev questions (including drafts)
+ * @param {Object} params { status, search }
+ */
+export const getAdminWebDevQuestions = async (params = {}) => {
+ const response = await api.get('/api/web-development/admin/questions', { params });
+ return response.data;
+};
+
+/**
+ * Admin: Get single question by ID for editor (includes solutionCode)
+ * @param {string} id
+ */
+export const getAdminWebDevQuestion = async (id) => {
+ const response = await api.get(`/api/web-development/admin/questions/${id}`);
+ return response.data;
+};
+
+/**
+ * Admin: Create a new web dev question
+ * @param {Object} payload
+ */
+export const createAdminWebDevQuestion = async (payload) => {
+ const response = await api.post('/api/web-development/admin/questions', payload);
+ return response.data;
+};
+
+/**
+ * Admin: Update an existing web dev question
+ * @param {string} id
+ * @param {Object} payload
+ */
+export const updateAdminWebDevQuestion = async (id, payload) => {
+ const response = await api.patch(`/api/web-development/admin/questions/${id}`, payload);
+ return response.data;
+};
+
+/**
+ * Admin: Delete a web dev question
+ * @param {string} id
+ */
+export const deleteAdminWebDevQuestion = async (id) => {
+ const response = await api.delete(`/api/web-development/admin/questions/${id}`);
+ return response.data;
+};
diff --git a/frontend/src/utils/webDevEvaluator.js b/frontend/src/utils/webDevEvaluator.js
new file mode 100644
index 0000000..e393304
--- /dev/null
+++ b/frontend/src/utils/webDevEvaluator.js
@@ -0,0 +1,301 @@
+/**
+ * Normalize CSS color (converts rgb/rgba to hex for reliable comparisons)
+ */
+export const normalizeColor = (colorStr) => {
+ if (!colorStr) return '';
+ colorStr = colorStr.trim().toLowerCase();
+ if (colorStr.startsWith('#')) return colorStr;
+
+ const rgbMatch = colorStr.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/);
+ if (rgbMatch) {
+ const r = parseInt(rgbMatch[1], 10).toString(16).padStart(2, '0');
+ const g = parseInt(rgbMatch[2], 10).toString(16).padStart(2, '0');
+ const b = parseInt(rgbMatch[3], 10).toString(16).padStart(2, '0');
+ return `#${r}${g}${b}`;
+ }
+ return colorStr;
+};
+
+/**
+ * Build the complete self-contained HTML payload to inject into the sandboxed iframe
+ */
+export const buildSandboxedIframeDoc = ({ html = '', css = '', javascript = '', tests = [] }) => {
+ // Serialize tests safely
+ const serializedTests = JSON.stringify(tests || []);
+
+ return `
+
+
+
+
+
+
+
+
+${html}
+
+
+
+
+
+
+
+`;
+};