import { checkDrawing, graphFromSmiles, prepareTarget } from '../drawing-v0.2.0/chemistry.mjs'; import { mountMoleculePad } from '../drawing-v0.2.0/pad.mjs'; import { renderSpectrum } from './spectrum.mjs'; import { mountLinkedUnknowns } from './linked.mjs'; const ui = Object.fromEntries([ 'settings', 'mode', 'start', 'loading', 'question', 'progress', 'prompt', 'scope', 'starter', 'starter-pad', 'pad', 'entry-actions', 'add', 'cancel-edit', 'check-set', 'clue', 'clue-text', 'reveal', 'feedback', 'tray', 'tray-empty', 'set-actions', 'count', 'cards', 'worked', 'worked-title', 'explanation', 'answers', 'next', 'end', 'summary', 'summary-title', 'totals', 'again', 'game', 'course', 'level', 'topics', 'length', 'case', 'match-count', 'show-count', 'spectrum', 'reasoning', 'reset-topics', 'linked', 'board', 'topic-access', ].map(id => [id, document.getElementById(`isomer-${id}`)])); const subscript = value => value.replace(/\d/g, digit => '₀₁₂₃₄₅₆₇₈₉'[digit]); const totals = { independent: 0, helped: 0, revealed: 0, skipped: 0, reasoning: 0, reasoningCorrect: 0 }; const levels = { starter: 'Starter', core: 'Core', mixed: 'Mixed', hard: 'Hard', extra: 'Extra hard' }; let bank = []; let round = []; let position = 0; let current; let targets; let givenCanonical; let pad; let padStart; let linked; let entries = []; let editing = -1; let attempted = false; let setAttempted = false; let helped = false; let resolved = false; let busy = false; let hintIndex = 0; let showCount = false; let reasoningAnswered = false; let reasoningScore = false; let retried = false; function feedback(message = '', status = '') { ui.feedback.textContent = message; ui.feedback.dataset.status = status; ui.feedback.hidden = !message; } function replacePad(starter = null) { ui.pad.replaceChildren(); pad = mountMoleculePad(ui.pad, { starter, smallRings: true }); padStart = JSON.stringify(pad.getGraph()); } function updateControls() { ui.linked.hidden = !linked; ui.pad.hidden = Boolean(linked) || resolved; ui['entry-actions'].hidden = resolved && !ui.worked.hidden; ui.add.hidden = Boolean(linked) || resolved; ui.add.textContent = editing < 0 ? (current.mode === 'one' ? 'Check drawing' : 'Add structure') : 'Save edit'; ui['cancel-edit'].hidden = Boolean(linked) || resolved || editing < 0; ui['set-actions'].hidden = Boolean(linked) || resolved || current.mode === 'one'; ui['check-set'].disabled = busy || editing >= 0 || entries.length === 0; ui.clue.hidden = resolved; const workedAvailable = attempted || (linked && hintIndex === current.hints.length); ui.reveal.hidden = !workedAvailable || !ui.worked.hidden; ui.next.hidden = false; ui.next.textContent = !resolved ? 'Skip question' : position + 1 === round.length ? 'Finish round' : 'Next question'; ui.next.classList.toggle('drawing-primary', resolved); for (const button of [ui.add, ui['cancel-edit'], ui.clue, ui.reveal, ui.next, ui.end]) button.disabled = busy; for (const button of ui.cards.querySelectorAll('button')) button.disabled = busy; ui['show-count'].disabled = busy; if (current.reasoning && (setAttempted || resolved || ['starter', 'core'].includes(current.level))) { ui.reasoning.hidden = false; } if (linked) linked.setState(resolved, busy); else pad.setReadOnly(resolved || busy); } function card(graph, caption) { const item = document.createElement('li'); item.className = 'isomer-card'; const drawing = document.createElement('div'); const text = document.createElement('p'); text.textContent = caption; item.append(drawing, text); mountMoleculePad(drawing, { starter: graph, readOnly: true }); return item; } function renderEntries() { ui.cards.replaceChildren(); if (linked) { ui.tray.hidden = true; return; } ui.tray.hidden = entries.length === 0 && (current.mode === 'one' || resolved); ui['tray-empty'].hidden = entries.length > 0; const givenCount = current.mode === 'complete' ? 1 : 0; const found = entries.length + givenCount; const correct = found === 1 ? 'correct structure' : 'correct structures'; ui.count.textContent = showCount ? `${found} of ${targets.size + givenCount} correct structures found${givenCount ? ' (including the one given)' : ''}` : `${found} ${correct} found${givenCount ? ' (including the one given)' : ''}`; ui['show-count'].hidden = current.mode === 'one' || resolved; ui['show-count'].textContent = showCount ? 'Hide total' : 'Show total'; ui['show-count'].setAttribute('aria-pressed', String(showCount)); entries.forEach(({ graph }, index) => { const item = card(graph, `Structure ${index + 1}`); ui.cards.append(item); if (resolved || current.mode === 'one') return; const actions = document.createElement('div'); actions.className = 'isomer-card-actions'; for (const [label, accessibleLabel, handler] of [ ['Copy to pad', `Copy structure ${index + 1} to pad`, () => copyToPad(index)], ['Edit', `Edit structure ${index + 1}`, () => edit(index)], ['Remove', `Remove structure ${index + 1}`, () => remove(index)], ]) { const button = document.createElement('button'); button.type = 'button'; button.textContent = label; button.setAttribute('aria-label', accessibleLabel); button.addEventListener('click', handler); actions.append(button); } item.append(actions); }); } function copyToPad(index) { if (JSON.stringify(pad.getGraph()) !== padStart && !window.confirm('Replace the drawing on the pad with this copy?')) return; editing = -1; replacePad(entries[index].graph); feedback(`Copied structure ${index + 1} to the pad. Change the copy to draw another isomer.`); updateControls(); ui.pad.querySelector('select').focus(); } function edit(index) { editing = index; replacePad(entries[index].graph); feedback(`Editing structure ${index + 1}.`); updateControls(); ui.add.focus(); } function remove(index) { entries.splice(index, 1); if (editing === index) { editing = -1; replacePad(); } else if (editing > index) { editing -= 1; } feedback('Structure removed.'); renderEntries(); updateControls(); ui.add.focus(); } async function openQuestion() { current = round[position]; entries = []; editing = -1; attempted = false; setAttempted = false; helped = false; resolved = false; retried = false; reasoningAnswered = false; reasoningScore = false; hintIndex = 0; showCount = ['starter', 'core'].includes(current.level); linked = null; ui.linked.replaceChildren(); ui.question.hidden = true; ui.loading.hidden = false; ui.loading.textContent = 'Opening the drawing pad…'; try { ui.progress.textContent = `Question ${position + 1} of ${round.length} · ${levels[current.level]} · ${subscript(current.formula)}`; ui.prompt.textContent = current.prompt; ui.scope.textContent = current.scope ?? ''; ui.scope.hidden = !current.scope; renderSpectrum(ui.spectrum, current.ir); ui['starter-pad'].replaceChildren(); if (current.mode === 'linked') { ui.starter.hidden = true; ui.pad.replaceChildren(); const keys = await Promise.all(current.unknowns.map(async ({answers}) => new Set(await Promise.all(answers.map(async ({smiles}) => (await prepareTarget(smiles)).canonicalSmiles))) )); linked = mountLinkedUnknowns(ui.linked, current, keys, { feedback, runAction, onSubmit: submitLinked, formatFormula: subscript, }); } else { const givenAnswer = current.answers[current.given]; const reference = current.answers.filter(answer => answer !== givenAnswer); const [targetsByName, starter, given] = await Promise.all([ Promise.all(reference.map(async ({ name, smiles }) => ({ name, smiles, target: await prepareTarget(smiles) }))), givenAnswer ? graphFromSmiles(givenAnswer.smiles) : null, givenAnswer ? prepareTarget(givenAnswer.smiles) : null, ]); targets = new Map(targetsByName.map(({ name, smiles, target }) => [target.canonicalSmiles, { name, smiles }])); givenCanonical = given?.canonicalSmiles; ui.starter.hidden = !starter || current.mode === 'one'; if (starter) mountMoleculePad(ui['starter-pad'], { starter, readOnly: true }); replacePad(current.mode === 'one' ? starter : null); } ui['clue-text'].hidden = true; ui.clue.textContent = 'Give me a clue'; ui.clue.setAttribute('aria-expanded', 'false'); ui.worked.hidden = true; ui.answers.replaceChildren(); renderReasoning(); feedback(); renderEntries(); updateControls(); ui.loading.hidden = true; ui.question.hidden = false; ui.prompt.focus(); } catch (error) { console.error(error); ui.loading.textContent = 'The drawing pad could not open. Try starting the round again.'; ui.settings.hidden = false; } } function markComplete() { resolved = true; totals[helped || retried ? 'helped' : 'independent'] += 1; if (linked) feedback('Every drawing fits its evidence.', 'correct'); else if (current.mode === 'one') feedback('That is a different structural isomer.', 'correct'); else feedback('You found the complete set.', 'correct'); renderEntries(); updateControls(); ui.next.focus(); } function submitLinked(complete, repeated) { attempted = true; setAttempted = true; if (complete) { markComplete(); return; } retried = true; feedback(repeated ? 'Each unknown is a different compound. Check the drawings you used more than once.' : 'Check the evidence for the drawings marked above.', 'invalid'); } async function submitDrawing() { const graph = pad.getGraph(); if (!graph.atoms.length) { feedback('Draw a structure first.', 'invalid'); return; } attempted = true; const result = await checkDrawing(graph); if (result.status !== 'correct') { pad.highlight(result.atomIds); feedback(result.message, 'invalid'); } else if (result.formula !== current.formula) { feedback(`Your structure has formula ${subscript(result.formula)}. Aim for ${subscript(current.formula)}.`, 'invalid'); } else if (result.canonicalSmiles === givenCanonical) { feedback('That is the given structure. Try connecting the atoms differently.', 'invalid'); } else if (entries.some((entry, index) => index !== editing && entry.key === result.canonicalSmiles)) { feedback('You already have that structure. Turning it around still gives the same isomer.', 'invalid'); } else if (!targets.has(result.canonicalSmiles)) { feedback('The molecular formula matches. Check whether your structure fits the question.', 'invalid'); } else { const entry = { graph, key: result.canonicalSmiles }; if (editing < 0) entries.push(entry); else entries[editing] = entry; const wasEditing = editing >= 0; editing = -1; if (current.mode === 'one') { markComplete(); return; } replacePad(); renderEntries(); feedback(wasEditing ? 'Correct structure updated.' : 'Correct structure added.', 'correct'); return; } retried = true; } async function showWorkedAnswer() { const answers = linked ? current.unknowns.flatMap(({label, answers, explanation}) => answers.map(answer => ({...answer, label, explanation}))) : current.answers; const references = await Promise.all(answers.map(async ({ name, smiles, label, explanation }) => { const graph = await graphFromSmiles(smiles); const item = card(graph, label ? `${label} · ${name}` : name); if (explanation) { const note = document.createElement('p'); note.textContent = explanation; item.append(note); } return item; })); if (!resolved) { totals.revealed += 1; resolved = true; feedback('Worked answer opened.'); } ui.explanation.textContent = current.explanation; ui.answers.replaceChildren(...references); ui.worked.hidden = false; renderEntries(); ui['worked-title'].focus(); } async function runAction(action) { if (busy) return; busy = true; updateControls(); try { await action(); } catch (error) { console.error(error); feedback('The drawing checker could not finish. Please try again.', 'invalid'); } finally { busy = false; updateControls(); } if (resolved && ui.worked.hidden) ui.next.focus(); else if (!resolved && document.activeElement === document.body) { if (linked) linked.focusPad(); else ui.add.focus(); } } function finishRound() { if (!resolved) totals.skipped += 1; recordReasoning(); ui.question.hidden = true; ui.summary.hidden = false; ui.totals.replaceChildren(); const results = [ ['Completed without clues or retries', totals.independent], ['Completed with a clue or retry', totals.helped], ['Worked answer opened', totals.revealed], ['Skipped', totals.skipped], ['Reasoning checks correct on the first try', `${totals.reasoningCorrect} of ${totals.reasoning}`], ]; for (const [label, value] of results) { const line = document.createElement('li'); line.textContent = `${label} · ${value}`; ui.totals.append(line); } ui['summary-title'].focus(); } function recordReasoning() { if (!reasoningAnswered) return; totals.reasoning += 1; if (reasoningScore) totals.reasoningCorrect += 1; reasoningAnswered = false; } function renderReasoning() { ui.reasoning.hidden = true; ui.reasoning.replaceChildren(); if (!current.reasoning) return; const { question, options, correct, explanation } = current.reasoning; const field = document.createElement('fieldset'); const legend = document.createElement('legend'); legend.textContent = question; field.append(legend); for (const { option, index } of shuffle(options.map((option, index) => ({ option, index })))) { const label = document.createElement('label'); const input = document.createElement('input'); input.type = 'radio'; input.name = 'isomer-reason'; input.value = String(index); label.append(input, document.createTextNode(option)); field.append(label); } const check = document.createElement('button'); check.type = 'button'; check.textContent = 'Check reasoning'; const result = document.createElement('p'); result.setAttribute('role', 'status'); check.addEventListener('click', () => { const selected = field.querySelector('input:checked'); if (!selected) { result.textContent = 'Choose an answer first.'; return; } reasoningAnswered = true; reasoningScore = Number(selected.value) === correct; field.disabled = true; check.disabled = true; result.textContent = `${reasoningScore ? 'Correct.' : 'Look at what the evidence tells you.'} ${explanation}`; if (!resolved) helped = true; }); ui.reasoning.append(field, check, result); } function questionsForTopics() { const topics = new Set([...ui.topics.querySelectorAll('input:checked')].map(input => input.value)); return bank.filter(question => (ui.course.value === 'y13' || question.course === 'y12') && (ui.game.dataset.memberBankUrl || question.topics.every(topic => topics.has(topic))) ); } function matchingQuestions(questions = questionsForTopics()) { return questions.filter(question => (ui.level.value === 'all' || question.level === ui.level.value) && (ui.mode.value === 'any' || question.mode === ui.mode.value) ); } function availableOptions(select, wildcard, choices) { for (const option of select.options) option.disabled = option.value !== wildcard && !choices.has(option.value); if (select.selectedOptions[0]?.disabled) select.value = wildcard; } function updateMatches(preselected = ui.case.value) { const questions = questionsForTopics(); availableOptions(ui.level, 'all', new Set(questions.map(question => question.level))); const atLevel = questions.filter(question => ui.level.value === 'all' || question.level === ui.level.value); availableOptions(ui.mode, 'any', new Set(atLevel.map(question => question.mode))); const matches = matchingQuestions(atLevel); ui.case.replaceChildren(new Option('Any matching question', '')); for (const question of matches) ui.case.add(new Option(question.title, question.id)); if (matches.some(question => question.id === preselected)) ui.case.value = preselected; ui['match-count'].textContent = matches.length === 0 ? ui.game.dataset.memberBankUrl ? 'No rounds match this course setting.' : 'No questions cover just these topics. Select another topic or reset them all.' : `${matches.length} ${matches.length === 1 ? 'question matches' : 'questions match'}`; ui.case.disabled = matches.length === 0; if (ui.game.dataset.memberBankUrl) { for (const option of ui.length.options) option.disabled = option.value !== 'all' && Number(option.value) > matches.length; if (ui.length.selectedOptions[0]?.disabled) ui.length.value = 'all'; } ui.length.disabled = Boolean(ui.case.value); ui.start.disabled = matches.length === 0; } function shuffle(questions) { const ordered = [...questions]; for (let index = ordered.length - 1; index > 0; index -= 1) { const swap = Math.floor(Math.random() * (index + 1)); [ordered[index], ordered[swap]] = [ordered[swap], ordered[index]]; } return ordered; } ui.settings.addEventListener('submit', event => { event.preventDefault(); const matches = matchingQuestions(); if (!matches.length) return; const selected = matches.find(question => question.id === ui.case.value); const limit = ui.length.value === 'all' ? matches.length : Number(ui.length.value); round = selected ? [selected] : shuffle(matches).slice(0, limit); ui.settings.hidden = true; ui.summary.hidden = true; for (const key of Object.keys(totals)) totals[key] = 0; position = 0; openQuestion(); }); for (const filter of [ui.course, ui.level, ui.mode, ui.topics]) filter.addEventListener('change', () => updateMatches()); ui['reset-topics'].addEventListener('click', () => { for (const checkbox of ui.topics.querySelectorAll('input')) checkbox.checked = true; updateMatches(); }); ui.case.addEventListener('change', () => { ui.length.disabled = Boolean(ui.case.value); }); ui.add.addEventListener('click', () => runAction(submitDrawing)); ui.reveal.addEventListener('click', () => runAction(showWorkedAnswer)); ui['check-set'].addEventListener('click', () => { setAttempted = true; if (entries.length === targets.size) markComplete(); else { helped = true; feedback('The structures you added are correct. There are more to find.'); updateControls(); } }); ui['cancel-edit'].addEventListener('click', () => { editing = -1; replacePad(); feedback('Edit cancelled. Your saved structure is still in the set.'); updateControls(); ui.add.focus(); }); ui.clue.addEventListener('click', () => { if (hintIndex === current.hints.length && !ui['clue-text'].hidden) { ui['clue-text'].hidden = true; ui.clue.textContent = 'Show clues'; ui.clue.setAttribute('aria-expanded', 'false'); return; } helped = true; hintIndex = Math.min(hintIndex + 1, current.hints.length); ui['clue-text'].textContent = current.hints.slice(0, hintIndex).join(' '); ui['clue-text'].hidden = false; ui.clue.textContent = hintIndex < current.hints.length ? 'Give me another clue' : 'Hide clues'; ui.clue.setAttribute('aria-expanded', 'true'); if (linked) updateControls(); }); ui['show-count'].addEventListener('click', () => { showCount = !showCount; if (showCount && !['starter', 'core'].includes(current.level)) helped = true; renderEntries(); }); ui.next.addEventListener('click', () => { if (position + 1 === round.length) { finishRound(); return; } if (!resolved) totals.skipped += 1; recordReasoning(); position += 1; openQuestion(); }); ui.end.addEventListener('click', finishRound); ui.again.addEventListener('click', () => { ui.summary.hidden = true; ui.settings.hidden = false; ui.mode.focus(); }); async function loadBank() { try { const response = await fetch(ui.game.dataset.bankUrl, { credentials: 'same-origin' }); if (!response.ok) throw new Error(`Question bank returned ${response.status}`); const data = await response.json(); bank = data.questions; ui.course.value = data.course === 'y12' ? 'y12' : 'y13'; const selected = new URL(location.href).searchParams.get('case'); const question = bank.find(entry => entry.id === selected); if (question && (question.course === 'y12' || ui.course.value === 'y13')) { ui.level.value = question.level; } updateMatches(selected); ui.loading.hidden = true; if (ui.game.dataset.memberBankUrl) loadAccountRounds(data); } catch (error) { console.error(error); ui.loading.textContent = 'The questions could not load. Refresh the page to try again.'; } } async function loadAccountRounds(guest) { try { const response = await fetch(ui.game.dataset.memberBankUrl, {credentials: 'include'}); if (!response.ok) return; const account = await response.json(); if (!account.ok || !['AQA', 'OCR-A'].includes(account.board) || !Array.isArray(account.questions)) return; if (account.board !== guest.board) { const matchingGuestUrl = new URL(ui.game.dataset.bankUrl, location.href); matchingGuestUrl.searchParams.set('board', account.board === 'OCR-A' ? 'ocr' : 'aqa'); const matchingResponse = await fetch(matchingGuestUrl, {credentials:'same-origin'}); if (!matchingResponse.ok) return; guest = await matchingResponse.json(); } bank = [...guest.questions, ...account.questions]; ui.board.textContent = account.board === 'OCR-A' ? 'OCR A' : 'AQA'; ui['topic-access'].hidden = true; const selected = ui.case.value || new URL(location.href).searchParams.get('case'); updateMatches(selected); } catch { // The guest rounds remain available if My Chemistry cannot be reached. } } loadBank();