-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq.ts
More file actions
473 lines (385 loc) · 14.8 KB
/
Copy pathq.ts
File metadata and controls
473 lines (385 loc) · 14.8 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
document.body.style.display = 'grid';
document.body.style.placeItems = 'center';
document.body.style.height = '100vh';
document.body.style.margin = '0px';
document.body.style.padding = '3vh';
type Question = {
questionText: string;
options: string[];
correctIndex: number;
result?: number;
}
const radio = (text: string) => {
const label = document.createElement('label');
label.style.display = 'flex';
label.style.gap = '.5ch';
label.style.cursor = 'pointer';
label.style.padding = '8px';
label.style.borderRadius = '3px';
label.onmouseenter = () => label.style.backgroundColor = '#eee';
label.onmouseleave = () => label.style.backgroundColor = '';
const input = document.createElement('input');
input.required = true;
input.name = 'x';
input.type = 'radio';
input.style.margin = '0px';
input.style.cursor = 'pointer';
const span = document.createElement('span');
span.textContent = text;
label.append(input, span);
return {
label,
input,
clear() {
label.style.cursor = '';
input.style.cursor = '';
label.onmouseenter = null;
label.onmouseleave = null;
}
};
};
const page = (question: Question) => {
const isResult = typeof question.result === 'number';
const form = document.createElement('form');
form.style.display = 'grid';
form.style.rowGap = '10px';
form.style.justifyContent = 'center';
const fieldset = document.createElement('fieldset');
fieldset.style.display = 'grid';
fieldset.style.rowGap = '10px';
fieldset.style.border = '1px solid #ccc';
fieldset.style.padding = '20px';
fieldset.disabled = isResult;
const radios = question.options.map(text => radio(text));
const questionDiv = document.createElement('div');
questionDiv.textContent = question.questionText;
questionDiv.style.width = 'fit-content';
questionDiv.style.placeSelf = 'center';
questionDiv.style.fontWeight = 'bold';
const submitButton = document.createElement('button');
submitButton.type = 'submit';
submitButton.textContent = 'I think I am right';
submitButton.style.marginTop = '20px';
const showAsResult = (selectedRadio: typeof radios[number], correctRadio: typeof radios[number]) => {
for (const item of radios) item.clear();
fieldset.disabled = true;
correctRadio.label.style.outline = '1px solid green';
if (selectedRadio !== correctRadio) selectedRadio.label.style.outline = '1px solid red';
submitButton.style.visibility = 'hidden';
submitButton.disabled = true;
};
form.append(questionDiv, fieldset);
fieldset.append(...radios.map(r => r.label));
if (isResult) {
const selectedRadio = radios[question.result as number];
const correctRadio = radios[question.correctIndex];
showAsResult(selectedRadio, correctRadio);
}
else {
form.append(submitButton);
}
const resolveSubmission: Promise<boolean> = new Promise(resolve => {
form.addEventListener('submit', (e) => {
e.preventDefault();
const correctRadio = radios[question.correctIndex]
const selectedRadio = radios.find(radio => radio.input.checked);
if (!selectedRadio) return;
showAsResult(selectedRadio, correctRadio);
question.result = radios.findIndex(radio => radio === selectedRadio);
resolve(selectedRadio === correctRadio);
});
});
return {
element: form,
resolveSubmission,
isResult
};
};
const game = (questions: Question[]) => {
const pages = questions.map(question => page(question));
let currentPage = 0;
let score = 0;
const main = document.createElement('main');
main.style.display = 'grid';
main.style.gridTemplateRows = '50px 50px min-content 50px';
main.style.gap = '5px;';
main.style.width = '400px';
main.style.height = 'fit-content';
const formDiv = document.createElement('div');
formDiv.style.margin = '30px 30px 0px 30px';
const topDiv = document.createElement('div');
topDiv.style.width = 'fit-content';
topDiv.style.placeSelf = 'center';
const scoreDiv = document.createElement('div');
scoreDiv.style.width = 'fit-content';
scoreDiv.style.placeSelf = 'end';
scoreDiv.textContent = 'Score: 0';
const buttonDiv = document.createElement('div');
buttonDiv.style.display = 'flex';
buttonDiv.style.justifyContent = 'space-between';
buttonDiv.style.alignItems = 'center';
const nextButton = document.createElement('button');
nextButton.type = 'button';
nextButton.addEventListener('click', () => {
if (currentPage === questions.length - 1) {
showUrl(createUrl(questions), main);
return;
}
currentPage++;
render();
});
const backButton = document.createElement('button');
backButton.textContent = 'Back';
backButton.type = 'button';
backButton.addEventListener('click', () => {
if (currentPage === 0) return;
currentPage--;
render();
});
buttonDiv.append(backButton, nextButton);
const render = () => {
const page = pages[currentPage];
formDiv.replaceChildren(page.element ?? 'Error. Fix this.');
backButton.style.visibility = currentPage === 0 ? 'hidden' : '';
nextButton.style.visibility = 'hidden';
page.resolveSubmission.then(isCorrect => {
nextButton.style.visibility = '';
nextButton.textContent = currentPage === questions.length - 1 ? 'Share Results' : 'Next';
if (!page.isResult && isCorrect) score++;
page.isResult = true;
scoreDiv.textContent = `Score: ${score}`;
})
topDiv.textContent = `Question ${currentPage + 1} of ${questions.length}`;
}
render();
main.append(scoreDiv, topDiv, formDiv, buttonDiv);
return main;
}
type AnswerInput = {
div: HTMLDivElement;
deleteButton: HTMLButtonElement;
readonly value: string;
readonly isCorrect: boolean;
}
const answerInput = (deleteSelf: (input: AnswerInput) => void, radioName: string): AnswerInput => {
const div = document.createElement('div');
div.style.display = 'flex';
div.style.gap = '5px';
const input = document.createElement('input');
input.type = 'text';
input.required = true;
input.pattern = '.*\\S.*';
input.maxLength = 40;
const radio = document.createElement('input');
radio.type = 'radio';
radio.required = true;
radio.name = radioName;
radio.style.margin = '0px';
radio.title = 'Correct answer';
const deleteButton = document.createElement('button');
deleteButton.type = 'button';
deleteButton.textContent = 'x';
deleteButton.title = 'Delete answer';
deleteButton.addEventListener('click', () => deleteSelf(obj));
deleteButton.style.visibility = 'hidden';
div.append(radio, input, deleteButton);
const obj = {
div,
deleteButton,
get value() {
return input.value;
},
get isCorrect() {
return radio.checked;
},
};
return obj;
};
type QuestionForm = {
form: HTMLFormElement;
buttonDiv: HTMLDivElement;
deleteQuestionButton: HTMLButtonElement;
readonly value: Question;
}
const questionForm = (deleteSelf: (q: QuestionForm) => void, updateButtonVisibility: (isEditing: boolean, current: QuestionForm) => void): QuestionForm => {
const form = document.createElement('form');
form.style.border = '1px solid #ccc';
form.style.padding = '15px';
form.addEventListener('submit', (e) => {
e.preventDefault();
fieldset.disabled = true;
updateButtonVisibility(false, obj);
buttonDiv.replaceChildren(editButton);
});
const fieldset = document.createElement('fieldset');
fieldset.style.display = 'grid';
fieldset.style.gap = '8px';
fieldset.style.border = '0px';
const questionTextInput = document.createElement('input');
questionTextInput.placeholder = 'Enter a question'
questionTextInput.type = 'text';
questionTextInput.required = true;
questionTextInput.pattern = '.*\\S.*';
questionTextInput.maxLength = 60;
const answerRadioName = crypto.randomUUID();
const answerInputs: AnswerInput[] = [];
const addAnswer = () => {
if (answerInputs.length >= 4) return;
const input = answerInput(() => removeAnswer(input), answerRadioName);
if (answerInputs.length) answerInputs[answerInputs.length - 1].div.after(input.div);
else questionTextInput.after(input.div);
answerInputs.push(input);
updateDeleteButtons();
addAnswerButton.style.visibility = answerInputs.length >= 4 ? 'hidden' : '';
};
const removeAnswer = (input: AnswerInput) => {
if (answerInputs.length <= 2) return;
input.div.remove();
answerInputs.splice(answerInputs.indexOf(input), 1);
updateDeleteButtons();
addAnswerButton.style.visibility = answerInputs.length >= 4 ? 'hidden' : '';
};
const updateDeleteButtons = () => {
for (const input of answerInputs) {
input.deleteButton.style.visibility = answerInputs.length > 2 ? 'visible' : 'hidden';
}
};
const buttonDiv = document.createElement('div');
buttonDiv.style.display = 'flex';
const deleteQuestionButton = document.createElement('button');
deleteQuestionButton.type = 'button';
deleteQuestionButton.textContent = 'Delete Question';
deleteQuestionButton.addEventListener('click', () => {
deleteSelf(obj);
updateButtonVisibility(false, obj);
});
const addAnswerButton = document.createElement('button');
addAnswerButton.type = 'button';
addAnswerButton.textContent = 'Add answer';
addAnswerButton.addEventListener('click', addAnswer);
const okButton = document.createElement('button');
okButton.type = 'submit';
okButton.textContent = 'OK';
const editButton = document.createElement('button');
editButton.type = 'button';
editButton.textContent = 'Edit';
editButton.addEventListener('click', () => {
fieldset.disabled = false;
buttonDiv.replaceChildren(deleteQuestionButton, addAnswerButton, okButton);
updateButtonVisibility(true, obj);
});
fieldset.append(questionTextInput);
addAnswer();
addAnswer();
buttonDiv.append(deleteQuestionButton, addAnswerButton, okButton);
form.append(fieldset, buttonDiv);
const obj = {
form,
buttonDiv,
deleteQuestionButton,
get value(): Question {
return {
questionText: questionTextInput.value.trim(),
options: answerInputs.map(input => input.value.trim()),
correctIndex: answerInputs.findIndex(input => input.isCorrect),
};
}
};
updateButtonVisibility(true, obj);
return obj;
};
const setup = () => {
const main = document.createElement('main');
main.style.padding = '10px';
main.style.display = 'grid';
main.style.gap = '30px';
const questionForms: QuestionForm[] = [];
const addQuestion = () => {
if (questionForms.length >= 10) return;
const q = questionForm(removeQuestion, updateButtonVisibility);
if (questionForms.length) questionForms[questionForms.length - 1].form.after(q.form);
else main.prepend(q.form);
questionForms.push(q);
};
const removeQuestion = (q: QuestionForm) => {
q.form.remove();
questionForms.splice(questionForms.indexOf(q), 1);
addQuestionButton.disabled = questionForms.length >= 10;
};
const addQuestionButton = document.createElement('button');
addQuestionButton.type = 'button';
addQuestionButton.textContent = 'Add a question';
addQuestionButton.addEventListener('click', addQuestion);
const saveQuizButton = document.createElement('button');
saveQuizButton.type = 'button';
saveQuizButton.textContent = 'Save Quiz';
saveQuizButton.style.visibility = 'hidden';
saveQuizButton.addEventListener('click', () => {
const questions = questionForms.map(q => q.value);
showUrl(createUrl(questions), main);
});
const buttonDiv = document.createElement('div');
buttonDiv.style.display = 'flex';
buttonDiv.append(addQuestionButton, saveQuizButton);
const updateButtonVisibility = (isEditing: boolean, current: QuestionForm) => {
addQuestionButton.disabled = questionForms.length >= 10;
buttonDiv.style.display = isEditing ? 'none' : 'flex';
for (const form of questionForms.filter(f => f !== current)) form.buttonDiv.style.visibility = isEditing ? 'hidden' : '';
saveQuizButton.style.visibility = questionForms.length ? 'visible' : 'hidden';
}
main.append(buttonDiv);
return main;
};
const showUrl = (url: string, main: HTMLElement) => {
const pre = document.createElement('pre');
const a = document.createElement('a');
a.href = url;
a.textContent = url;
pre.append(a);
pre.style.width = '500px';
pre.style.whiteSpace = 'pre-wrap';
pre.style.wordBreak = 'break-word';
main.replaceChildren(pre);
}
const getResults = (questions: Question[]) => {
const pages = questions.map(q => page(q)).map(p => p.element);
for (const page of pages) {
page.style.boxShadow = '0px 0px 3px 1px #eee';
page.style.padding = '30px';
}
const main = document.createElement('main');
main.style.display = 'flex';
main.style.flexFlow = 'row wrap';
main.style.gap = '40px';
main.append(...pages);
return main;
}
const createUrl = (questions: Question[]) => {
const url = new URL('/quiz/index.html', window.location.origin);
url.search = `?${convertQuestionsToBase64(questions)}`;
return url.toString();
};
const convertQuestionsToBase64 = (questions: Question[]): string => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(questions))));
const getQuestionsFromBase64 = (str: string): Question[] => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(str), c => c.charCodeAt(0))));
const startGame = (questions: Question[]) => document.body.replaceChildren(game(questions));
const startSetup = () => document.body.replaceChildren(setup());
const showResults = (questions: Question[]) => document.body.replaceChildren(getResults(questions));
const base64String = window.location.search.slice(1);
if (base64String) {
try {
const questions = getQuestionsFromBase64(base64String);
if (typeof questions[0].result === 'number') {
showResults(questions);
console.log(questions);
}
else {
startGame(questions);
}
}
catch {
startSetup();
}
}
else {
startSetup();
}