quiz-maker / index.html
Examups's picture
Update index.html
6178d95 verified
Raw History Blame Contribute Delete
19.9 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quiz Parser</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.section-tab.active { @apply bg-blue-500 text-white; }
.section-content { display: none; }
.section-content.active { display: block; }
</style>
</head>
<body class="bg-gray-100 min-h-screen p-4 md:p-8">
<div class="max-w-4xl mx-auto bg-white shadow-lg rounded-lg p-6">
<h1 class="text-3xl font-bold mb-6 text-center text-gray-800">Quiz Parser</h1>
<div class="mb-6">
<label for="testInstruction" class="block text-sm font-medium text-gray-700 mb-1">Test Instruction:</label>
<input type="text" id="testInstruction" value="General Quiz Test" class="w-full p-2 border border-gray-300 rounded-md">
</div>
<div id="sectionTabs" class="flex flex-wrap gap-2 mb-4"></div>
<div id="sectionContainer" class="mb-6"></div>
<div class="flex flex-wrap justify-center gap-4 mb-6">
<button onclick="addNewSection()" class="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors">
Add New Section
</button>
<button onclick="parseQuiz()" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors">Parse Quiz</button>
<button onclick="downloadHTML()" class="px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600 transition-colors">Download as HTML</button>
</div>
<div>
<h2 class="text-2xl font-semibold mb-3 text-gray-800">Parsed Quiz Output:</h2>
<div id="output" class="w-full h-64 p-3 bg-gray-50 border border-gray-300 rounded-md overflow-auto whitespace-pre-wrap text-sm"></div>
</div>
</div>
<script>
let sections = [];
let currentSectionIndex = 0;
let parsedHTML = '';
const sectionTemplate = (index) => `
<div class="section-content p-4 border rounded ${index === 0 ? 'active' : ''}" data-index="${index}">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
<div>
<label class="block text-sm font-medium text-gray-700">Section Name</label>
<input type="text" class="section-name w-full p-2 border rounded" value="Section ${index + 1}">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Section Duration</label>
<input type="number" class="section-duration w-full p-2 border rounded" value="25">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Section Marks</label>
<span class="section-marks-display block p-2 bg-gray-50 rounded">0</span>
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Default Marks</label>
<input type="number" class="default-marks w-full p-2 border rounded" value="1">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Negative Marks</label>
<input type="number" class="negative-marks w-full p-2 border rounded" value="0.25">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Default Tag</label>
<input type="text" class="default-tag w-full p-2 border rounded" value="General Knowledge">
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Default Difficulty</label>
<select class="default-difficulty w-full p-2 border rounded">
<option value="Easy">Easy</option>
<option value="Medium" selected>Medium</option>
<option value="Intense">Intense</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Answer Time (minutes)</label>
<input type="number" class="answer-time w-full p-2 border rounded" value="3">
</div>
</div>
<label class="block text-sm font-medium text-gray-700 mb-2">Questions:</label>
<textarea class="section-questions w-full h-48 p-3 border rounded"></textarea>
</div>
`;
function addNewSection() {
const index = sections.length;
sections.push({
name: `Section ${index + 1}`,
duration: 25,
marks: 0,
defaultMarks: 1,
negativeMarks: 0.25,
defaultTag: "General Knowledge",
defaultDifficulty: "Medium",
answerTime: 3,
questions: ""
});
const tab = document.createElement('div');
tab.className = `section-tab px-4 py-2 cursor-pointer border rounded ${index === 0 ? 'active' : ''}`;
tab.textContent = `Section ${index + 1}`;
tab.onclick = () => switchSection(index);
const closeBtn = document.createElement('span');
closeBtn.className = 'ml-2 text-gray-500 hover:text-gray-700';
closeBtn.innerHTML = '×';
closeBtn.onclick = (e) => {
e.stopPropagation();
removeSection(index);
};
tab.appendChild(closeBtn);
document.getElementById('sectionTabs').appendChild(tab);
const content = document.createElement('div');
content.innerHTML = sectionTemplate(index);
document.getElementById('sectionContainer').appendChild(content);
const sectionElement = content.querySelector(`.section-content[data-index="${index}"]`);
sectionElement.querySelector('.section-questions').addEventListener('input', () => updateSectionMarks(index));
sectionElement.querySelector('.default-marks').addEventListener('input', () => updateSectionMarks(index));
sectionElement.querySelector('.section-duration').addEventListener('input', () => updateSectionMarks(index));
switchSection(index);
updateSectionMarks(index);
}
function updateSectionMarks(index) {
const sectionElement = document.querySelector(`.section-content[data-index="${index}"]`);
const questions = sectionElement.querySelector('.section-questions').value;
const defaultMarks = parseFloat(sectionElement.querySelector('.default-marks').value) || 0;
const duration = parseFloat(sectionElement.querySelector('.section-duration').value) || 0;
const questionCount = questions.split(/\n---\n/).filter(block => block.trim() !== '').length;
const sectionMarks = questionCount * defaultMarks;
sectionElement.querySelector('.section-marks-display').textContent = sectionMarks;
sections[index].marks = sectionMarks;
sections[index].duration = duration;
sections[index].defaultMarks = defaultMarks;
}
function switchSection(index) {
document.querySelectorAll('.section-tab').forEach((tab, i) => {
tab.classList.toggle('active', i === index);
});
document.querySelectorAll('.section-content').forEach((content, i) => {
content.classList.toggle('active', i === index);
});
currentSectionIndex = index;
}
function removeSection(index) {
sections.splice(index, 1);
document.querySelectorAll('.section-tab')[index].remove();
document.querySelectorAll('.section-content')[index].remove();
sections.forEach((_, i) => {
document.querySelectorAll('.section-tab')[i].textContent = `Section ${i + 1}`;
});
if (index === currentSectionIndex) switchSection(Math.max(0, index - 1));
}
function convertMarkdownTableToHTML(markdownTable) {
const rows = markdownTable.trim().split('\n').map(row =>
row.replace(/^\||\|$/g, '').split('|').map(cell => cell.trim())
);
// Remove separator row
const separatorIndex = rows.findIndex(row => row.some(cell => /^-+$/.test(cell)));
if (separatorIndex > -1) rows.splice(separatorIndex, 1);
let html = `
<table class=MsoTable15Grid1LightAccent1 border=1 cellspacing=0 cellpadding=0 style='border-collapse:collapse;border:none'>
<tbody>`;
rows.forEach((row, rowIndex) => {
const isHeaderRow = rowIndex === 0;
html += '\n <tr>';
row.forEach((cell, cellIndex) => {
const borderStyle = isHeaderRow
? 'border:solid #B4C6E7 1.0pt;border-bottom:solid #8EAADB 1.5pt'
: 'border:solid #B4C6E7 1.0pt';
html += `
<td valign=top style='${borderStyle};padding:0cm 5.4pt 0cm 5.4pt'>
<p class=MsoNormal style='margin-bottom:8.0pt;line-height:107%'>${cell.replace(/\*\*/g, '<b>').replace(/\*\//g, '</b>')}</p>
</td>`;
});
html += '\n </tr>';
});
html += '\n </tbody>\n</table>';
return html;
}
function parseQuiz() {
let totalTestDuration = 0;
let totalTestMarks = 0;
const processedSections = [];
// First pass: Calculate totals
sections.forEach((section, index) => {
const sectionElement = document.querySelector(`.section-content[data-index="${index}"]`);
const questions = sectionElement.querySelector('.section-questions').value;
const questionBlocks = questions.split(/\n---\n/).filter(block => block.trim() !== '');
const sectionMarks = questionBlocks.length * section.defaultMarks;
processedSections.push({
...section,
name: sectionElement.querySelector('.section-name').value,
questionBlocks,
sectionMarks,
duration: section.duration,
negativeMarks: parseFloat(sectionElement.querySelector('.negative-marks').value) || 0,
defaultTag: sectionElement.querySelector('.default-tag').value,
defaultDifficulty: sectionElement.querySelector('.default-difficulty').value,
answerTime: parseFloat(sectionElement.querySelector('.answer-time').value) || 0
});
totalTestDuration += section.duration;
totalTestMarks += sectionMarks;
});
// Generate HTML
parsedHTML = `
<html>
<head>
<meta charset="UTF-8">
<meta name=Generator content="Microsoft Word 15 (filtered)">
<style>
p.MsoNormal, li.MsoNormal, div.MsoNormal {
margin-top:0cm; margin-right:0cm; margin-bottom:8.0pt; margin-left:0cm;
line-height:107%; font-size:11.0pt; font-family:"Noto Sans Devanagari", "Arial Unicode MS", sans-serif;
}
body {
word-wrap:break-word;
}
</style>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari&display=swap" rel="stylesheet">
</head>
<body lang="HI" style='word-wrap:break-word'>
<div class="WordSection1">
<p class=MsoNormal>[TEST INSTRUCTION] ${document.getElementById('testInstruction').value}</p>
<p class=MsoNormal>[TEST DURATION] ${totalTestDuration}</p>
<p class=MsoNormal>[TEST MAXIMUM MARKS] ${totalTestMarks}</p>
<p class=MsoNormal>&nbsp;</p>`;
// Second pass: Add sections
processedSections.forEach(section => {
parsedHTML += `
<p class=MsoNormal>[SECTION] ${section.name}</p>
<p class=MsoNormal>[SECTION DURATION] ${section.duration}</p>
<p class=MsoNormal>[SECTION MARKS] ${section.sectionMarks}</p>
<p class=MsoNormal>&nbsp;</p>`;
section.questionBlocks.forEach((block, qIndex) => {
// const questionTextMatch = block.match(/\*\*\d+\.\s*(.*?)\*\*/);
let processedBlock = block;
const questionTextMatch = processedBlock.match(/\*\*\d+\.\s*(.*?)\*\*/);
let questionText = questionTextMatch ? questionTextMatch[1].trim() : '';
let chartsection = '';
const chartTypeRegex = /(pie\s*chart|bar\s*chart|line\s*chart|doughnut|radar|polar\s*area)/gi;
const chartMatch = processedBlock.match(chartTypeRegex);
let chartType = 'bar';
const chartTypeMap = { 'pie chart': 'pie', 'bar chart': 'bar', 'line chart': 'line', 'doughnut': 'doughnut', 'radar': 'radar', 'polar area': 'polarArea' };
if (chartMatch) chartType = chartTypeMap[chartMatch[0].toLowerCase()] || 'bar';
const tableMatches = processedBlock.match(/(\|.*\|(\n\|.*\|)+)/g);
if (tableMatches) {
for (const table of tableMatches) {
const htmlTable = convertMarkdownTableToHTML(table);
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlTable;
const tableEl = tempDiv.querySelector('table');
const headers = Array.from(tableEl.rows[0].cells).map(cell => cell.textContent.replace(/(<([^>]+)>)/gi, '').trim());
const rows = Array.from(tableEl.rows).slice(1).map(row => Array.from(row.cells).map(cell => parseFloat(cell.textContent) || cell.textContent.trim()));
const canvas = document.createElement('canvas');
canvas.width = 600;
canvas.height = 400;
canvas.style.position = 'fixed';
canvas.style.left = '-9999px';
document.body.appendChild(canvas);
new Chart(canvas.getContext('2d'), {
type: chartType,
data: { labels: rows.map(r => r[0]), datasets: [{
label: headers[1],
data: rows.map(r => r[1]),
backgroundColor: ['rgba(255, 99, 132, 0.2)','rgba(54, 162, 235, 0.2)','rgba(255, 206, 86, 0.2)','rgba(75, 192, 192, 0.2)','rgba(153, 102, 255, 0.2)'],
borderColor: ['rgba(255, 99, 132, 1)','rgba(54, 162, 235, 1)','rgba(255, 206, 86, 1)','rgba(75, 192, 192, 1)','rgba(153, 102, 255, 1)'],
borderWidth: 1
}]},
options: { animation: false, responsive: false, plugins: {
legend: { display: true }, // Show legend
datalabels: {
anchor: 'center', // Keep label inside the bar
align: 'center', // Align label in the middle of the bar
formatter: (value) => value, // Show value inside bars
color: 'white', // Make text readable (adjust as needed)
font: { weight: 'bold', size: 14 }
}
}, scales: chartType === 'pie' ? null : { y: { beginAtZero: true } } }
});
setTimeout(() => {
console.log("Work completed!");
}, 2000);
let base64 = canvas.toDataURL('image/png');
document.body.removeChild(canvas);
processedBlock = processedBlock.replace(table, ``);
questionText += `${htmlTable}<br><div style="text-align:center; margin:20px 0"><img src="${base64}" style="max-width:600px; display:inline-block"></div>`
// const chartsection = processedBlock.replace(/\*\*\d+\.\s*(.*?)\*\*/, ``);
}
}
const options = [];
const optionMatches = processedBlock.matchAll(/([a-d])\)\s*(.*?)\n/g);
for (const match of optionMatches) {
options.push({ letter: match[1], text: match[2].trim() });
}
options.splice(4);
const correctAnswerMatch = processedBlock.match(/\*\*Correct Answer:\*\*\s*([a-d])\)/i);
const correctLetter = correctAnswerMatch ? correctAnswerMatch[1].trim() : '';
const explanationMatch = processedBlock.match(/\*\*Explanation:\*\*\s*(.*)/);
const explanation = explanationMatch ? explanationMatch[1].trim() : '';
const tagMatch = processedBlock.match(/\[TAG:\s*(.*?)\]/);
const difficultyMatch = processedBlock.match(/\[DIFFICULTY:\s*(.*?)\]/);
parsedHTML += `
<p class=MsoNormal><b>Q.${qIndex + 1})</b> ${questionText}</p>
${options.map((opt, i) => `
<p class=MsoNormal>${opt.letter === correctLetter ? '*' : ''}[${i + 1}] ${opt.text}</p>
`).join('')}
<p class=MsoNormal>[MARKS] ${section.defaultMarks}</p>
<p class=MsoNormal>[NEGATIVE MARKS] ${section.negativeMarks}</p>
<p class=MsoNormal>[TAG] ${tagMatch ? tagMatch[1] : section.defaultTag}</p>
<p class=MsoNormal>[DIFFICULTY] ${difficultyMatch ? difficultyMatch[1] : section.defaultDifficulty}</p>
<p class=MsoNormal>[ANSWER TIME] ${section.answerTime}</p>
<p class=MsoNormal>[QUESTION TYPE] Multi_choice</p>
<p class=MsoNormal>[SOLUTION] (${correctLetter}) Explanation: ${explanation}</p>
<div class=MsoNormal align=center style='text-align:center'>
<hr size=2 width="100%" align=center>
</div>`;
});
});
parsedHTML += `</div></body></html>`;
/* Add this line before setting the output */
parsedHTML = parsedHTML.replace(/>\s+</g, '><');
document.getElementById('output').textContent = parsedHTML;
}
function downloadHTML() {
const blob = new Blob([parsedHTML], { type: "text/html" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${document.getElementById('testInstruction').value}.html`;
a.click();
URL.revokeObjectURL(url);
}
addNewSection();
</script>
</body>
</html>