Spaces:
Running
Running
Download index.html from Examups/Mock_Test_Maker: direct link, hf CLI and curl.
- Browser
- Download file 176 kB
-
https://huggingface.co/spaces/Examups/Mock_Test_Maker/resolve/main/index.html
- Command line
-
hf download hf://spaces/Examups/Mock_Test_Maker/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Examups/Mock_Test_Maker/resolve/main/index.html
176 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Examups Quiz Builder</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
<style>
:root {
--primary-color: #4f46e5;
--primary-color-hover: #4338ca;
--primary-light: #eef2ff;
--secondary-bg: #f8f9fa;
--text-color: #1f2937;
--text-light: #6b7280;
--border-color: #e5e7eb;
--danger-color: #ef4444;
--danger-color-hover: #dc2626;
--success-color: #10b981;
--success-color-hover: #059669;
--white-color: #ffffff;
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
--shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
--radius: 0.5rem;
}
body {
font-family: var(--font-family);
background-color: var(--secondary-bg);
color: var(--text-color);
margin: 0;
font-size: 16px;
line-height: 1.6;
height: 100vh;
display: flex;
flex-direction: column;
}
h2 {
color: var(--text-color);
padding-bottom: 10px;
margin-top: 0;
margin-bottom: 2rem;
font-weight: 700;
font-size: 1.25rem;
border-bottom: 1px solid var(--border-color);
}
.top-bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 1.5rem;
background: var(--white-color);
border-bottom: 1px solid var(--border-color);
flex-shrink: 0;
}
.logo-container {
display: flex;
align-items: center;
}
#brand-logo {
height: 35px;
width: auto;
}
.top-bar .actions {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
.builder-layout {
display: flex;
flex-grow: 1;
overflow: hidden;
}
.sidebar, .center-panel {
padding: 1.5rem;
overflow-y: auto;
height: 100%;
box-sizing: border-box;
}
.left-sidebar {
flex: 0 0 380px;
background: var(--white-color);
border-right: 1px solid var(--border-color);
}
.center-panel {
flex-grow: 1;
}
.right-sidebar {
flex: 0 0 320px;
background: var(--white-color);
border-left: 1px solid var(--border-color);
}
.section-builder {
margin-bottom: 2.5rem;
}
.form-group { margin-bottom: 1.25rem; }
.form-group-inline { display: flex; align-items: center; gap: 10px; margin-bottom: 1rem; }
.form-group-inline input { width: auto; }
label {
display: block;
font-weight: 500;
margin-bottom: 0.5rem;
font-size: 0.875rem;
color: var(--text-light);
}
input[type="text"], input[type="number"], textarea, select {
width: 100%;
padding: 12px 15px;
border: 1px solid var(--border-color);
border-radius: 0.375rem;
font-size: 1rem;
box-sizing: border-box;
transition: all 0.2s ease;
background-color: #fff;
}
input[type="text"]:focus, input[type="number"]:focus, textarea:focus, select:focus {
outline: none;
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.15);
}
textarea { min-height: 80px; resize: vertical; }
.btn {
padding: 10px 20px;
border: none;
border-radius: 0.375rem;
cursor: pointer;
font-size: 0.9rem;
font-weight: 600;
transition: all 0.2s ease;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.6rem;
}
.btn .material-symbols-outlined { font-size: 1.25em; }
.btn:disabled { background-color: #ccc; cursor: not-allowed; }
.btn-primary { background-color: var(--primary-color); color: white; }
.btn-primary:hover { background-color: var(--primary-color-hover); transform: translateY(-1px); }
.btn-danger { background-color: var(--danger-color); color: white; }
.btn-danger:hover { background-color: var(--danger-color-hover); transform: translateY(-1px); }
.btn-success { background-color: var(--success-color); color: white; }
.btn-secondary { background-color: #F3F4F6; color: var(--text-color); border: 1px solid var(--border-color); }
.btn-secondary:hover { background-color: #E5E7EB; }
.btn-icon-only { padding: 8px; line-height: 0; }
.btn-icon-only .material-symbols-outlined { font-size: 1.5em; margin: 0; }
#quiz-summary-details {
background-color: var(--white-color);
border: 1px solid var(--border-color);
padding: 1.5rem;
border-radius: var(--radius);
margin-bottom: 1.5rem;
box-shadow: var(--shadow);
}
#quiz-summary-details h3 {
margin-top: 0;
margin-bottom: 1rem;
font-size: 1.1rem;
font-weight: 600;
color: var(--text-color);
padding-bottom: 1rem;
border-bottom: 1px solid var(--border-color);
}
#section-summary-list {
list-style-type: none;
padding: 0;
margin: 0;
}
.summary-section-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.8rem 0.25rem;
border-bottom: 1px dashed #e0e7ff;
font-size: 0.95rem;
}
.summary-section-item:last-child {
border-bottom: none;
}
.summary-section-name {
font-weight: 500;
color: var(--text-light);
}
.summary-question-count {
font-weight: 600;
background-color: #eff6ff;
color: #3b82f6;
padding: 4px 10px;
border-radius: 99px;
font-size: 0.8rem;
}
#section-summary-list li:only-child {
color: var(--text-light);
font-style: italic;
text-align: center;
padding: 1rem 0;
border: none;
}
.question-card {
background-color: #fcfdff;
padding: 1.5rem;
border-radius: var(--radius);
margin-bottom: 1rem;
border: 1px solid #e0e7ff;
cursor: grab;
}
.question-card.dragging {
opacity: 0.5;
cursor: grabbing;
background-color: #eef2ff;
}
.card-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.question-card .card-header {
margin-top: 0;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--border-color);
}
.card-header h4 { margin: 0; font-size: 1.1rem; color: var(--text-color); }
.question-card-grid {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1.5rem;
}
.question-config {
border-right: 1px solid var(--border-color);
padding-right: 1.5rem;
}
.options-container-dynamic {
display: flex;
flex-direction: column;
gap: 1rem;
margin-top: 0.5rem;
margin-bottom: 1.5rem;
}
.option-entry {
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.option-letter {
flex-shrink: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
border: 1px solid var(--border-color);
border-radius: 4px;
background: #fff;
margin-top: 10px;
}
.option-entry input[type="text"] { flex-grow: 1; }
.option-actions { display: flex; gap: 0.5rem; margin-top: 10px;}
.btn-correct { background-color: var(--secondary-bg); color: #9ca3af; }
.option-entry.is-correct .btn-correct { background-color: var(--success-color); color: white; }
.option-entry.is-correct .btn-correct:hover { background-color: var(--success-color-hover); }
.section-container {
cursor: grab;
}
.section-container.dragging {
opacity: 0.5;
cursor: grabbing;
}
.section-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
border-bottom: 0;
padding-bottom: 0;
margin-bottom: 0;
}
.section-header .section-name { font-size: 1.25rem; font-weight: 600; border: none; padding: 0; background: transparent; }
.section-header .section-name:focus { box-shadow: none; }
.section-header-question-count {
font-size: 0.8rem;
font-weight: 600;
background-color: #f3f4f6;
color: var(--text-light);
padding: 3px 10px;
border-radius: 99px;
margin-left: 0.75rem;
}
#preview-modal, #wp-code-modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); align-items: center; justify-content: center;}
.preview-content, .wp-modal-content { background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; border-radius: 8px; display: flex; flex-direction: column; }
.preview-content { width: 95%; height: 90%; }
.wp-modal-content { width: 90%; max-width: 680px; }
.preview-header, .wp-modal-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 10px; border-bottom: 1px solid var(--border-color); margin-bottom: 1rem; }
.close-preview, .close-wp-modal { color: #aaa; font-size: 28px; font-weight: bold; cursor: pointer; }
#preview-iframe { width: 100%; height: 100%; border: none; margin-top: 10px; }
#wp-code-modal p { margin: 0 0 1rem 0; }
#wp-code-modal ol { padding-left: 20px; margin-bottom: 1.5rem; }
#wp-code-modal li { margin-bottom: 0.5rem; }
#wp-code-textarea { font-family: monospace; resize: vertical; margin-bottom: 1rem; }
#copy-wp-code-btn { width: auto; }
.import-actions { display: flex; flex-wrap: wrap; gap: 1rem; margin-top: 1.5rem; align-items: flex-end; }
.format-guide { font-size: 0.9rem; background-color: #eff6ff; border-radius: var(--radius); padding: 1rem; border: 1px solid #dbeafe; margin-top: 1.5rem; }
.format-guide summary { font-weight: 600; cursor: pointer; color: var(--primary-color); }
.format-guide pre { white-space: pre-wrap; word-wrap: break-word; background: #e0e7ff; padding: 1rem; border-radius: 0.375rem; margin-top: 0.75rem; font-family: monospace; color: #3730a3; }
.hidden { display: none !important; }
/* --- ENHANCED Quiz Structure Styles --- */
.quiz-structure-container {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.structure-item-container details { width: 100%; }
.structure-item-container details > summary {
list-style: none;
padding: 0;
width: 100%;
}
.structure-item-container details > summary::-webkit-details-marker { display: none; }
.structure-item {
padding: 10px 14px;
border-radius: 8px;
background-color: transparent;
border: 1px solid transparent;
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
width: 100%;
transition: background-color 0.2s ease, border-color 0.2s ease;
}
.structure-item:hover {
background-color: var(--secondary-bg);
}
.structure-item.active {
background-color: var(--primary-light);
border-color: var(--primary-color);
color: var(--primary-color);
}
.structure-item-content {
display: flex;
align-items: center;
gap: 12px;
flex-grow: 1;
overflow: hidden;
}
.structure-item .item-icon {
font-size: 20px;
color: var(--text-light);
}
.structure-item[data-type="main"] .item-icon {
color: var(--primary-color);
}
.structure-item[data-type="quiz"] .item-icon {
color: #3b82f6;
}
.structure-item-name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
background: transparent;
border: none;
padding: 2px;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
color: inherit;
width: 100%;
text-align: left;
border-radius: 4px;
}
.structure-item-name:focus{
outline: 2px solid var(--primary-color);
background-color: var(--white-color);
}
.structure-item-count {
margin-left: auto;
margin-right: 8px;
font-size: 0.75rem;
font-weight: 500;
color: var(--text-light);
background-color: var(--secondary-bg);
padding: 2px 8px;
border-radius: 4px;
white-space: nowrap;
}
.structure-item.active .structure-item-count {
background-color: var(--white-color);
color: var(--primary-color);
}
.structure-item-actions {
display: flex;
gap: 6px;
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.2s ease-in-out;
}
.structure-item:hover .structure-item-actions,
.structure-item.active .structure-item-actions {
visibility: visible;
opacity: 1;
}
.action-btn {
background: none;
border: none;
cursor: pointer;
padding: 5px;
border-radius: 50%;
display:flex;
align-items:center;
justify-content:center;
color: var(--text-light);
transition: background-color 0.2s ease, color 0.2s ease;
}
.action-btn .material-symbols-outlined { font-size: 18px; }
.action-btn:hover { background-color: var(--border-color); color: var(--text-color); }
.action-btn.delete-btn:hover { background-color: #fee2e2; color: var(--danger-color-hover); }
.structure-children {
padding-left: 28px;
display: flex;
flex-direction: column;
gap: 0.3rem;
margin-top: 0.3rem;
border-left: 2px solid var(--border-color);
margin-left: 25px;
}
.structure-item[data-type="main"] .structure-item-name { font-weight: 600; font-size: 1rem; }
.structure-item[data-type="sub"] { font-size: 0.95rem; }
.structure-item[data-type="quiz"] { font-size: 0.9rem; }
.drag-placeholder {
height: 60px;
background-color: #eef2ff;
border: 2px dashed var(--primary-color);
border-radius: var(--radius);
margin: 1rem 0;
}
/* --- New Dropdown Styles --- */
.section-builder-header {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--border-color);
padding-bottom: 10px;
margin-bottom: 1.5rem;
}
.section-builder-header h2 {
margin: 0;
padding: 0;
border: none;
}
.manage-all-dropdown {
position: relative;
}
.dropdown-menu {
display: none;
position: absolute;
right: 0;
top: 100%;
margin-top: 0.5rem;
background-color: var(--white-color);
border: 1px solid var(--border-color);
border-radius: var(--radius);
box-shadow: var(--shadow-lg);
z-index: 100;
min-width: 220px;
padding: 0.5rem 0;
opacity: 0;
visibility: hidden;
transform: translateY(-10px);
transition: opacity 0.2s ease, transform 0.2s ease, visibility 0.2s;
}
.manage-all-dropdown.open .dropdown-menu {
display: block;
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.dropdown-item {
display: block;
width: 100%;
padding: 0.75rem 1.25rem;
text-align: left;
background: none;
border: none;
font-size: 0.9rem;
color: var(--text-color);
cursor: pointer;
}
.dropdown-item:hover {
background-color: var(--secondary-bg);
}
.dropdown-item.danger-item {
color: var(--danger-color);
}
.dropdown-item.danger-item:hover {
background-color: #fee2e2;
color: #991b1b;
}
.dropdown-divider {
height: 1px;
background-color: var(--border-color);
margin: 0.5rem 0;
}
.btn-sm {
padding: 8px 12px;
font-size: 0.85rem;
}
.btn-sm .material-symbols-outlined { font-size: 1.1em; }
.section-container {
background: var(--white-color);
border: 1px solid var(--border-color);
border-radius: var(--radius);
margin-top: 1rem;
box-shadow: var(--shadow);
padding: 0;
}
.section-container details > summary {
list-style: none;
cursor: pointer;
padding: 1rem 1.5rem;
}
.section-container details > summary::-webkit-details-marker {
display: none;
}
.section-container details[open] > summary {
border-bottom: 1px solid var(--border-color);
}
.section-content-wrapper {
padding: 1.5rem;
}
.section-header .section-name-wrapper {
display: flex;
align-items: center;
flex-grow: 1;
}
.section-header .section-name::before {
content: '';
position: absolute;
left: 0;
top: 50%;
width: 0;
height: 0;
border-style: solid;
border-width: 5px 0 5px 8.7px;
border-color: transparent transparent transparent var(--text-light);
transform: translateY(-50%) rotate(0);
transition: transform 0.2s ease-in-out;
}
.section-container details[open] .section-header .section-name::before {
transform: translateY(-50%) rotate(90deg);
}
/* --- End New Styles --- */
@media (max-width: 1200px) {
.question-card-grid { grid-template-columns: 1fr; }
.question-config { border-right: 0; padding-right: 0; border-bottom: 1px solid var(--border-color); padding-bottom: 1rem; margin-bottom: 1rem; }
}
@media (max-width: 1024px) {
.builder-layout { flex-direction: column; }
.left-sidebar, .right-sidebar { flex-basis: auto; border: 0; }
.left-sidebar { border-bottom: 1px solid var(--border-color); }
.right-sidebar { border-top: 1px solid var(--border-color); }
.sidebar, .center-panel { padding: 1rem; }
.top-bar { flex-direction: column; align-items: flex-start; gap: 1rem;}
}
@media (max-width: 768px) {
.options-grid { flex-direction: column; }
.btn { width: 100%; }
.top-bar .actions { width: 100%; }
}
</style>
</head>
<body>
<header class="top-bar">
<div class="logo-container">
<img src="https://examups.com/wp-content/uploads/2024/08/cropped-Untitled_design-removebg-preview.png" alt="Examups Logo" id="brand-logo">
</div>
<div class="actions">
<button id="preview-quiz-btn" class="btn btn-secondary">
<span class="material-symbols-outlined">visibility</span>
Preview
</button>
<button id="download-practice-btn" class="btn btn-secondary">
<span class="material-symbols-outlined">description</span>
Practice Sheet
</button>
<button id="get-wp-code-btn" class="btn btn-secondary">
<span class="material-symbols-outlined">integration_instructions</span>
Get WordPress Code
</button>
<button id="download-html-btn" class="btn btn-primary">
<span class="material-symbols-outlined">download</span>
Download HTML
</button>
</div>
</header>
<div class="builder-layout">
<aside class="sidebar left-sidebar">
<div class="section-builder">
<h2>1. General Settings</h2>
<div class="form-group"><label for="quiz-title">Quiz Title</label><input type="text" id="quiz-title" placeholder="e.g., General Mock Test" disabled></div>
<div class="form-group"><label for="output-filename">Output File Name</label><input type="text" id="output-filename" placeholder="e.g., mock-test-series" value="quiz-series"></div>
<div class="form-group"><label for="user-name">Default User Name (optional)</label><input type="text" id="user-name" placeholder="e.g., Rajesh Kumar" value="Rajesh Kumar"></div>
<div class="form-group">
<label for="test-status">Test Status</label>
<select id="test-status">
<option value="Free Test">Free Test</option>
<option value="Live Test">Live Test</option>
<option value="Paid Test">Paid Test</option>
<option value="Other">Other...</option>
</select>
</div>
<div class="form-group hidden" id="custom-status-container">
<label for="test-status-custom">Custom Status</label>
<input type="text" id="test-status-custom" placeholder="Enter custom status">
</div>
<div class="form-group">
<label for="timer-duration">Total Timer (in minutes, 0 for none)</label>
<input type="number" id="timer-duration" min="0" value="20">
</div>
<div class="form-group"><label for="lang-primary-name">Primary Language Name</label><input type="text" id="lang-primary-name" value="English"></div>
<div class="form-group"><label for="lang-secondary-name">Secondary Language Name</label><input type="text" id="lang-secondary-name" value="Hindi"></div>
<div class="form-group">
<label for="quiz-instructions">Quiz Instructions (HTML allowed)</label>
<textarea id="quiz-instructions" rows="10"><h3>General Instructions:</h3>
<p>Please read the instructions carefully.</p>
<ol>
<li>The clock has been set at the server and the countdown timer at the top right corner of your screen will display the remaining time for you to complete the exam. When the clock runs out, the exam ends by default - you are not required to end or submit your exam.</li>
<li>The questions palette at the right of the screen shows one of the following statuses of each of the questions numbered:
<ul style="list-style: none; padding-left: 20px;">
<li style="margin-bottom: 5px; display: flex; align-items: center;"><span style="display: inline-flex; width: 25px; height: 25px; font-weight: bold; justify-content: center; align-items: center; border-radius: 4px; background-color: #fff; color: #6b7280; border: 1px solid #e5e7eb; margin-right: 10px;">1</span> You have <strong>not visited</strong> the question yet.</li>
<li style="margin-bottom: 5px; display: flex; align-items: center;"><span style="display: inline-flex; width: 25px; height: 25px; font-weight: bold; justify-content: center; align-items: center; border-radius: 4px; background-color: #ef4444; color: white; margin-right: 10px;">3</span> You have <strong>not answered</strong> the question.</li>
<li style="margin-bottom: 5px; display: flex; align-items: center;"><span style="display: inline-flex; width: 25px; height: 25px; font-weight: bold; justify-content: center; align-items: center; border-radius: 4px; background-color: #22c55e; color: white; margin-right: 10px;">5</span> You have <strong>answered</strong> the question.</li>
<li style="margin-bottom: 5px; display: flex; align-items: center;"><span style="display: inline-flex; width: 25px; height: 25px; font-weight: bold; justify-content: center; align-items: center; border-radius: 4px; background-color: #8b5cf6; color: white; margin-right: 10px;">7</span> You have <strong>NOT answered</strong> the question but have <strong>marked the question for review</strong>.</li>
<li style="margin-bottom: 5px; display: flex; align-items: center;"><span style="position: relative; display: inline-flex; width: 25px; height: 25px; font-weight: bold; justify-content: center; align-items: center; border-radius: 4px; background-color: #8b5cf6; color: white; margin-right: 10px;"><span style="position: absolute; bottom: 2px; right: 2px; width: 8px; height: 8px; background: #22c55e; border-radius: 50%;"></span></span> You have <strong>answered</strong> the question but <strong>marked it for review</strong>.</li>
</ul>
<p>The "Marked for Review" status simply acts as a reminder that you have set to look at the question again. If an answer is selected for a question that is Marked for Review, the answer will be considered in the final evaluation.</p>
</li>
</ol>
<h4>Navigating to a question:</h4>
<ol start="3">
<li>To select a question to answer, you can do one of the following:
<ol type="a" style="padding-left: 20px;">
<li>Click on the <strong>question number</strong> on the question palette at the right of your screen to go to that numbered question directly. Note that using this option does NOT save your answer to the current question.</li>
<li>Click on <strong>Save and Next</strong> to save your answer for the current question, and then go to the next question in sequence.</li>
<li>Click on <strong>Mark for Review and Next</strong> to save your answer for the current question, mark it for review, and then go to the next question in sequence.</li>
</ol>
</li>
</ol>
<h4>Answering Questions:</h4>
<ol start="4">
<li>For multiple-choice type questions:
<ol type="a" style="padding-left: 20px;">
<li>To <strong>select your answer</strong>, click on one of the option buttons.</li>
<li>To <strong>change your answer</strong>, click another desired option button.</li>
<li>To <strong>save your answer</strong>, you MUST click on <strong>Save & Next</strong>.</li>
<li>To <strong>deselect a chosen answer</strong>, click on the <strong>Clear Response</strong> button.</li>
<li>To mark a question for review, click on <strong>Mark for Review & Next</strong>. If an answer is selected for a question that is Marked for Review, the answer will be considered in the final evaluation.</li>
</ol>
</li>
</ol>
<h4>Navigating through sections:</h4>
<ol start="5">
<li>Sections in this question paper are displayed on the top bar of the screen. Questions in a section can be viewed by clicking on the section name. The section you are currently viewing is highlighted.</li>
<li>After clicking the last button on the last question for a section, you will automatically be taken to the first question of the next section.</li>
<li>You can shuffle between sections and questions anytime during the examination as per your convenience.</li>
</ol></textarea>
</div>
</div>
<div class="section-builder">
<h2>2. Import Test</h2>
<div>
<label for="bulk-text">Paste Test Content Here</label>
<textarea id="bulk-text" rows="10" placeholder="Paste the entire test content (HTML or text) here..."></textarea>
</div>
<div class="import-actions">
<button id="import-btn" class="btn btn-primary">
<span class="material-symbols-outlined">upload_file</span>
Import from Pasted Text
</button>
<div class="form-group" style="flex-grow:1; margin-bottom: 0;">
<label for="file-import">Or Import from File (.html, .txt, .csv)</label>
<input type="file" id="file-import" accept=".html,.txt,.csv" style="padding: 10px;">
</div>
</div>
<div class="format-guide">
<details>
<summary>View Import Format Guide</summary>
<p>You can import a previously generated Quiz HTML file, which supports the full category structure. Plain text and CSV import are also supported for individual quizzes.</p>
<h5>Plain Text (.txt) - For a single quiz</h5>
<p>The importer identifies questions by `Q.x)` and options by `[x]`. Mark the correct option with `*`. Use `||` to separate primary and secondary language content on the same line. Use tags like `[MARKS]`, `[NEGATIVE MARKS]`, `[TAG]`, and `[SOLUTION]` after a question's options to add metadata.</p>
<pre><code>[SECTION] Science
Q.1) What is H2O? || पानी क्या है?
*[1] Water || पानी
[2] Gas || गैस
[3] Solid || ठोस
[MARKS] 1
[NEGATIVE MARKS] 0.25
[TAG] Chemistry
[SOLUTION] H2O is the chemical formula for water. || H2O पानी का रासायनिक सूत्र है।
...
</code></pre>
<h5>CSV Format (.csv) - For a single quiz</h5>
<p>The first row must be a header. This will import into the currently selected quiz.</p>
<pre><code>Section,Question,Option 1,*Option 2,Option 3,Explanation
Science,What is H2O?,Gas,*Water,Solid,It's the chemical formula for water.</code></pre>
</details>
</div>
</div>
</aside>
<main class="center-panel">
<div id="quiz-editor-panel" class="section-builder hidden">
<div class="section-builder-header">
<h2>3. Quiz Content & Sections</h2>
<div class="manage-all-dropdown">
<button class="btn btn-secondary btn-sm" id="manage-all-btn">
Manage All
<span class="material-symbols-outlined">expand_more</span>
</button>
<div class="dropdown-menu" id="manage-all-menu">
<button class="dropdown-item" id="expand-all-btn">Expand All Sections</button>
<button class="dropdown-item" id="collapse-all-btn">Collapse All Sections</button>
<div class="dropdown-divider"></div>
<button class="dropdown-item danger-item" id="delete-all-questions-btn">Delete All Questions</button>
<button class="dropdown-item danger-item" id="delete-all-sections-btn">Delete All Sections</button>
</div>
</div>
</div>
<div id="quiz-summary-details">
<h3>Quiz Overview</h3>
<ul id="section-summary-list">
<li>No sections have been added yet.</li>
</ul>
</div>
<div id="sections-container"></div>
<button id="add-section-btn" class="btn btn-secondary">
<span class="material-symbols-outlined">add</span>
Add Section
</button>
</div>
<div id="welcome-panel">
<h2>Welcome to the Examups Quiz Builder</h2>
<p>To get started:</p>
<ol>
<li>Click <strong>"Add Main Category"</strong> in the right sidebar to create a new test category (e.g., "Mock Tests").</li>
<li>Select the new category, then add a quiz or a sub-category to it.</li>
<li>Select a quiz to begin adding sections and questions in this panel.</li>
</ol>
</div>
</main>
<aside class="sidebar right-sidebar">
<h2>Quiz Structure</h2>
<div class="action-buttons" style="margin-bottom: 1rem; display: flex; gap: 0.5rem;">
<button id="add-main-tab-btn" class="btn btn-secondary" style="width:100%;">
<span class="material-symbols-outlined">add</span>
Add Main Category
</button>
<button id="download-all-practice-btn" class="btn btn-secondary" title="Download All Practice Sheets">
<span class="material-symbols-outlined">collections_bookmark</span>
</button>
<button id="copy-html-btn" class="btn btn-secondary" title="Copy Full HTML Source">
<span class="material-symbols-outlined">content_copy</span>
</button>
</div>
<div id="quiz-structure-container" class="quiz-structure-container"></div>
<h2 style="margin-top: 2rem;">4. More Options</h2>
<div class="form-group">
<label for="difficulty-level">Difficulty Level</label>
<select id="difficulty-level">
<option value="Easy">Easy</option>
<option value="Medium" selected>Medium</option>
<option value="Hard">Hard</option>
<option value="Expert">Expert</option>
</select>
</div>
<div class="form-group form-group-inline">
<input type="checkbox" id="enable-view-answer" checked>
<label for="enable-view-answer" style="margin-bottom:0;">Enable View Answer</label>
</div>
<div class="form-group form-group-inline">
<input type="checkbox" id="enable-answer-shuffle">
<label for="enable-answer-shuffle" style="margin-bottom:0;">Enable Answer Shuffle</label>
</div>
<div class="form-group form-group-inline">
<input type="checkbox" id="enable-quiz-randomization">
<label for="enable-quiz-randomization" style="margin-bottom:0;">Enable Quiz Randomization</label>
</div>
<div class="form-group form-group-inline">
<input type="checkbox" id="enable-percentile" checked>
<label for="enable-percentile" style="margin-bottom:0;">Enable Percentile Ranking</label>
</div>
</aside>
</div>
<div id="preview-modal">
<div class="preview-content">
<div class="preview-header"><h2>Quiz Preview</h2><span class="close-preview">×</span></div>
<iframe id="preview-iframe"></iframe>
</div>
</div>
<div id="wp-code-modal">
<div class="wp-modal-content">
<div class="wp-modal-header">
<h2>WordPress Embed Code</h2>
<span class="close-wp-modal">×</span>
</div>
<p><strong>Instructions:</strong></p>
<ol>
<li>Click the "Download HTML" button in the top bar to save your quiz file.</li>
<li>Upload this file to your WordPress Media Library or another place on your web server.</li>
<li>Copy the public URL of the uploaded file.</li>
<li>Replace <strong>`YOUR_QUIZ_URL/...`</strong> in the code below with the file's actual URL.</li>
<li>Paste the final code into a 'Custom HTML' block in your WordPress post or page.</li>
</ol>
<textarea id="wp-code-textarea" rows="5" readonly></textarea>
<button id="copy-wp-code-btn" class="btn btn-primary">
<span class="material-symbols-outlined">content_copy</span>
Copy Code
</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
let sectionCounter = 0;
let questionCounter = 0;
let _idCounter = 0;
let quizStructure = [];
let activeItemId = null;
const sectionsContainer = document.getElementById('sections-container');
const addSectionBtn = document.getElementById('add-section-btn');
const downloadHtmlBtn = document.getElementById('download-html-btn');
const copyHtmlBtn = document.getElementById('copy-html-btn');
const previewQuizBtn = document.getElementById('preview-quiz-btn');
const downloadPracticeBtn = document.getElementById('download-practice-btn');
const downloadAllPracticeBtn = document.getElementById('download-all-practice-btn');
const previewModal = document.getElementById('preview-modal');
const closePreviewBtn = document.querySelector('.close-preview');
const previewIframe = document.getElementById('preview-iframe');
const importBtn = document.getElementById('import-btn');
const bulkTextArea = document.getElementById('bulk-text');
const fileImportInput = document.getElementById('file-import');
const testStatusSelect = document.getElementById('test-status');
const customStatusContainer = document.getElementById('custom-status-container');
const quizEditorPanel = document.getElementById('quiz-editor-panel');
const welcomePanel = document.getElementById('welcome-panel');
const quizStructureContainer = document.getElementById('quiz-structure-container');
const addMainTabBtn = document.getElementById('add-main-tab-btn');
const manageAllBtn = document.getElementById('manage-all-btn');
const manageAllDropdown = document.querySelector('.manage-all-dropdown');
const expandAllBtn = document.getElementById('expand-all-btn');
const collapseAllBtn = document.getElementById('collapse-all-btn');
const deleteAllQuestionsBtn = document.getElementById('delete-all-questions-btn');
const deleteAllSectionsBtn = document.getElementById('delete-all-sections-btn');
// New WordPress code modal elements
const getWpCodeBtn = document.getElementById('get-wp-code-btn');
const wpCodeModal = document.getElementById('wp-code-modal');
const closeWpModalBtn = wpCodeModal.querySelector('.close-wp-modal');
const copyWpCodeBtn = document.getElementById('copy-wp-code-btn');
const wpCodeTextarea = document.getElementById('wp-code-textarea');
const generateId = (prefix) => `${prefix}-${_idCounter++}`;
function countQuizzes(item) {
if (item.type === 'quiz') {
return 1;
}
if (!item.children || item.children.length === 0) {
return 0;
}
return item.children.reduce((total, child) => total + countQuizzes(child), 0);
}
function createNewQuizData(name = 'New Quiz') {
return {
id: generateId('quiz'),
type: 'quiz',
name: name,
data: {
title: name,
userName: 'Rajesh Kumar',
status: 'Free Test',
instructions: document.getElementById('quiz-instructions').value,
timerDuration: 20,
difficulty: 'Medium',
languages: { primary: 'English', secondary: 'Hindi' },
settings: { viewAnswer: true, shuffleAnswers: false, randomizeQuiz: false, showPercentile: true },
sections: []
}
};
}
function switchActiveItem(itemId) {
if (activeItemId === itemId) return;
if (activeItemId) {
collectQuizData();
}
activeItemId = itemId;
let itemToLoad = null;
function findAndSet(items) {
for(const item of items) {
if (item.id === itemId) {
itemToLoad = item;
return true;
}
if (item.children && findAndSet(item.children)) return true;
}
return false;
}
findAndSet(quizStructure);
if (itemToLoad && itemToLoad.type === 'quiz') {
loadQuizData(itemToLoad);
} else {
loadQuizData(null); // It's a folder, so clear/hide the editor
}
renderStructure();
}
function addItem(parentId, type) {
let newItem;
if (type === 'quiz') {
const name = prompt("Enter the name for the new quiz:", "New Quiz");
if (!name) return;
newItem = createNewQuizData(name);
} else {
const name = prompt(`Enter the name for the new ${type === 'main' ? 'category' : 'sub-category'}:`, `New ${type === 'main' ? 'Category' : 'Sub-Category'}`);
if (!name) return;
newItem = {
id: generateId(type),
type: type,
name: name,
children: []
};
}
if (parentId === null) {
quizStructure.push(newItem);
} else {
function findAndAdd(items) {
for (const item of items) {
if (item.id === parentId) {
item.children.push(newItem);
return true;
}
if (item.children && findAndAdd(item.children)) return true;
}
return false;
}
findAndAdd(quizStructure);
}
renderStructure();
switchActiveItem(newItem.id);
}
function deleteItem(itemId) {
if (!confirm('Are you sure you want to delete this item and all its contents?')) return;
function findAndRemove(items, idToDelete) {
for (let i = 0; i < items.length; i++) {
if (items[i].id === idToDelete) {
items.splice(i, 1);
return true;
}
if (items[i].children && findAndRemove(items[i].children, idToDelete)) {
return true;
}
}
return false;
}
if (itemId === activeItemId) {
activeItemId = null;
loadQuizData(null);
}
findAndRemove(quizStructure, itemId);
renderStructure();
}
function updateItemName(itemId, newName) {
function findAndUpdate(items) {
for (const item of items) {
if (item.id === itemId) {
item.name = newName;
if(item.type === 'quiz') item.data.title = newName;
return true;
}
if (item.children && findAndUpdate(item.children)) return true;
}
return false;
}
findAndUpdate(quizStructure);
if(itemId === activeItemId) {
document.getElementById('quiz-title').value = newName;
}
}
function renderStructure() {
quizStructureContainer.innerHTML = '';
function renderLevel(items, parentElement) {
items.forEach(item => {
const itemContainer = document.createElement('div');
itemContainer.className = 'structure-item-container';
const canHaveChildren = item.type === 'main' || item.type === 'sub';
let actionsHtml = '';
if(item.type === 'main') {
actionsHtml += `<button class="action-btn" title="Add Sub-Category" data-action="add" data-type="sub" data-parent-id="${item.id}"><span class="material-symbols-outlined">create_new_folder</span></button>`;
}
if(canHaveChildren) {
actionsHtml += `<button class="action-btn" title="Add Quiz" data-action="add" data-type="quiz" data-parent-id="${item.id}"><span class="material-symbols-outlined">add</span></button>`;
}
actionsHtml += `<button class="action-btn delete-btn" title="Delete" data-action="delete" data-id="${item.id}"><span class="material-symbols-outlined">delete</span></button>`;
const iconName = canHaveChildren ? 'folder' : 'article';
let countHtml = '';
if (canHaveChildren) {
const quizCount = countQuizzes(item);
if (quizCount > 0) {
countHtml = `<span class="structure-item-count">${quizCount}</span>`;
}
}
const itemHtml = `
<div class="structure-item ${item.id === activeItemId ? 'active' : ''}" data-type="${item.type}" data-id="${item.id}">
<div class="structure-item-content">
<span class="material-symbols-outlined item-icon">${iconName}</span>
<input class="structure-item-name" value="${item.name}" data-id="${item.id}" readonly>
</div>
${countHtml}
<div class="structure-item-actions">
${actionsHtml}
</div>
</div>
`;
if (canHaveChildren) {
itemContainer.innerHTML = `
<details open>
<summary>${itemHtml}</summary>
<div class="structure-children"></div>
</details>
`;
if (item.children && item.children.length > 0) {
renderLevel(item.children, itemContainer.querySelector('.structure-children'));
}
} else {
itemContainer.innerHTML = itemHtml;
}
parentElement.appendChild(itemContainer);
});
}
renderLevel(quizStructure, quizStructureContainer);
}
quizStructureContainer.addEventListener('click', (e) => {
const itemEl = e.target.closest('.structure-item');
if (itemEl) {
const itemId = itemEl.dataset.id;
const actionBtn = e.target.closest('[data-action]');
if (actionBtn) {
e.stopPropagation();
const action = actionBtn.dataset.action;
if (action === 'add') {
addItem(actionBtn.dataset.parentId, actionBtn.dataset.type);
} else if (action === 'delete') {
deleteItem(actionBtn.dataset.id);
}
} else {
switchActiveItem(itemId);
}
}
});
quizStructureContainer.addEventListener('dblclick', e => {
const nameInput = e.target.closest('.structure-item-name');
if (nameInput) {
nameInput.readOnly = false;
nameInput.focus();
nameInput.select();
}
});
quizStructureContainer.addEventListener('focusout', (e) => {
const nameInput = e.target.closest('.structure-item-name');
if (nameInput && !nameInput.readOnly) {
nameInput.readOnly = true;
updateItemName(nameInput.dataset.id, nameInput.value);
renderStructure();
}
});
quizStructureContainer.addEventListener('keydown', (e) => {
const nameInput = e.target.closest('.structure-item-name');
if (nameInput && e.key === 'Enter') {
nameInput.blur();
}
});
addMainTabBtn.addEventListener('click', () => addItem(null, 'main'));
function loadQuizData(item) {
if (!item || item.type !== 'quiz') {
quizEditorPanel.classList.add('hidden');
welcomePanel.classList.remove('hidden');
document.getElementById('quiz-title').value = '';
document.getElementById('quiz-title').disabled = true;
return;
}
const data = item.data;
welcomePanel.classList.add('hidden');
quizEditorPanel.classList.remove('hidden');
document.getElementById('quiz-title').disabled = false;
document.getElementById('quiz-title').value = data.title;
document.getElementById('output-filename').value = data.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'quiz-series';
document.getElementById('user-name').value = data.userName;
document.getElementById('test-status').value = data.status;
document.getElementById('timer-duration').value = data.timerDuration;
document.getElementById('lang-primary-name').value = data.languages.primary;
document.getElementById('lang-secondary-name').value = data.languages.secondary;
document.getElementById('quiz-instructions').value = data.instructions;
document.getElementById('difficulty-level').value = data.difficulty;
document.getElementById('enable-view-answer').checked = data.settings.viewAnswer;
document.getElementById('enable-answer-shuffle').checked = data.settings.shuffleAnswers;
document.getElementById('enable-quiz-randomization').checked = data.settings.randomizeQuiz;
document.getElementById('enable-percentile').checked = data.settings.showPercentile;
sectionsContainer.innerHTML = '';
sectionCounter = 0;
questionCounter = 0;
if(data.sections) {
data.sections.forEach(sectionData => {
const sectionDiv = addSection(sectionData, false);
const questionsList = sectionDiv.querySelector('.questions-list');
if(sectionData.questions){
sectionData.questions.forEach(questionData => {
addQuestion(questionsList, questionData);
});
}
});
}
updateCountsAndSummaries();
}
window.updateCountsAndSummaries = function() {
renderStructure();
const sections = document.querySelectorAll('.section-container');
const summaryList = document.getElementById('section-summary-list');
if (!summaryList) return;
summaryList.innerHTML = '';
if (sections.length === 0) {
summaryList.innerHTML = '<li>No sections have been added yet.</li>';
return;
}
sections.forEach((section) => {
const nameInput = section.querySelector('.section-name');
const name = nameInput ? (nameInput.value.trim() || 'Unnamed Section') : 'Unnamed Section';
const questionCount = section.querySelectorAll('.question-card').length;
const listItem = document.createElement('li');
listItem.className = 'summary-section-item';
listItem.innerHTML = `
<span class="summary-section-name">${name}</span>
<span class="summary-question-count">${questionCount} Questions</span>
`;
summaryList.appendChild(listItem);
const countSpan = section.querySelector('.section-header-question-count');
if (countSpan) {
countSpan.textContent = `${questionCount} Qs`;
}
});
}
window.deleteSection = function(btn) {
if (confirm('Are you sure you want to delete this entire section and all its questions?')) {
btn.closest('.section-container').remove();
updateCountsAndSummaries();
}
}
window.deleteQuestion = function(btn) {
btn.closest('.question-card').remove();
updateCountsAndSummaries();
}
function collectQuestionData(card) {
const primaryOptions = Array.from(card.querySelectorAll('.option-entry')).map(entry => ({
text: entry.querySelector('.option-text').value,
image: entry.querySelector('.option-image').value,
}));
const secondaryOptions = Array.from(card.querySelectorAll('.option-entry')).map(entry => ({
text: entry.querySelector('.option-text-secondary').value,
image: entry.querySelector('.option-image-secondary').value,
}));
const correctEntry = card.querySelector('.option-entry.is-correct');
const correctIndex = correctEntry ? Array.from(card.querySelector('.options-container-dynamic').children).indexOf(correctEntry) : -1;
const data = {
content: {
primary: {
text: card.querySelector('.question-text').value,
image: card.querySelector('.question-image').value,
options: primaryOptions,
explanation: card.querySelector('.explanation-text').value,
explanation_image: card.querySelector('.explanation-image').value
},
secondary: {
text: card.querySelector('.question-text-secondary').value,
image: card.querySelector('.question-image-secondary').value,
options: secondaryOptions,
explanation: card.querySelector('.explanation-text-secondary').value,
explanation_image: card.querySelector('.explanation-image-secondary').value
}
},
correct: correctIndex,
positiveMark: parseFloat(card.querySelector('.positive-mark').value),
negativeMark: parseFloat(card.querySelector('.negative-mark').value),
topic: card.querySelector('.question-topic').value,
difficulty: card.querySelector('.question-difficulty').value,
instruction: card.querySelector('.question-instruction').value,
};
return data;
}
window.duplicateQuestion = function(btn) {
const originalCard = btn.closest('.question-card');
const questionsList = originalCard.parentElement;
const dataToDuplicate = collectQuestionData(originalCard);
addQuestion(questionsList, dataToDuplicate, originalCard);
};
window.duplicateSection = function(btn) {
const originalSection = btn.closest('.section-container');
const sectionData = {
name: originalSection.querySelector('.section-name').value + ' (Copy)',
duration: parseInt(originalSection.querySelector('.section-duration').value, 10),
rules: originalSection.querySelector('.section-rules').value,
};
const newSectionEl = addSection(sectionData, true, originalSection);
const newQuestionsList = newSectionEl.querySelector('.questions-list');
originalSection.querySelectorAll('.question-card').forEach(card => {
const questionData = collectQuestionData(card);
addQuestion(newQuestionsList, questionData);
});
updateCountsAndSummaries();
};
manageAllBtn.addEventListener('click', (e) => {
e.stopPropagation();
manageAllDropdown.classList.toggle('open');
});
window.addEventListener('click', (e) => {
if (!manageAllDropdown.contains(e.target)) {
manageAllDropdown.classList.remove('open');
}
});
expandAllBtn.addEventListener('click', () => {
document.querySelectorAll('#sections-container details').forEach(detail => detail.open = true);
manageAllDropdown.classList.remove('open');
});
collapseAllBtn.addEventListener('click', () => {
document.querySelectorAll('#sections-container details').forEach(detail => detail.open = false);
manageAllDropdown.classList.remove('open');
});
deleteAllQuestionsBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to delete ALL questions from ALL sections? This cannot be undone.')) {
document.querySelectorAll('.question-card').forEach(card => card.remove());
updateCountsAndSummaries();
}
manageAllDropdown.classList.remove('open');
});
deleteAllSectionsBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to delete ALL sections? This will remove all content. This cannot be undone.')) {
document.querySelectorAll('.section-container').forEach(sec => sec.remove());
updateCountsAndSummaries();
}
manageAllDropdown.classList.remove('open');
});
addSectionBtn.addEventListener('click', () => addSection());
downloadHtmlBtn.addEventListener('click', generateAndDownloadQuiz);
copyHtmlBtn.addEventListener('click', generateAndCopyQuiz);
previewQuizBtn.addEventListener('click', previewQuiz);
downloadPracticeBtn.addEventListener('click', generateAndDownloadPracticeSheet);
downloadAllPracticeBtn.addEventListener('click', generateAndDownloadAllPracticeSheets);
importBtn.addEventListener('click', () => handlePlainTextImport(bulkTextArea.value));
fileImportInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => {
const content = ev.target.result;
const filenameLower = file.name.toLowerCase();
if (filenameLower.endsWith('.csv')) {
handleCsvImport(content);
} else if (filenameLower.endsWith('.txt')) {
handlePlainTextImport(content);
} else if (filenameLower.endsWith('.html')) {
if (content.includes('[SECTION]') && content.includes('Q.1)')) {
handlePlainTextImport(content);
} else {
handleFullTestImport(content);
}
}
};
reader.readAsText(file);
e.target.value = '';
});
closePreviewBtn.addEventListener('click', () => previewModal.style.display = 'none');
window.addEventListener('click', (event) => { if (event.target == previewModal) { previewModal.style.display = 'none'; } });
testStatusSelect.addEventListener('change', (e) => {
if (e.target.value === 'Other') {
customStatusContainer.classList.remove('hidden');
} else {
customStatusContainer.classList.add('hidden');
}
});
function addSection(data = {}, updateSummary = true, insertAfterEl = null) {
sectionCounter++;
const sectionId = `s${sectionCounter}`;
const sectionDiv = document.createElement('div');
sectionDiv.className = 'section-container';
sectionDiv.id = sectionId;
sectionDiv.setAttribute('draggable', 'true');
sectionDiv.innerHTML = `
<details open>
<summary>
<div class="section-header">
<div class="section-name-wrapper">
<input type="text" class="section-name" oninput="updateCountsAndSummaries()" placeholder="Enter Section Name" value="${data.name || `Section ${sectionCounter}`}">
<span class="section-header-question-count">0 Qs</span>
</div>
<div class="section-header-actions">
<button class="btn btn-secondary btn-icon-only" title="Duplicate Section" onclick="duplicateSection(this)">
<span class="material-symbols-outlined">content_copy</span>
</button>
<button class="btn btn-danger btn-icon-only" title="Delete Section" onclick="deleteSection(this)">
<span class="material-symbols-outlined">delete</span>
</button>
</div>
</div>
</summary>
<div class="section-content-wrapper">
<div class="options-grid">
<div class="form-group">
<label>Section Duration (minutes, 0 for none)</label>
<input type="number" class="section-duration" min="0" value="${data.duration || 0}">
</div>
<div class="form-group">
<label>Section Rules</label>
<textarea class="section-rules" placeholder="e.g., You cannot return to this section after leaving.">${data.rules || ''}</textarea>
</div>
</div>
<div class="questions-list"></div>
<button class="btn btn-secondary" style="margin-top: 1rem;" onclick="addQuestion(this.previousElementSibling)">
<span class="material-symbols-outlined">add</span>
Add Question
</button>
</div>
</details>
`;
if (insertAfterEl) {
insertAfterEl.after(sectionDiv);
} else {
sectionsContainer.appendChild(sectionDiv);
}
if (updateSummary) {
updateCountsAndSummaries();
}
const questionsList = sectionDiv.querySelector('.questions-list');
questionsList.addEventListener('dragover', e => {
e.preventDefault();
const draggingCard = document.querySelector('.question-card.dragging');
if (!draggingCard) return;
const afterElement = getDragAfterElement(questionsList, e.clientY);
if (afterElement == null) {
questionsList.appendChild(draggingCard);
} else {
questionsList.insertBefore(draggingCard, afterElement);
}
});
return sectionDiv;
}
window.updateOptionLetters = function(optionsContainer) {
const optionEntries = optionsContainer.querySelectorAll('.option-entry');
optionEntries.forEach((entry, index) => {
entry.querySelector('.option-letter').textContent = String.fromCharCode(65 + index);
});
}
window.addOption = function(optionsContainer, data = {}) {
const optionEntry = document.createElement('div');
optionEntry.className = 'option-entry';
optionEntry.innerHTML = `
<span class="option-letter"></span>
<div style="flex-grow: 1; display: flex; flex-direction: column; gap: 0.5rem;">
<input type="text" class="option-text" placeholder="Write an answer option" value="${data.primary || ''}">
<input type="text" class="option-image" placeholder="Image URL (opt.)" value="${data.image || ''}">
<input type="text" class="option-text-secondary hidden" placeholder="Secondary language option" value="${data.secondary || ''}">
<input type="text" class="option-image-secondary hidden" placeholder="Secondary image URL (opt.)" value="${data.secondary_image || ''}">
</div>
<div class="option-actions">
<button class="btn btn-icon-only btn-correct" title="Mark as correct" onclick="markCorrect(this)">
<span class="material-symbols-outlined">check</span>
</button>
<button class="btn btn-icon-only btn-danger" title="Delete option" onclick="deleteOption(this)">
<span class="material-symbols-outlined">delete</span>
</button>
</div>
`;
optionsContainer.appendChild(optionEntry);
updateOptionLetters(optionsContainer);
}
window.deleteOption = function(btn) {
const optionEntry = btn.closest('.option-entry');
const optionsContainer = optionEntry.parentElement;
if (optionsContainer.children.length <= 1) {
alert("A question must have at least one option.");
return;
}
optionEntry.remove();
updateOptionLetters(optionsContainer);
}
window.markCorrect = function(btn) {
const currentEntry = btn.closest('.option-entry');
const optionsContainer = currentEntry.parentElement;
const isAlreadyCorrect = currentEntry.classList.contains('is-correct');
optionsContainer.querySelectorAll('.option-entry').forEach(entry => {
entry.classList.remove('is-correct');
});
if (!isAlreadyCorrect) {
currentEntry.classList.add('is-correct');
}
}
window.toggleSecondaryFields = function(checkbox) {
const card = checkbox.closest('.question-card');
const isChecked = checkbox.checked;
card.querySelectorAll('.secondary-lang-field').forEach(field => {
field.classList.toggle('hidden', !isChecked);
});
card.querySelectorAll('.option-text-secondary, .option-image-secondary').forEach(field => {
field.classList.toggle('hidden', !isChecked);
});
}
window.addQuestion = function(questionsList, data = null, insertAfterEl = null) {
questionCounter++;
const questionId = `q${questionCounter}`;
const questionCard = document.createElement('div');
questionCard.className = 'question-card';
questionCard.id = questionId;
questionCard.setAttribute('draggable', 'true');
const primaryContent = data?.content?.primary || {};
const secondaryContent = data?.content?.secondary || {};
questionCard.innerHTML = `
<div class="card-header">
<h4>Multiple Choice Question</h4>
<div class="card-header-actions">
<button class="btn btn-secondary btn-icon-only" title="Duplicate Question" onclick="duplicateQuestion(this)">
<span class="material-symbols-outlined">content_copy</span>
</button>
<button class="btn btn-danger btn-icon-only" title="Delete Question" onclick="deleteQuestion(this)">
<span class="material-symbols-outlined">delete</span>
</button>
</div>
</div>
<div class="question-card-grid">
<div class="question-config">
<div class="form-group">
<label>Positive Marks</label>
<input type="number" class="positive-mark" value="${data?.positiveMark ?? '1.0'}" step="0.25">
</div>
<div class="form-group">
<label>Negative Marks</label>
<input type="number" class="negative-mark" value="${data?.negativeMark ?? '0.25'}" step="0.25">
</div>
<div class="form-group">
<label>Difficulty</label>
<select class="question-difficulty">
<option ${data?.difficulty === 'Easy' ? 'selected' : ''}>Easy</option>
<option ${(!data?.difficulty || data?.difficulty === 'Medium') ? 'selected' : ''}>Medium</option>
<option ${data?.difficulty === 'Hard' ? 'selected' : ''}>Hard</option>
</select>
</div>
<div class="form-group">
<label>Tags</label>
<input type="text" class="question-topic" placeholder="e.g., Algebra, History" value="${data?.topic || ''}">
</div>
<div class="form-group-inline">
<input type="checkbox" id="q${questionCounter}-multi-answer" class="multi-answer">
<label for="q${questionCounter}-multi-answer" style="margin-bottom:0;">Multiple Answer</label>
</div>
<div class="form-group-inline">
<input type="checkbox" id="q${questionCounter}-partial-marking" class="partial-marking">
<label for="q${questionCounter}-partial-marking" style="margin-bottom:0;">Partial Marking</label>
</div>
</div>
<div class="question-content">
<div class="form-group">
<label>Instruction</label>
<textarea class="question-instruction" rows="2" placeholder="Write instructions for this question (optional)">${data?.instruction || ''}</textarea>
</div>
<div class="form-group">
<label>Question*</label>
<textarea class="question-text" placeholder="Write the question here...">${primaryContent.text || ''}</textarea>
<input type="text" class="question-image" style="margin-top: 0.5rem;" placeholder="Image URL for Question (optional)" value="${primaryContent.image || ''}">
</div>
<label>Choices*</label>
<div class="options-container-dynamic"></div>
<button class="btn btn-secondary" style="width: auto;" onclick="addOption(this.previousElementSibling)">
<span class="material-symbols-outlined">add</span> Add Choice
</button>
<div class="form-group" style="margin-top: 1.5rem;">
<label>Explanation</label>
<textarea class="explanation-text" rows="3" placeholder="Write an answer explanation...">${primaryContent.explanation || ''}</textarea>
<input type="text" class="explanation-image" style="margin-top: 0.5rem;" placeholder="Image URL for Explanation (optional)" value="${primaryContent.explanation_image || ''}">
</div>
<div class="form-group-inline" style="margin-top: 1.5rem; border-top: 1px dashed var(--border-color); padding-top: 1rem;">
<input type="checkbox" onchange="toggleSecondaryFields(this)" id="q${questionCounter}-secondary-lang">
<label for="q${questionCounter}-secondary-lang" style="margin-bottom:0;">Add Secondary Language Content</label>
</div>
<div class="secondary-lang-field hidden">
<div class="form-group">
<label>Question (Secondary)</label>
<textarea class="question-text-secondary" placeholder="Enter secondary language question...">${secondaryContent.text || ''}</textarea>
<input type="text" class="question-image-secondary" style="margin-top: 0.5rem;" placeholder="Image URL for Question (optional)" value="${secondaryContent.image || ''}">
</div>
<label>Choices (Secondary)</label>
<div class="form-group" style="margin-top: 1rem;">
<label>Explanation (Secondary)</label>
<textarea class="explanation-text-secondary" placeholder="Enter secondary language explanation...">${secondaryContent.explanation || ''}</textarea>
<input type="text" class="explanation-image-secondary" style="margin-top: 0.5rem;" placeholder="Image URL for Explanation (optional)" value="${secondaryContent.explanation_image || ''}">
</div>
</div>
</div>
</div>
`;
if (insertAfterEl) {
insertAfterEl.after(questionCard);
} else {
questionsList.appendChild(questionCard);
}
const optionsContainer = questionCard.querySelector('.options-container-dynamic');
const optionsData = primaryContent.options && primaryContent.options.length > 0 ? primaryContent.options : [{}, {}, {}, {}];
optionsData.forEach((optData, i) => {
const secondaryOptData = secondaryContent.options ? secondaryContent.options[i] : {};
const mergedOptionData = {
primary: optData.text || '',
image: optData.image || '',
secondary: secondaryOptData?.text || '',
secondary_image: secondaryOptData?.image || ''
};
addOption(optionsContainer, mergedOptionData);
});
if (data && typeof data.correct === 'number' && data.correct > -1) {
const correctBtn = optionsContainer.children[data.correct]?.querySelector('.btn-correct');
if (correctBtn) markCorrect(correctBtn);
}
const hasSecondaryContent = secondaryContent.text || secondaryContent.image || (secondaryContent.options && secondaryContent.options.some(o => o.text || o.image)) || secondaryContent.explanation;
if (hasSecondaryContent) {
const secondaryCheckbox = questionCard.querySelector(`#q${questionCounter}-secondary-lang`);
secondaryCheckbox.checked = true;
toggleSecondaryFields(secondaryCheckbox);
}
updateCountsAndSummaries();
}
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('[draggable="true"]:not(.dragging)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child };
} else {
return closest;
}
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
sectionsContainer.addEventListener('dragstart', e => {
if (e.target.classList.contains('section-container')) {
e.target.classList.add('dragging');
} else if (e.target.classList.contains('question-card')) {
e.target.classList.add('dragging');
}
});
sectionsContainer.addEventListener('dragend', e => {
if (e.target.classList.contains('section-container') || e.target.classList.contains('question-card')) {
e.target.classList.remove('dragging');
updateCountsAndSummaries();
}
});
sectionsContainer.addEventListener('dragover', e => {
e.preventDefault();
const draggingSection = document.querySelector('.section-container.dragging');
if (draggingSection) {
const afterElement = getDragAfterElement(sectionsContainer, e.clientY);
if (afterElement == null) {
sectionsContainer.appendChild(draggingSection);
} else {
sectionsContainer.insertBefore(draggingSection, afterElement);
}
}
});
function handleCsvImport(csvContent) {
if (!activeItemId) {
alert("Please select a quiz from the right sidebar to import questions into.");
return;
}
if (!csvContent.trim()) {
alert("The CSV file is empty."); return;
}
if (!confirm("This will add questions to the currently selected quiz. Are you sure?")) {
return;
}
const rows = csvContent.split('\n').map(row => row.trim()).filter(Boolean);
if (rows.length < 2) {
alert("CSV file must have a header row and at least one question row."); return;
}
const header = rows.shift().split(',').map(h => h.trim().toLowerCase());
const findIndex = (regex) => header.findIndex(h => regex.test(h));
const sectionIdx = findIndex(/section/i);
const questionIdx = findIndex(/question/i);
const optionIndices = header.map((h, i) => /option/i.test(h) ? i : -1).filter(i => i !== -1);
const explanationIdx = findIndex(/explanation/i);
const sectionMap = {};
rows.forEach(row => {
const cols = row.split(',');
const sectionName = sectionIdx > -1 ? cols[sectionIdx] : 'Imported Section';
if(!sectionMap[sectionName]) {
const sectionDiv = addSection({ name: sectionName });
sectionMap[sectionName] = sectionDiv.querySelector('.questions-list');
}
const questionsList = sectionMap[sectionName];
const options = [];
let correctIndex = -1;
optionIndices.forEach(optIdx => {
if (cols[optIdx]) {
let optionText = cols[optIdx].trim();
if (optionText.startsWith('*')) {
optionText = optionText.substring(1);
correctIndex = options.length;
}
options.push({ text: optionText, image: '' });
}
});
const questionData = {
content: { primary: { text: questionIdx > -1 ? cols[questionIdx] : '', options: options, explanation: explanationIdx > -1 ? cols[explanationIdx] : '' }},
correct: correctIndex,
};
addQuestion(questionsList, questionData);
});
alert('Questions from CSV file imported successfully!');
}
function handlePlainTextImport(text) {
if (!activeItemId) {
alert("Please select a quiz from the right sidebar to import questions into.");
return;
}
if (!text.trim()) {
alert("The text content is empty.");
return;
}
if (!confirm("This will add new sections and questions to the currently selected quiz based on the pasted text. Are you sure?")) {
return;
}
const lines = text.split('\n').filter(line => line.trim() !== '');
let currentSectionEl = null;
let currentQuestionData = null;
const sectionMap = {};
const processCurrentQuestion = () => {
if (currentQuestionData && currentSectionEl) {
if (currentQuestionData.content.primary.options.length > 0) {
addQuestion(currentSectionEl, currentQuestionData);
}
}
currentQuestionData = null;
};
lines.forEach(line => {
line = line.trim();
const sectionMatch = line.match(/^\s*\[SECTION\]\s*(.*)/i);
const questionMatch = line.match(/^\s*Q\.\d+\)\s*(.*)/i);
const optionMatch = line.match(/^\s*(\*?)\s*\[\d+\]\s*(.*)/i);
const marksMatch = line.match(/^\s*\[MARKS\]\s*([\d\.-]+)/i);
const negMarksMatch = line.match(/^\s*\[NEGATIVE MARKS\]\s*([\d\.-]+)/i);
const tagMatch = line.match(/^\s*\[TAG\]\s*(.*)/i);
const solutionMatch = line.match(/^\s*\[SOLUTION\]\s*(.*)/i);
if (sectionMatch) {
processCurrentQuestion();
const sectionName = sectionMatch[1].trim();
let existingSection = Array.from(document.querySelectorAll('.section-container')).find(s => s.querySelector('.section-name').value === sectionName);
if (existingSection) {
currentSectionEl = existingSection.querySelector('.questions-list');
} else {
const sectionDiv = addSection({ name: sectionName });
currentSectionEl = sectionDiv.querySelector('.questions-list');
}
} else if (questionMatch && currentSectionEl) {
processCurrentQuestion();
currentQuestionData = {
content: {
primary: { text: '', image: '', options: [], explanation: '', explanation_image: '' },
secondary: { text: '', image: '', options: [], explanation: '', explanation_image: '' }
},
correct: -1,
positiveMark: 1.0,
negativeMark: 0.25,
topic: '',
difficulty: 'Medium',
instruction: '',
};
const [primaryText, secondaryText] = (questionMatch[1] || '').split('||').map(s => s.trim());
currentQuestionData.content.primary.text = primaryText;
if(secondaryText) currentQuestionData.content.secondary.text = secondaryText;
} else if (optionMatch && currentQuestionData) {
const isCorrect = optionMatch[1] === '*';
const [primaryOpt, secondaryOpt] = (optionMatch[2] || '').split('||').map(s => s.trim());
currentQuestionData.content.primary.options.push({ text: primaryOpt, image: '' });
currentQuestionData.content.secondary.options.push({ text: secondaryOpt || '', image: '' });
if (isCorrect) {
currentQuestionData.correct = currentQuestionData.content.primary.options.length - 1;
}
} else if (marksMatch && currentQuestionData) {
currentQuestionData.positiveMark = parseFloat(marksMatch[1]);
} else if (negMarksMatch && currentQuestionData) {
currentQuestionData.negativeMark = parseFloat(negMarksMatch[1]);
} else if (tagMatch && currentQuestionData) {
currentQuestionData.topic = (tagMatch[1] || '').trim();
} else if (solutionMatch && currentQuestionData) {
const [primarySol, secondarySol] = (solutionMatch[1] || '').split('||').map(s => s.trim());
currentQuestionData.content.primary.explanation = primarySol;
if(secondarySol) currentQuestionData.content.secondary.explanation = secondarySol;
}
});
processCurrentQuestion();
updateCountsAndSummaries();
alert('Text imported successfully!');
}
function handleFullTestImport(content) {
if (!content.trim()) {
alert("The import content is empty."); return;
}
const structureMatch = content.match(/const quizStructureData = (\[[\s\S]*?\]);/);
const seriesMatch = content.match(/const quizSeriesData = (\[[\s\S]*?\]);/);
if (structureMatch && structureMatch[1]) {
if (!confirm("This will replace the entire quiz structure. Are you sure?")) return;
try {
quizStructure = JSON.parse(structureMatch[1]);
_idCounter = quizStructure.reduce((maxId, item) => Math.max(maxId, parseInt(item.id.split('-')[1] || 0)), 0) + 1;
activeItemId = null;
renderStructure();
loadQuizData(null);
alert('Quiz Structure imported successfully!');
} catch (e) {
console.error("Failed to parse quiz structure data:", e);
alert("Could not import quiz structure. The file may be corrupted.");
}
return;
}
if (seriesMatch && seriesMatch[1]) {
if (!confirm("This will import quizzes from an old file format into a new category, replacing the current structure. Are you sure?")) return;
try {
const seriesObject = JSON.parse(seriesMatch[1]);
const newMainCategory = {
id: generateId('main'),
type: 'main',
name: 'Imported Quizzes',
children: seriesObject.map(quizData => ({
id: generateId('quiz'),
type: 'quiz',
name: quizData.title,
data: quizData
}))
};
quizStructure = [newMainCategory];
activeItemId = null;
renderStructure();
loadQuizData(null);
alert('Old quiz series format imported successfully into a new category!');
} catch(e) {
alert("Could not parse the old format file.");
}
return;
}
alert("Could not detect a valid quiz structure in the file. Make sure it is a file previously generated by this tool.");
}
function collectQuizData() {
if (!activeItemId) return;
let activeQuiz = null;
function findActive(items) {
for(const item of items) {
if (item.id === activeItemId) {
activeQuiz = item;
return true;
}
if(item.children && findActive(item.children)) return true;
}
return false;
}
findActive(quizStructure);
if (!activeQuiz || activeQuiz.type !== 'quiz') return;
const statusSelect = document.getElementById('test-status');
let status = statusSelect.value;
if (status === 'Other') {
status = document.getElementById('test-status-custom').value || 'Custom Test';
}
const title = document.getElementById('quiz-title').value || 'Mock Test';
activeQuiz.name = title;
activeQuiz.data = {
title: title,
userName: document.getElementById('user-name').value || 'Guest',
status: status,
instructions: document.getElementById('quiz-instructions').value,
timerDuration: parseInt(document.getElementById('timer-duration').value, 10),
difficulty: document.getElementById('difficulty-level').value,
languages: {
primary: document.getElementById('lang-primary-name').value || 'Primary',
secondary: document.getElementById('lang-secondary-name').value || 'Secondary'
},
settings: {
viewAnswer: document.getElementById('enable-view-answer').checked,
shuffleAnswers: document.getElementById('enable-answer-shuffle').checked,
randomizeQuiz: document.getElementById('enable-quiz-randomization').checked,
showPercentile: document.getElementById('enable-percentile').checked,
},
sections: []
};
document.querySelectorAll('.section-container').forEach(secDiv => {
const sectionData = {
name: secDiv.querySelector('.section-name').value || 'Unnamed Section',
duration: parseInt(secDiv.querySelector('.section-duration').value, 10) || 0,
rules: secDiv.querySelector('.section-rules').value,
questions: []
};
secDiv.querySelectorAll('.question-card').forEach(card => {
sectionData.questions.push(collectQuestionData(card));
});
if (sectionData.questions.length > 0) activeQuiz.data.sections.push(sectionData);
});
const nameInputInTree = quizStructureContainer.querySelector(`.structure-item[data-id="${activeItemId}"] .structure-item-name`);
if(nameInputInTree && nameInputInTree.value !== title) {
nameInputInTree.value = title;
}
}
function generateAndDownloadQuiz() {
collectQuizData();
if(quizStructure.length === 0) {
alert('Please add at least one category before downloading.');
return;
}
const htmlContent = generateQuizSeriesHTML(quizStructure);
const blob = new Blob([htmlContent], { type: 'text/html' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
let filename = document.getElementById('output-filename').value.trim().replace(/\s+/g, '-');
filename = filename ? filename : 'quiz-series';
if (!filename.toLowerCase().endsWith('.html')) {
filename += '.html';
}
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function generateAndCopyQuiz() {
collectQuizData();
if (quizStructure.length === 0) {
alert('Please add at least one category before copying.');
return;
}
const htmlContent = generateQuizSeriesHTML(quizStructure);
navigator.clipboard.writeText(htmlContent).then(() => {
alert('Quiz Series HTML copied to clipboard!');
}, () => {
alert('Failed to copy HTML. Please try again.');
});
}
function previewQuiz() {
collectQuizData();
if (quizStructure.length === 0) {
alert('Please add at least one category to preview.');
return;
}
const htmlContent = generateQuizSeriesHTML(quizStructure);
previewIframe.srcdoc = htmlContent;
previewModal.style.display = 'flex';
}
function generateAndDownloadPracticeSheet() {
collectQuizData();
let activeQuizData = null;
function findAndGet(items) {
for (const item of items) {
if (item.id === activeItemId && item.type === 'quiz') {
activeQuizData = item.data;
return true;
}
if (item.children && findAndGet(item.children)) return true;
}
return false;
}
findAndGet(quizStructure);
if (!activeQuizData) {
alert("Please select an active quiz before downloading a practice sheet.");
return;
}
const totalQuestions = activeQuizData.sections.reduce((total, sec) => total + (sec.questions ? sec.questions.length : 0), 0);
if (totalQuestions === 0) {
alert("The selected quiz has no questions. Please add questions before generating a sheet.");
return;
}
const htmlContent = generatePracticeTestHTML(activeQuizData);
const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
let filename = (activeQuizData.title || 'practice-test').replace(/[^a-z0-9]+/gi, '_').toLowerCase();
a.download = `${filename}_practice_sheet.html`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function generateAndDownloadAllPracticeSheets() {
collectQuizData();
const allQuizzes = [];
function findAllQuizzes(items) {
for (const item of items) {
if (item.type === 'quiz') {
allQuizzes.push(item);
}
if (item.children) {
findAllQuizzes(item.children);
}
}
}
findAllQuizzes(quizStructure);
if (allQuizzes.length === 0) {
alert("There are no quizzes in the project to download.");
return;
}
const htmlContent = generateAllPracticeSheetsHTML(allQuizzes);
const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'all_quizzes_practice_sheet.html';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// --- New WordPress Code Functions ---
getWpCodeBtn.addEventListener('click', () => {
const filename = document.getElementById('output-filename').value.trim() || 'quiz-series';
const finalFilename = filename.toLowerCase().endsWith('.html') ? filename : filename + '.html';
const embedCode = `<iframe src="YOUR_QUIZ_URL/${finalFilename}" style="width:100%;height:800px;border:none;" title="Interactive Quiz"></iframe>`;
wpCodeTextarea.value = embedCode;
wpCodeModal.style.display = 'flex';
});
closeWpModalBtn.addEventListener('click', () => {
wpCodeModal.style.display = 'none';
});
copyWpCodeBtn.addEventListener('click', () => {
navigator.clipboard.writeText(wpCodeTextarea.value).then(() => {
alert('Embed code copied to clipboard!');
wpCodeModal.style.display = 'none';
}, (err) => {
alert('Failed to copy code. Please select and copy it manually.');
console.error('Could not copy text: ', err);
});
});
window.addEventListener('click', (event) => {
if (event.target == wpCodeModal) {
wpCodeModal.style.display = 'none';
}
});
// --- End WordPress Code Functions ---
function generateAllPracticeSheetsHTML(allQuizzes) {
let bodyContent = '';
let tocHTML = `
<main class="test-container toc">
<header class="test-header">
<img src="https://examups.com/wp-content/uploads/2024/08/cropped-Untitled_design-removebg-preview.png" alt="Examups Logo" class="test-logo">
<h1>Complete Practice Test Set</h1>
<p>A collection of all practice tests by Examups</p>
</header>
<h2 class="section-title">Table of Contents</h2>
<ol class="toc-list">
`;
allQuizzes.forEach((quiz, index) => {
tocHTML += `<li><a href="#quiz-${index}">${quiz.name}</a></li>`;
});
tocHTML += '</ol></main>';
bodyContent += tocHTML;
allQuizzes.forEach((quiz, index) => {
bodyContent += `<div class="quiz-page-wrapper" id="quiz-${index}">`;
bodyContent += generatePracticeTestContent(quiz.data);
bodyContent += `</div>`;
});
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>All Quizzes Practice Sheet</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-color: #4f46e5; --text-color: #1f2937; --text-light: #6b7280;
--bg-color: #f8f9fa; --content-bg: #ffffff; --border-color: #e5e7eb;
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body { font-family: 'Inter', sans-serif; line-height: 1.7; background-color: var(--bg-color); color: var(--text-color); margin: 0; padding: 1rem; }
.test-container { max-width: 8.5in; margin: 1rem auto; padding: 2rem; background: var(--content-bg); border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
.test-header { text-align: center; padding-bottom: 1.5rem; border-bottom: 1px solid var(--border-color); margin-bottom: 2rem; }
.test-logo { max-height: 50px; width: auto; margin-bottom: 1rem; }
.test-header h1 { font-size: 2rem; color: var(--text-color); margin: 0 0 0.5rem 0; }
.test-header p { color: var(--text-light); font-size: 1rem; margin: 0; }
.section-title { font-size: 1.5rem; font-weight: 600; color: var(--primary-color); border-bottom: 2px solid var(--border-color); padding-bottom: 0.5rem; margin: 2.5rem 0 1.5rem 0; }
.question-item { margin-bottom: 2rem; page-break-inside: avoid; }
.question-text { font-size: 1.1rem; font-weight: 500; margin-bottom: 1rem; }
.question-image { max-width: 100%; height: auto; border-radius: 6px; margin-bottom: 1rem; border: 1px solid var(--border-color); }
ol.options-list { list-style-type: lower-alpha; padding-left: 1.5rem; margin: 0; }
ol.options-list li { padding-left: 0.5rem; margin-bottom: 0.5rem; }
.table-container { overflow-x: auto; }
.answer-key-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; margin: 1rem 0; }
.answer-key-table th, .answer-key-table td { border: 1px solid var(--border-color); padding: 0.6rem; text-align: center; min-width: 50px; }
.answer-key-table th { background-color: var(--bg-color); font-weight: 600; }
.explanations-list { list-style: none; padding: 0; }
.explanation-item { padding: 1rem 0; border-bottom: 1px dashed var(--border-color); page-break-inside: avoid; }
.explanation-item:last-child { border-bottom: none; }
.explanation-item p { margin: 0 0 0.5rem 0; font-size: 1.05rem; }
.explanation-content { color: #374151; }
.explanation-image { max-width: 350px; height: auto; border-radius: 6px; margin-top: 0.5rem; border: 1px solid var(--border-color); }
.toc { page-break-after: always; }
.toc-list { padding-left: 0; list-style-position: inside; }
.toc-list li { font-size: 1.2rem; margin-bottom: 0.75rem; }
.toc-list a { text-decoration: none; color: var(--primary-color); font-weight: 500; }
.toc-list a:hover { text-decoration: underline; }
.quiz-page-wrapper { page-break-before: always; }
@media print {
body { padding: 0; background-color: #fff; }
.test-container { box-shadow: none; border: none; margin: 0; padding: 0.5in; max-width: 100%; }
.section-title { color: #000; }
.quiz-page-wrapper { margin-top: 1in; }
}
</style>
</head>
<body>
${bodyContent}
</body>
</html>
`;
}
function generatePracticeTestHTML(data) {
const bodyContent = generatePracticeTestContent(data);
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${data.title || 'Practice Test'}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-color: #4f46e5; --text-color: #1f2937; --text-light: #6b7280;
--bg-color: #f8f9fa; --content-bg: #ffffff; --border-color: #e5e7eb;
}
* { box-sizing: border-box; }
body { font-family: 'Inter', sans-serif; line-height: 1.7; background-color: var(--bg-color); color: var(--text-color); margin: 0; padding: 1rem; }
.test-container { max-width: 8.5in; margin: 1rem auto; padding: 2rem; background: var(--content-bg); border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
.test-header { text-align: center; padding-bottom: 1.5rem; border-bottom: 1px solid var(--border-color); margin-bottom: 2rem; }
.test-logo { max-height: 50px; width: auto; margin-bottom: 1rem; }
.test-header h1 { font-size: 2rem; color: var(--text-color); margin: 0 0 0.5rem 0; }
.test-header p { color: var(--text-light); font-size: 1rem; margin: 0; }
.section-title { font-size: 1.5rem; font-weight: 600; color: var(--primary-color); border-bottom: 2px solid var(--border-color); padding-bottom: 0.5rem; margin: 2.5rem 0 1.5rem 0; }
.question-item { margin-bottom: 2rem; page-break-inside: avoid; }
.question-text { font-size: 1.1rem; font-weight: 500; margin-bottom: 1rem; }
.question-image { max-width: 100%; height: auto; border-radius: 6px; margin-bottom: 1rem; border: 1px solid var(--border-color); }
ol.options-list { list-style-type: lower-alpha; padding-left: 1.5rem; margin: 0; }
ol.options-list li { padding-left: 0.5rem; margin-bottom: 0.5rem; }
.table-container { overflow-x: auto; }
.answer-key-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; margin: 1rem 0; }
.answer-key-table th, .answer-key-table td { border: 1px solid var(--border-color); padding: 0.6rem; text-align: center; min-width: 50px; }
.answer-key-table th { background-color: var(--bg-color); font-weight: 600; }
.explanations-list { list-style: none; padding: 0; }
.explanation-item { padding: 1rem 0; border-bottom: 1px dashed var(--border-color); page-break-inside: avoid; }
.explanation-item:last-child { border-bottom: none; }
.explanation-item p { margin: 0 0 0.5rem 0; font-size: 1.05rem; }
.explanation-content { color: #374151; }
.explanation-image { max-width: 350px; height: auto; border-radius: 6px; margin-top: 0.5rem; border: 1px solid var(--border-color); }
@media print {
body { padding: 0; background-color: #fff; }
.test-container { box-shadow: none; border: none; margin: 0; padding: 0.5in; max-width: 100%; }
.section-title { color: #000; }
}
</style>
</head>
<body>
${bodyContent}
</body>
</html>
`;
}
function generatePracticeTestContent(data) {
const topicName = data.title || 'Practice Test';
const toLetter = (index) => String.fromCharCode(97 + index);
let allQuestions = [];
data.sections.forEach(section => {
if (section.questions) allQuestions.push(...section.questions)
});
if (allQuestions.length === 0) {
return `
<main class="test-container">
<header class="test-header">
<img src="https://examups.com/wp-content/uploads/2024/08/cropped-Untitled_design-removebg-preview.png" alt="Examups Logo" class="test-logo">
<h1>${topicName}</h1>
</header>
<p>This test currently has no questions.</p>
</main>
`;
}
let questionsHTML = '';
allQuestions.forEach((q, index) => {
const primary = q.content.primary;
let optionsList = '';
primary.options.forEach(opt => {
optionsList += `<li>${opt.text || ''}</li>`;
});
questionsHTML += `
<div class="question-item">
<div class="question-text">
<strong>Q${index + 1}: </strong>${primary.text || ''}
</div>
${primary.image ? `<img src="${primary.image}" class="question-image" alt="Question ${index + 1} Image">` : ''}
<ol type="a" class="options-list">${optionsList}</ol>
</div>
`;
});
let answerKeyHTML = '<div class="table-container"><table class="answer-key-table">';
const numRows = Math.ceil(allQuestions.length / 10);
for (let i = 0; i < numRows; i++) {
let headerRow = '<tr>';
let answerRow = '<tr>';
for (let j = 0; j < 10; j++) {
const qIndex = i * 10 + j;
if (qIndex < allQuestions.length) {
headerRow += `<th>Q${qIndex + 1}</th>`;
answerRow += `<td>${allQuestions[qIndex].correct > -1 ? toLetter(allQuestions[qIndex].correct) : '-'}</td>`;
} else {
headerRow += '<th></th>';
answerRow += '<td></td>';
}
}
headerRow += '</tr>';
answerRow += '</tr>';
answerKeyHTML += headerRow + answerRow;
}
answerKeyHTML += '</table></div>';
let explanationsHTML = '';
allQuestions.forEach((q, index) => {
const primary = q.content.primary;
const correctOpt = q.correct > -1 && primary.options[q.correct] ? primary.options[q.correct] : null;
explanationsHTML += `
<li class="explanation-item">
<p><strong>${index + 1}. ${correctOpt ? `${toLetter(q.correct)}) ${correctOpt.text}` : 'N/A'}</strong></p>
<div class="explanation-content">
${primary.explanation || '<i>No explanation provided.</i>'}
${primary.explanation_image ? `<img src="${primary.explanation_image}" class="explanation-image" alt="Explanation Image">` : ''}
</div>
</li>`;
});
return `
<main class="test-container">
<header class="test-header">
<img src="https://examups.com/wp-content/uploads/2024/08/cropped-Untitled_design-removebg-preview.png" alt="Examups Logo" class="test-logo">
<h1>${topicName}</h1>
<p>A practice test by Examups</p>
</header>
<section>
<h2 class="section-title">📝 Questions</h2>
${questionsHTML}
</section>
<section>
<h2 class="section-title">✅ Answer Key</h2>
${answerKeyHTML}
</section>
<section>
<h2 class="section-title">📘 Explanations</h2>
<ol class="explanations-list">${explanationsHTML}</ol>
</section>
</main>`;
}
function generateQuizSeriesHTML(structure) {
let allQuizzesData = {};
function extractQuizzes(items) {
for(const item of items) {
if (item.type === 'quiz') {
allQuizzesData[item.id] = item.data;
}
if (item.children) {
extractQuizzes(item.children);
}
}
}
extractQuizzes(structure);
let mainTabsHtml = '';
let mainContentPanelsHtml = '';
let firstMain = true;
structure.forEach(mainTab => {
if (mainTab.type !== 'main') return;
const mainQuizCount = countQuizzes(mainTab);
mainTabsHtml += `<button class="main-tab-btn ${firstMain ? 'active' : ''}" data-target="#main-content-${mainTab.id}">${mainTab.name} (${mainQuizCount})</button>`;
let panelContent = '';
const hasSubTabs = mainTab.children.some(c => c.type === 'sub');
if(hasSubTabs) {
let subTabsHtml = '<div class="sub-tabs-container">';
let subContentPanelsHtml = '<div class="sub-content-panels">';
let firstSub = true;
mainTab.children.forEach(subTab => {
if (subTab.type !== 'sub') return;
const subQuizCount = countQuizzes(subTab);
subTabsHtml += `<button class="sub-tab-btn ${firstSub ? 'active' : ''}" data-target="#sub-content-${subTab.id}">${subTab.name} (${subQuizCount})</button>`;
let quizListHtml = '<div class="test-list-container">';
subTab.children.forEach(quiz => {
if (quiz.type !== 'quiz') return;
const totalQuestions = quiz.data.sections.reduce((sum, sec) => sum + (sec.questions ? sec.questions.length : 0), 0);
const totalMarks = quiz.data.sections.reduce((sum, sec) => sum + (sec.questions ? sec.questions.reduce((qSum, q) => qSum + q.positiveMark, 0) : 0), 0);
quizListHtml += `
<div class="test-card">
<div class="test-card-left">
<div class="test-icon-container"><span class="material-symbols-outlined">article</span></div>
<div class="test-details">
<h3 class="test-title">${quiz.name}</h3>
<div class="test-meta">
<span><span class="material-symbols-outlined">schedule</span> ${quiz.data.timerDuration} Minutes</span>
<span><span class="material-symbols-outlined">quiz</span> ${totalQuestions} Questions</span>
<span><span class="material-symbols-outlined">emoji_events</span> ${totalMarks.toFixed(0)} Marks</span>
</div>
</div>
</div>
<button class="btn-attempt" onclick="showInstructions('${quiz.id}')">Attempt Test</button>
</div>`;
});
quizListHtml += '</div>';
subContentPanelsHtml += `<div class="sub-tab-content ${firstSub ? 'active' : ''}" id="sub-content-${subTab.id}">${quizListHtml}</div>`;
firstSub = false;
});
subTabsHtml += '</div>';
subContentPanelsHtml += '</div>';
const wrappedSubTabs = `
<div class="tabs-wrapper">
<button class="scroll-arrow left-arrow material-symbols-outlined">chevron_left</button>
${subTabsHtml}
<button class="scroll-arrow right-arrow material-symbols-outlined">chevron_right</button>
</div>
`;
panelContent = wrappedSubTabs + subContentPanelsHtml;
} else { // No sub-tabs, just quizzes
let quizListHtml = '<div class="test-list-container">';
mainTab.children.forEach(quiz => {
if (quiz.type !== 'quiz') return;
const totalQuestions = quiz.data.sections.reduce((sum, sec) => sum + (sec.questions ? sec.questions.length : 0), 0);
const totalMarks = quiz.data.sections.reduce((sum, sec) => sum + (sec.questions ? sec.questions.reduce((qSum, q) => qSum + q.positiveMark, 0) : 0), 0);
quizListHtml += `
<div class="test-card">
<div class="test-card-left">
<div class="test-icon-container"><span class="material-symbols-outlined">article</span></div>
<div class="test-details">
<h3 class="test-title">${quiz.name}</h3>
<div class="test-meta">
<span><span class="material-symbols-outlined">schedule</span> ${quiz.data.timerDuration} Minutes</span>
<span><span class="material-symbols-outlined">quiz</span> ${totalQuestions} Questions</span>
<span><span class="material-symbols-outlined">emoji_events</span> ${totalMarks.toFixed(0)} Marks</span>
</div>
</div>
</div>
<button class="btn-attempt" onclick="showInstructions('${quiz.id}')">Attempt Test</button>
</div>`;
});
quizListHtml += '</div>';
panelContent = quizListHtml;
}
mainContentPanelsHtml += `<div class="main-tab-content ${firstMain ? 'active' : ''}" id="main-content-${mainTab.id}">${panelContent}</div>`;
firstMain = false;
});
const landingPageHtml = `
<h1 class="series-header">${document.getElementById('output-filename').value || "Quiz Series"}</h1>
<div class="tabs-wrapper">
<button class="scroll-arrow left-arrow material-symbols-outlined">chevron_left</button>
<div class="main-tabs-container">${mainTabsHtml}</div>
<button class="scroll-arrow right-arrow material-symbols-outlined">chevron_right</button>
</div>
<div class="main-content-panels">${mainContentPanelsHtml}</div>`;
const runnerScript = `
const allQuizzesData = ${JSON.stringify(allQuizzesData, null, 2)};
let quizData = null;
let charts = {};
let lastResultData = null;
const dom = {
seriesLanding: document.getElementById("series-landing-screen"),
instructions: document.getElementById("instructions-screen"),
quiz: document.getElementById("quiz-screen"),
result: document.getElementById("result-screen"),
submitSummary: document.getElementById('submit-summary-screen'),
timer: document.getElementById("timer"),
sectionTabs: document.getElementById("section-tabs"),
qNum: document.getElementById("question-num"),
qMarks: document.getElementById('question-marks'),
qText: document.getElementById("question-text"),
options: document.getElementById("options-container"),
palette: document.getElementById("palette-grid"),
saveNextBtn: document.getElementById("save-next-btn"),
markBtn: document.getElementById("mark-btn"),
clearBtn: document.getElementById("clear-btn"),
submitBtn: document.getElementById("submit-btn"),
submitConfirmBtn: document.getElementById('submit-confirm-btn'),
backToTestBtn: document.getElementById('back-to-test-btn'),
viewAnswersBtn: document.getElementById('view-answers-btn-main'),
viewAnswersContainer: document.getElementById('view-answers-container'),
themeToggleBtn: document.getElementById('theme-toggle-btn'),
themeIconSun: document.getElementById('theme-icon-sun'),
themeIconMoon: document.getElementById('theme-icon-moon'),
userNameDisplay: document.getElementById('user-name-display'),
userIcon: document.getElementById('user-icon'),
langSwitcher: document.getElementById('lang-switcher'),
palettePanel: document.getElementById('palette-panel'),
paletteToggleBtn: document.getElementById('palette-toggle-btn'),
closePaletteBtn: document.getElementById('close-palette-btn'),
paletteOverlay: document.getElementById('palette-overlay'),
closeResultBtn: document.getElementById('close-result-btn'),
quizHeaderTitle: document.getElementById('quiz-header-title'),
};
let flatQuestions = [], questionStates = [], currentQuestionIndex = 0, activeSectionIndex = 0, currentLanguage = 'primary';
let mainTimerId, questionLoadTime = 0;
let timeSpentPerQuestion = [];
const STATUS = { NOT_VISITED: "not-visited", NOT_ANSWERED: "not-answered", ANSWERED: "answered", MARKED_REVIEW: "marked-review", ANSWERED_MARKED_REVIEW: "answered-marked-review" };
function initializeTabScrolling() {
document.querySelectorAll('.tabs-wrapper').forEach(wrapper => {
const tabContainer = wrapper.querySelector('.main-tabs-container, .sub-tabs-container');
if (!tabContainer) return;
const leftArrow = wrapper.querySelector('.left-arrow');
const rightArrow = wrapper.querySelector('.right-arrow');
const scrollAmount = 300;
const checkArrows = () => {
if (window.innerWidth < 1025) {
leftArrow.style.display = 'none';
rightArrow.style.display = 'none';
return;
}
const isScrollable = tabContainer.scrollWidth > tabContainer.clientWidth;
if (isScrollable) {
leftArrow.style.display = 'flex';
rightArrow.style.display = 'flex';
const { scrollLeft, scrollWidth, clientWidth } = tabContainer;
leftArrow.disabled = scrollLeft <= 0;
rightArrow.disabled = scrollLeft + clientWidth >= scrollWidth - 1;
} else {
leftArrow.style.display = 'none';
rightArrow.style.display = 'none';
}
};
leftArrow.addEventListener('click', () => {
tabContainer.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
});
rightArrow.addEventListener('click', () => {
tabContainer.scrollBy({ left: scrollAmount, behavior: 'smooth' });
});
let scrollTimeout;
tabContainer.addEventListener('scroll', () => {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(checkArrows, 50);
});
window.addEventListener('resize', checkArrows);
setTimeout(checkArrows, 100);
});
}
function showInstructions(quizId) {
quizData = allQuizzesData[quizId];
if(!quizData) { console.error("Quiz not found:", quizId); return; }
const instructionsScreen = dom.instructions;
instructionsScreen.innerHTML = \`
<div class="card instructions-box">
<h2>General Instructions</h2>
<div class="instructions-content">
<div class="instructions-form" style="background:transparent; padding: 1rem 0 2rem 0;">
<div>
<label for="student-name" style="font-weight: 600;">Enter Your Name</label>
<input type="text" id="student-name" class="input-field" value="\${quizData.userName}">
</div>
<div style="margin-top: 1.5rem;">
<label for="default-language" style="font-weight: 600;">Choose your default language:</label>
<select id="default-language" class="input-field">
<option value="primary" selected>\${quizData.languages.primary}</option>
<option value="secondary">\${quizData.languages.secondary}</option>
</select>
</div>
</div>
\${quizData.instructions}
</div>
<div class="instructions-footer">
<button id="start-quiz-btn" class="btn-start-now">I'm Ready, Begin</button>
</div>
</div>
\`;
dom.seriesLanding.classList.add("hidden");
instructionsScreen.classList.remove("hidden");
document.getElementById("start-quiz-btn").addEventListener("click", startQuiz);
const elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen().catch(err => {
console.log(\`Error attempting to enable full-screen mode: \${err.message} (\${err.name})\`);
});
}
}
function applyTheme(theme) {
if (theme === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark'); dom.themeIconSun.classList.remove('hidden'); dom.themeIconMoon.classList.add('hidden');
} else {
document.documentElement.removeAttribute('data-theme'); dom.themeIconSun.classList.add('hidden'); dom.themeIconMoon.classList.remove('hidden');
}
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
localStorage.setItem('quizTheme', newTheme);
applyTheme(newTheme);
if (!dom.result.classList.contains('hidden') && lastResultData) { renderAllCharts(); }
}
function toggleMobilePalette() { dom.palettePanel.classList.toggle('open'); dom.paletteOverlay.classList.toggle('open'); }
function setupLanguageSwitcher() {
const primarySelected = currentLanguage === 'primary' ? 'selected' : '';
const secondarySelected = currentLanguage === 'secondary' ? 'selected' : '';
let switcherHTML = \`<select id="language-select-dropdown" class="lang-dropdown"><option value="primary" \${primarySelected}>\${quizData.languages.primary}</option>\`;
if (flatQuestions.some(q => q.content.secondary && q.content.secondary.text)) {
switcherHTML += \`<option value="secondary" \${secondarySelected}>\${quizData.languages.secondary}</option>\`;
}
switcherHTML += \`</select>\`;
dom.langSwitcher.innerHTML = switcherHTML;
const dropdown = document.getElementById('language-select-dropdown');
if(dropdown) {
dropdown.addEventListener('change', e => {
currentLanguage = e.target.value;
loadQuestion(currentQuestionIndex);
});
}
}
function initializeQuiz() {
flatQuestions = [];
questionStates = [];
currentQuestionIndex = 0;
activeSectionIndex = 0;
let globalIndex = 0;
quizData.sections.forEach((section, sIndex) => {
let questionsToPush = section.questions.map((q, qIndex) => ({ ...q, globalIndex: 0, sectionIndex: sIndex, sectionQuestionIndex: qIndex }));
if (quizData.settings.randomizeQuiz) {
for (let i = questionsToPush.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [questionsToPush[i], questionsToPush[j]] = [questionsToPush[j], questionsToPush[i]]; }
}
questionsToPush.forEach(q => {
q.globalIndex = globalIndex; flatQuestions.push(q); questionStates.push({ status: STATUS.NOT_VISITED, selectedOption: null }); globalIndex++;
});
});
timeSpentPerQuestion = new Array(flatQuestions.length).fill(0);
const sectionCounters = new Array(quizData.sections.length).fill(0);
flatQuestions.forEach(q => { q.sectionQuestionIndex = sectionCounters[q.sectionIndex]++; });
dom.viewAnswersBtn.addEventListener('click', () => { renderAllAnswers(); dom.viewAnswersContainer.scrollIntoView({ behavior: 'smooth' }); });
dom.themeToggleBtn.addEventListener('click', toggleTheme);
dom.submitBtn.addEventListener("click", showSubmitSummary);
dom.submitConfirmBtn.addEventListener("click", finalSubmit);
dom.backToTestBtn.addEventListener("click", () => dom.submitSummary.classList.add('hidden'));
dom.paletteToggleBtn.addEventListener('click', toggleMobilePalette);
dom.closePaletteBtn.addEventListener('click', toggleMobilePalette);
dom.paletteOverlay.addEventListener('click', toggleMobilePalette);
dom.closeResultBtn.addEventListener('click', () => location.reload());
const savedTheme = localStorage.getItem('quizTheme') || 'light';
applyTheme(savedTheme);
}
function startQuiz() {
const studentNameInput = document.getElementById('student-name');
const newName = studentNameInput.value.trim();
if (newName) {
quizData.userName = newName; dom.userNameDisplay.textContent = newName; dom.userIcon.textContent = newName.charAt(0).toUpperCase();
}
currentLanguage = document.getElementById('default-language').value;
initializeQuiz();
dom.instructions.classList.add("hidden"); dom.quiz.classList.remove("hidden");
dom.quizHeaderTitle.textContent = quizData.title;
if(quizData.timerDuration > 0) startTimer(quizData.timerDuration * 60);
else dom.timer.style.display = 'none';
setupLanguageSwitcher(); renderSectionTabs(); switchSection(0, true);
}
function startTimer(duration) {
let timeLeft = duration;
const update = () => {
const minutes = Math.floor(timeLeft / 60).toString().padStart(2, '0');
const seconds = (timeLeft % 60).toString().padStart(2, '0');
dom.timer.textContent = \`\${minutes}:\${seconds}\`;
};
update();
mainTimerId = setInterval(() => { timeLeft--; update(); if (timeLeft <= 0) { clearInterval(mainTimerId); finalSubmit(); } }, 1000);
}
function recordTimeSpent() {
if (questionLoadTime > 0) {
const timeSpent = (Date.now() - questionLoadTime) / 1000;
timeSpentPerQuestion[currentQuestionIndex] += timeSpent;
}
questionLoadTime = Date.now();
}
function loadQuestion(index) {
if (index < 0 || index >= flatQuestions.length) return;
recordTimeSpent();
if(questionStates[currentQuestionIndex].status === STATUS.NOT_VISITED) { questionStates[currentQuestionIndex].status = STATUS.NOT_ANSWERED; }
updatePaletteButton(currentQuestionIndex);
currentQuestionIndex = index;
const question = flatQuestions[index];
const state = questionStates[index];
if (state.status === STATUS.NOT_VISITED) state.status = STATUS.NOT_ANSWERED;
const content = (question.content[currentLanguage] && (question.content[currentLanguage].text || question.content[currentLanguage].image)) ? question.content[currentLanguage] : question.content.primary;
dom.qNum.textContent = \`Question \${question.sectionQuestionIndex + 1}\`;
dom.qMarks.textContent = \`Marks: +\${question.positiveMark.toFixed(2)}, -\${question.negativeMark.toFixed(2)}\`;
let questionHTML = '';
if (content.image) {
questionHTML += \`<img src="\${content.image}" alt="Question Image" class="q-media">\`;
}
questionHTML += content.text || '';
dom.qText.innerHTML = questionHTML;
dom.options.innerHTML = "";
let optionsToRender = content.options;
if (quizData.settings.shuffleAnswers) {
optionsToRender = [...content.options].sort(() => Math.random() - 0.5);
question.shuffledOptionsMap = optionsToRender.map(opt => content.options.indexOf(opt));
} else {
question.shuffledOptionsMap = optionsToRender.map((_, i) => i);
}
optionsToRender.forEach((opt, i) => {
const originalIndex = question.shuffledOptionsMap[i];
const optDiv = document.createElement("div");
optDiv.className = "option";
optDiv.dataset.index = originalIndex;
if (state.selectedOption === originalIndex) optDiv.classList.add("selected");
let optContentHTML = '';
if (opt.image) {
optContentHTML += \`<img src="\${opt.image}" alt="Option Image" class="opt-media">\`;
}
if (opt.text) {
optContentHTML += \`<div class="option-text">\${opt.text}</div>\`;
}
optDiv.innerHTML = \`<div class="option-label">\${String.fromCharCode(65 + i)}</div><div class="option-content">\${optContentHTML}</div>\`;
optDiv.addEventListener("click", () => selectOption(originalIndex));
dom.options.appendChild(optDiv);
});
updatePaletteButton(index); updateActivePaletteButton(index);
const isLastQuestion = index === flatQuestions.length - 1;
dom.saveNextBtn.textContent = isLastQuestion ? "Save" : "Save & Next";
dom.markBtn.disabled = isLastQuestion;
}
function renderSectionTabs() {
dom.sectionTabs.innerHTML = "";
quizData.sections.forEach((section, index) => {
const tab = document.createElement("li");
tab.className = "section-tab"; tab.textContent = section.name; tab.dataset.index = index;
if (index === activeSectionIndex) tab.classList.add("active");
tab.addEventListener("click", () => switchSection(index));
dom.sectionTabs.appendChild(tab);
});
}
function renderPalette() {
dom.palette.innerHTML = "";
flatQuestions.forEach((q, index) => {
if (q.sectionIndex === activeSectionIndex) {
const btn = document.createElement("button");
btn.className = "palette-btn"; btn.textContent = q.sectionQuestionIndex + 1; btn.dataset.index = index;
btn.addEventListener("click", () => {
processAndNavigate(index);
if (window.innerWidth <= 1024 && dom.palettePanel.classList.contains('open')) { toggleMobilePalette(); }
});
dom.palette.appendChild(btn); updatePaletteButton(index);
}
});
updateActivePaletteButton(currentQuestionIndex);
}
function updatePaletteButton(index) {
const btn = dom.palette.querySelector(\`[data-index="\${index}"]\`);
if (btn) { btn.className = "palette-btn"; btn.classList.add(questionStates[index].status); }
}
function updateActivePaletteButton(index) {
dom.palette.querySelectorAll(".palette-btn").forEach(b => b.classList.remove("active"));
const btn = dom.palette.querySelector(\`[data-index="\${index}"]\`);
if (btn) btn.classList.add("active");
}
function selectOption(index) {
questionStates[currentQuestionIndex].selectedOption = index;
dom.options.querySelectorAll(".option").forEach(opt => { opt.classList.toggle("selected", parseInt(opt.dataset.index) === index); });
}
function processCurrentQuestionState() {
const state = questionStates[currentQuestionIndex];
if (state.status !== STATUS.MARKED_REVIEW && state.status !== STATUS.ANSWERED_MARKED_REVIEW) {
state.status = state.selectedOption !== null ? STATUS.ANSWERED : STATUS.NOT_ANSWERED;
}
updatePaletteButton(currentQuestionIndex);
}
function processAndNavigate(nextIndex) {
processCurrentQuestionState();
if (nextIndex < flatQuestions.length) loadQuestion(nextIndex);
}
function switchSection(index, isInitial = false) {
if (!isInitial) processCurrentQuestionState();
activeSectionIndex = index;
renderSectionTabs(); renderPalette();
const firstQuestionOfSection = flatQuestions.findIndex(q => q.sectionIndex === index);
if (firstQuestionOfSection !== -1) { loadQuestion(firstQuestionOfSection); }
}
function showSubmitSummary() {
const answered = questionStates.filter(s => s.status === STATUS.ANSWERED || s.status === STATUS.ANSWERED_MARKED_REVIEW).length;
const notAnswered = questionStates.filter(s => s.status === STATUS.NOT_ANSWERED || s.status === STATUS.NOT_VISITED).length;
const marked = questionStates.filter(s => s.status === STATUS.MARKED_REVIEW || s.status === STATUS.ANSWERED_MARKED_REVIEW).length;
document.getElementById("summary-total").textContent = flatQuestions.length;
document.getElementById("summary-answered").textContent = answered;
document.getElementById("summary-not-answered").textContent = notAnswered;
document.getElementById("summary-marked").textContent = marked;
dom.submitSummary.classList.remove('hidden');
}
function finalSubmit() {
dom.submitSummary.classList.add('hidden'); recordTimeSpent(); clearInterval(mainTimerId);
let score = 0, correct = 0, incorrect = 0, attempted = 0, totalMarks = 0;
let timeOnCorrect = 0, timeOnIncorrect = 0, timeOnSkipped = 0;
let marksGained = 0, marksLost = 0, marksMissed = 0;
let sectionAnalysis = quizData.sections.map(s => ({ name: s.name, score: 0, correct: 0, incorrect: 0, attempted: 0, totalMarks: 0 }));
let topicAnalysis = {};
flatQuestions.forEach((q, i) => {
const state = questionStates[i];
const sectionStat = sectionAnalysis[q.sectionIndex];
totalMarks += q.positiveMark;
sectionStat.totalMarks += q.positiveMark;
const topic = q.topic || 'Uncategorized';
if (!topicAnalysis[topic]) { topicAnalysis[topic] = { myScore: 0, totalMarks: 0 }; }
topicAnalysis[topic].totalMarks += q.positiveMark;
if (state.selectedOption !== null) {
attempted++; sectionStat.attempted++;
if (state.selectedOption === q.correct) {
const mark = q.positiveMark; score += mark; correct++; marksGained += mark; sectionStat.score += mark; sectionStat.correct++; topicAnalysis[topic].myScore += mark; timeOnCorrect += timeSpentPerQuestion[i];
} else {
const mark = q.negativeMark; score -= mark; incorrect++; marksLost += mark; sectionStat.score -= mark; sectionStat.incorrect++; topicAnalysis[topic].myScore -= mark; timeOnIncorrect += timeSpentPerQuestion[i];
}
} else {
marksMissed += q.positiveMark; timeOnSkipped += timeSpentPerQuestion[i];
}
});
const userAccuracy = attempted > 0 ? (correct / attempted * 100) : 0;
lastResultData = {
score, totalMarks, marksGained, marksLost, marksMissed, correct, incorrect, attempted, totalTimeSpent: timeSpentPerQuestion.reduce((a, b) => a + b, 0), timeOnCorrect, timeOnIncorrect, timeOnSkipped, sectionAnalysis, topicAnalysis, userAccuracy,
};
dom.quiz.classList.add("hidden"); dom.result.classList.remove("hidden"); renderResultScreen(lastResultData);
}
function renderResultScreen(data) {
document.getElementById('result-quiz-title').textContent = quizData.title;
document.getElementById('result-score-display').innerHTML = \`<span id="final-score">\${data.score.toFixed(2)}</span> / \${data.totalMarks}\`;
document.getElementById('final-score').textContent = data.score.toFixed(2);
document.getElementById('result-summary-sentence').innerHTML = \`You have scored <b>\${data.marksGained.toFixed(2)} marks</b> for correct answers, lost <b>\${data.marksLost.toFixed(2)} marks</b> on incorrect answers, and missed <b>\${data.marksMissed.toFixed(2)} marks</b> by skipping questions.\`;
const totalTimeMinutes = Math.floor(data.totalTimeSpent / 60);
const totalTimeSeconds = Math.round(data.totalTimeSpent % 60);
document.getElementById('total-time-spent').innerHTML = \`\${totalTimeMinutes}m \${totalTimeSeconds}s\`;
document.getElementById('time-on-correct').textContent = data.totalTimeSpent > 0 ? \`\${(data.timeOnCorrect / data.totalTimeSpent * 100).toFixed(0)}%\` : '0%';
document.getElementById('time-on-incorrect').textContent = data.totalTimeSpent > 0 ? \`\${(data.timeOnIncorrect / data.totalTimeSpent * 100).toFixed(0)}%\` : '0%';
document.getElementById('time-on-skipped').textContent = data.totalTimeSpent > 0 ? \`\${(data.timeOnSkipped / data.totalTimeSpent * 100).toFixed(0)}%\` : '0%';
document.getElementById('score-summary-sentence').innerHTML = \`You have scored <b>\${data.marksGained.toFixed(2)} marks</b> for correct answers, lost <b>\${data.marksLost.toFixed(2)} marks</b> due to negative marking and missed <b>\${data.marksMissed.toFixed(2)} marks</b> by skipping questions.\`;
const sectionCardsContainer = document.getElementById('section-analysis-cards');
sectionCardsContainer.innerHTML = '';
data.sectionAnalysis.forEach(s => {
const accuracy = s.attempted > 0 ? (s.correct / s.attempted * 100).toFixed(0) : 0;
const percentage = s.totalMarks > 0 ? (s.score / s.totalMarks * 100).toFixed(0) : 0;
const percentile = (percentage * 0.9) + (Math.random() * 10);
sectionCardsContainer.innerHTML += \`<div class="card section-summary-card"><h4>\${s.name}</h4><div class="section-score-circle"><span>\${s.score.toFixed(2)}</span><span>out of \${s.totalMarks.toFixed(0)}</span></div><div class="section-card-stats"><div><span>Percentile</span> <strong>\${quizData.settings.showPercentile ? percentile.toFixed(2) : 'N/A'}</strong></div><div><span>Accuracy</span> <strong>\${accuracy}%</strong></div><div><span>Percentage</span> <strong>\${percentage}%</strong></div></div></div>\`;
});
const leaderboardBody = document.getElementById('leaderboard-body');
leaderboardBody.innerHTML = '';
const mockLeaderboard = [ { rank: 1, name: 'Aarav Sharma', score: Math.min(data.totalMarks, data.score * 1.8 + 25) }, { rank: 2, name: 'Priya Patel', score: Math.min(data.totalMarks, data.score * 1.5 + 15) }, { rank: 3, name: 'Rohan Gupta', score: Math.min(data.totalMarks, data.score * 1.2 + 5) } ];
const userEntry = { rank: 0, name: quizData.userName + ' (You)', score: data.score };
mockLeaderboard.push(userEntry);
mockLeaderboard.sort((a,b) => b.score - a.score).forEach((entry, i) => entry.rank = i + 1);
mockLeaderboard.slice(0, 5).forEach(entry => {
const isUser = entry.name.includes('(You)');
leaderboardBody.innerHTML += \`<tr class="\${isUser ? 'user-rank-row' : ''}"><td>#\${entry.rank}</td><td>\${entry.name}</td><td>\${entry.score.toFixed(2)}</td></tr>\`;
});
renderAllCharts();
}
function renderAllCharts() {
if (!lastResultData) return;
Object.values(charts).forEach(chart => chart.destroy());
const styles = getComputedStyle(document.documentElement);
const data = lastResultData;
const chartTextColor = styles.getPropertyValue('--text-primary').trim();
const primaryColor = styles.getPropertyValue('--primary').trim();
const greenColor = styles.getPropertyValue('--green').trim();
const redColor = styles.getPropertyValue('--red').trim();
const neutralColor = styles.getPropertyValue('--bg-alt').trim();
const lighterNeutralColor = styles.getPropertyValue('--border').trim();
const topperScore = Math.min(data.totalMarks, data.score * 1.8 + 25);
const avgScore = (topperScore + data.score) / 2 * 0.85;
const topperAccuracy = Math.min(99, data.userAccuracy * 1.2 + 15);
const avgAccuracy = Math.min(95, data.userAccuracy * 1.1 + 10);
charts.time = new Chart(document.getElementById('time-analysis-chart'), { type: 'doughnut', data: { datasets: [{ data: [data.timeOnCorrect, data.timeOnIncorrect, data.timeOnSkipped], backgroundColor: [greenColor, redColor, '#6b7280'], borderWidth: 0 }] }, options: { responsive: true, cutout: '70%', plugins: { legend: { display: false }, tooltip: { enabled: false } } } });
charts.score = new Chart(document.getElementById('score-analysis-chart'), { type: 'bar', data: { labels: ['Correct', 'Incorrect', 'Skipped'], datasets: [{ data: [data.correct, data.incorrect, (flatQuestions.length - data.attempted)], backgroundColor: [greenColor, redColor, '#a0aec0'], barThickness: 20, borderRadius: 4 }] }, options: { indexAxis: 'y', responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { x: { beginAtZero: true, grid: { display: false }, ticks: { color: chartTextColor } }, y: { grid: { display: false }, ticks: { color: chartTextColor } } } } });
charts.comparisonScore = new Chart(document.getElementById('comparison-score-chart'), { type: 'bar', data: { labels: ['Score'], datasets: [{ label: 'You', data: [data.score], backgroundColor: primaryColor }, { label: 'Topper', data: [topperScore], backgroundColor: neutralColor }, { label: 'Average', data: [avgScore], backgroundColor: lighterNeutralColor }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom', labels: { color: chartTextColor } } }, scales: { y: { beginAtZero: true, ticks: { color: chartTextColor } }, x: { ticks: { color: chartTextColor } } } } });
charts.comparisonAccuracy = new Chart(document.getElementById('comparison-accuracy-chart'), { type: 'bar', data: { labels: ['Accuracy'], datasets: [{ label: 'You', data: [data.userAccuracy], backgroundColor: primaryColor }, { label: 'Topper', data: [topperAccuracy], backgroundColor: neutralColor }, { label: 'Average', data: [avgAccuracy], backgroundColor: lighterNeutralColor }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom', labels: { color: chartTextColor } } }, scales: { y: { beginAtZero: true, max: 100, ticks: { color: chartTextColor, callback: (value) => value + '%' } }, x: { ticks: { color: chartTextColor } } } } });
charts.topic = new Chart(document.getElementById('topic-analysis-chart'), { type: 'bar', data: { labels: Object.keys(data.topicAnalysis), datasets: [{ label: 'My Score', data: Object.values(data.topicAnalysis).map(t => t.myScore), backgroundColor: primaryColor }, { label: 'Total Marks', data: Object.values(data.topicAnalysis).map(t => t.totalMarks), backgroundColor: neutralColor }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom', labels: { color: chartTextColor } } }, scales: { y: { beginAtZero: true, ticks: { color: chartTextColor } }, x: { ticks: { color: chartTextColor } } } } });
}
function renderAllAnswers() {
dom.viewAnswersBtn.textContent = 'Hide Solutions';
const container = dom.viewAnswersContainer;
if (!container.classList.contains('hidden')) {
container.classList.add('hidden'); dom.viewAnswersBtn.textContent = 'View Solutions'; return;
}
container.innerHTML = '<h3>Question Report</h3>';
flatQuestions.forEach((q, i) => {
const state = questionStates[i];
const card = document.createElement('div');
card.className = 'card view-answers-q-card';
const primaryContent = q.content.primary;
let optionsHTML = '';
const optionsOrder = q.shuffledOptionsMap || primaryContent.options.map((_, i) => i);
optionsOrder.forEach((originalIndex, displayIndex) => {
const opt = primaryContent.options[originalIndex];
let className = 'view-answers-option';
if (originalIndex === q.correct) className += ' correct';
else if (originalIndex === state.selectedOption) className += ' incorrect';
let singleOptionHTML = '';
if (opt.image) {
singleOptionHTML += \`<img src="\${opt.image}" alt="Option Image" class="opt-media" style="max-height: 200px;">\`;
}
if(opt.text) singleOptionHTML += \`<div>\${String.fromCharCode(65 + displayIndex)}. \${opt.text}</div>\`;
optionsHTML += \`<div class="\${className}">\${singleOptionHTML}</div>\`;
});
let explanationHTML = '';
if(primaryContent.explanation || primaryContent.explanation_image) {
explanationHTML = \`<div class="explanation"><strong>Explanation:</strong>\`;
if (primaryContent.explanation_image) {
explanationHTML += \`<img src="\${primaryContent.explanation_image}" alt="Explanation Image" class="expl-media">\`;
}
if (primaryContent.explanation) {
explanationHTML += \`<div>\${primaryContent.explanation}</div>\`;
}
explanationHTML += \`</div>\`;
}
let questionTextHTML = '';
if(primaryContent.image) {
questionTextHTML += \`<img src="\${primaryContent.image}" alt="Question Image" class="q-media">\`;
}
if(primaryContent.text) questionTextHTML += \`<div>\${primaryContent.text}</div>\`;
card.innerHTML = \`<div class="q-text"><strong>Q\${q.sectionQuestionIndex + 1}:</strong> \${questionTextHTML}</div><div>\${optionsHTML}</div>\${explanationHTML}\`;
container.appendChild(card);
});
container.classList.remove('hidden');
}
dom.saveNextBtn.addEventListener("click", () => {
if(currentQuestionIndex < flatQuestions.length -1) { processAndNavigate(currentQuestionIndex + 1) } else { processCurrentQuestionState(); }
});
dom.markBtn.addEventListener("click", () => {
const state = questionStates[currentQuestionIndex];
state.status = state.selectedOption !== null ? STATUS.ANSWERED_MARKED_REVIEW : STATUS.MARKED_REVIEW;
if(currentQuestionIndex < flatQuestions.length -1) { processAndNavigate(currentQuestionIndex + 1); } else { updatePaletteButton(currentQuestionIndex); }
});
dom.clearBtn.addEventListener("click", () => {
questionStates[currentQuestionIndex].selectedOption = null;
const state = questionStates[currentQuestionIndex];
if(state.status === STATUS.ANSWERED_MARKED_REVIEW) state.status = STATUS.MARKED_REVIEW;
else if(state.status === STATUS.ANSWERED) state.status = STATUS.NOT_ANSWERED;
loadQuestion(currentQuestionIndex);
});
document.addEventListener('click', e => {
if (e.target.matches('.main-tab-btn')) {
document.querySelectorAll('.main-tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.main-tab-content').forEach(p => p.classList.remove('active'));
e.target.classList.add('active');
const targetPanel = document.querySelector(e.target.dataset.target);
if (targetPanel) targetPanel.classList.add('active');
initializeTabScrolling();
}
if (e.target.matches('.sub-tab-btn')) {
const parentPanel = e.target.closest('.main-tab-content');
parentPanel.querySelectorAll('.sub-tab-btn').forEach(b => b.classList.remove('active'));
parentPanel.querySelectorAll('.sub-tab-content').forEach(p => p.classList.remove('active'));
e.target.classList.add('active');
const targetPanel = document.querySelector(e.target.dataset.target);
if (targetPanel) targetPanel.classList.add('active');
}
});
initializeTabScrolling();
`;
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${document.getElementById('output-filename').value || "Quiz Series"}</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"><\/script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"><\/script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"><\/script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
<style>
:root { --font-sans: 'Inter', sans-serif; --bg: #f8f9fa; --bg-alt: #ffffff; --text-primary: #1a202c; --text-secondary: #4a5568; --border: #e2e8f0; --primary: #4f46e5; --primary-light: #e0e7ff; --primary-dark: #4338ca; --green: #10b981; --red: #ef4444; --purple: #8b5cf6; --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05); --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); }
html[data-theme='dark'] { --bg: #1a202c; --bg-alt: #2d3748; --text-primary: #f7fafc; --text-secondary: #a0aec0; --border: #4a5568; --primary: #667eea; --primary-light: #3c366b; --primary-dark: #7f9cf5; }
html[data-theme='dark'] .instructions-content span[style*="background-color: #fff"] { background-color: var(--bg-alt) !important; color: var(--text-primary) !important; border-color: var(--border) !important; }
html[data-theme='dark'] .test-icon-container { background-color: var(--primary-light); }
* { box-sizing: border-box; } html { font-family: var(--font-sans); } body { margin: 0; background-color: var(--bg); color: var(--text-primary); font-size: 16px; line-height: 1.6; transition: background-color 0.3s, color 0.3s; }
button { font-family: var(--font-sans); cursor: pointer; border: none; transition: all 0.2s ease-in-out; }
.hidden { display: none !important; } .mobile-only { display: none; } .screen { min-height: 100vh; display: flex; flex-direction: column; } .container { max-width: 1280px; margin: 0 auto; width: 100%; padding: 0 1.5rem; }
.card { background-color: var(--bg-alt); border-radius: 12px; box-shadow: var(--shadow-md); border: 1px solid var(--border); transition: background-color 0.3s, border-color 0.3s; }
.input-field { width: 100%; padding: 12px; border-radius: 8px; border: 1px solid var(--border); font-size: 1rem; background-color: var(--bg); color: var(--text-primary); margin-top: 0.5rem; }
#series-landing-screen { justify-content: flex-start; align-items: stretch; padding-top: 2rem;}
.series-container { max-width: 900px; margin: 0 auto; width: 100%; padding: 2rem 1rem; }
.series-header { font-size: 1.75rem; font-weight: 700; margin-bottom: 2rem; color: var(--text-primary); }
.main-tabs-container { display: flex; border-bottom: 2px solid var(--border); margin-bottom: 1.5rem; overflow-x: auto; white-space: nowrap; scrollbar-width: none; -ms-overflow-style: none; }
.main-tabs-container::-webkit-scrollbar { display: none; }
.main-tab-btn { background: none; border: none; padding: 1rem 1.5rem; font-size: 1.1rem; font-weight: 600; cursor: pointer; color: var(--text-secondary); position: relative; }
.main-tab-btn.active { color: var(--primary); }
.main-tab-btn.active::after { content: ''; position: absolute; bottom: -2px; left: 0; right: 0; height: 2px; background: var(--primary); }
.main-tab-content { display: none; } .main-tab-content.active { display: block; }
.sub-tabs-container { display: flex; flex-wrap: nowrap; gap: 0.75rem; padding: 0.5rem; margin-bottom: 1.5rem; justify-content: flex-start; border-bottom: 1px solid var(--border); padding-bottom: 1rem; overflow-x: auto; scrollbar-width: none; -ms-overflow-style: none; }
.sub-tabs-container::-webkit-scrollbar { display: none; }
.sub-tab-btn { background: var(--bg); border: 1px solid var(--border); padding: 0.5rem 1.25rem; border-radius: 99px; font-size: 0.9rem; font-weight: 500; cursor: pointer; color: var(--text-secondary); white-space: nowrap; }
.sub-tab-btn.active { color: var(--primary); border-color: var(--primary); background-color: var(--primary-light); }
.sub-tab-content { display: none; } .sub-tab-content.active { display: block; }
.tabs-wrapper { position: relative; }
.scroll-arrow { position: absolute; top: 50%; transform: translateY(-50%); z-index: 5; background: var(--bg-alt); border: 1px solid var(--border); border-radius: 50%; width: 36px; height: 36px; cursor: pointer; display: none; justify-content: center; align-items: center; font-size: 24px; color: var(--text-secondary); box-shadow: var(--shadow-sm); }
.scroll-arrow:hover { background-color: var(--bg); color: var(--primary); }
.scroll-arrow.left-arrow { left: -18px; }
.scroll-arrow.right-arrow { right: -18px; }
.scroll-arrow:disabled { opacity: 0.3; cursor: not-allowed; }
.test-list-container { display: flex; flex-direction: column; gap: 1rem; }
.test-card { display: flex; justify-content: space-between; align-items: center; padding: 1.5rem; background-color: var(--bg-alt); border: 1px solid var(--border); border-radius: 12px; box-shadow: var(--shadow-sm); transition: box-shadow 0.2s ease-in-out, transform 0.2s ease-in-out; }
.test-card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); }
.test-card-left { display: flex; align-items: center; gap: 1.5rem; }
.test-icon-container { flex-shrink: 0; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; background-color: #eef2ff; color: var(--primary); border-radius: 8px; }
.test-icon-container .material-symbols-outlined { font-size: 24px; }
.test-details .test-title { font-size: 1.1rem; font-weight: 600; margin: 0 0 0.5rem 0; color: var(--text-primary); }
.test-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 1.5rem; font-size: 0.875rem; color: var(--text-secondary); }
.test-meta span { display: flex; align-items: center; gap: 0.5rem; }
.test-meta .material-symbols-outlined { font-size: 18px; }
.btn-attempt { background: var(--primary); color: white; padding: 10px 24px; border-radius: 8px; font-weight: 600; white-space: nowrap; }
#instructions-screen { justify-content: center; align-items: center; padding: 2rem 1rem; }
.instructions-box { max-width: 580px; width: 100%; padding: 0; overflow: hidden; display: flex; flex-direction: column; height: auto; max-height: 90vh; }
.btn-start-now { background-color: var(--primary); color: white; padding: 10px 24px; font-size: 1rem; border-radius: 6px; font-weight: 600; }
.instructions-box h2 { font-size: 1.5rem; margin: 0; text-align: center; padding: 1.5rem 1rem; border-bottom: 1px solid var(--border); }
.instructions-content { padding: 1.5rem 2rem 2rem; flex-grow: 1; overflow-y: auto; }
.instructions-content ol { padding-left: 20px; }
.instructions-footer { padding: 1.5rem 2rem; border-top: 1px solid var(--border); text-align: right; background-color: var(--bg-alt); }
#quiz-screen { height: 100vh; display: flex; flex-direction: column; overflow: hidden; background-color: var(--bg); }
.quiz-header { display: flex; justify-content: space-between; align-items: center; padding: 0 1.5rem; height: 65px; background: var(--bg-alt); border-bottom: 1px solid var(--border); flex-shrink: 0; box-shadow: var(--shadow-sm); }
.quiz-title { font-weight: 600; font-size: 1.25rem; }
.header-right { display: flex; align-items: center; gap: 1rem; }
#timer { font-size: 1.2rem; font-weight: 700; color: var(--text-secondary); }
.user-profile { display: flex; align-items: center; gap: 0.75rem; }
.user-icon { width: 36px; height: 36px; border-radius: 50%; background: var(--primary); color: white; display: flex; justify-content: center; align-items: center; font-weight: 600; font-size: 1.1rem; }
.theme-toggle { background: none; border-radius: 50%; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; color: var(--text-secondary); }
.lang-dropdown { background-color: var(--bg); color: var(--text-primary); border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; font-size: 0.9rem; font-family: var(--font-sans); font-weight: 500; -webkit-appearance: none; appearance: none; cursor: pointer; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e"); background-position: right 0.5rem center; background-repeat: no-repeat; background-size: 1.5em 1.5em; padding-right: 2.5rem; }
.section-bar { display: flex; align-items: center; justify-content: flex-start; padding: 0 1.5rem; height: 55px; background: var(--bg-alt); border-bottom: 1px solid var(--border); flex-shrink: 0; overflow-x: auto; scrollbar-width: none; }
.section-tabs { display: flex; gap: 0.5rem; list-style: none; margin: 0; padding: 0.5rem; background-color: var(--bg); border-radius: 8px; white-space: nowrap; }
.section-tab { padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-weight: 500; color: var(--text-secondary); flex-shrink: 0; }
.section-tab.active { background: var(--primary); color: white; box-shadow: var(--shadow-md); }
.quiz-main { display: flex; flex-grow: 1; overflow: hidden; gap: 1.5rem; padding: 1.5rem; }
.question-panel { flex-grow: 1; padding: 2rem; overflow-y: auto; display: flex; flex-direction: column; }
#question-header { display:flex; justify-content: space-between; align-items: center; }
#question-text { font-size: 1.2rem; line-height: 1.7; margin: 1.5rem 0 2rem 0; color: var(--text-primary); }
.options-container { display: grid; grid-template-columns: 1fr; gap: 1rem; }
.option { display: flex; align-items: center; gap: 1rem; padding: 1rem; border: 2px solid var(--border); border-radius: 8px; cursor: pointer; transition: all 0.2s ease-in-out; }
.option:hover { border-color: var(--primary); transform: translateY(-2px); }
.option.selected { border-color: var(--primary); background-color: var(--primary-light); }
.option.selected .option-label { background: var(--primary); color: white; border-color: var(--primary); }
.option-label { width: 28px; height: 28px; border-radius: 50%; border: 2px solid var(--border); display: flex; justify-content: center; align-items: center; font-weight: 600; flex-shrink: 0; }
.option-content { flex-grow: 1; }
.q-media, .opt-media, .expl-media { max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 0.75rem; background-color: var(--bg); }
.action-bar { margin-top: auto; padding-top: 1.5rem; border-top: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
.btn { border-radius: 8px; font-weight: 600; padding: 0.7rem 1.4rem; }
.btn-save { background: var(--green); color: white; } .btn-mark { background: var(--purple); color: white; } .btn-clear { background: none; color: var(--red); border: 1px solid var(--red); }
.palette-panel { width: 320px; flex-shrink: 0; padding: 1.5rem; display: flex; flex-direction: column; }
.palette-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(42px, 1fr)); gap: 1rem; flex-grow: 1; overflow-y: auto; padding: .5rem; }
.palette-btn { width: 44px; height: 44px; border-radius: 50%; border: 2px solid var(--border); cursor: pointer; font-size: 1rem; font-weight: 600; }
.palette-btn.active { border-color: var(--red); transform: scale(1.1); box-shadow: 0 0 0 3px var(--primary-light); }
.palette-btn.not-visited { background-color: var(--bg); color: var(--text-secondary); }
.palette-btn.not-answered { background-color: var(--red); color: white; border-color: var(--red); }
.palette-btn.answered { background-color: var(--green); color: white; border-color: var(--green); }
.palette-btn.marked-review { background-color: var(--purple); color: white; border-color: var(--purple); }
.palette-btn.answered-marked-review { background: linear-gradient(135deg, var(--purple) 50%, var(--green) 50%); color: white; border:none; }
#submit-btn { width: 100%; padding: 0.8rem; margin-top: 1.5rem; font-size: 1.1rem; border-radius: 8px; background-color: var(--primary); color: white; }
#close-palette-btn { display: none; }
.palette-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1999; opacity: 0; visibility: hidden; }
.palette-overlay.open { opacity: 1; visibility: visible; }
#submit-summary-screen { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 2000; display: flex; justify-content: center; align-items: center; text-align: center; }
.submit-summary-box { max-width: 450px; width: 100%; padding: 2.5rem; margin: 1rem; }
.submit-summary-box h2 { font-size: 1.75rem; border: none; margin-bottom: 0.5rem;}
.summary-stats { border: 1px solid var(--border); border-radius: 8px; margin-bottom: 2rem; text-align: left; }
.stat-item { display: flex; justify-content: space-between; align-items: center; padding: 1rem; font-size: 1rem; }
.stat-item:not(:last-child) { border-bottom: 1px solid var(--border); }
#result-screen { height: 100vh; overflow: hidden; }
.result-header { display: flex; justify-content: space-between; align-items: center; padding: 0 1.5rem; height: 65px; background: var(--bg-alt); border-bottom: 1px solid var(--border); }
.result-container { max-width: 1024px; margin: 0 auto; width: 100%; height: calc(100vh - 65px); overflow-y: auto; padding: 2rem 1rem;}
.result-section { margin-bottom: 3rem; }
.result-header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; }
.analysis-grid { display: grid; grid-template-columns: 1fr; gap: 2rem; }
@media (min-width: 768px) { .analysis-grid { grid-template-columns: 320px 1fr; } }
.analysis-card { padding: 1.5rem; }
.time-chart-container { max-width: 180px; margin: 0 auto; position: relative; }
.time-chart-center-text { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }
.section-cards-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 1.5rem; }
.section-summary-card { padding: 1.5rem; text-align: center; }
#view-answers-container { margin-top: 2.5rem; background-color: var(--bg-alt); padding: 1.5rem; border-radius: 12px; }
.view-answers-q-card { margin-bottom: 1.5rem; padding: 1.5rem; }
.view-answers-option { padding: 0.75rem; border-radius: 6px; margin-bottom: 0.5rem; border: 1px solid var(--border); }
.view-answers-option.correct { background: #10b98120; border-left: 4px solid var(--green); }
.view-answers-option.incorrect { background: #ef444420; border-left: 4px solid var(--red); }
.explanation { background-color: var(--bg); padding: 1rem; margin-top: 1rem; border-radius: 8px; border: 1px solid var(--border); }
#leaderboard table { width: 100%; border-collapse: collapse; }
.chart-container { position: relative; height: 250px; width: 100%; }
@media (max-width: 1024px) {
.mobile-only { display: flex; }
.quiz-header {
flex-direction: column;
height: auto;
gap: 0.75rem;
padding: 0.75rem 1rem;
align-items: center;
}
.quiz-title {
order: 1;
font-size: 1.1rem;
text-align: center;
}
.header-right {
order: 2;
width: 100%;
justify-content: space-between;
}
.quiz-main { flex-direction: column; padding: 0; gap: 0; overflow-y: auto; flex-grow: 1; }
.question-panel { padding: 1.5rem; padding-bottom: 120px; }
.palette-panel { position: fixed; top: 0; right: 0; bottom: 0; width: 300px; max-width: 80vw; z-index: 2000; transform: translateX(100%); transition: transform 0.3s ease-in-out; border-radius: 0; padding-top: 50px; }
.palette-panel.open { transform: translateX(0); }
#close-palette-btn { display: block; position: absolute; top: 10px; right: 15px; font-size: 2rem; background: none; border: none; }
}
@media (max-width: 768px) {
.test-card { flex-direction: column; align-items: flex-start; gap: 1.5rem; }
.test-card-left { flex-direction: column; align-items: flex-start; gap: 1rem; }
}
@media (max-width: 480px) {
#user-name-display { display: none; }
.header-right { gap: 0.5rem; }
}
</style>
</head>
<body>
<div id="series-landing-screen" class="screen">
<div class="series-container">
${landingPageHtml}
</div>
</div>
<div id="instructions-screen" class="screen hidden"></div>
<div id="quiz-screen" class="screen hidden">
<header class="quiz-header">
<div id="quiz-header-title" class="quiz-title"></div>
<div class="header-right">
<div id="lang-switcher"></div>
<div id="timer">00:00</div>
<div class="user-profile">
<div id="user-icon" class="user-icon">G</div>
<span id="user-name-display" style="font-weight:500;">Guest</span>
</div>
<button id="theme-toggle-btn" class="theme-toggle" title="Toggle Theme"><span id="theme-icon-sun" class="material-symbols-outlined hidden">light_mode</span><span id="theme-icon-moon" class="material-symbols-outlined">dark_mode</span></button>
<button id="palette-toggle-btn" class="theme-toggle mobile-only" title="Toggle Question Palette"><span class="material-symbols-outlined">apps</span></button>
</div>
</header>
<nav class="section-bar"><ul id="section-tabs" class="section-tabs"></ul></nav>
<main class="quiz-main">
<div class="question-panel card">
<div id="question-header"><div id="question-num" style="font-weight: 600;">Question 1</div><div id="question-marks"></div></div>
<p id="question-text">Question text will appear here.</p>
<div id="options-container" class="options-container"></div>
<div class="action-bar">
<div><button id="mark-btn" class="btn btn-mark">Mark & Next</button><button id="clear-btn" class="btn btn-clear">Clear</button></div>
<button id="save-next-btn" class="btn btn-save">Save & Next</button>
</div>
</div>
<div id="palette-panel" class="palette-panel card"><button id="close-palette-btn">×</button><div id="palette-grid" class="palette-grid"></div><button id="submit-btn" class="btn">Submit Test</button></div>
<div id="palette-overlay" class="palette-overlay"></div>
</main>
</div>
<div id="submit-summary-screen" class="screen hidden">
<div class="card submit-summary-box">
<h2>Submit Test?</h2><p>You are about to submit the test. Please review your attempt summary below.</p>
<div class="summary-stats">
<div class="stat-item"><span class="label">Total Questions</span><span id="summary-total" class="count">0</span></div>
<div class="stat-item"><span class="label">Answered</span><span id="summary-answered" class="count">0</span></div>
<div class="stat-item"><span class="label">Not Answered</span><span id="summary-not-answered" class="count">0</span></div>
<div class="stat-item"><span class="label">Marked for Review</span><span id="summary-marked" class="count">0</span></div>
</div>
<button id="submit-confirm-btn" class="btn-start-now" style="width:100%;">Confirm & Submit</button><button id="back-to-test-btn">Back to Test</button>
</div>
</div>
<div id="result-screen" class="screen hidden">
<header class="result-header">
<h2>Result</h2>
<button id="close-result-btn" title="Close"><span class="material-symbols-outlined">close</span></button>
</header>
<div class="result-container">
<div class="result-section"><div class="card" style="padding: 2rem; text-align:center;"><h1 id="result-quiz-title"></h1><div id="result-score-display"></div><p id="result-summary-sentence"></p><button id="view-answers-btn-main" class="btn-primary">View Solutions</button></div></div>
<div class="result-section"><div class="result-header-bar"><h2>Section Analysis</h2></div><div id="section-analysis-cards" class="section-cards-container"></div></div>
<div class="result-section"><div class="result-header-bar"><h2>How did you perform?</h2></div><div class="analysis-grid"><div class="analysis-card card"><h3>Time Analysis</h3><div class="time-chart-container"><canvas id="time-analysis-chart"></canvas><div class="time-chart-center-text"><strong id="total-time-spent"></strong><span>Total Time</span></div></div><div class="time-stats"><div><span>On Correct Answers</span> <strong id="time-on-correct"></strong></div><div><span>On Incorrect Answers</span> <strong id="time-on-incorrect"></strong></div><div><span>On Skipped</span> <strong id="time-on-skipped"></strong></div></div></div><div class="analysis-card card"><h3>Score Analysis</h3><div class="chart-container"><canvas id="score-analysis-chart"></canvas></div><p id="score-summary-sentence"></p></div></div></div>
<div class="result-section"><div class="result-header-bar"><h2>Where do you stand?</h2><span style="font-size: 0.9rem; color: var(--text-secondary);">*Leaderboard is simulated data</span></div><div class="analysis-grid"><div class="analysis-card card" id="leaderboard"><table><thead><tr><th>Rank</th><th>Learner Name</th><th>Score</th></tr></thead><tbody id="leaderboard-body"></tbody></table></div><div class="analysis-card card"><h3>You vs Topper vs Average</h3><div class="chart-container"><canvas id="comparison-score-chart"></canvas></div><div class="chart-container" style="margin-top:2rem"><canvas id="comparison-accuracy-chart"></canvas></div></div></div></div>
<div class="result-section"><div class="result-header-bar"><h2>Topic Report</h2></div><div class="card" style="padding:1.5rem;"><div class="chart-container"><canvas id="topic-analysis-chart"></canvas></div></div></div>
<div id="view-answers-container" class="hidden"></div>
</div>
</div>
<script>${runnerScript}<\/script>
</body>
</html>`;
}
// Initialize
init();
function init() {
renderStructure();
loadQuizData(null);
}
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Examups Quiz Builder</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
<style>
:root {
--primary-color: #4f46e5;
--primary-color-hover: #4338ca;
--primary-light: #eef2ff;
--secondary-bg: #f8f9fa;
--text-color: #1f2937;
--text-light: #6b7280;
--border-color: #e5e7eb;
--danger-color: #ef4444;
--danger-color-hover: #dc2626;
--success-color: #10b981;
--success-color-hover: #059669;
--white-color: #ffffff;
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
--shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
--radius: 0.5rem;
}
body {
font-family: var(--font-family);
background-color: var(--secondary-bg);
color: var(--text-color);
margin: 0;
font-size: 16px;
line-height: 1.6;
height: 100vh;
display: flex;
flex-direction: column;
}
h2 {
color: var(--text-color);
padding-bottom: 10px;
margin-top: 0;
margin-bottom: 2rem;
font-weight: 700;
font-size: 1.25rem;
border-bottom: 1px solid var(--border-color);
}
.top-bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 1.5rem;
background: var(--white-color);
border-bottom: 1px solid var(--border-color);
flex-shrink: 0;
}
.logo-container {
display: flex;
align-items: center;
}
#brand-logo {
height: 35px;
width: auto;
}
.top-bar .actions {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
.builder-layout {
display: flex;
flex-grow: 1;
overflow: hidden;
}
.sidebar, .center-panel {
padding: 1.5rem;
overflow-y: auto;
height: 100%;
box-sizing: border-box;
}
.left-sidebar {
flex: 0 0 380px;
background: var(--white-color);
border-right: 1px solid var(--border-color);
}
.center-panel {
flex-grow: 1;