Repository navigation
Expand file tree
/
Copy pathcourse-quiz.js
More file actions
231 lines (218 loc) · 10.1 KB
/
Copy pathcourse-quiz.js
File metadata and controls
231 lines (218 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { restoreQuizState, quizScore, quizResultLevel, quizReviewTopics, shuffleQuizChoices, updateQuizState } from './course-quiz-state.js';
const labels = {
en: {
question: (step, total) => `Question ${step} of ${total}`,
progress: 'Quiz progress',
unsaved: 'This browser cannot save your progress. You can still take the quiz on this page.',
submit: 'Submit answer', next: 'Next question', finish: 'Show result', restart: 'Try again',
correct: 'Correct', incorrect: 'Incorrect', selected: 'Selected answer',
review: 'Review: ',
correctCount: (score, total) => `Correct answers: ${score} of ${total}`,
results: {
success: { title: 'Congratulations! 🎉', description: 'You have a good understanding of this topic.' },
gaps: { title: 'Some gaps remain 🤔', description: 'Review the topics where you made mistakes:' },
reread: { title: 'Some things are still unclear 😢', description: 'Read through the whole topic again, then try the quiz once more.' },
},
},
ru: {
question: (step, total) => `Вопрос ${step} из ${total}`,
progress: 'Прогресс теста',
unsaved: 'Браузер не позволяет сохранить прогресс. Вы можете пройти тест на этой странице.',
submit: 'Отправить ответ', next: 'Следующий вопрос', finish: 'Показать результат', restart: 'Пройти ещё раз',
correct: 'Верно', incorrect: 'Неверно', selected: 'Выбранный ответ',
review: 'Повторить: ',
correctCount: (score, total) => `Правильных ответов: ${score} из ${total}`,
results: {
success: { title: 'Поздравляем! 🎉', description: 'Вы хорошо разобрались в теме.' },
gaps: { title: 'Остались пробелы 🤔', description: 'Повторите темы, в которых были ошибки:' },
reread: { title: 'Пока не всё понятно 😢', description: 'Перечитайте тему целиком и попробуйте пройти тест ещё раз.' },
},
},
};
function element(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
document.querySelectorAll('[data-course-quiz]').forEach((root) => {
const quiz = JSON.parse(root.dataset.courseQuiz);
const t = labels[root.dataset.locale] ?? labels.en;
const key = `course-quiz:${quiz.id}`;
let stored = null;
let storageAvailable = true;
try {
stored = localStorage.getItem(key);
// Check availability without changing an existing attempt.
localStorage.setItem(`${key}:probe`, '1');
localStorage.removeItem(`${key}:probe`);
} catch { storageAvailable = false; }
let state = restoreQuizState(quiz, stored);
const choiceOrders = new Map();
const progress = element('div', 'course-total-progress-bar');
progress.setAttribute('role', 'progressbar');
progress.setAttribute('aria-label', t.progress);
progress.setAttribute('aria-valuemin', '0');
progress.setAttribute('aria-valuemax', String(quiz.questions.length));
const segments = quiz.questions.map(() => {
const segment = element('span', 'course-total-progress-segment');
segment.setAttribute('aria-hidden', 'true');
segment.append(element('span'));
progress.append(segment);
return segment;
});
const body = element('div', 'course-quiz-body');
const storage = element('p', 'course-quiz-storage');
root.replaceChildren(progress, body, storage);
function renderStorage() {
storage.hidden = storageAvailable;
storage.textContent = storageAvailable ? '' : t.unsaved;
}
function save() {
try { localStorage.setItem(key, JSON.stringify(state)); storageAvailable = true; }
catch { storageAvailable = false; }
}
function transition(action, value) {
if (action === 'restart') {
for (const [id, previous] of choiceOrders) {
const next = shuffleQuizChoices(previous);
if (next.length > 1 && next.every((choice, index) => choice.id === previous[index].id)) next.push(next.shift());
choiceOrders.set(id, next);
}
}
state = updateQuizState(quiz, state, action, value);
save();
render(true);
}
function button(label, action) {
const node = element('button', 'course-button', label);
node.type = 'button';
node.addEventListener('click', () => transition(action));
return node;
}
function reviewLink(question) {
const paragraph = element('p', 'course-quiz-review', t.review);
const link = element('a', '', question.review.label);
link.href = question.review.href;
paragraph.append(link);
return paragraph;
}
function choices(question, answer, submitted, onChange) {
const fieldset = element('fieldset', 'course-quiz-choices');
const legend = element('legend', '', question.prompt);
legend.tabIndex = -1;
fieldset.append(legend);
if (!choiceOrders.has(question.id)) choiceOrders.set(question.id, shuffleQuizChoices(question.choices));
for (const choice of choiceOrders.get(question.id)) {
const label = element('label', 'course-quiz-choice');
const radio = element('input');
radio.type = 'radio';
radio.name = `${quiz.id}-${question.id}`;
radio.value = choice.id;
radio.checked = answer === choice.id;
radio.disabled = submitted;
if (submitted && choice.id === question.answer) label.dataset.correct = 'true';
if (submitted && radio.checked && choice.id !== question.answer) label.dataset.correct = 'false';
if (submitted) {
const description = [radio.checked ? t.selected : '', choice.id === question.answer ? t.correct : radio.checked ? t.incorrect : ''].filter(Boolean).join('. ');
if (description) radio.setAttribute('aria-label', `${choice.text}. ${description}`);
}
if (onChange) radio.addEventListener('change', () => onChange(choice.id));
label.append(radio, element('span', '', choice.text));
fieldset.append(label);
}
return fieldset;
}
function explanation(question, answer) {
const selected = question.choices.find((choice) => choice.id === answer);
const correct = question.choices.find((choice) => choice.id === question.answer);
const feedback = element('div', 'course-quiz-feedback');
feedback.dataset.correct = String(answer === question.answer);
feedback.tabIndex = -1;
feedback.setAttribute('role', 'status');
feedback.setAttribute('aria-label', answer === question.answer ? t.correct : t.incorrect);
if (answer !== question.answer) {
feedback.append(element('p', '', selected.explanation));
}
feedback.append(element('p', '', correct.explanation), reviewLink(question));
return feedback;
}
function render(focus = false) {
const total = quiz.questions.length;
const score = quizScore(quiz, state);
progress.setAttribute('aria-valuenow', String(state.answers.length));
progress.setAttribute('aria-valuetext', state.complete ? t.correctCount(score, total) : t.question(state.step + 1, total));
segments.forEach((segment, index) => {
const answered = index < state.answers.length;
const current = !state.complete && index === state.step && !answered;
segment.firstElementChild.style.width = answered ? '100%' : current ? '50%' : '0';
segment.dataset.state = state.complete
? state.answers[index] === quiz.questions[index].answer ? 'correct' : 'incorrect'
: answered ? 'done' : current ? 'current' : 'new';
});
root.dataset.state = state.complete ? 'complete' : 'question';
renderStorage();
body.replaceChildren();
let focusTarget;
if (state.complete) {
const level = quizResultLevel(quiz, state);
const result = t.results[level];
const title = element('p', 'course-quiz-result-title', result.title);
title.tabIndex = -1;
focusTarget = title;
body.append(title, element('p', '', result.description));
const topics = level === 'gaps' ? quizReviewTopics(quiz, state) : [];
if (topics.length) {
const list = element('ul', 'course-quiz-topics');
topics.forEach((topic) => {
const item = element('li');
const link = element('a', '', topic.label);
link.href = topic.href;
item.append(link);
list.append(item);
});
body.append(list);
}
body.append(button(t.restart, 'restart'));
} else {
const question = quiz.questions[state.step];
const submitted = state.answers.length > state.step;
const form = element('form', 'course-quiz-form');
let submit;
const fieldset = choices(question, state.selected, submitted, submitted ? null : (answer) => {
state = updateQuizState(quiz, state, 'choose', answer);
save();
renderStorage();
submit.disabled = false;
});
focusTarget = fieldset.querySelector('legend');
form.append(fieldset);
if (!submitted) {
submit = element('button', 'course-button', t.submit);
submit.type = 'submit';
submit.disabled = state.selected === null;
form.append(submit);
}
form.addEventListener('submit', (event) => {
event.preventDefault();
if (state.selected !== null && !submitted) transition('submit');
});
body.append(form);
if (submitted) {
const feedback = explanation(question, state.answers[state.step]);
focusTarget = feedback;
body.append(feedback, button(state.step === total - 1 ? t.finish : t.next, 'next'));
}
}
if (focus && focusTarget) focusTarget.focus({ preventScroll: true });
}
// Keep concurrent tabs and the other locale on the same saved attempt.
window.addEventListener('storage', (event) => {
if (event.key !== key && event.key !== null) return;
let value = null;
try { value = localStorage.getItem(key); } catch { storageAvailable = false; }
state = restoreQuizState(quiz, value);
render();
});
render();
});