// ========== STOICHIOMETRIC FACTOR DRILL - CORE (no DOM) ==========
// n(B) = n(A) r(B,A), r(B,A) = nu(B)/nu(A). Reactions, question templates, exact arithmetic and the
// LaTeX all live here so dev/tests/stoich-factor.test.cjs can run them in Node.
sfdCore = {
// Balanced reactions with state symbols, all at 25 C. Coefficients are exact.
const REACTIONS = [
'2 H2(g) + O2(g) -> 2 H2O(l)',
'N2(g) + 3 H2(g) -> 2 NH3(g)',
'CH4(g) + 2 O2(g) -> CO2(g) + 2 H2O(l)',
'C3H8(g) + 5 O2(g) -> 3 CO2(g) + 4 H2O(l)',
'2 C2H6(g) + 7 O2(g) -> 4 CO2(g) + 6 H2O(l)',
'2 C4H10(g) + 13 O2(g) -> 8 CO2(g) + 10 H2O(l)',
'2 C8H18(l) + 25 O2(g) -> 16 CO2(g) + 18 H2O(l)',
'C2H5OH(l) + 3 O2(g) -> 2 CO2(g) + 3 H2O(l)',
'C6H12O6(s) + 6 O2(g) -> 6 CO2(g) + 6 H2O(l)',
'4 Fe(s) + 3 O2(g) -> 2 Fe2O3(s)',
'4 Al(s) + 3 O2(g) -> 2 Al2O3(s)',
'2 Mg(s) + O2(g) -> 2 MgO(s)',
'3 Mg(s) + N2(g) -> Mg3N2(s)',
'2 Na(s) + Cl2(g) -> 2 NaCl(s)',
'P4(s) + 5 O2(g) -> P4O10(s)',
'2 SO2(g) + O2(g) -> 2 SO3(l)',
'4 NH3(g) + 5 O2(g) -> 4 NO(g) + 6 H2O(l)',
'4 NH3(g) + 3 O2(g) -> 2 N2(g) + 6 H2O(l)',
'3 NO2(g) + H2O(l) -> 2 HNO3(aq) + NO(g)',
'Fe2O3(s) + 3 CO(g) -> 2 Fe(s) + 3 CO2(g)',
'2 KClO3(s) -> 2 KCl(s) + 3 O2(g)',
'2 H2O2(aq) -> 2 H2O(l) + O2(g)',
'2 NaN3(s) -> 2 Na(s) + 3 N2(g)',
'CaCO3(s) -> CaO(s) + CO2(g)',
'2 Al(s) + 6 HCl(aq) -> 2 AlCl3(aq) + 3 H2(g)',
'Zn(s) + 2 HCl(aq) -> ZnCl2(aq) + H2(g)',
'H2SO4(aq) + 2 NaOH(aq) -> Na2SO4(aq) + 2 H2O(l)',
'3 Cu(s) + 8 HNO3(aq) -> 3 Cu(NO3)2(aq) + 2 NO(g) + 4 H2O(l)'
];
function parseTerm(t) {
const m = t.trim().match(/^(?:(\d+)\s+)?(.+)\((s|l|g|aq)\)$/);
if (!m) throw new Error('bad term: ' + t);
return { nu: m[1] ? +m[1] : 1, f: m[2], st: m[3] };
}
function parseReaction(s) {
const [lhs, rhs] = s.split('->');
const sp = [];
lhs.split(' + ').forEach(t => sp.push(Object.assign(parseTerm(t), { side: 'R' })));
rhs.split(' + ').forEach(t => sp.push(Object.assign(parseTerm(t), { side: 'P' })));
return sp;
}
const RX = REACTIONS.map(parseReaction);
// 'Cu(NO3)2' -> Cu(NO<sub>3</sub>)<sub>2</sub> and \mathrm{Cu(NO_3)_2}
const formulaHtml = f => f.replace(/([A-Za-z)])(\d+)/g, '$1<sub>$2</sub>');
const formulaTex = f => '\\mathrm{' + f.replace(/([A-Za-z)])(\d+)/g, '$1_{$2}').replace(/_\{(\d)\}/g, '_$1') + '}';
// a quantity's argument: n(H2O) but n[Cu(NO3)2], since the species already has parentheses (DS-7)
const argHtml = f => /\(/.test(f) ? '[' + formulaHtml(f) + ']' : '(' + formulaHtml(f) + ')';
// ---- question templates: {B} asked-for species, {N} given amount, {A} given species ----
// RP reactant -> product, PR product -> reactant, RR reactant -> reactant, PP product -> product.
// A given amount takes a singular verb ("3.00 mol of A reacts"); "moles of B react" stays plural.
const TEMPLATES = {
RP: [
'How many moles of {B} can be produced from {N} of {A}?',
'What amount of {B} forms when {N} of {A} reacts completely?',
'Calculate the amount of {B} (in mol) produced by the complete reaction of {N} of {A}.',
'{Art} {N} sample of {A} reacts completely. How many moles of {B} form?',
'Find the maximum amount of {B} that {N} of {A} can yield.',
'How much {B} (in mol) can be produced from {N} of {A}?',
'Calculate the number of moles of {B} produced from {N} of {A}.'
],
PR: [
'How many moles of {B} are required to produce {N} of {A}?',
'What amount of {B} is consumed when {N} of {A} forms?',
'Calculate the amount of {B} (in mol) needed to make {N} of {A}.',
'The reaction produced {N} of {A}. How many moles of {B} reacted?',
'Find the amount of {B} that must react to form {N} of {A}.',
'How much {B} (in mol) is required to produce {N} of {A}?',
'Determine the number of moles of {B} needed to form {N} of {A}.'
],
RR: [
'How many moles of {B} react with {N} of {A}?',
'What amount of {B} is needed to react completely with {N} of {A}?',
'Calculate the amount of {B} (in mol) consumed along with {N} of {A}.',
'{Art} {N} sample of {A} reacts completely. How many moles of {B} react with it?',
'How much {B} (in mol) reacts with {N} of {A}?',
'Find the number of moles of {B} that react with {N} of {A}.'
],
PP: [
'How many moles of {B} form along with {N} of {A}?',
'When {N} of {A} is produced, what amount of {B} is also produced?',
'Calculate the amount of {B} (in mol) formed in the same reaction that produces {N} of {A}.',
'The reaction yielded {N} of {A}. How many moles of {B} formed?',
'How much {B} (in mol) forms along with {N} of {A}?',
'Determine the number of moles of {B} formed along with {N} of {A}.'
]
};
// "an 8.00 mol sample", "an 11.5 mol sample", "an 18 mol sample"; everything else takes "a"
const article = n => /^(8|11(?!\d)|18(?!\d))/.test(n) ? 'An' : 'A';
// ---- exact decimal arithmetic (BigInt): the answer is M nu(B) / (nu(A) 10^k) ----
const TEN = 10n;
const pow10 = e => TEN ** BigInt(e);
// I x 10^p as a plain decimal string
function decStr(I, p) {
let s = I.toString();
if (p >= 0) return s + '0'.repeat(p);
const d = -p;
if (s.length <= d) s = '0'.repeat(d - s.length + 1) + s;
return s.slice(0, s.length - d) + '.' + s.slice(s.length - d);
}
// floor(log10(N/D)) for positive N/D
function mag(N, D) {
let e = Math.floor(Math.log10(Number(N) / Number(D)));
const ge = (e2) => e2 >= 0 ? N >= D * pow10(e2) : N * pow10(-e2) >= D;
while (!ge(e)) e--;
while (ge(e + 1)) e++;
return e;
}
// floor(N/D x 10^-p) and its remainder
function scaled(N, D, p) {
const num = p <= 0 ? N * pow10(-p) : N, den = p <= 0 ? D : D * pow10(p);
return { q: num / den, r: num % den, den };
}
// sf figures: the bar on the last significant figure plus two TRUNCATED guards, and the final
// value rounded half to even
function figures(N, D, sf) {
const e = mag(N, D), lsf = e - (sf - 1);
const g = scaled(N, D, lsf - 2).q; // sf + 2 digits, truncated
const guardPlain = decStr(g, lsf - 2);
let seen = 0, guardTex = '';
for (let i = guardPlain.length - 1; i >= 0; i--) {
const ch = guardPlain[i];
if (ch >= '0' && ch <= '9') { seen++; guardTex = (seen === 3 ? '\\bar{' + ch + '}' : ch) + guardTex; }
else guardTex = ch + guardTex;
}
const f = scaled(N, D, lsf);
let q = f.q;
const twice = 2n * f.r;
if (twice > f.den || (twice === f.den && q % 2n === 1n)) q += 1n;
let fl = lsf;
if (q === pow10(sf)) { q /= TEN; fl += 1; } // 9.996 to three figures is 10.0
return { e, lsf, guardPlain, guardTex, final: decStr(q, fl) };
}
function sigFigs(str) {
str = String(str).trim();
const hasDot = str.includes('.');
const digits = str.replace('.', '').replace(/^0+/, '');
if (digits === '') return 1;
if (hasDot) return digits.length;
return digits.replace(/0+$/, '').length || 1;
}
// a trailing zero with no decimal point hides the count of figures: never print one
const ambiguous = s => !s.includes('.') && /0$/.test(s);
function barInput(str) {
let i = str.length - 1;
while (i >= 0 && !(str[i] >= '0' && str[i] <= '9')) i--;
return str.slice(0, i) + '\\bar{' + str[i] + '}' + str.slice(i + 1);
}
// given amount: 2 or 3 figures, 0.100 to 20.0 mol
function makeGiven(rng) {
for (let t = 0; t < 200; t++) {
const sf = rng() < 0.4 ? 2 : 3;
const u = rng(), e = u < 0.3 ? -1 : (u < 0.75 ? 0 : 1);
const M = BigInt(Math.floor(pow10n(sf - 1) + rng() * (pow10n(sf) - pow10n(sf - 1))));
const k = sf - 1 - e; // value = M x 10^-k
const str = decStr(M, -k);
const v = +str;
if (v < 0.1 || v > 20 || ambiguous(str) || sigFigs(str) !== sf) continue;
return { str, sf, M, k };
}
return { str: '2.50', sf: 3, M: 250n, k: 2 };
}
function pow10n(e) { return Math.pow(10, e); }
function solve(sp, ai, bi, given) {
const N = given.M * BigInt(sp[bi].nu), D = BigInt(sp[ai].nu) * pow10(given.k);
const fig = figures(N, D, given.sf);
const v = Number(N) / Number(D);
const okRange = v >= 0.001 && v < 1000 && !ambiguous(fig.final);
return Object.assign({ value: v, ok: okRange }, fig);
}
const caseOf = (sp, ai, bi) => sp[ai].side + sp[bi].side; // 'RP', 'PR', 'RR' or 'PP'
// kind: 'rx' new reaction, 'pair' same reaction new species pair, 'amt' same pair new amount
function makeProblem(rng, kind, prev) {
const pick = n => Math.floor(rng() * n);
for (let t = 0; t < 500; t++) {
let ri = prev && kind !== 'rx' ? prev.ri : pick(RX.length);
if (prev && kind === 'rx' && RX.length > 1 && ri === prev.ri) continue;
const sp = RX[ri];
let ai, bi;
if (prev && kind === 'amt') { ai = prev.ai; bi = prev.bi; }
else {
ai = pick(sp.length); bi = pick(sp.length);
if (ai === bi) continue;
if (prev && kind === 'pair' && ai === prev.ai && bi === prev.bi) continue;
}
const given = makeGiven(rng);
if (prev && kind === 'amt' && given.str === prev.given.str) continue;
const ans = solve(sp, ai, bi, given);
if (!ans.ok) continue;
const cs = caseOf(sp, ai, bi);
const list = TEMPLATES[cs];
let ti = pick(list.length);
if (prev && prev.cs === cs && list.length > 1 && ti === prev.ti) ti = (ti + 1 + pick(list.length - 1)) % list.length;
return { ri, ai, bi, cs, ti, given, ans };
}
throw new Error('no problem found');
}
// the question: {N} and {A} carry the given color, {B} is bold
function question(p) {
const sp = RX[p.ri], A = sp[p.ai], B = sp[p.bi];
const t = TEMPLATES[p.cs][p.ti];
const fill = (nFn, aFn, bFn, art) => t
.replace('{Art}', art).replace('{N}', nFn).replace('{A}', aFn).replace('{B}', bFn);
const htmlQ = fill('<span class="sfd-qg">' + p.given.str + ' mol</span>',
'<span class="sfd-qg">' + formulaHtml(A.f) + '</span>',
'<strong class="sfd-qb">' + formulaHtml(B.f) + '</strong>', article(p.given.str));
const text = fill(p.given.str + ' mol', A.f, B.f, article(p.given.str));
return { html: htmlQ, text };
}
// the worked lines; each row is wrapped in a class so the widget can reveal it in step
function tex(p) {
const sp = RX[p.ri], A = sp[p.ai], B = sp[p.bi];
// written as stoichiometry.qmd writes them: \mathrm{H_2O}, r(\mathrm{O_2, H_2O}), \mathrm{mol~O_2}
const inner = f => formulaTex(f).slice('\\mathrm{'.length, -1);
const a = inner(A.f), b = inner(B.f);
const row = (k, body) => '\\class{sfd-r' + k + '}{' + body + '}';
const q = (sym, x) => sym + (/\(/.test(x) ? '[\\mathrm{' + x + '}]' : '(\\mathrm{' + x + '})');
return '\\begin{aligned}' +
row(1, q('n', b)) + ' &' + row(1, '{}= ' + q('n', a) + '~' + q('r', b + ', ' + a)) + ' \\\\[1.5ex]' +
' &' + row(1, '{}= ' + q('n', a) + '~\\dfrac{\\class{sfd-cm}{' + q('\\nu', b) + '}}{\\class{sfd-cd}{' + q('\\nu', a) + '}}') + ' \\\\[1.5ex]' +
' &' + row(2, '{}= \\left( \\class{sfd-cg}{' + barInput(p.given.str) + '~\\mathrm{mol~' + a + '}} \\right)' +
'\\left( \\dfrac{\\class{sfd-cm}{' + B.nu + '}~\\mathrm{mol~' + b + '}}{\\class{sfd-cd}{' + A.nu + '}~\\mathrm{mol~' + a + '}} \\right)') + ' \\\\[1.5ex]' +
' &' + row(4, '{}= ' + p.ans.guardTex + '~\\mathrm{mol~' + b + '}') + ' \\\\[1.5ex]' +
' &' + row(4, '{}= ' + p.ans.final + '~\\mathrm{mol~' + b + '}') +
'\\end{aligned}';
}
return { REACTIONS, RX, parseReaction, formulaHtml, formulaTex, argHtml, TEMPLATES, article, decStr, mag, figures,
sigFigs, ambiguous, barInput, makeGiven, solve, caseOf, makeProblem, question, tex };
}Skill Drill: Stoichiometric Factor
Interactive drill for mole-to-mole conversions. Convert a given amount of one species into the amount of another with the stoichiometric factor from a balanced equation.
// ========== STOICHIOMETRIC FACTOR DRILL - MATHJAX LOADER ==========
// Same host guard as _titration-lab.qmd (MJ-HOST-GUARD): if the page owns a MathJax engine, wait
// for it and never replace it. Only a page with no engine (the Skill Hub page has no source math)
// loads the standalone copy, inheriting the site config that Quarto writes on every page.
sfdMathjax = {
const engineScript = Array.from(document.scripts).some(s =>
/mathjax/i.test(s.src) && !/mathjax-[a-z]/i.test(s.src));
if ((window.MathJax && window.MathJax.typesetPromise) || engineScript) {
const waitForHost = (ms) => {
const MJ = window.MathJax;
if (MJ && MJ.startup && MJ.startup.promise) return MJ.startup.promise.then(() => 'ready');
if (ms <= 0) return Promise.resolve('host-never-started');
return new Promise(r => setTimeout(() => r(waitForHost(ms - 250)), 250));
};
return waitForHost(20000);
}
if (window.__sfdMathjaxLoading) return window.__sfdMathjaxLoading;
window.__sfdMathjaxLoading = new Promise(resolve => {
const cfg = window.MathJax || {
loader: { load: ['[tex]/html'] },
tex: { packages: {'[+]': ['html']} },
output: { font: 'mathjax-stix2' }
};
const prevReady = cfg.startup && cfg.startup.ready;
cfg.startup = Object.assign({}, cfg.startup, {
ready: () => {
if (prevReady) prevReady();
else window.MathJax.startup.defaultReady();
resolve('ready');
}
});
window.MathJax = cfg;
const s = document.createElement('script');
s.src = 'https://cdn.jsdelivr.net/npm/mathjax@4.1.3/tex-mml-chtml.js';
s.async = true;
document.head.appendChild(s);
});
return window.__sfdMathjaxLoading;
}// ========== STOICHIOMETRIC FACTOR DRILL - STYLES ==========
html`<style>
.sfd-widget {
--sfd-g: #0B66A8; /* the given amount */
--sfd-m: #A84600; /* multiply by nu(B) */
--sfd-d: #963A73; /* divide by nu(A) */
--sfd-ink: #1f2933;
--sfd-muted: #5b6672;
--sfd-faint: #6b747d;
--sfd-line: #d7dde3;
--sfd-panel: #f6f8fa;
--sfd-bg: #fdfdfd;
--sfd-btn: #ffffff;
max-width: 760px;
margin: 1.5rem auto;
padding: 1rem 1.25rem 1.25rem;
border: 1px solid var(--sfd-line);
border-radius: 8px;
color: var(--sfd-ink);
}
.sfd-title { font-size: 1.3rem; font-weight: 600; text-align: center; margin: 0 0 0.6rem; }
.sfd-q { font-size: 1.1rem; line-height: 1.5; margin: 0 0 0.5rem; min-height: 3em; }
.sfd-qg { color: var(--sfd-g); font-weight: 600; }
.sfd-qb { font-weight: 700; }
/* a reaction too wide even at the 13 px floor scrolls sideways, drawing and arrows together */
.sfd-scroll { overflow-x: auto; overflow-y: hidden; }
.sfd-scroll:focus { outline: none; }
.sfd-scroll:focus-visible { outline: 2px solid var(--sfd-g); outline-offset: 2px; }
.sfd-stage { position: relative; padding: 0 0 68px; width: max-content; min-width: 100%; }
/* a zero-size box whose top edge is the coefficient's baseline: the arrows are placed from it */
.sfd-bl { display: inline-block; width: 0; height: 0; vertical-align: baseline; }
.sfd-svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }
.sfd-eq {
display: flex; flex-wrap: nowrap; justify-content: center; align-items: baseline;
gap: 0 0.45em; font-size: 1.5rem; white-space: nowrap; line-height: 1.4;
}
.sfd-coef { margin-right: 0.15em; }
.sfd-coef.is-one { color: var(--sfd-faint); }
.sfd-st { font-size: 0.8em; }
.sfd-term.is-a .sfd-form { color: var(--sfd-g); }
.sfd-term.is-a .sfd-coef, .sfd-term.is-b .sfd-coef { transition: color 0.3s; }
/* color plus an underline, never bold: bold would widen the equation after it was fitted */
.sfd-s2 .sfd-term.is-b .sfd-coef { color: var(--sfd-m); text-decoration: underline 2px; text-underline-offset: 3px; }
.sfd-s3 .sfd-term.is-a .sfd-coef { color: var(--sfd-d); text-decoration: underline 2px; text-underline-offset: 3px; }
.sfd-chip {
position: absolute; top: 0; white-space: nowrap;
border: 1.5px solid var(--sfd-line); border-radius: 6px; background: var(--sfd-bg);
padding: 2px 8px; font-size: 0.95rem; line-height: 1.5;
}
.sfd-chip-g { border-color: var(--sfd-g); color: var(--sfd-g); font-weight: 600; }
.sfd-chip-f { font-weight: 600; }
.sfd-cap { font-weight: 400; font-size: 0.8em; color: var(--sfd-muted); margin-right: 0.3em; }
.sfd-svg path { fill: none; stroke-width: 2; stroke-linecap: round; }
.sfd-svg .sfd-mul path, .sfd-svg .sfd-mul polygon { stroke: var(--sfd-m); }
.sfd-svg .sfd-div path, .sfd-svg .sfd-div polygon { stroke: var(--sfd-d); }
.sfd-svg polygon { stroke-width: 1; stroke-linejoin: round; }
.sfd-svg .sfd-mul polygon { fill: var(--sfd-m); }
.sfd-svg .sfd-div polygon { fill: var(--sfd-d); }
.sfd-svg text {
font-size: 13px; font-weight: 600; text-anchor: middle; dominant-baseline: middle;
paint-order: stroke; stroke: var(--sfd-bg); stroke-width: 5px; stroke-linejoin: round;
}
.sfd-svg .sfd-mul text { fill: var(--sfd-m); }
.sfd-svg .sfd-div text { fill: var(--sfd-d); }
.sfd-svg .sfd-stem { stroke-dasharray: 1; stroke-dashoffset: 1; transition: stroke-dashoffset 0.5s ease-out; }
.sfd-svg .sfd-plate { fill: var(--sfd-bg); stroke: none; }
.sfd-svg polygon, .sfd-svg text, .sfd-svg .sfd-plate { opacity: 0; transition: opacity 0.25s 0.35s; }
.sfd-svg .sfd-mul, .sfd-svg .sfd-div { visibility: hidden; }
.sfd-s2 .sfd-svg .sfd-mul, .sfd-s3 .sfd-svg .sfd-div { visibility: visible; }
.sfd-s2 .sfd-svg .sfd-mul .sfd-stem, .sfd-s3 .sfd-svg .sfd-div .sfd-stem { stroke-dashoffset: 0; }
.sfd-s2 .sfd-svg .sfd-mul polygon, .sfd-s2 .sfd-svg .sfd-mul text, .sfd-s2 .sfd-svg .sfd-mul .sfd-plate,
.sfd-s3 .sfd-svg .sfd-div polygon, .sfd-s3 .sfd-svg .sfd-div text, .sfd-s3 .sfd-svg .sfd-div .sfd-plate { opacity: 1; }
.sfd-controls {
display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center;
gap: 0.6rem 1rem; padding-top: 0.75rem; border-top: 1px solid var(--sfd-line);
}
.sfd-new, .sfd-ans { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
.sfd-widget button {
font: inherit; font-size: 0.95rem; padding: 0.4rem 0.8rem; border-radius: 6px; cursor: pointer;
border: 1px solid var(--sfd-line); background: var(--sfd-btn); color: var(--sfd-ink);
}
.sfd-widget button:hover { border-color: var(--sfd-muted); }
.sfd-widget button:focus-visible, .sfd-switch input:focus-visible { outline: 2px solid var(--sfd-g); outline-offset: 2px; }
.sfd-widget .sfd-show { border-color: var(--sfd-g); color: var(--sfd-g); font-weight: 600; }
.sfd-widget .sfd-show[hidden] { display: none; }
.sfd-switch { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.95rem; cursor: pointer; margin: 0; }
.sfd-switch input { width: 1.05rem; height: 1.05rem; margin: 0; accent-color: var(--sfd-g); }
.sfd-math { margin-top: 0.75rem; padding: 0.25rem 0.75rem; background: var(--sfd-panel); border-radius: 6px; overflow-x: auto; }
.sfd-math:focus { outline: none; }
.sfd-math:focus-visible { outline: 2px solid var(--sfd-g); outline-offset: 2px; }
.sfd-math.is-hidden { visibility: hidden; }
.sfd-math .sfd-r1, .sfd-math .sfd-r2, .sfd-math .sfd-r4 { opacity: 0; transition: opacity 0.35s; }
.sfd-s1 .sfd-math .sfd-r1, .sfd-s2 .sfd-math .sfd-r2, .sfd-s4 .sfd-math .sfd-r4 { opacity: 1; }
.sfd-math .sfd-cg { color: var(--sfd-g); }
.sfd-math .sfd-cm { color: var(--sfd-m); }
.sfd-math .sfd-cd { color: var(--sfd-d); }
.sfd-sr { position: absolute !important; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; margin: 0; padding: 0; }
@media (max-width: 575.98px) {
.sfd-widget { padding: 0.75rem 0.5rem 1rem; }
.sfd-title { font-size: 1.2rem; }
.sfd-q { font-size: 1rem; }
.sfd-eq { gap: 0 0.25em; }
.sfd-coef { margin-right: 0.08em; }
.sfd-controls { justify-content: flex-start; }
.sfd-math { padding: 0.25rem 0.4rem; }
.sfd-math mjx-container { font-size: 85% !important; }
}
@media (prefers-reduced-motion: reduce) {
.sfd-widget *, .sfd-widget .sfd-svg * { transition: none !important; }
}
body.quarto-dark .sfd-widget, [data-bs-theme="dark"] .sfd-widget {
--sfd-g: #6CB6FF;
--sfd-m: #FF9E57;
--sfd-d: #E58BC4;
--sfd-ink: #e6e9f0;
--sfd-muted: #a8afc7;
--sfd-faint: #7d8597;
--sfd-line: rgba(168, 175, 199, 0.35);
--sfd-panel: rgba(255, 255, 255, 0.04);
--sfd-bg: #0b0c14;
--sfd-btn: rgba(255, 255, 255, 0.04);
}
</style>`// ========== STOICHIOMETRIC FACTOR DRILL - WIDGET ==========
{
sfdMathjax;
const C = sfdCore;
// the heading sits one level under the host section: h4 under the book's ### section; the
// Skill Hub page sets window.__sfdHeadingLevel = 2 under its (visually hidden) h1
const level = window.__sfdHeadingLevel || 4;
const STORE = 'sfd-always-show';
const reduce = () => !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
const root = document.createElement('div');
root.className = 'sfd-widget';
root.innerHTML =
'<div class="sfd-title" role="heading" aria-level="' + level + '">Stoichiometric Factor</div>' +
'<p class="sfd-q"></p>' +
'<div class="sfd-scroll"><div class="sfd-stage">' +
'<svg class="sfd-svg" aria-hidden="true" focusable="false"></svg>' +
'<div class="sfd-chip sfd-chip-g" aria-hidden="true"><span class="sfd-cap">given:</span><span class="sfd-chip-v"></span></div>' +
'<div class="sfd-chip sfd-chip-f" aria-hidden="true"><span class="sfd-cap">find:</span><span class="sfd-chip-v"></span></div>' +
'<div class="sfd-eq"></div>' +
'</div></div>' +
'<div class="sfd-controls">' +
'<div class="sfd-new">' +
'<button type="button" data-act="rx">New reaction</button>' +
'<button type="button" data-act="pair">New pair</button>' +
'<button type="button" data-act="amt">New amount</button>' +
'</div>' +
'<div class="sfd-ans">' +
'<button type="button" class="sfd-show">Show answer</button>' +
'<label class="sfd-switch"><input type="checkbox" role="switch"> Always show answer</label>' +
'</div>' +
'</div>' +
'<div class="sfd-math is-hidden" tabindex="-1" aria-hidden="true"></div>' +
'<p class="sfd-sr" role="status"></p>';
const $ = s => root.querySelector(s);
const qEl = $('.sfd-q'), scroller = $('.sfd-scroll'), stage = $('.sfd-stage'), svg = $('.sfd-svg'), eqEl = $('.sfd-eq');
const chipG = $('.sfd-chip-g'), chipF = $('.sfd-chip-f'), mathEl = $('.sfd-math');
const showBtn = $('.sfd-show'), sw = $('.sfd-switch input'), srEl = $('.sfd-sr');
let p = null, shown = false, timers = [], always = false, recenter = false;
try { always = localStorage.getItem(STORE) === '1'; } catch (e) {}
sw.checked = always;
showBtn.hidden = always;
function setStep(n) {
for (let i = 1; i <= 4; i++) root.classList.toggle('sfd-s' + i, i <= n);
}
function renderEquation() {
const sp = C.RX[p.ri];
let h = '', placedArrow = false;
sp.forEach((s, i) => {
if (s.side === 'P' && !placedArrow) { h += '<span class="sfd-op" aria-hidden="true">→</span>'; placedArrow = true; }
else if (i > 0) h += '<span class="sfd-op">+</span>';
const role = i === p.ai ? ' is-a' : (i === p.bi ? ' is-b' : '');
// a coefficient of 1 is never written, but when it is part of the problem it is shown faintly
const bl = '<span class="sfd-bl"></span>';
const coef = s.nu === 1 ? (role ? '<span class="sfd-coef is-one">1' + bl + '</span>' : '<span class="sfd-coef"></span>')
: '<span class="sfd-coef">' + s.nu + bl + '</span>';
h += '<span class="sfd-term' + role + '">' + coef + '<span class="sfd-form">' + C.formulaHtml(s.f) +
'</span><span class="sfd-st">(' + s.st + ')</span></span>';
});
eqEl.innerHTML = h;
const text = sp.filter(s => s.side === 'R').map(s => (s.nu > 1 ? s.nu + ' ' : '') + s.f + '(' + s.st + ')').join(' + ') +
' yields ' + sp.filter(s => s.side === 'P').map(s => (s.nu > 1 ? s.nu + ' ' : '') + s.f + '(' + s.st + ')').join(' + ');
eqEl.setAttribute('role', 'img');
eqEl.setAttribute('aria-label', 'Reaction: ' + text);
}
// arrowhead as a filled triangle; the stem stops at its base
function head(tx, ty, cx, cy) {
const L = 7, W = 3.2;
let dx = tx - cx, dy = ty - cy; const m = Math.hypot(dx, dy) || 1; dx /= m; dy /= m;
const bx = tx - dx * L, by = ty - dy * L;
return { base: [bx, by], pts: [tx, ty, bx - dy * W, by + dx * W, bx + dy * W, by - dx * W] };
}
const ROW = 34, LANE1 = 50;
function layout() {
if (!p) return;
// shrink a long equation to fit the width, down to 13 px; past that the drawing scrolls sideways
const FLOOR = 13, avail = scroller.clientWidth;
eqEl.style.fontSize = '';
let fs = parseFloat(getComputedStyle(eqEl).fontSize);
while (eqEl.scrollWidth > avail + 1 && fs > FLOOR) { fs = Math.max(FLOOR, fs - 1); eqEl.style.fontSize = fs + 'px'; }
// a scrolling region must be reachable from the keyboard (arrow keys scroll it) and named
if (stage.offsetWidth > avail + 1) {
scroller.tabIndex = 0;
scroller.setAttribute('role', 'region');
scroller.setAttribute('aria-label', 'Reaction drawing, scrolls sideways');
} else {
scroller.removeAttribute('tabindex');
scroller.removeAttribute('role');
scroller.removeAttribute('aria-label');
}
const terms = eqEl.querySelectorAll('.sfd-term');
const tA = terms[p.ai], tB = terms[p.bi];
const cxOf = el => { const r = el.getBoundingClientRect(); return r.left + r.width / 2; };
const sr0 = stage.getBoundingClientRect();
const xA = cxOf(tA) - sr0.left, xB = cxOf(tB) - sr0.left;
// a new problem opens with A and B in view; a resize keeps the reader's own scroll
if (recenter && avail) { scroller.scrollLeft = Math.max(0, (xA + xB) / 2 - avail / 2); recenter = false; }
// exact widths: offsetWidth rounds, which lets a chip clamped to the right edge stick out
const wG = chipG.getBoundingClientRect().width, wF = chipF.getBoundingClientRect().width, W = sr0.width;
const clampX = (x, w) => Math.max(0, Math.min(W - w, x - w / 2));
const lg = clampX(xA, wG), lf = clampX(xB, wF);
const overlap = lg < lf + wF + 6 && lf < lg + wG + 6;
const rows = overlap ? 2 : 1;
stage.style.paddingTop = (rows * ROW + LANE1) + 'px';
chipG.style.left = lg + 'px'; chipG.style.top = ((rows - 1) * ROW) + 'px';
chipF.style.left = lf + 'px'; chipF.style.top = '0px';
const sr = stage.getBoundingClientRect();
const box = el => { const r = el.getBoundingClientRect(); return { l: r.left - sr.left, t: r.top - sr.top, b: r.bottom - sr.top, cx: r.left - sr.left + r.width / 2 }; };
const cA = box(tA.querySelector('.sfd-coef')), cB = box(tB.querySelector('.sfd-coef'));
const g = box(chipG);
// multiply by nu(B): from the given chip down to the coefficient of B
// digits stand about 0.72 em above the baseline; the underline reaches 5 px below it
// (offset 3 px + 2 px thick). Every tip and stem end keeps a clear gap from both.
const fsEq = parseFloat(getComputedStyle(eqEl).fontSize);
const base = el => box(el.querySelector('.sfd-bl')).t;
const blA = base(tA), blB = base(tB);
const x0 = g.cx, y0 = g.b + 3, x1 = cB.cx, y1 = blB - 0.72 * fsEq - 4, ym = (y0 + y1) / 2;
const hm = head(x1, y1, x1, ym);
const mulPath = 'M' + x0 + ' ' + y0 + ' C' + x0 + ' ' + ym + ' ' + x1 + ' ' + ym + ' ' + hm.base[0] + ' ' + hm.base[1];
// divide by nu(A): a curve under the equation from nu(B) back to nu(A)
const yb = Math.max(blA, blB) + 5 + 4, depth = 32;
const ha = head(cA.cx, yb, cA.cx, yb + depth * 1.33);
const divPath = 'M' + cB.cx + ' ' + yb + ' C' + cB.cx + ' ' + (yb + depth * 1.33) + ' ' + cA.cx + ' ' + (yb + depth * 1.33) + ' ' + ha.base[0] + ' ' + ha.base[1];
const sp = C.RX[p.ri];
// "multiply by" sits on its curve with a backing plate; "divide by" sits under its curve
const lx = x => Math.max(48, Math.min(W - 48, x));
svg.innerHTML =
'<g class="sfd-mul"><path class="sfd-stem" pathLength="1" d="' + mulPath + '"/>' +
'<polygon points="' + hm.pts.join(' ') + '"/>' +
'<text x="' + lx((x0 + x1) / 2) + '" y="' + ym + '">multiply by ' + sp[p.bi].nu + '</text></g>' +
'<g class="sfd-div"><path class="sfd-stem" pathLength="1" d="' + divPath + '"/>' +
'<polygon points="' + ha.pts.join(' ') + '"/>' +
'<text x="' + lx((cA.cx + cB.cx) / 2) + '" y="' + (yb + depth + 14) + '">divide by ' + sp[p.ai].nu + '</text></g>';
svg.querySelectorAll('text').forEach(t => {
let b; try { b = t.getBBox(); } catch (e) { return; }
if (!b.width) return;
const r = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
r.setAttribute('x', b.x - 4); r.setAttribute('y', b.y - 1);
r.setAttribute('width', b.width + 8); r.setAttribute('height', b.height + 2);
r.setAttribute('rx', 3); r.setAttribute('class', 'sfd-plate');
t.parentNode.insertBefore(r, t);
});
}
function typeset() {
const MJ = window.MathJax;
if (!MJ) return;
if (MJ.typesetClear) MJ.typesetClear([mathEl]);
if (MJ.typesetPromise) MJ.typesetPromise([mathEl]).catch(() => {});
}
function clearTimers() { timers.forEach(clearTimeout); timers = []; }
const answerText = () => 'Answer: ' + p.ans.final + ' mol of ' + C.RX[p.ri][p.bi].f + '.';
// speak = false when the answer has already gone out with the question
function show(animate, speak = true) {
shown = true;
showBtn.hidden = true;
mathEl.classList.remove('is-hidden');
mathEl.removeAttribute('aria-hidden');
const finish = () => {
setStep(4);
if (speak) srEl.textContent = answerText();
};
if (!animate || reduce()) { finish(); return; }
setStep(1);
timers.push(setTimeout(() => setStep(2), 600));
timers.push(setTimeout(() => setStep(3), 1300));
timers.push(setTimeout(finish, 2000));
}
function newProblem(kind, announce) {
clearTimers();
p = C.makeProblem(Math.random, kind, p);
shown = false;
setStep(0);
const q = C.question(p);
qEl.innerHTML = q.html;
// a new question is read out (with its answer when Always show is on); the first one on page
// load is not
if (announce) srEl.textContent = always ? q.text + ' ' + answerText() : q.text;
renderEquation();
// the chips name the quantities; the numbers live in the question and the worked math
const sp = C.RX[p.ri];
chipG.querySelector('.sfd-chip-v').innerHTML = '<i>n</i>' + C.argHtml(sp[p.ai].f);
chipF.querySelector('.sfd-chip-v').innerHTML = '<i>n</i>' + C.argHtml(sp[p.bi].f);
mathEl.innerHTML = '$$' + C.tex(p) + '$$';
mathEl.classList.add('is-hidden');
mathEl.setAttribute('aria-hidden', 'true');
showBtn.hidden = always;
typeset();
recenter = true;
layout();
if (always) show(true, false);
}
root.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => newProblem(b.dataset.act, true)));
showBtn.addEventListener('click', () => { show(true); mathEl.focus(); });
sw.addEventListener('change', () => {
always = sw.checked;
try { localStorage.setItem(STORE, always ? '1' : '0'); } catch (e) {}
if (always) { showBtn.hidden = true; if (!shown) show(true); }
else showBtn.hidden = shown;
});
let rafId = 0, dead = false;
const ro = new ResizeObserver(() => { cancelAnimationFrame(rafId); rafId = requestAnimationFrame(layout); });
ro.observe(scroller);
// a late web-font swap changes the glyph widths without resizing the stage
if (document.fonts && document.fonts.ready) document.fonts.ready.then(() => { if (!dead) layout(); });
invalidation.then(() => { dead = true; ro.disconnect(); cancelAnimationFrame(rafId); clearTimers(); });
newProblem('rx');
// the first layout needs the node in the document
requestAnimationFrame(layout);
return root;
}