Download app.js from RBSesl13/README: direct link, hf CLI and curl.
- Browser
- Download file 57.4 kB
-
https://huggingface.co/spaces/RBSesl13/README/resolve/main/app.js
- Command line
-
hf download hf://spaces/RBSesl13/README/app.js
-
curl -L -o app.js https://huggingface.co/spaces/RBSesl13/README/resolve/main/app.js
57.4 kB
// ESL SPARK ENGINE v1.2.0
// Utilities
const ACTIVITY_ORDER = ['act-1', 'act-2', 'act-3', 'act-4', 'act-5', 'act-6'];
let sessionState = null;
function normalize(str) {
return String(str)
.trim()
.toLowerCase()
.replace(/[.,!?'"()]/g, '')
.replace(/\s+/g, ' ');
}
function isCorrect(userInput, acceptedAnswers) {
const normalized = normalize(userInput);
return acceptedAnswers.some((answer) => normalize(answer) === normalized);
}
function isPartial(userInput, correctAnswer) {
const user = normalize(userInput);
const correct = normalize(correctAnswer);
if (!user || !correct) {
return false;
}
return (user.includes(correct) || correct.includes(user)) && user !== correct;
}
function shuffleArray(arr) {
const copy = [...arr];
for (let i = copy.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
function createTimer() {
let start = null;
return {
begin() {
start = performance.now();
},
elapsed() {
return start ? Math.round(performance.now() - start) : 0;
},
reset() {
start = null;
}
};
}
function fireAttempt(element, detail) {
if (!(element instanceof EventTarget)) {
return;
}
element.dispatchEvent(new CustomEvent('esl:attempt', {
bubbles: true,
detail: {
...detail,
time_on_item_ms: detail.time_on_item_ms || 0
}
}));
}
function createAttemptTracker(config) {
const attempts = new Map();
return {
record(itemId) {
const count = (attempts.get(itemId) || 0) + 1;
attempts.set(itemId, count);
return count;
},
get(itemId) {
return attempts.get(itemId) || 0;
},
isExhausted(itemId) {
if (config.attempts_max === null) {
return false;
}
return this.get(itemId) >= config.attempts_max;
},
shouldShowHint(itemId) {
return Boolean(
config.hint &&
config.hint.trigger === 'after_first_wrong_attempt' &&
this.get(itemId) >= 1
);
},
reset() {
attempts.clear();
}
};
}
function renderMedia(container, media) {
if (!media) {
return;
}
const figure = document.createElement('figure');
figure.className = 'esl-media-block';
const img = document.createElement('img');
img.src = media.src;
img.alt = media.alt;
img.className = 'esl-media-img';
figure.appendChild(img);
if (media.caption) {
const caption = document.createElement('figcaption');
caption.className = 'esl-media-caption';
caption.textContent = media.caption;
figure.appendChild(caption);
}
container.prepend(figure);
}
function makeDraggable(element, options) {
const { signal, onDragStart, onDragMove, onDragEnd } = options;
let isDragging = false;
let ghost = null;
let offsetX = 0;
let offsetY = 0;
const cleanupPointerDrag = () => {
isDragging = false;
if (ghost) {
ghost.remove();
ghost = null;
}
element.classList.remove('dragging');
};
element.style.touchAction = 'none';
element.setAttribute('draggable', 'true');
element.addEventListener('dragstart', (event) => {
event.dataTransfer.setData('text/plain', element.dataset.tokenId);
event.dataTransfer.effectAllowed = 'move';
element.classList.add('dragging');
onDragStart?.(element, event);
}, { signal });
element.addEventListener('dragend', (event) => {
cleanupPointerDrag();
onDragEnd?.(element, event, null);
}, { signal });
element.addEventListener('pointerdown', (event) => {
if (event.pointerType === 'mouse') {
return;
}
isDragging = true;
element.setPointerCapture(event.pointerId);
const rect = element.getBoundingClientRect();
offsetX = event.clientX - rect.left;
offsetY = event.clientY - rect.top;
ghost = element.cloneNode(true);
ghost.classList.add('drag-ghost');
ghost.style.position = 'fixed';
ghost.style.zIndex = '9999';
ghost.style.pointerEvents = 'none';
ghost.style.width = `${rect.width}px`;
document.body.appendChild(ghost);
element.classList.add('dragging');
onDragStart?.(element, event);
}, { signal });
element.addEventListener('pointermove', (event) => {
if (!isDragging || !ghost) {
return;
}
ghost.style.left = `${event.clientX - offsetX}px`;
ghost.style.top = `${event.clientY - offsetY}px`;
onDragMove?.(element, event);
}, { signal });
element.addEventListener('pointerup', (event) => {
if (!isDragging) {
return;
}
cleanupPointerDrag();
const dropTarget = document.elementFromPoint(event.clientX, event.clientY);
onDragEnd?.(element, event, dropTarget);
}, { signal });
element.addEventListener('pointercancel', cleanupPointerDrag, { signal });
}
function makeDropZone(element, options) {
const { signal, onDrop } = options;
element.addEventListener('dragover', (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
element.classList.add('drag-over');
}, { signal });
element.addEventListener('dragleave', () => {
element.classList.remove('drag-over');
}, { signal });
element.addEventListener('drop', (event) => {
event.preventDefault();
element.classList.remove('drag-over');
const tokenId = event.dataTransfer.getData('text/plain');
onDrop?.(tokenId, element, event);
}, { signal });
}
function createSessionState(activities) {
const state = new Map();
activities.forEach((activity) => {
state.set(activity.id, {
score: 0,
max_score: activity.max_score,
completed: false,
resolved: false
});
});
return {
update(activityId, score, maxScore, resolved) {
state.set(activityId, {
score,
max_score: maxScore,
completed: score >= maxScore * 0.6,
resolved
});
this.refreshProgressBar();
},
get(activityId) {
return state.get(activityId);
},
getTotalScore() {
let score = 0;
let max = 0;
state.forEach((value) => {
score += value.score;
max += value.max_score;
});
return { score, max };
},
isAllResolved() {
return [...state.values()].every((value) => value.resolved);
},
refreshProgressBar() {
document.querySelectorAll('.progress-dot').forEach((dot) => {
const dotState = state.get(dot.dataset.activity);
dot.classList.toggle('completed', Boolean(dotState?.completed));
});
},
reset() {
state.forEach((value, key) => {
state.set(key, {
score: 0,
max_score: value.max_score,
completed: false,
resolved: false
});
});
this.refreshProgressBar();
}
};
}
function createEl(tagName, className, text) {
const element = document.createElement(tagName);
if (className) {
element.className = className;
}
if (typeof text === 'string') {
element.textContent = text;
}
return element;
}
function clearContainer(container) {
if (container._abortController) {
container._abortController.abort();
}
container.innerHTML = '';
}
function createActivityFrame(container, config, controller) {
const activity = createEl('article', 'esl-activity');
activity.dataset.activityId = config.id;
const meta = createEl('div', 'esl-activity__meta');
meta.append(
createEl('span', 'esl-badge', config.stage_label),
createEl('span', 'esl-badge', config.activity_type.replace('_', ' '))
);
const title = createEl('h2', 'esl-activity__title', config.title);
const intro = createEl('p', 'esl-activity__intro', config.intro);
const status = createEl('p', 'esl-activity__status', config.status_intro);
activity.append(meta, title, intro, status);
container.appendChild(activity);
const stack = createEl('div', 'esl-stack');
activity.appendChild(stack);
const footer = createEl('footer', 'esl-footer');
const statusLine = createEl('div', 'esl-status-line');
const scoreline = createEl('p', 'esl-scoreline', `Score: 0 / ${config.max_score}`);
const footerNote = createEl('p', 'esl-footer-note', config.footer_note);
statusLine.append(scoreline, footerNote);
const actions = createEl('div', 'esl-footer-actions');
const resetBtn = createEl('button', 'esl-btn esl-btn--secondary', 'Reset');
resetBtn.type = 'button';
resetBtn.setAttribute('aria-label', `Reset ${config.title}`);
const nextBtn = createEl('button', 'esl-btn esl-btn--accent', 'Next');
nextBtn.type = 'button';
nextBtn.disabled = true;
nextBtn.setAttribute('aria-label', `Go to the next activity after ${config.title}`);
actions.append(resetBtn, nextBtn);
footer.append(statusLine, actions);
activity.appendChild(footer);
resetBtn.addEventListener('click', () => {
controller.abort();
renderActivityByConfig(config.id);
}, { signal: controller.signal });
nextBtn.addEventListener('click', () => {
goToNextActivity(config.id);
}, { signal: controller.signal });
return {
activity,
stack,
footer,
scoreline,
footerNote,
nextBtn
};
}
function updateActivityState(activityId, score, maxScore, resolved, scoreline, nextBtn, footerNote, noteText) {
sessionState.update(activityId, score, maxScore, resolved);
scoreline.textContent = `Score: ${score} / ${maxScore}`;
footerNote.textContent = noteText;
nextBtn.disabled = !resolved;
updateActiveDot();
const resultSection = document.getElementById('final-result');
if (sessionState.isAllResolved()) {
showFinalResult();
} else if (resultSection) {
resultSection.classList.add('hidden');
}
}
function getMotivationMessage(score, maxScore, cefr, age) {
const ratio = maxScore === 0 ? 0 : score / maxScore;
if (age <= 11) {
if (ratio === 1) return 'Perfect! Excellent work!';
if (ratio >= 0.8) return 'Great job! Almost perfect!';
if (ratio >= 0.6) return 'Good effort! Review and try again.';
return "Keep practicing! You'll get there.";
}
if (cefr === 'A1' || cefr === 'A2') {
if (ratio === 1) return 'Perfect! Excellent work!';
if (ratio >= 0.8) return 'Great job! Almost perfect!';
if (ratio >= 0.6) return 'Good effort! Review and try again.';
return "Keep practicing! You'll get there.";
}
if (ratio === 1) return 'Flawless! Outstanding!';
if (ratio >= 0.8) return 'Great job! Just a few to review.';
if (ratio >= 0.6) return 'Good progress. Review the tricky ones.';
return 'Keep at it! Focus on the hints.';
}
function activateTab(activityId) {
document.querySelectorAll('.tab-content').forEach((panel) => {
const isActive = panel.id === activityId;
panel.classList.toggle('active', isActive);
panel.hidden = !isActive;
});
document.querySelectorAll('.tab-btn').forEach((button) => {
const isActive = button.dataset.tab === activityId;
button.classList.toggle('active', isActive);
button.setAttribute('aria-selected', String(isActive));
button.tabIndex = isActive ? 0 : -1;
});
updateActiveDot(activityId);
}
function updateActiveDot(activityId = document.querySelector('.tab-content.active')?.id) {
document.querySelectorAll('.progress-dot').forEach((dot) => {
dot.classList.toggle('active', dot.dataset.activity === activityId);
});
}
function goToNextActivity(currentId) {
const index = ACTIVITY_ORDER.indexOf(currentId);
if (index === -1) {
return;
}
const nextId = ACTIVITY_ORDER[index + 1];
if (nextId) {
activateTab(nextId);
document.getElementById(nextId)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
return;
}
if (sessionState.isAllResolved()) {
showFinalResult();
}
}
function showFinalResult() {
const resultSection = document.getElementById('final-result');
const scoreDisplay = document.getElementById('score-display');
const motivationMsg = document.getElementById('motivation-msg');
if (!resultSection || !scoreDisplay || !motivationMsg || !sessionState) {
return;
}
resultSection.classList.remove('hidden');
const { score, max } = sessionState.getTotalScore();
scoreDisplay.textContent = `${score} / ${max}`;
motivationMsg.textContent = getMotivationMessage(score, max, 'A1', 14);
}
// Renderers
// CoT - quiz - Sports Images / Conversation Quiz
// 1. OBJETIVO: validar reconhecimento visual e selecao de respostas objetivas.
// 2. DOM: article, figure, button.quiz-option, div.quiz-feedback, button.esl-btn, button.show-answer-btn.
// 3. EVENTOS: click em opcao, click reset, click next, click show answer.
// 4. EDGE CASES: sem selecao, hint apos erro, esgotar tentativas, reset completo, imagem ausente.
// 5. TOKENS + EVENT: usa tokens --esl-* e dispara esl:attempt por questao.
function renderQuiz(container, config) {
clearContainer(container);
const controller = new AbortController();
container._abortController = controller;
const timer = createTimer();
timer.begin();
const attempts = createAttemptTracker(config);
const frame = createActivityFrame(container, config, controller);
const content = createEl('div', 'quiz-container');
frame.stack.appendChild(content);
const state = new Map();
config.items.forEach((item) => {
state.set(item.id, { solved: false, score: 0, revealed: false });
});
function updateSummary() {
const resolvedCount = [...state.values()].filter((value) => value.solved || value.revealed).length;
const score = [...state.values()].reduce((sum, value) => sum + value.score, 0);
const note = resolvedCount === config.items.length
? 'Activity complete. Use Next to continue.'
: `${resolvedCount} / ${config.items.length} items resolved`;
updateActivityState(config.id, score, config.max_score, resolvedCount === config.items.length, frame.scoreline, frame.nextBtn, frame.footerNote, note);
}
function revealCorrectAnswer(questionCard, item) {
const feedback = questionCard.querySelector('.quiz-feedback');
feedback.textContent = `Answer: ${item.choices[item.answer_index].label || item.choices[item.answer_index]}`;
state.get(item.id).revealed = true;
questionCard.querySelectorAll('.quiz-option').forEach((option) => {
option.disabled = true;
const isCorrectOption = Number(option.dataset.index) === item.answer_index;
option.classList.toggle('state-correct', isCorrectOption);
});
updateSummary();
}
config.items.forEach((item, itemIndex) => {
const questionCard = createEl('article', 'quiz-question');
const head = createEl('div', 'quiz-question__head');
const title = createEl('h3', '', `${itemIndex + 1}. ${item.question}`);
const badge = createEl('span', 'esl-badge', 'Instant check');
head.append(title, badge);
questionCard.appendChild(head);
if (item.media) {
const mediaBlock = createEl('div', 'esl-panel');
renderMedia(mediaBlock, item.media);
questionCard.appendChild(mediaBlock);
}
const options = createEl('div', 'quiz-options');
options.setAttribute('role', 'radiogroup');
options.setAttribute('aria-label', item.question);
questionCard.appendChild(options);
const feedback = createEl('p', 'quiz-feedback', 'Choose one answer.');
questionCard.appendChild(feedback);
const hintWrap = createEl('div', 'esl-hint hidden');
const hintBtn = createEl('button', 'esl-mini-btn hint-btn', 'Hint');
hintBtn.type = 'button';
hintBtn.setAttribute('aria-label', `Show hint for ${item.id}`);
const hintText = createEl('p', 'esl-hint-text hidden', item.hint?.text || config.hint?.text || '');
const showAnswerBtn = createEl('button', 'esl-mini-btn hidden', 'Show Answer');
showAnswerBtn.type = 'button';
showAnswerBtn.setAttribute('aria-label', `Show answer for ${item.id}`);
hintWrap.append(hintBtn, hintText, showAnswerBtn);
questionCard.appendChild(hintWrap);
hintBtn.addEventListener('click', () => {
hintText.classList.toggle('hidden');
}, { signal: controller.signal });
showAnswerBtn.addEventListener('click', () => {
revealCorrectAnswer(questionCard, item);
}, { signal: controller.signal });
const mappedChoices = config.shuffle
? shuffleArray(item.choices.map((choice, choiceIndex) => ({ choice, sourceIndex: choiceIndex })))
: item.choices.map((choice, choiceIndex) => ({ choice, sourceIndex: choiceIndex }));
mappedChoices.forEach((entry) => {
const option = createEl('button', 'quiz-option');
option.type = 'button';
option.dataset.index = String(entry.sourceIndex);
option.dataset.itemId = item.id;
option.setAttribute('role', 'radio');
option.setAttribute('aria-checked', 'false');
option.setAttribute('aria-label', `Answer option for ${item.question}`);
if (typeof entry.choice === 'string') {
option.appendChild(createEl('span', 'quiz-option__label', entry.choice));
} else {
option.classList.add('choice-image');
const img = document.createElement('img');
img.src = entry.choice.src;
img.alt = entry.choice.alt;
option.appendChild(img);
option.appendChild(createEl('span', 'quiz-option__label', entry.choice.label));
}
option.addEventListener('click', () => {
if (state.get(item.id).solved || state.get(item.id).revealed) {
return;
}
questionCard.querySelectorAll('.quiz-option').forEach((btn) => {
btn.classList.remove('selected');
btn.setAttribute('aria-checked', 'false');
});
option.classList.add('selected');
option.setAttribute('aria-checked', 'true');
const attemptNumber = attempts.record(item.id);
const isCorrectAnswer = Number(option.dataset.index) === item.answer_index;
const entryState = state.get(item.id);
option.classList.toggle('state-correct', isCorrectAnswer);
option.classList.toggle('state-incorrect', !isCorrectAnswer);
feedback.textContent = isCorrectAnswer ? 'Correct answer.' : 'Try again.';
if (isCorrectAnswer) {
questionCard.querySelectorAll('.quiz-option').forEach((btn) => btn.disabled = true);
entryState.solved = true;
entryState.score = 1;
} else {
window.setTimeout(() => {
option.classList.remove('state-incorrect', 'selected');
}, 900);
if (attempts.shouldShowHint(item.id) && (item.hint?.text || config.hint?.text)) {
hintWrap.classList.remove('hidden');
}
if (attempts.isExhausted(item.id)) {
showAnswerBtn.classList.remove('hidden');
}
}
fireAttempt(questionCard, {
activity_id: config.id,
item_id: item.id,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: isCorrectAnswer,
is_partial: false,
attempt_number: attemptNumber,
score: [...state.values()].reduce((sum, value) => sum + value.score, 0),
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
updateSummary();
}, { signal: controller.signal });
options.appendChild(option);
});
content.appendChild(questionCard);
});
updateSummary();
}
// CoT - short_answer - Chart Answers
// 1. OBJETIVO: apoiar respostas em frase completa com modelo e autoavaliacao.
// 2. DOM: table, example card, input.sa-input, buttons check/show answer/self-check, feedback text.
// 3. EVENTOS: input, click em Check, click em Show Answer, click em botoes de autoavaliacao, reset, next.
// 4. EDGE CASES: input vazio, diferenca de pontuacao parcial, esgotar tentativas, reset da autoavaliacao.
// 5. TOKENS + EVENT: usa tokens --esl-* e dispara esl:attempt por item submetido.
function renderShortAnswer(container, config) {
clearContainer(container);
const controller = new AbortController();
container._abortController = controller;
const timer = createTimer();
timer.begin();
const attempts = createAttemptTracker(config);
const frame = createActivityFrame(container, config, controller);
const panel = createEl('div', 'esl-panel esl-stack');
frame.stack.appendChild(panel);
const tableWrap = createEl('div', 'esl-panel');
const table = createEl('table', 'esl-chart');
const thead = document.createElement('thead');
const headRow = document.createElement('tr');
config.table.headers.forEach((header) => {
const th = document.createElement('th');
th.textContent = header;
headRow.appendChild(th);
});
thead.appendChild(headRow);
const tbody = document.createElement('tbody');
config.table.rows.forEach((row) => {
const tr = document.createElement('tr');
row.forEach((cell) => {
const td = document.createElement('td');
td.textContent = cell;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.append(thead, tbody);
tableWrap.appendChild(table);
panel.appendChild(tableWrap);
const example = createEl('div', 'esl-example');
example.append(
createEl('p', 'esl-example__caption', 'Example'),
createEl('p', '', `${config.example.question} ${config.example.answer}`)
);
panel.appendChild(example);
const answersWrap = createEl('div', 'short-answer-container');
panel.appendChild(answersWrap);
const state = new Map();
config.items.forEach((item) => {
state.set(item.id, { resolved: false, score: 0 });
});
function updateSummary() {
const resolvedCount = [...state.values()].filter((value) => value.resolved).length;
const score = [...state.values()].reduce((sum, value) => sum + value.score, 0);
const note = resolvedCount === config.items.length
? 'Self-check complete. Use Next to continue.'
: `${resolvedCount} / ${config.items.length} answers reviewed`;
updateActivityState(config.id, score, config.max_score, resolvedCount === config.items.length, frame.scoreline, frame.nextBtn, frame.footerNote, note);
}
config.items.forEach((item, itemIndex) => {
const card = createEl('article', 'sa-card');
const head = createEl('div', 'sa-card__head');
head.append(createEl('h3', '', `${itemIndex + 2}. ${item.question}`), createEl('span', 'esl-badge', 'Model + self-check'));
card.appendChild(head);
const label = createEl('label', 'sr-only', item.question);
label.setAttribute('for', `${config.id}-${item.id}`);
const input = createEl('input', 'sa-input');
input.id = `${config.id}-${item.id}`;
input.type = 'text';
input.autocomplete = 'off';
input.setAttribute('aria-label', item.question);
card.append(label, input);
const feedback = createEl('p', 'sa-feedback', 'Write a full sentence.');
card.appendChild(feedback);
const actionRow = createEl('div', 'sa-actions');
const checkBtn = createEl('button', 'esl-mini-btn', 'Check');
checkBtn.type = 'button';
const showBtn = createEl('button', 'esl-mini-btn hidden', 'Show Answer');
showBtn.type = 'button';
actionRow.append(checkBtn, showBtn);
card.appendChild(actionRow);
const model = createEl('div', 'sa-model hidden');
model.append(
createEl('p', '', `Model answer: ${item.model_answer}`),
createEl('p', 'esl-footer-note', 'Checklist: correct person word, correct detail from the chart, full sentence.')
);
card.appendChild(model);
const selfCheckGroup = createEl('div', 'esl-self-check-group hidden');
const gotItBtn = createEl('button', 'esl-self-check-btn', 'I got it');
const almostBtn = createEl('button', 'esl-self-check-btn', 'Almost');
const helpBtn = createEl('button', 'esl-self-check-btn', 'I need help');
gotItBtn.type = 'button';
almostBtn.type = 'button';
helpBtn.type = 'button';
selfCheckGroup.append(gotItBtn, almostBtn, helpBtn);
card.appendChild(selfCheckGroup);
function lockCard(note, className, scoreValue) {
card.classList.remove('state-correct', 'state-partial', 'state-incorrect');
if (className) {
card.classList.add(className);
}
input.disabled = true;
checkBtn.disabled = true;
showBtn.disabled = true;
gotItBtn.disabled = true;
almostBtn.disabled = true;
helpBtn.disabled = true;
feedback.textContent = note;
const entry = state.get(item.id);
entry.resolved = true;
entry.score = scoreValue;
updateSummary();
}
function revealSelfCheck() {
model.classList.remove('hidden');
selfCheckGroup.classList.remove('hidden');
}
checkBtn.addEventListener('click', () => {
if (!input.value.trim()) {
feedback.textContent = 'Please type an answer first.';
input.classList.add('state-incorrect');
return;
}
const attemptNumber = attempts.record(item.id);
const exact = isCorrect(input.value, item.accepted_answers);
const partial = !exact && isPartial(input.value, item.model_answer);
input.classList.remove('state-correct', 'state-partial', 'state-incorrect');
if (exact) {
input.classList.add('state-correct');
lockCard('Strong answer. You can move on.', 'state-correct', 1);
} else if (partial) {
input.classList.add('state-partial');
feedback.textContent = 'Close. Compare with the model answer.';
revealSelfCheck();
} else {
input.classList.add('state-incorrect');
feedback.textContent = 'Check the chart again and compare with the model.';
revealSelfCheck();
}
if (!exact && attempts.isExhausted(item.id)) {
showBtn.classList.remove('hidden');
} else if (!exact) {
showBtn.classList.remove('hidden');
}
fireAttempt(card, {
activity_id: config.id,
item_id: item.id,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: exact,
is_partial: partial,
attempt_number: attemptNumber,
score: [...state.values()].reduce((sum, value) => sum + value.score, 0),
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
updateSummary();
}, { signal: controller.signal });
showBtn.addEventListener('click', () => {
revealSelfCheck();
feedback.textContent = 'Use the model answer and choose a self-check option.';
}, { signal: controller.signal });
gotItBtn.addEventListener('click', () => {
fireAttempt(card, {
activity_id: config.id,
item_id: item.id,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: true,
is_partial: false,
attempt_number: attempts.get(item.id),
score: [...state.values()].reduce((sum, value) => sum + value.score, 0) + 1,
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
lockCard('You matched the model. Good work.', 'state-correct', 1);
}, { signal: controller.signal });
almostBtn.addEventListener('click', () => {
fireAttempt(card, {
activity_id: config.id,
item_id: item.id,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: false,
is_partial: true,
attempt_number: attempts.get(item.id),
score: [...state.values()].reduce((sum, value) => sum + value.score, 0),
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
lockCard('Almost there. Review the model and try it out loud.', 'state-partial', 0);
}, { signal: controller.signal });
helpBtn.addEventListener('click', () => {
fireAttempt(card, {
activity_id: config.id,
item_id: item.id,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: false,
is_partial: false,
attempt_number: attempts.get(item.id),
score: [...state.values()].reduce((sum, value) => sum + value.score, 0),
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
lockCard('Keep the model visible and say the answer once more.', 'state-incorrect', 0);
}, { signal: controller.signal });
answersWrap.appendChild(card);
});
updateSummary();
}
// CoT - word_match - Conversation Match
// 1. OBJETIVO: associar perguntas e respostas curtas com feedback imediato.
// 2. DOM: duas colunas de botoes .match-item, bloco de feedback, footer com reset/next.
// 3. EVENTOS: click esquerda, click direita, reset, next.
// 4. EDGE CASES: dois cliques na mesma coluna, mismatch temporario, embaralhamento da coluna direita.
// 5. TOKENS + EVENT: usa tokens --esl-* e dispara esl:attempt por par tentado.
function renderWordMatch(container, config) {
clearContainer(container);
const controller = new AbortController();
container._abortController = controller;
const timer = createTimer();
timer.begin();
const attempts = createAttemptTracker(config);
const frame = createActivityFrame(container, config, controller);
const content = createEl('div', 'word-match-container');
frame.stack.appendChild(content);
const board = createEl('div', 'match-columns');
const leftColumn = createEl('div', 'match-column');
const rightColumn = createEl('div', 'match-column');
board.append(leftColumn, rightColumn);
content.appendChild(board);
const feedback = createEl('p', 'match-feedback', 'Select a question, then select the matching answer.');
content.appendChild(feedback);
const state = {
selectedLeftId: null,
matched: new Set(),
score: 0
};
function updateSummary() {
const matchedCount = state.matched.size;
const note = matchedCount === config.pairs.length
? 'All pairs matched. Use Next to continue.'
: `${matchedCount} of ${config.pairs.length} pairs matched`;
updateActivityState(config.id, state.score, config.max_score, matchedCount === config.pairs.length, frame.scoreline, frame.nextBtn, frame.footerNote, note);
}
const shuffledRight = config.shuffle ? shuffleArray(config.pairs) : config.pairs;
config.pairs.forEach((pair, index) => {
const left = createEl('button', 'match-item');
left.type = 'button';
left.dataset.pairId = pair.id;
left.setAttribute('aria-label', `Question ${index + 1}`);
left.textContent = pair.left;
leftColumn.appendChild(left);
left.addEventListener('click', () => {
if (state.matched.has(pair.id)) {
return;
}
state.selectedLeftId = pair.id;
leftColumn.querySelectorAll('.match-item').forEach((item) => item.classList.remove('selected'));
left.classList.add('selected');
}, { signal: controller.signal });
});
shuffledRight.forEach((pair) => {
const right = createEl('button', 'match-item');
right.type = 'button';
right.dataset.pairId = pair.id;
right.setAttribute('aria-label', 'Answer option');
right.textContent = pair.right;
rightColumn.appendChild(right);
right.addEventListener('click', () => {
if (!state.selectedLeftId || state.matched.has(pair.id)) {
return;
}
const attemptNumber = attempts.record(pair.id);
const matched = state.selectedLeftId === pair.id;
const leftButton = leftColumn.querySelector(`[data-pair-id="${state.selectedLeftId}"]`);
if (matched) {
leftButton.classList.add('matched', 'state-correct');
right.classList.add('matched', 'state-correct');
leftButton.disabled = true;
right.disabled = true;
state.matched.add(pair.id);
state.score = state.matched.size;
feedback.textContent = 'Correct match.';
} else {
const wrongLeft = leftButton;
wrongLeft.classList.add('state-incorrect');
right.classList.add('state-incorrect');
feedback.textContent = 'Not a match. Try again.';
window.setTimeout(() => {
wrongLeft.classList.remove('state-incorrect', 'selected');
right.classList.remove('state-incorrect');
}, 800);
}
fireAttempt(right, {
activity_id: config.id,
item_id: pair.id,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: matched,
is_partial: state.matched.size > 0 && state.matched.size < config.max_score,
attempt_number: attemptNumber,
score: state.score,
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
state.selectedLeftId = null;
leftColumn.querySelectorAll('.match-item').forEach((item) => item.classList.remove('selected'));
updateSummary();
}, { signal: controller.signal });
});
updateSummary();
}
// CoT - category_sort - Country Sort
// 1. OBJETIVO: classificar paises nas categorias corretas usando drag and drop.
// 2. DOM: pool de .sort-token, bins .sort-bin com areas internas, feedback, footer.
// 3. EVENTOS: dragstart/drop, pointerdown/pointerup, reset, next.
// 4. EDGE CASES: drop em area invalida, reset de tokens, mobile touch, item solto fora de bin.
// 5. TOKENS + EVENT: usa tokens --esl-* e dispara esl:attempt por drop.
function renderCategorySort(container, config) {
clearContainer(container);
const controller = new AbortController();
container._abortController = controller;
const timer = createTimer();
timer.begin();
const frame = createActivityFrame(container, config, controller);
const content = createEl('div', 'category-sort-container');
frame.stack.appendChild(content);
const pool = createEl('div', 'sort-pool');
const board = createEl('div', 'sort-board');
const feedback = createEl('p', 'sort-feedback', 'Drag each country to the correct region.');
content.append(pool, board, feedback);
const state = {
selectedTokenId: null,
placed: new Set(),
score: 0
};
function updateSummary() {
const resolved = state.placed.size === config.items.length;
const note = resolved
? 'All countries sorted. Use Next to continue.'
: `${state.placed.size} of ${config.items.length} countries sorted correctly`;
updateActivityState(config.id, state.score, config.max_score, resolved, frame.scoreline, frame.nextBtn, frame.footerNote, note);
}
const tokenMap = new Map();
const bins = new Map();
function handleDrop(tokenId, binElement, eventLike) {
const token = tokenMap.get(tokenId);
if (!token || state.placed.has(tokenId)) {
return;
}
const categoryId = binElement.dataset.categoryId;
const isCorrectDrop = token.dataset.categoryId === categoryId;
const attemptNumber = (token.dataset.attempts ? Number(token.dataset.attempts) : 0) + 1;
token.dataset.attempts = String(attemptNumber);
if (isCorrectDrop) {
token.classList.add('state-correct');
token.classList.remove('selected');
token.disabled = true;
token.setAttribute('aria-disabled', 'true');
token.setAttribute('aria-pressed', 'false');
binElement.querySelector('.sort-bin__items').appendChild(token);
state.placed.add(tokenId);
state.score = state.placed.size;
feedback.textContent = 'Correct category.';
} else {
token.classList.add('state-incorrect');
feedback.textContent = 'That country belongs in a different column.';
window.setTimeout(() => {
token.classList.remove('state-incorrect');
}, 800);
}
fireAttempt(binElement, {
activity_id: config.id,
item_id: `drop-${tokenId}`,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: isCorrectDrop,
is_partial: state.placed.size > 0 && state.placed.size < config.max_score,
attempt_number: attemptNumber,
score: state.score,
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
updateSummary();
}
config.categories.forEach((category) => {
const bin = createEl('div', 'sort-bin');
bin.dataset.categoryId = category.id;
bin.tabIndex = 0;
bin.setAttribute('aria-label', `${category.label} category`);
const title = createEl('h3', 'sort-bin__title', category.label);
const itemsWrap = createEl('div', 'sort-bin__items');
bin.append(title, itemsWrap);
board.appendChild(bin);
bins.set(category.id, bin);
makeDropZone(bin, {
signal: controller.signal,
onDrop: handleDrop
});
bin.addEventListener('click', () => {
if (!state.selectedTokenId) {
return;
}
handleDrop(state.selectedTokenId, bin);
state.selectedTokenId = null;
tokenMap.forEach((tokenElement) => tokenElement.classList.remove('selected'));
}, { signal: controller.signal });
bin.addEventListener('keydown', (event) => {
if (!state.selectedTokenId || (event.key !== 'Enter' && event.key !== ' ')) {
return;
}
event.preventDefault();
handleDrop(state.selectedTokenId, bin);
state.selectedTokenId = null;
tokenMap.forEach((tokenElement) => {
tokenElement.classList.remove('selected');
tokenElement.setAttribute('aria-pressed', 'false');
});
}, { signal: controller.signal });
});
const tokens = config.shuffle ? shuffleArray(config.items) : config.items;
tokens.forEach((item) => {
const token = createEl('button', 'sort-token');
token.type = 'button';
token.textContent = item.text;
token.dataset.tokenId = item.id;
token.dataset.categoryId = item.category_id;
token.setAttribute('aria-label', `Drag ${item.text}`);
token.setAttribute('aria-pressed', 'false');
pool.appendChild(token);
tokenMap.set(item.id, token);
token.addEventListener('click', () => {
if (state.placed.has(item.id)) {
return;
}
const isSelected = state.selectedTokenId === item.id;
state.selectedTokenId = isSelected ? null : item.id;
tokenMap.forEach((tokenElement, tokenId) => {
const selected = state.selectedTokenId === tokenId;
tokenElement.classList.toggle('selected', selected);
tokenElement.setAttribute('aria-pressed', String(selected));
});
if (state.selectedTokenId) {
feedback.textContent = `Selected ${item.text}. Click a region column to place it.`;
} else {
feedback.textContent = 'Drag each country to the correct region.';
}
}, { signal: controller.signal });
makeDraggable(token, {
signal: controller.signal,
onDragEnd: (element, event, dropTarget) => {
const validTarget = dropTarget?.closest?.('.sort-bin');
if (validTarget) {
handleDrop(element.dataset.tokenId, validTarget, event);
}
}
});
});
updateSummary();
}
// CoT - true_false - True or False
// 1. OBJETIVO: verificar compreensao de leitura com decisoes binarias.
// 2. DOM: cards por item, botoes true/false, feedback por card, footer.
// 3. EVENTOS: click em true/false, reset, next, show answer apos tentativas.
// 4. EDGE CASES: tentativas esgotadas, hint opcional, score parcial no global.
// 5. TOKENS + EVENT: usa tokens --esl-* e dispara esl:attempt por item.
function renderTrueFalse(container, config) {
clearContainer(container);
const controller = new AbortController();
container._abortController = controller;
const timer = createTimer();
timer.begin();
const attempts = createAttemptTracker(config);
const frame = createActivityFrame(container, config, controller);
const content = createEl('div', 'true-false-container');
frame.stack.appendChild(content);
const state = new Map();
config.statements.forEach((statement) => {
state.set(statement.id, { solved: false, revealed: false, score: 0 });
});
function updateSummary() {
const resolvedCount = [...state.values()].filter((value) => value.solved || value.revealed).length;
const score = [...state.values()].reduce((sum, value) => sum + value.score, 0);
const note = resolvedCount === config.statements.length
? 'Activity complete. Use Next to continue.'
: `${resolvedCount} / ${config.statements.length} statements resolved`;
updateActivityState(config.id, score, config.max_score, resolvedCount === config.statements.length, frame.scoreline, frame.nextBtn, frame.footerNote, note);
}
config.statements.forEach((statement, index) => {
const card = createEl('article', 'tf-card');
const head = createEl('div', 'tf-card__head');
head.append(createEl('h3', '', `${index + 1}. ${statement.text}`), createEl('span', 'esl-badge', 'True / False'));
card.appendChild(head);
const options = createEl('div', 'tf-options');
const trueBtn = createEl('button', 'tf-option', 'True');
const falseBtn = createEl('button', 'tf-option', 'False');
trueBtn.type = 'button';
falseBtn.type = 'button';
options.append(trueBtn, falseBtn);
card.appendChild(options);
const feedback = createEl('p', 'tf-feedback', 'Choose True or False.');
card.appendChild(feedback);
const showAnswer = createEl('button', 'esl-mini-btn hidden', 'Show Answer');
showAnswer.type = 'button';
card.appendChild(showAnswer);
function finishReveal() {
state.get(statement.id).revealed = true;
feedback.textContent = `Answer: ${statement.answer ? 'True' : 'False'}. ${statement.justification_hint}`;
trueBtn.disabled = true;
falseBtn.disabled = true;
trueBtn.classList.toggle('state-correct', statement.answer === true);
falseBtn.classList.toggle('state-correct', statement.answer === false);
updateSummary();
}
showAnswer.addEventListener('click', finishReveal, { signal: controller.signal });
[trueBtn, falseBtn].forEach((button, buttonIndex) => {
button.addEventListener('click', () => {
if (state.get(statement.id).solved || state.get(statement.id).revealed) {
return;
}
const answerValue = buttonIndex === 0;
const attemptNumber = attempts.record(statement.id);
const isCorrectAnswer = answerValue === statement.answer;
if (isCorrectAnswer) {
button.classList.add('state-correct');
trueBtn.disabled = true;
falseBtn.disabled = true;
const itemState = state.get(statement.id);
itemState.solved = true;
itemState.score = 1;
feedback.textContent = 'Correct answer.';
} else {
button.classList.add('state-incorrect');
feedback.textContent = 'Try again.';
window.setTimeout(() => button.classList.remove('state-incorrect'), 800);
if (attempts.isExhausted(statement.id)) {
showAnswer.classList.remove('hidden');
}
}
fireAttempt(card, {
activity_id: config.id,
item_id: statement.id,
activity_type: config.activity_type,
renderer: config.renderer,
cefr: config.cefr,
difficulty: config.difficulty,
feedback_mode: config.feedback_mode,
is_correct: isCorrectAnswer,
is_partial: false,
attempt_number: attemptNumber,
score: [...state.values()].reduce((sum, value) => sum + value.score, 0),
max_score: config.max_score,
time_on_item_ms: timer.elapsed()
});
updateSummary();
}, { signal: controller.signal });
});
content.appendChild(card);
});
updateSummary();
}
// Configs
const ACTIVITY_CONFIGS = [
{
id: 'act-1',
title: 'The Real World A - Label the pictures',
stage_label: 'Presentation',
intro: 'Look at each sports picture and choose the correct word.',
status_intro: 'This activity uses image-based multiple choice with instant feedback.',
footer_note: 'Aim for 4 correct answers.',
activity_type: 'quiz',
renderer: 'renderQuiz',
cefr: 'A1',
idade_aluno: 14,
difficulty: 1,
feedback_mode: 'instant_check',
attempts_max: 2,
shuffle: false,
hint: {
text: 'Match the picture to the sport word.',
trigger: 'after_first_wrong_attempt'
},
items: [
{
id: 'q1',
question: 'Which sport matches this picture?',
answer_mode: 'single',
choices: ['basketball', 'table tennis', 'soccer', 'baseball'],
answer_index: 3,
media: {
type: 'image',
src: 'images/baseball-placeholder.png',
alt: 'A baseball icon placeholder with a white ball and red stitching.',
caption: 'baseball'
}
},
{
id: 'q2',
question: 'Which sport matches this picture?',
answer_mode: 'single',
choices: ['table tennis', 'soccer', 'baseball', 'basketball'],
answer_index: 0,
media: {
type: 'image',
src: 'images/table-tennis-icon.png',
alt: 'A black table tennis paddle icon with a small ball.',
caption: 'table tennis'
}
},
{
id: 'q3',
question: 'Which sport matches this picture?',
answer_mode: 'single',
choices: ['soccer', 'baseball', 'basketball', 'table tennis'],
answer_index: 0,
media: {
type: 'image',
src: 'images/soccer-ball-icon.png',
alt: 'A black and white soccer ball icon.',
caption: 'soccer'
}
},
{
id: 'q4',
question: 'Which sport matches this picture?',
answer_mode: 'single',
choices: ['soccer', 'basketball', 'table tennis', 'baseball'],
answer_index: 1,
media: {
type: 'image',
src: 'images/basketball-icon.png',
alt: 'An orange basketball icon with black lines.',
caption: 'basketball'
}
}
],
media: null,
audio: null,
scaffold_steps: null,
max_score: 4,
points_label: '4 items'
},
{
id: 'act-2',
title: 'Language Focus B - Look at the chart',
stage_label: 'Presentation',
intro: 'Read the chart, write a full sentence, then compare with the model answer.',
status_intro: 'This activity uses self-check and guided comparison.',
footer_note: 'Use the chart and the model sentence structure.',
activity_type: 'short_answer',
renderer: 'renderShortAnswer',
cefr: 'A1',
idade_aluno: 14,
difficulty: 2,
feedback_mode: 'self_check',
attempts_max: 2,
shuffle: false,
hint: {
text: 'Use her or his and write one complete sentence.',
trigger: 'after_first_wrong_attempt'
},
table: {
headers: ['', 'Jennifer', 'Matt'],
rows: [
['Favorite color', 'green', 'white'],
['Favorite video game', 'Tomb Raider', 'World of Warcraft'],
['Favorite movie', 'Aladdin', 'Star Wars'],
['Favorite singer', 'Bruno Mars', 'Ed Sheeran']
]
},
example: {
question: "What's Jennifer's favorite color?",
answer: 'Her favorite color is green.'
},
items: [
{
id: 'sa-1',
question: "What's her favorite movie?",
model_answer: 'Her favorite movie is Tomb Raider.',
accepted_answers: ['Her favorite movie is Tomb Raider.', 'Her favorite movie is Tomb Raider', 'Tomb Raider']
},
{
id: 'sa-2',
question: "Who's her favorite singer?",
model_answer: 'Her favorite singer is Bruno Mars.',
accepted_answers: ['Her favorite singer is Bruno Mars.', 'Her favorite singer is Bruno Mars', 'Bruno Mars']
},
{
id: 'sa-3',
question: "What's Matt's favorite video game?",
model_answer: 'His favorite video game is World of Warcraft.',
accepted_answers: ['His favorite video game is World of Warcraft.', 'His favorite video game is World of Warcraft', 'World of Warcraft']
},
{
id: 'sa-4',
question: "What's his favorite color?",
model_answer: 'His favorite color is white.',
accepted_answers: ['His favorite color is white.', 'His favorite color is white', 'white']
},
{
id: 'sa-5',
question: "What's his favorite movie?",
model_answer: 'His favorite movie is Star Wars.',
accepted_answers: ['His favorite movie is Star Wars.', 'His favorite movie is Star Wars', 'Star Wars']
}
],
media: null,
audio: null,
scaffold_steps: {
step1: 'modeled',
step2: 'guided',
step3: 'independent'
},
max_score: 5,
points_label: '5 review items'
},
{
id: 'act-3',
title: 'Language Focus A - Complete the conversations',
stage_label: 'Practice',
intro: 'Choose the correct word to complete each conversation.',
status_intro: 'Click one answer in each dialogue card.',
footer_note: 'Aim for 6 correct answers.',
activity_type: 'quiz',
renderer: 'renderQuiz',
cefr: 'A1',
idade_aluno: 14,
difficulty: 2,
feedback_mode: 'instant_check',
attempts_max: 2,
shuffle: false,
hint: {
text: 'Check the person word and match it to the subject.',
trigger: 'after_first_wrong_attempt'
},
items: [
{
id: 'q1',
question: "Claire: What's her / your favorite video game? Sam: My favorite video game is League of Legends.",
answer_mode: 'single',
choices: ['her', 'your'],
answer_index: 1
},
{
id: 'q2',
question: "Isabella: What's his favorite music app? Jack: His / Their favorite music app is Spotify.",
answer_mode: 'single',
choices: ['His', 'Their'],
answer_index: 0
},
{
id: 'q3',
question: "Diego: Who's / What's her favorite singer? Jenny: Lady Gaga.",
answer_mode: 'single',
choices: ["Who's", "What's"],
answer_index: 0
},
{
id: 'q4',
question: "Maria: What's your favorite season? Peng: My / Their favorite season is spring.",
answer_mode: 'single',
choices: ['My', 'Their'],
answer_index: 0
},
{
id: 'q5',
question: "Tammy: What's his / her favorite movie? Ying: Incredibles 2. She loves it!",
answer_mode: 'single',
choices: ['his', 'her'],
answer_index: 1
},
{
id: 'q6',
question: "Luka: Who's / What's their favorite color? Ben: Their favorite color is red.",
answer_mode: 'single',
choices: ["Who's", "What's"],
answer_index: 1
}
],
media: null,
audio: null,
scaffold_steps: null,
max_score: 6,
points_label: '6 items'
},
{
id: 'act-4',
title: 'Language Focus C - Match',
stage_label: 'Practice',
intro: 'Match the question to the correct answer.',
status_intro: 'Select a question, then choose the matching response.',
footer_note: 'Aim for 4 correct matches.',
activity_type: 'word_match',
renderer: 'renderWordMatch',
cefr: 'A1',
idade_aluno: 14,
difficulty: 2,
feedback_mode: 'instant_check',
attempts_max: 3,
shuffle: true,
hint: {
text: 'Read the favorite item word and match the same topic.',
trigger: 'after_first_wrong_attempt'
},
pairs: [
{ id: 'pair-1', left: "What's his favorite season?", right: 'Spring.' },
{ id: 'pair-2', left: "What's your favorite book?", right: 'My favorite book is On the Come Up.' },
{ id: 'pair-3', left: "What's their favorite movie?", right: 'Their favorite movie is Toy Story 4.' },
{ id: 'pair-4', left: "What's her favorite music app?", right: 'Spotify.' }
],
media: null,
audio: null,
scaffold_steps: null,
max_score: 4,
points_label: '4 pairs'
},
{
id: 'act-5',
title: 'The Real World B - Complete the chart',
stage_label: 'Practice',
intro: 'Sort each country into the correct region.',
status_intro: 'Drag or drop each country into the right category.',
footer_note: 'Aim for 4 correctly sorted countries.',
activity_type: 'category_sort',
renderer: 'renderCategorySort',
cefr: 'A1',
idade_aluno: 14,
difficulty: 2,
feedback_mode: 'instant_check',
attempts_max: 3,
shuffle: true,
hint: {
text: 'Think about the continent or area where the country belongs.',
trigger: 'after_first_wrong_attempt'
},
categories: [
{ id: 'asia', label: 'Asia' },
{ id: 'north-america', label: 'North America' },
{ id: 'south-america', label: 'South America' }
],
items: [
{ id: 'country-1', text: 'the United States', category_id: 'north-america' },
{ id: 'country-2', text: 'Brazil', category_id: 'south-america' },
{ id: 'country-3', text: 'Japan', category_id: 'asia' },
{ id: 'country-4', text: 'China', category_id: 'asia' }
],
media: null,
audio: null,
scaffold_steps: null,
max_score: 4,
points_label: '4 items'
},
{
id: 'act-6',
title: 'The Real World C - True or False',
stage_label: 'Production',
intro: 'Read each statement and decide if it is true or false.',
status_intro: 'Use the sports and countries information to make your choice.',
footer_note: 'Aim for 3 correct answers.',
activity_type: 'true_false',
renderer: 'renderTrueFalse',
cefr: 'A1',
idade_aluno: 14,
difficulty: 2,
feedback_mode: 'instant_check',
attempts_max: 2,
shuffle: false,
hint: {
text: 'Think about which country matches each sport.',
trigger: 'after_first_wrong_attempt'
},
statements: [
{
id: 'tf-1',
text: 'Baseball is the favorite sport in China.',
answer: false,
justification_hint: 'China is linked to table tennis here.'
},
{
id: 'tf-2',
text: 'Basketball is a popular sport in the United States.',
answer: true,
justification_hint: 'The United States appears with basketball in the reading set.'
},
{
id: 'tf-3',
text: 'Many people in Brazil like soccer.',
answer: true,
justification_hint: 'Brazil is connected to soccer in the unit.'
}
],
media: null,
audio: null,
scaffold_steps: null,
max_score: 3,
points_label: '3 items'
}
];
// Boot
function renderActivityByConfig(activityId) {
const config = ACTIVITY_CONFIGS.find((entry) => entry.id === activityId);
const shell = document.querySelector(`.esl-activity-shell[data-activity-id="${activityId}"]`);
if (!config || !shell) {
return;
}
const renderer = window[config.renderer];
if (typeof renderer !== 'function') {
return;
}
renderer(shell, config);
}
function renderAllActivities() {
ACTIVITY_CONFIGS.forEach((config) => {
renderActivityByConfig(config.id);
});
}
function bindTabs() {
if (document.body._tabAbortController) {
document.body._tabAbortController.abort();
}
const controller = new AbortController();
document.body._tabAbortController = controller;
const tabButtons = [...document.querySelectorAll('.tab-btn')];
tabButtons.forEach((button, index) => {
button.addEventListener('click', () => {
activateTab(button.dataset.tab);
}, { signal: controller.signal });
button.addEventListener('keydown', (event) => {
const currentIndex = tabButtons.indexOf(button);
if (currentIndex === -1) {
return;
}
let nextIndex = currentIndex;
if (event.key === 'ArrowRight') {
nextIndex = (currentIndex + 1) % tabButtons.length;
} else if (event.key === 'ArrowLeft') {
nextIndex = (currentIndex - 1 + tabButtons.length) % tabButtons.length;
} else if (event.key === 'Home') {
nextIndex = 0;
} else if (event.key === 'End') {
nextIndex = tabButtons.length - 1;
} else {
return;
}
event.preventDefault();
tabButtons[nextIndex].focus();
activateTab(tabButtons[nextIndex].dataset.tab);
}, { signal: controller.signal });
});
const retryBtn = document.getElementById('retry-btn');
if (!retryBtn) {
return;
}
retryBtn.addEventListener('click', () => {
if (!sessionState) {
return;
}
sessionState.reset();
document.getElementById('final-result')?.classList.add('hidden');
renderAllActivities();
activateTab('act-1');
}, { signal: controller.signal });
}
document.addEventListener('DOMContentLoaded', () => {
sessionState = createSessionState(ACTIVITY_CONFIGS);
bindTabs();
renderAllActivities();
activateTab('act-1');
});
// ESL SPARK ENGINE v1.2.0
// Utilities
const ACTIVITY_ORDER = ['act-1', 'act-2', 'act-3', 'act-4', 'act-5', 'act-6'];
let sessionState = null;
function normalize(str) {
return String(str)
.trim()
.toLowerCase()
.replace(/[.,!?'"()]/g, '')
.replace(/\s+/g, ' ');
}
function isCorrect(userInput, acceptedAnswers) {
const normalized = normalize(userInput);
return acceptedAnswers.some((answer) => normalize(answer) === normalized);
}
function isPartial(userInput, correctAnswer) {
const user = normalize(userInput);
const correct = normalize(correctAnswer);
if (!user || !correct) {
return false;
}
return (user.includes(correct) || correct.includes(user)) && user !== correct;
}
function shuffleArray(arr) {
const copy = [...arr];
for (let i = copy.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
function createTimer() {
let start = null;
return {
begin() {
start = performance.now();
},
elapsed() {
return start ? Math.round(performance.now() - start) : 0;
},
reset() {
start = null;
}
};
}
function fireAttempt(element, detail) {
if (!(element instanceof EventTarget)) {
return;
}
element.dispatchEvent(new CustomEvent('esl:attempt', {
bubbles: true,
detail: {
...detail,
time_on_item_ms: detail.time_on_item_ms || 0
}
}));
}
function createAttemptTracker(config) {
const attempts = new Map();
return {
record(itemId) {
const count = (attempts.get(itemId) || 0) + 1;
attempts.set(itemId, count);
return count;
},
get(itemId) {
return attempts.get(itemId) || 0;
},
isExhausted(itemId) {
if (config.attempts_max === null) {
return false;
}
return this.get(itemId) >= config.attempts_max;
},
shouldShowHint(itemId) {
return Boolean(
config.hint &&
config.hint.trigger === 'after_first_wrong_attempt' &&
this.get(itemId) >= 1
);
},
reset() {
attempts.clear();
}
};
}
function renderMedia(container, media) {
if (!media) {
return;
}