// ========== TITRATION LAB - SYSTEMS DATA ==========
tlSystems = ({
acids: {
HCl: { name: 'hydrochloric acid', plain: 'HCl', a: 1, M: 36.46 },
HNO3: { name: 'nitric acid', plain: 'HNO₃', a: 1, M: 63.02 }, // 1.01 + 14.01 + 3(16.00), as the solution mixer
H2SO4: { name: 'sulfuric acid', plain: 'H₂SO₄', a: 2, M: 98.08 }
},
bases: {
NaOH: { name: 'sodium hydroxide', plain: 'NaOH', b: 1, cation: 'Na<sup>+</sup>', cationTex: '\\mathrm{Na^+}' },
KOH: { name: 'potassium hydroxide', plain: 'KOH', b: 1, cation: 'K<sup>+</sup>', cationTex: '\\mathrm{K^+}' },
BaOH2: { name: 'barium hydroxide', plain: 'Ba(OH)₂', b: 2, cation: 'Ba<sup>2+</sup>', cationTex: '\\mathrm{Ba^{2+}}' }
},
// precipitation titrants, each with its compatible analytes (analyte sits in the flask)
precip: {
AgNO3: {
titrant: 'AgNO₃', method: 'Mohr',
ionPlain: 'Ag<sup>+</sup>', ionTex: '\\mathrm{Ag^+}', // reactive ion the titrant delivers
specPlain: 'NO<sub>3</sub><sup>−</sup>', specTex: '\\mathrm{NO_3^-}', // spectator carried in by the titrant
indicator: { name: 'potassium chromate, K<sub>2</sub>CrO<sub>4</sub>', low: 'pale yellow', high: 'brick-red', lag: 0.08, endpointSolid: true },
analytes: {
Cl: { name: 'chloride', plain: 'Cl⁻', symbol: '\\mathrm{Cl^-}', M: 35.45, salt: 'AgCl', Msalt: 143.32,
eq: '\\mathrm{Ag^+(aq) + Cl^-(aq) \\longrightarrow AgCl(s)}' },
Br: { name: 'bromide', plain: 'Br⁻', symbol: '\\mathrm{Br^-}', M: '79.90', salt: 'AgBr', Msalt: 187.77,
eq: '\\mathrm{Ag^+(aq) + Br^-(aq) \\longrightarrow AgBr(s)}' }
}
},
KSCN: {
titrant: 'KSCN', method: 'Volhard',
ionPlain: 'SCN<sup>−</sup>', ionTex: '\\mathrm{SCN^-}',
specPlain: 'K<sup>+</sup>', specTex: '\\mathrm{K^+}',
indicator: { name: 'iron(III), Fe<sup>3+</sup>', low: 'pale', high: 'blood-red', lag: 0.03, endpointSolid: false },
analytes: {
Ag: { name: 'silver(I)', plain: 'Ag⁺', symbol: '\\mathrm{Ag^+}', M: 107.87, salt: 'AgSCN', Msalt: 165.95,
eq: '\\mathrm{Ag^+(aq) + SCN^-(aq) \\longrightarrow AgSCN(s)}' }
}
}
},
eqLatex: {
'HCl|NaOH': '\\mathrm{HCl(aq) + NaOH(aq) \\longrightarrow NaCl(aq) + H_2O(l)}',
'HCl|KOH': '\\mathrm{HCl(aq) + KOH(aq) \\longrightarrow KCl(aq) + H_2O(l)}',
'HCl|BaOH2': '\\mathrm{2~HCl(aq) + Ba(OH)_2(aq) \\longrightarrow BaCl_2(aq) + 2~H_2O(l)}',
'HNO3|NaOH': '\\mathrm{HNO_3(aq) + NaOH(aq) \\longrightarrow NaNO_3(aq) + H_2O(l)}',
'HNO3|KOH': '\\mathrm{HNO_3(aq) + KOH(aq) \\longrightarrow KNO_3(aq) + H_2O(l)}',
'HNO3|BaOH2': '\\mathrm{2~HNO_3(aq) + Ba(OH)_2(aq) \\longrightarrow Ba(NO_3)_2(aq) + 2~H_2O(l)}',
'H2SO4|NaOH': '\\mathrm{H_2SO_4(aq) + 2~NaOH(aq) \\longrightarrow Na_2SO_4(aq) + 2~H_2O(l)}',
'H2SO4|KOH': '\\mathrm{H_2SO_4(aq) + 2~KOH(aq) \\longrightarrow K_2SO_4(aq) + 2~H_2O(l)}',
'H2SO4|BaOH2':'\\mathrm{H_2SO_4(aq) + Ba(OH)_2(aq) \\longrightarrow BaSO_4(s) + 2~H_2O(l)}'
}
})Learning Lab: Titration
Interactive titration lab: choose an acid-base or precipitation system and titrate to the endpoint, with the equivalence-point stoichiometry worked step by step.
mutable tlDarkMode = document.documentElement.getAttribute('data-bs-theme') === 'dark'
|| document.body.classList.contains('quarto-dark')
tlThemeObserver = {
const check = () => {
const dark = document.documentElement.getAttribute('data-bs-theme') === 'dark'
|| document.body.classList.contains('quarto-dark');
if (dark !== mutable tlDarkMode) mutable tlDarkMode = dark;
};
const obs = new MutationObserver(check);
obs.observe(document.documentElement, {attributes: true, attributeFilter: ['data-bs-theme']});
obs.observe(document.body, {attributes: true, attributeFilter: ['class']});
invalidation.then(() => obs.disconnect());
}// ========== TITRATION LAB - MATHJAX LOADER ==========
tlMathjax = {
// NOTATION HOVERTIPS TRAVEL WITH THE WIDGET (2026-08-20). mkit-page-terms.js is a
// per-chapter opt-in declared in each book page's frontmatter (63 pages), so a widget
// embedded anywhere else - skill-hub/*, book/learning-lab-* - had no dictionary at all and
// its generated LaTeX could never be decorated. Load it alongside the widget instead, so the
// behaviour follows the widget rather than the host page. Idempotent: pages that already
// declare the script in frontmatter are left alone.
// Root-absolute like the other site-wide scripts in _quarto.yml include-after-body;
// mkit-page-terms' assetBase() strips the filename to find latex-terms.js + the dictionary.
// Keep ?v= in step with the frontmatter tags (plans/fable-scripts/_bumpv.cjs).
if (!document.querySelector('script[src*="mkit-page-terms"]')) {
const _pt = document.createElement('script');
_pt.src = '/assets/mkit-page-terms.js?v=2026-09-26a';
_pt.async = true;
document.head.appendChild(_pt);
}
// MJ-HOST-GUARD (2026-08-20) - see the same note in _solution-mixing-lab.qmd.
// The old guard tested window.MathJax.typesetPromise, which does not exist until the
// host's MathJax has finished booting - so on a book page it lost the race, overwrote
// the host config and loaded MathJax 3 alongside MathJax 4.
// RULE: if window.MathJax exists at all, the host owns it - wait, never replace.
// A bare window.MathJax CONFIG object is NOT an engine. Quarto injects one via
// include-in-header on EVERY page, including pages with no source math that therefore
// never load the engine at all - waiting on that would hang this widget forever.
// _heating-curve.qmd documented this first; the same detection is used here. Exclude
// helper scripts named mathjax-*.js (mathjax-help-fix, mathjax-zoom-modal): their
// "mathjax" substring otherwise falsely reports an engine.
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.__tlMathjaxLoading) return window.__tlMathjaxLoading;
// Standalone fallback only; v4.1.3 to match the site.
window.__tlMathjaxLoading = new Promise(resolve => {
// INHERIT, DO NOT REPLACE - see the same note in _solution-mixing-lab.qmd. Quarto emits
// the site's window.MathJax config (with output.font 'mathjax-stix2') on every page,
// including ones that never load an engine and land here; overwriting it loses the font.
const cfg = window.MathJax || {
loader: { load: ['[tex]/html'] },
tex: { packages: {'[+]': ['html']} },
output: { font: 'mathjax-stix2' }
};
cfg.chtml = Object.assign({ scale: 0.96 }, cfg.chtml || {});
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.__tlMathjaxLoading;
}// ========== TITRATION LAB - NUMERIC HELPERS ==========
tlFmt = {
function sigFigs(str) {
str = String(str).trim();
if (str.startsWith('-')) str = str.slice(1);
const hasDot = str.includes('.');
let digits = str.replace('.', '').replace(/^0+/, '');
if (digits === '') return 1;
if (hasDot) return digits.length;
return (digits.replace(/0+$/, '').length) || 1;
}
function barInput(str) {
str = String(str).trim();
if (str === '' || +str === 0) return str;
let i = str.length - 1;
if (str.includes('.')) { while (i >= 0 && !(str[i] >= '0' && str[i] <= '9')) i--; }
else { while (i > 0 && str[i] === '0') i--; }
return str.slice(0, i) + '\\bar{' + str[i] + '}' + str.slice(i + 1);
}
function sigfig(x, n) { // round-half-to-even (banker's)
if (!(Math.abs(x) > 0)) return 0;
const sign = x < 0 ? -1 : 1;
const ax = Math.abs(x);
const m = Math.pow(10, n - 1 - Math.floor(Math.log10(ax)));
const y = ax * m;
const fl = Math.floor(y);
const tol = (y + 1) * 1e-9; // absorb binary noise on exact halves
const r = (Math.abs(y - fl - 0.5) < tol) ? (fl % 2 === 0 ? fl : fl + 1) : Math.round(y);
return sign * r / m;
}
function sigfigStr(x, n) {
if (!(Math.abs(x) > 0)) return '0';
const r = sigfig(x, n);
const dp = Math.max(0, n - 1 - Math.floor(Math.log10(Math.abs(r))));
return r.toFixed(dp);
}
function barTex(x, n) {
if (!(x > 0)) return '0';
const d = Math.floor(Math.log10(x) + 1e-12);
const lsf = d - (n - 1);
const decimals = Math.max(0, -(lsf - 2));
const full = x.toFixed(decimals + 4);
const dot = full.indexOf('.');
const str = decimals === 0 ? full.slice(0, dot) : full.slice(0, dot + 1 + decimals);
const dotIdx = str.indexOf('.');
let intPart = dotIdx === -1 ? str : str.slice(0, dotIdx);
let fracPart = dotIdx === -1 ? '' : str.slice(dotIdx + 1);
if (lsf >= 0) {
const idx = intPart.length - 1 - lsf;
if (idx >= 0 && idx < intPart.length)
intPart = intPart.slice(0, idx) + '\\bar{' + intPart[idx] + '}' + intPart.slice(idx + 1);
} else {
const idx = -lsf - 1;
if (idx >= 0 && idx < fracPart.length)
fracPart = fracPart.slice(0, idx) + '\\bar{' + fracPart[idx] + '}' + fracPart.slice(idx + 1);
}
return fracPart ? intPart + '.' + fracPart : intPart;
}
// ---- titration arithmetic, no DOM, so dev/tests/titration-lab-engine.test.cjs can run it ----
const BURET = 50; // mL: one fill of a real buret
// slider range: a little past equivalence, never more than one buret
function vtMax(Veq) { return Math.min(BURET, Math.max(20, Math.ceil(Veq * 1.4 / 5) * 5)); }
// power of ten of the last significant digit of x written to n figures
function placeOf(x, n) { return Math.floor(Math.log10(Math.abs(x)) + 1e-12) - (n - 1); }
// Figures kept by x1 - x2. A difference is known to the coarser DECIMAL PLACE of its two terms,
// not to the smaller count of figures: 0.002500 - 0.002450 = 0.000050 (two figures, not four).
function diffSf(x1, n1, x2, n2) {
const d = Math.abs(x1 - x2);
if (!(Math.abs(x2) > 0)) return Math.max(1, n1);
if (!(Math.abs(x1) > 0)) return Math.max(1, n2);
if (!(d > 0)) return 1;
return Math.max(1, Math.floor(Math.log10(d) + 1e-12) - Math.max(placeOf(x1, n1), placeOf(x2, n2)) + 1);
}
function decimalsOf(str) { const t = String(str).trim(); const i = t.indexOf('.'); return i < 0 ? 0 : t.length - i - 1; }
// figures kept by a sum of two typed values: the fewer decimal places decides
function sumSf(sum, aStr, bStr) {
if (!(sum > 0)) return 1;
return Math.max(1, Math.floor(Math.log10(sum) + 1e-12) + 1 + Math.min(decimalsOf(aStr), decimalsOf(bStr)));
}
// sys: { a, b } = reactive units per formula of analyte and of titrant.
// inp: { ct, ctStr, ca, caStr, Va, VaStr, Vt, VtStr } with volumes in mL. Amounts come back in mol.
function calc(sys, inp) {
const a = sys.a, b = sys.b;
const sf = { ct: sigFigs(inp.ctStr), ca: sigFigs(inp.caStr), Va: sigFigs(inp.VaStr), Vt: sigFigs(inp.VtStr) };
const Veq = a * inp.ca * inp.Va / (b * inp.ct);
const Vt = inp.Vt, Vtot = inp.Va + Vt;
const sfNt = Math.max(1, Math.min(sf.ct, sf.Vt)), sfNa = Math.max(1, Math.min(sf.ca, sf.Va));
const nt = inp.ct * Vt / 1000, nIon = b * nt, nSpec = nt;
const nAnalyte = inp.ca * inp.Va / 1000, nAnRxv = a * nAnalyte;
const endpoint = Vt >= Veq - 1e-9, atEq = Math.abs(Vt - Veq) < 0.06;
const remaining = Math.max(0, nAnRxv - nIon), excess = Math.max(0, nIon - nAnRxv);
const sfDiff = diffSf(nAnRxv, sfNa, nIon, sfNt);
const sfVtot = sumSf(Vtot, inp.VaStr, inp.VtStr);
return { Veq, VtMax: vtMax(Veq), overBuret: Veq > BURET + 1e-9, Vt, Vtot, sf, sfNt, sfNa, sfVtot,
nt, nIon, nSpec, nAnalyte, nAnRxv, endpoint, atEq,
nReacted: Math.min(nIon, nAnRxv), sfReacted: endpoint ? sfNa : sfNt,
remaining, excess, sfDiff, sfConc: Math.max(1, Math.min(sfDiff, sfVtot)),
cRemaining: remaining / (Vtot / 1000), cExcess: excess / (Vtot / 1000),
cSpec: nSpec / (Vtot / 1000), sfSpec: Math.max(1, Math.min(sfNt, sfVtot)),
pct: Veq > 0 ? Vt / Veq * 100 : 0 };
}
return { sigFigs, barInput, sigfig, sigfigStr, barTex, BURET, vtMax, placeOf, diffSf, decimalsOf, sumSf, calc };
}// ========== TITRATION LAB - MAIN WIDGET ==========
tlWidget = {
tlMathjax;
const st = tlState;
const isDark = tlDarkMode;
const S = tlSystems;
const F = tlFmt;
if (!window.__tlLive)
window.__tlLive = { ct: 0.1000, ctStr: '0.1000', ca: 0.1000, caStr: '0.1000',
Va: 25.00, VaStr: '25.00', Vt: 0, VtStr: '0',
open: {} };
const live = window.__tlLive;
// (V_t persists across system/tab changes — clamped to the new VtMax in updateDynamic —
// consistent with how concentration/volume edits persist)
const c = isDark ? {
glass: '#4a5072', stop: '#64748b',
titrant: 'rgba(0,217,255,0.45)', titrantStroke: 'rgba(0,217,255,0.7)',
acidBar: '#00d9ff', baseBar: '#ff007c',
trackStroke: '#3b4262', marker: '#ff007c', label: '#cbd5e1', sub: '#8b949e',
panelBg: 'rgba(15,23,42,0.25)',
solPreAB: 'rgba(148,163,184,0.16)', solPostAB: 'rgba(255,0,124,0.32)',
solPreMohr: 'rgba(190,195,205,0.18)', solPostMohr: 'rgba(220,60,40,0.20)',
precipWhite: '#6b7390', precipRed: '#ff4d4f'
} : {
glass: '#9ca3af', stop: '#6b7280',
titrant: 'rgba(147,197,253,0.7)', titrantStroke: '#3b82f6',
acidBar: '#0d9488', baseBar: '#db2777',
trackStroke: '#cbd5e1', marker: '#dc2626', label: '#374151', sub: '#6b7280',
panelBg: 'rgba(248,250,252,0.6)',
solPreAB: 'rgba(148,163,184,0.28)', solPostAB: 'rgba(219,39,119,0.30)',
solPreMohr: 'rgba(190,195,205,0.22)', solPostMohr: 'rgba(220,60,40,0.20)',
precipWhite: '#cbd5e1', precipRed: '#b22222'
};
function sysParams() {
if (st.rxn === 'acidbase') {
const acid = S.acids[st.acidId], base = S.bases[st.baseId];
// Sulfuric acid with barium hydroxide is the one acid-base pair whose salt is insoluble:
// Ba2+ leaves the solution as BaSO4(s) (137.33 + 32.06 + 4(16.00)), it is not a spectator.
const baso4 = (st.acidId === 'H2SO4' && st.baseId === 'BaOH2')
? { plain: 'BaSO<sub>4</sub>', tex: '\\mathrm{BaSO_4}', lbl: 'BaSO<sub>4</sub>(s)', M: 233.39 } : null;
return { a: acid.a, b: base.b, acid, base, baso4, eq: S.eqLatex[st.acidId + '|' + st.baseId] };
}
const titr = S.precip[st.precipId];
const an = titr.analytes[st.analyteId] || titr.analytes[Object.keys(titr.analytes)[0]];
return { a: 1, b: 1, titr, an, eq: an.eq };
}
const sp = sysParams();
const isPrecip = st.rxn === 'precip';
const veqOf = () => sp.a * live.ca * live.Va / (sp.b * live.ct);
const plainTitrant = isPrecip ? sp.titr.titrant : sp.base.plain;
const plainAnalyte = isPrecip ? sp.an.plain : sp.acid.plain;
const Manalyte = isPrecip ? sp.an.M : sp.acid.M;
const indicator = isPrecip ? sp.titr.indicator : { name: 'phenolphthalein', low: 'colorless', high: 'pink', lag: 0.04, endpointSolid: false };
// species tex / plain
const ionDelivTex = isPrecip ? sp.titr.ionTex : '\\mathrm{OH^-}';
const ionDelivPlain = isPrecip ? sp.titr.ionPlain : 'OH<sup>−</sup>';
const analyteIonTex = isPrecip ? sp.an.symbol : '\\mathrm{H_3O^+}';
const analyteIonPlain = isPrecip ? sp.an.plain : 'H<sub>3</sub>O<sup>+</sup>';
const specTex = isPrecip ? sp.titr.specTex : sp.base.cationTex;
const specPlain = isPrecip ? sp.titr.specPlain : sp.base.cation;
const saltTex = isPrecip ? `\\mathrm{${sp.an.salt}}` : null;
const saltPlain = isPrecip ? sp.an.salt : null;
const Msalt = isPrecip ? sp.an.Msalt : null;
// state-annotated species names for the collapsible line labels
const ionDelivLbl = ionDelivPlain + '(aq)';
const analyteIonLbl = analyteIonPlain + '(aq)';
const specLbl = specPlain + '(aq)';
const saltLbl = isPrecip ? saltPlain + '(s)' : null;
// the solid that forms in the flask, if any
const solid = isPrecip ? { plain: saltPlain, tex: saltTex, lbl: saltLbl, M: Msalt } : (sp.baso4 || null);
// ===================== DOM SCAFFOLD =====================
const root = document.createElement('div');
root.className = 'tl-widget';
// fullscreen / new-tab button (hidden on the standalone viewer page itself)
if (!window.__tlNoFs) {
const fsBtn = document.createElement('button');
fsBtn.className = 'tl-fs-btn'; fsBtn.textContent = '⛶'; fsBtn.title = 'Open in new tab';
fsBtn.setAttribute('aria-label', 'Open in new tab');
fsBtn.addEventListener('click', e => { e.preventDefault(); window.open('/files/ojs/titration-lab-viewer.html', '_blank'); });
root.appendChild(fsBtn);
}
// the widget's visible title is a real heading: h2 under a page's own visible h1 (the book), or
// the page's h1 itself where the page sets window.__tlTitleH1 (Skill Hub and viewer pages, whose
// Quarto title is hidden), so a screen reader hears the same title a sighted reader sees
const title = document.createElement(window.__tlTitleH1 ? 'h1' : 'h2');
title.className = 'tl-title';
title.id = 'tl-title';
root.setAttribute('role', 'region');
root.setAttribute('aria-labelledby', 'tl-title');
title.textContent = 'Titration Lab';
root.appendChild(title);
const tabRow = document.createElement('div');
tabRow.className = 'tl-tab-row';
const tg = document.createElement('div');
tg.className = 'tl-tabs';
tg.setAttribute('role', 'group'); tg.setAttribute('aria-label', 'Type of titration');
[{label: 'Acid–base', val: 'acidbase'}, {label: 'Precipitation', val: 'precip'}].forEach(o => {
const b = document.createElement('button');
b.type = 'button';
b.className = 'tl-tab' + (o.val === st.rxn ? ' active' : '');
b.setAttribute('aria-pressed', String(o.val === st.rxn)); // which titration is showing, in words a screen reader gets
b.textContent = o.label;
b.addEventListener('click', () => { if (o.val !== st.rxn) mutable tlState = {...st, rxn: o.val}; });
tg.appendChild(b);
});
tabRow.appendChild(tg);
root.appendChild(tabRow);
const bodyEl = document.createElement('div');
bodyEl.className = 'tl-body';
root.appendChild(bodyEl);
const leftCol = document.createElement('div');
leftCol.className = 'tl-left';
const rightCol = document.createElement('div');
rightCol.className = 'tl-right';
bodyEl.appendChild(leftCol);
bodyEl.appendChild(rightCol);
const controls = document.createElement('div');
controls.className = 'tl-controls';
leftCol.appendChild(controls);
let ctrlN = 0; // ids that tie each visible label to its control
function selectRow(labelText, options, current, onChange) {
const row = document.createElement('div');
row.className = 'tl-ctrl-row';
const lab = document.createElement('label');
lab.className = 'tl-ctrl-label';
lab.textContent = labelText;
const sel = document.createElement('select');
sel.className = 'tl-select';
options.forEach(o => {
const opt = document.createElement('option');
opt.value = o.val; opt.textContent = o.label;
if (o.val === current) opt.selected = true;
sel.appendChild(opt);
});
sel.addEventListener('change', () => onChange(sel.value));
sel.setAttribute('aria-label', labelText);
sel.id = 'tl-ctrl-' + (++ctrlN); lab.htmlFor = sel.id;
row.appendChild(lab); row.appendChild(sel);
return row;
}
if (!isPrecip) {
controls.appendChild(selectRow('Acid (analyte in flask)',
Object.keys(S.acids).map(k => ({val: k, label: S.acids[k].name})),
st.acidId, v => mutable tlState = {...st, acidId: v}));
controls.appendChild(selectRow('Base (titrant in buret)',
Object.keys(S.bases).map(k => ({val: k, label: S.bases[k].name})),
st.baseId, v => mutable tlState = {...st, baseId: v}));
} else {
controls.appendChild(selectRow('Titrant (in buret)',
Object.keys(S.precip).map(k => ({val: k, label: `${S.precip[k].titrant} (${S.precip[k].method})`})),
st.precipId, v => mutable tlState = {...st, precipId: v, analyteId: Object.keys(S.precip[v].analytes)[0]}));
controls.appendChild(selectRow('Analyte (in flask)',
Object.keys(S.precip[st.precipId].analytes).map(k => ({val: k, label: S.precip[st.precipId].analytes[k].name})),
st.analyteId, v => mutable tlState = {...st, analyteId: v}));
}
function clamp(x, lo, hi) { return Math.min(hi, Math.max(lo, x)); }
// Custom ▲▼ stepper: native number spinners ignore margin, so we hide them
// and add our own buttons (with a real gap) that re-fire input/change events.
function makeStepper(inp) {
const wrap = document.createElement('div');
wrap.className = 'tl-stepper';
const btns = document.createElement('div');
btns.className = 'tl-stepbtns';
const up = document.createElement('button');
up.type = 'button'; up.className = 'tl-stepbtn'; up.tabIndex = -1; up.innerHTML = '<span aria-hidden="true">▲</span>';
up.setAttribute('aria-label', 'Increase');
const dn = document.createElement('button');
dn.type = 'button'; dn.className = 'tl-stepbtn'; dn.tabIndex = -1; dn.innerHTML = '<span aria-hidden="true">▼</span>';
dn.setAttribute('aria-label', 'Decrease');
const step = parseFloat(inp.step) || 1;
const dec = (String(inp.step).split('.')[1] || '').length;
const mn = (inp.min === '' ? -Infinity : parseFloat(inp.min));
const mx = (inp.max === '' ? Infinity : parseFloat(inp.max));
function bump(dir) {
let cur = parseFloat(inp.value); if (!isFinite(cur)) cur = isFinite(mn) ? mn : 0;
let v = Math.round((cur + dir * step) / step) * step;
v = Math.min(mx, Math.max(mn, v));
inp.value = v.toFixed(dec);
inp.dispatchEvent(new Event('input', { bubbles: true }));
inp.dispatchEvent(new Event('change', { bubbles: true }));
}
up.addEventListener('click', () => bump(1));
dn.addEventListener('click', () => bump(-1));
btns.appendChild(up); btns.appendChild(dn);
wrap.appendChild(inp); wrap.appendChild(btns);
return wrap;
}
function numberRow(labelHTML, key, min, max, step) {
const row = document.createElement('div');
row.className = 'tl-ctrl-row';
const lab = document.createElement('label');
lab.className = 'tl-ctrl-label';
lab.innerHTML = labelHTML;
const inp = document.createElement('input');
inp.type = 'number'; inp.className = 'tl-number';
inp.min = min; inp.max = max; inp.step = step;
inp.value = live[key + 'Str'];
inp.setAttribute('aria-label', lab.textContent);
inp.id = 'tl-ctrl-' + (++ctrlN); lab.htmlFor = inp.id;
inp.addEventListener('input', () => {
const v = parseFloat(inp.value);
if (!isFinite(v)) return;
const cv = clamp(v, min, max);
live[key] = cv;
live[key + 'Str'] = (cv === v) ? inp.value : String(cv); // keep typed format in range; clamp the displayed value if out of range so math + substitution agree
updateDynamic();
});
inp.addEventListener('change', () => {
let v = parseFloat(inp.value);
if (!isFinite(v)) { inp.value = live[key + 'Str']; updateDynamic(); return; }
if (v < min) { v = min; inp.value = String(min); live[key + 'Str'] = String(min); }
else if (v > max) { v = max; inp.value = String(max); live[key + 'Str'] = String(max); }
else { live[key + 'Str'] = inp.value; }
live[key] = v;
updateDynamic();
});
row.appendChild(lab); row.appendChild(makeStepper(inp));
return row;
}
controls.appendChild(numberRow('Titrant conc. / mol L<sup>−1</sup>', 'ct', 0.0100, 0.5000, 0.0010));
controls.appendChild(numberRow('Analyte conc. / mol L<sup>−1</sup>', 'ca', 0.0100, 0.3000, 0.0010));
controls.appendChild(numberRow('Sample volume / mL', 'Va', 5.00, 50.00, 0.50));
const vtLab = document.createElement('div');
vtLab.className = 'tl-ctrl-label tl-vt-label';
vtLab.textContent = 'Titrant delivered / mL';
const vtRow = document.createElement('div');
vtRow.className = 'tl-slider-row';
const vtSlider = document.createElement('input');
vtSlider.type = 'range'; vtSlider.className = 'tl-slider';
vtSlider.min = 0; vtSlider.step = 0.05; vtSlider.value = 0;
vtSlider.setAttribute('aria-label', 'Titrant volume delivered (mL)');
const vtNum = document.createElement('input');
vtNum.type = 'number'; vtNum.className = 'tl-vtnum';
vtNum.min = 0; vtNum.step = 0.05; vtNum.value = '0';
vtNum.setAttribute('aria-label', 'Titrant volume delivered (mL)');
// equivalence-point tick overlaid on the slider track (positioned in updateDynamic)
const sliderWrap = document.createElement('div');
sliderWrap.className = 'tl-slider-wrap';
const veqMark = document.createElement('div');
veqMark.className = 'tl-veq-mark'; veqMark.title = 'Equivalence point';
veqMark.setAttribute('aria-hidden', 'true');
sliderWrap.appendChild(vtSlider); sliderWrap.appendChild(veqMark);
function applyVt(v) {
const hi = +vtSlider.max || 50;
v = clamp(v, 0, hi);
live.Vt = v; vtSlider.value = v;
updateDynamic();
return v;
}
vtSlider.addEventListener('input', () => {
const hi = +vtSlider.max || 50;
const v = clamp(+vtSlider.value, 0, hi);
live.VtStr = (+v).toFixed(2); vtNum.value = live.VtStr;
applyVt(v);
});
vtNum.addEventListener('input', () => {
const v = parseFloat(vtNum.value);
if (!isFinite(v)) return;
const cv = clamp(v, 0, +vtSlider.max || 50);
live.VtStr = (cv === v) ? vtNum.value : String(cv); // clamp display if out of range so the worked solution can't show an over-range volume
applyVt(cv);
});
vtNum.addEventListener('change', () => {
let v = parseFloat(vtNum.value);
const hi = +vtSlider.max || 50;
if (!isFinite(v)) { vtNum.value = live.VtStr; return; }
if (v < 0) { v = 0; vtNum.value = '0'; live.VtStr = '0'; }
else if (v > hi) { v = hi; vtNum.value = String(hi); live.VtStr = String(hi); }
else { live.VtStr = vtNum.value; }
applyVt(v);
});
controls.appendChild(vtLab);
vtRow.appendChild(sliderWrap); vtRow.appendChild(makeStepper(vtNum));
controls.appendChild(vtRow);
const snapBtn = document.createElement('button');
snapBtn.className = 'tl-snap-btn';
snapBtn.textContent = 'Jump to endpoint';
snapBtn.addEventListener('click', () => {
const target = veqOf() + (live.indError ? (indicator.lag || 0) : 0); // color change lags equivalence when error mode is on
// Rounded UP to the 0.01 mL the box shows: the volume used in the arithmetic is then the one
// printed, and it is never a hair short of equivalence (which left the flask uncolored).
const v = clamp(Math.ceil(target * 100 - 1e-6) / 100, 0, +vtSlider.max || 50);
live.VtStr = (+v).toFixed(2); vtNum.value = live.VtStr; // set string BEFORE render
applyVt(v);
});
controls.appendChild(snapBtn);
// indicator-error mode: endpoint (color change) lags the true equivalence by ~one drop
const errRow = document.createElement('label');
errRow.className = 'tl-check';
const errBox = document.createElement('input');
errBox.type = 'checkbox'; errBox.checked = !!live.indError;
errBox.addEventListener('change', () => { live.indError = errBox.checked; updateDynamic(); });
const errTxt = document.createElement('span');
errTxt.textContent = 'Show indicator error';
errRow.appendChild(errBox); errRow.appendChild(errTxt);
controls.appendChild(errRow);
// announced when it changes (before, at or past equivalence), which is a few times per titration
const statusNote = document.createElement('div');
statusNote.className = 'tl-status';
statusNote.setAttribute('role', 'status');
controls.appendChild(statusNote);
// shown only when the chosen concentrations need more titrant than one buret holds
const buretNote = document.createElement('div');
buretNote.className = 'tl-errnote tl-buretnote';
buretNote.setAttribute('role', 'status');
buretNote.hidden = true;
controls.appendChild(buretNote);
// view toggle: apparatus drawing ⇄ reaction-progress curve
if (!('leftView' in live)) live.leftView = 'apparatus';
const viewTog = document.createElement('div');
viewTog.className = 'tl-viewtog';
viewTog.setAttribute('role', 'group'); viewTog.setAttribute('aria-label', 'View');
const viewBtns = [];
[['apparatus', 'Apparatus'], ['curve', 'Curve']].forEach(([val, label]) => {
const b = document.createElement('button');
b.type = 'button'; b.className = 'tl-viewbtn'; b.dataset.view = val; b.textContent = label;
b.addEventListener('click', () => setView(val));
viewTog.appendChild(b); viewBtns.push(b);
});
leftCol.appendChild(viewTog);
const svg = d3.create('svg')
.attr('viewBox', '-60 -14 320 470')
.attr('class', 'tl-chart')
.attr('preserveAspectRatio', 'xMidYMid meet')
.attr('aria-hidden', 'true').attr('focusable', 'false'); // decorative; the numeric state is in the strip + bins
leftCol.appendChild(svg.node());
const svgCurve = d3.create('svg')
.attr('viewBox', '0 0 320 264')
.attr('class', 'tl-chart tl-curve')
.attr('preserveAspectRatio', 'xMidYMid meet')
.attr('aria-hidden', 'true').attr('focusable', 'false');
leftCol.appendChild(svgCurve.node());
const indicatorNote = document.createElement('div');
indicatorNote.className = 'tl-indicator';
leftCol.appendChild(indicatorNote);
const errNote = document.createElement('div');
errNote.className = 'tl-errnote';
leftCol.appendChild(errNote);
function setView(v) {
live.leftView = v;
viewBtns.forEach(b => { const on = b.dataset.view === v; b.classList.toggle('active', on); b.setAttribute('aria-pressed', String(on)); });
svg.node().style.display = v === 'apparatus' ? '' : 'none';
svgCurve.node().style.display = v === 'curve' ? '' : 'none';
indicatorNote.style.display = v === 'apparatus' ? '' : 'none';
updateDynamic();
}
// ===================== APPARATUS DRAW =====================
function drawApparatus(Veq, VtMax, endpoint) {
svg.selectAll('*').remove();
const bcx = 92, tubeL = 83, tubeR = 101, tubeTop = 20, drainY = 250;
const tubeH = drainY - tubeTop;
const yOf = v => tubeTop + (v / VtMax) * tubeH;
svg.append('rect').attr('x', tubeL).attr('y', tubeTop)
.attr('width', tubeR - tubeL).attr('height', tubeH)
.attr('fill', 'none').attr('stroke', c.glass).attr('stroke-width', 1.5).attr('rx', 2);
const menY = yOf(Math.min(live.Vt, VtMax));
svg.append('rect').attr('x', tubeL + 1.5).attr('y', menY)
.attr('width', tubeR - tubeL - 3).attr('height', Math.max(0, drainY - menY))
.attr('fill', c.titrant).attr('stroke', c.titrantStroke).attr('stroke-width', 0.5);
const majorStep = VtMax <= 25 ? 5 : (VtMax <= 60 ? 10 : 20);
for (let v = 0; v <= VtMax + 1e-6; v += majorStep) {
const gy = yOf(v);
svg.append('line').attr('x1', tubeL).attr('y1', gy).attr('x2', tubeL + 6).attr('y2', gy)
.attr('stroke', c.glass).attr('stroke-width', 0.8);
svg.append('text').attr('x', tubeL - 3).attr('y', gy).attr('text-anchor', 'end')
.attr('dominant-baseline', 'middle').attr('font-size', '8px').attr('fill', c.sub).text(v);
}
for (let v = majorStep / 2; v < VtMax; v += majorStep) {
const gy = yOf(v);
svg.append('line').attr('x1', tubeL).attr('y1', gy).attr('x2', tubeL + 3.5).attr('y2', gy)
.attr('stroke', c.glass).attr('stroke-width', 0.5);
}
// current-volume readout on the RIGHT of the buret (leader points left to the tube); equivalence label on the LEFT
if (live.Vt > 0) {
svg.append('line').attr('x1', tubeL).attr('y1', menY).attr('x2', tubeR).attr('y2', menY)
.attr('stroke', c.titrantStroke).attr('stroke-width', 1);
svg.append('line').attr('x1', tubeR).attr('y1', menY).attr('x2', tubeR + 14).attr('y2', menY)
.attr('stroke', c.titrantStroke).attr('stroke-width', 1);
svg.append('text').attr('x', tubeR + 17).attr('y', menY).attr('text-anchor', 'start').attr('font-size', '9px')
.attr('fill', c.titrantStroke).attr('dominant-baseline', 'middle')
.text(`${live.Vt.toFixed(2)} mL`);
}
if (Veq <= VtMax) {
const eY = yOf(Veq);
svg.append('line').attr('x1', 44).attr('y1', eY).attr('x2', tubeL).attr('y2', eY)
.attr('stroke', c.marker).attr('stroke-width', 1.4).attr('stroke-dasharray', '3,2');
svg.append('text').attr('x', 41).attr('y', eY).attr('text-anchor', 'end')
.attr('font-size', '9px').attr('fill', c.marker).attr('dominant-baseline', 'middle')
.text(`equiv. ${Veq.toFixed(2)} mL`);
}
// stopcock valve barrel
svg.append('rect').attr('x', bcx - 7).attr('y', drainY).attr('width', 14).attr('height', 11)
.attr('rx', 3).attr('fill', c.stop);
// stopcock handle (tap) facing right
svg.append('rect').attr('x', bcx + 7).attr('y', drainY + 3).attr('width', 13).attr('height', 5)
.attr('rx', 2.5).attr('fill', c.stop);
svg.append('circle').attr('cx', bcx + 21).attr('cy', drainY + 5.5).attr('r', 3).attr('fill', c.stop);
// tapered delivery jet narrowing to a fine tip
svg.append('polygon')
.attr('points', `${bcx - 4},${drainY + 11} ${bcx + 4},${drainY + 11} ${bcx + 1},${drainY + 27} ${bcx - 1},${drainY + 27}`)
.attr('fill', c.glass);
// forming drop at the tip
svg.append('ellipse').attr('cx', bcx).attr('cy', drainY + 31).attr('rx', 2.4).attr('ry', 3.4)
.attr('fill', c.titrant).attr('stroke', c.titrantStroke).attr('stroke-width', 0.5);
const fcx = 92, neckTop = 286, bodyTop = 305, bodyBot = 418, neckHalf = 10, baseHalf = 54;
const leftX = y => fcx - neckHalf - (y - bodyTop) / (bodyBot - bodyTop) * (baseHalf - neckHalf);
const rightX = y => fcx + neckHalf + (y - bodyTop) / (bodyBot - bodyTop) * (baseHalf - neckHalf);
// rounded bottom corners (like a real Erlenmeyer): quadratic curve where each slant meets the base
const cr = 14;
const _run = baseHalf - neckHalf, _sl = Math.hypot(_run, bodyBot - bodyTop);
const _ux = _run / _sl, _uy = (bodyBot - bodyTop) / _sl; // slant unit components
const BLx = fcx - baseHalf, BRx = fcx + baseHalf;
const L1x = BLx + cr * _ux, L1y = bodyBot - cr * _uy; // left slant, just above the corner
const R2x = BRx - cr * _ux, R2y = bodyBot - cr * _uy; // right slant, just above the corner
const flaskBody = `M ${fcx - neckHalf} ${bodyTop} L ${L1x} ${L1y} Q ${BLx} ${bodyBot} ${BLx + cr} ${bodyBot} ` +
`L ${BRx - cr} ${bodyBot} Q ${BRx} ${bodyBot} ${R2x} ${R2y} L ${fcx + neckHalf} ${bodyTop} Z`;
// clip the liquid / precipitate fills to the body so they follow the rounded bottom
svg.append('defs').append('clipPath').attr('id', 'tl-flaskclip').append('path').attr('d', flaskBody);
const fillsG = svg.append('g').attr('clip-path', 'url(#tl-flaskclip)');
const levelFrac = Math.min(0.9, 0.44 + (live.Vt / VtMax) * 0.22);
const solTop = bodyBot - levelFrac * (bodyBot - bodyTop);
const preCol = isPrecip ? c.solPreMohr : c.solPreAB;
const postCol = isPrecip ? c.solPostMohr : c.solPostAB;
// the bulk solution only turns red when the endpoint color is a dissolved species (phenolphthalein
// pink, Volhard FeSCN²⁺); for Mohr the endpoint color is the Ag₂CrO₄ *precipitate*, so the solution stays pale
fillsG.append('polygon')
.attr('points', `${leftX(solTop)},${solTop} ${rightX(solTop)},${solTop} ${rightX(bodyBot)},${bodyBot} ${leftX(bodyBot)},${bodyBot}`)
.attr('fill', (endpoint && !indicator.endpointSolid) ? postCol : preCol);
// precipitate as settled granular particles (deterministic sin-hash positions so they
// don't jitter while dragging — only the count and pile height grow as more solid forms)
if (solid && live.Vt > 0 && Veq > 0) {
const frac = Math.min(1, live.Vt / Veq);
const Ncap = 64, maxPileH = 26;
const Nshow = Math.round(frac * Ncap);
const pileH = Math.max(3, frac * maxPileH);
const pseudo = n => { const v = Math.sin(n * 127.1 + 11.3) * 43758.5453; return v - Math.floor(v); };
for (let i = 0; i < Nshow; i++) {
const fy = Math.pow(pseudo(i * 2 + 1), 1.7); // 0 = bottom, 1 = top of pile (dense at bottom)
const py = bodyBot - 2.5 - fy * pileH;
const lX = leftX(py) + 3, rX = rightX(py) - 3;
const px = lX + pseudo(i * 2 + 2) * (rX - lX);
const pr = 1.6 + pseudo(i * 3 + 5) * 1.2;
const isRed = endpoint && indicator.endpointSolid && fy > 0.72; // red Ag₂CrO₄ precipitate (Mohr only); Volhard's red is the solution, not a solid
fillsG.append('circle').attr('cx', px).attr('cy', py).attr('r', pr)
.attr('fill', isRed ? c.precipRed : c.precipWhite)
.attr('stroke', isDark ? 'rgba(0,0,0,0.35)' : 'rgba(0,0,0,0.18)').attr('stroke-width', 0.5)
.attr('opacity', 0.92);
}
}
svg.append('path')
.attr('d', `M ${fcx - neckHalf} ${neckTop} L ${fcx - neckHalf} ${bodyTop} L ${L1x} ${L1y} Q ${BLx} ${bodyBot} ${BLx + cr} ${bodyBot} L ${BRx - cr} ${bodyBot} Q ${BRx} ${bodyBot} ${R2x} ${R2y} L ${fcx + neckHalf} ${bodyTop} L ${fcx + neckHalf} ${neckTop}`)
.attr('fill', 'none').attr('stroke', c.glass).attr('stroke-width', 1.5).attr('stroke-linejoin', 'round');
const flaskTxt = isPrecip ? (endpoint ? 'red endpoint' : (live.Vt > 0 ? 'white precipitate' : indicator.low))
: (endpoint ? 'pink' : (solid && live.Vt > 0 ? 'white precipitate' : 'colorless'));
svg.append('text').attr('x', fcx).attr('y', bodyBot - 24)
.attr('text-anchor', 'middle').attr('font-size', '10px').attr('fill', c.sub)
.attr('font-style', 'italic').text(flaskTxt);
// species labels: formula with italic (aq) state symbol hugging the apparatus,
// role word on the outer side so it reads "NaOH(aq) / titrant", "HCl(aq) / analyte" at a glance
function speciesLabel(x, formulaY, roleY, plain, role) {
const f = svg.append('text').attr('x', x).attr('y', formulaY)
.attr('text-anchor', 'middle').attr('font-size', '10px')
.attr('font-weight', '600').attr('fill', c.label);
f.append('tspan').text(plain);
f.append('tspan').attr('font-style', 'italic').text('(aq)');
svg.append('text').attr('x', x).attr('y', roleY)
.attr('text-anchor', 'middle').attr('font-size', '8px')
.attr('font-style', 'italic').attr('fill', c.sub).text(role);
}
speciesLabel(bcx, tubeTop - 12, tubeTop - 25, plainTitrant, 'Titrant');
speciesLabel(fcx, bodyBot + 20, bodyBot + 33, plainAnalyte, 'Analyte');
}
// ===================== REACTION-PROGRESS CURVE =====================
// reactive analyte ion remaining (falls to 0 at equivalence), then excess titrant ion rising
function drawCurve(Veq, VtMax) {
svgCurve.selectAll('*').remove();
const W = 320, H = 264, mL = 48, mR = 16, mT = 16, mB = 34;
const a = sp.a, b = sp.b, ca = live.ca, Va = live.Va, ct = live.ct, Vt = live.Vt;
const remAt = v => Math.max(0, a * ca * Va - b * ct * v) / 1000; // mol analyte ion left
const excAt = v => Math.max(0, b * ct * v - a * ca * Va) / 1000; // mol titrant ion in excess
const yMax = (Math.max(remAt(0), excAt(VtMax)) || 1e-3) * 1.12;
const x = d3.scaleLinear().domain([0, VtMax]).range([mL, W - mR]);
const y = d3.scaleLinear().domain([0, yMax]).range([H - mB, mT]);
const axisCol = c.trackStroke, tickCol = c.sub, labCol = c.label;
const anCol = isDark ? '#34d399' : '#0d9488'; // analyte remaining
const tiCol = isDark ? '#38bdf8' : '#2563eb'; // titrant excess
// plot background panel (white in light mode, dark card in dark mode)
svgCurve.append('rect').attr('x', mL).attr('y', mT).attr('width', (W - mR) - mL).attr('height', (H - mB) - mT)
.attr('fill', isDark ? '#11162a' : '#ffffff').attr('stroke', axisCol).attr('stroke-width', 1).attr('rx', 4);
svgCurve.append('line').attr('x1', mL).attr('y1', H - mB).attr('x2', W - mR).attr('y2', H - mB).attr('stroke', axisCol).attr('stroke-width', 1);
svgCurve.append('line').attr('x1', mL).attr('y1', mT).attr('x2', mL).attr('y2', H - mB).attr('stroke', axisCol).attr('stroke-width', 1);
const xStep = VtMax <= 25 ? 5 : (VtMax <= 60 ? 10 : 20);
for (let v = 0; v <= VtMax + 1e-6; v += xStep) {
svgCurve.append('line').attr('x1', x(v)).attr('y1', H - mB).attr('x2', x(v)).attr('y2', H - mB + 4).attr('stroke', axisCol).attr('stroke-width', 0.8);
svgCurve.append('text').attr('x', x(v)).attr('y', H - mB + 14).attr('text-anchor', 'middle').attr('font-size', '8px').attr('fill', tickCol).text(v);
}
y.ticks(4).forEach(t => {
svgCurve.append('line').attr('x1', mL - 4).attr('y1', y(t)).attr('x2', mL).attr('y2', y(t)).attr('stroke', axisCol).attr('stroke-width', 0.8);
svgCurve.append('text').attr('x', mL - 6).attr('y', y(t) + 3).attr('text-anchor', 'end').attr('font-size', '8px').attr('fill', tickCol).text(+(t * 1000).toFixed(2));
});
svgCurve.append('text').attr('x', (mL + W - mR) / 2).attr('y', H - 3).attr('text-anchor', 'middle').attr('font-size', '9px').attr('fill', labCol).text('titrant added (mL)');
const yl = svgCurve.append('text').attr('transform', `translate(12,${(mT + H - mB) / 2}) rotate(-90)`).attr('text-anchor', 'middle').attr('font-size', '9px').attr('fill', labCol);
yl.append('tspan').text('amount / 10'); yl.append('tspan').attr('font-size', '6px').attr('dy', '-3').text('−3'); yl.append('tspan').attr('dy', '3').text(' mol');
// equivalence vertical (not drawn when equivalence lies beyond the buret)
if (Veq <= VtMax) {
svgCurve.append('line').attr('x1', x(Veq)).attr('y1', mT).attr('x2', x(Veq)).attr('y2', H - mB).attr('stroke', c.marker).attr('stroke-width', 1.2).attr('stroke-dasharray', '4,3');
svgCurve.append('text').attr('x', x(Veq)).attr('y', H - mB - 5).attr('text-anchor', 'middle').attr('font-size', '8px').attr('fill', c.marker).text('Veq');
}
// segments
svgCurve.append('line').attr('x1', x(0)).attr('y1', y(remAt(0))).attr('x2', x(Math.min(Veq, VtMax))).attr('y2', y(remAt(Math.min(Veq, VtMax)))).attr('stroke', anCol).attr('stroke-width', 2.4);
if (Veq < VtMax) svgCurve.append('line').attr('x1', x(Veq)).attr('y1', y(0)).attr('x2', x(VtMax)).attr('y2', y(excAt(VtMax))).attr('stroke', tiCol).attr('stroke-width', 2.4);
// current point
const cy = Vt <= Veq ? remAt(Vt) : excAt(Vt);
svgCurve.append('circle').attr('cx', x(Math.min(Vt, VtMax))).attr('cy', y(cy)).attr('r', 4).attr('fill', Vt <= Veq ? anCol : tiCol).attr('stroke', isDark ? '#0b0c14' : '#fff').attr('stroke-width', 1.2);
// legend (top-left, stacked)
const lx = mL + 6, ly = mT + 2;
svgCurve.append('line').attr('x1', lx).attr('y1', ly).attr('x2', lx + 13).attr('y2', ly).attr('stroke', anCol).attr('stroke-width', 2.4);
svgCurve.append('text').attr('x', lx + 17).attr('y', ly + 3).attr('font-size', '8px').attr('fill', tickCol).text('analyte left');
svgCurve.append('line').attr('x1', lx).attr('y1', ly + 12).attr('x2', lx + 13).attr('y2', ly + 12).attr('stroke', tiCol).attr('stroke-width', 2.4);
svgCurve.append('text').attr('x', lx + 17).attr('y', ly + 15).attr('font-size', '8px').attr('fill', tickCol).text('titrant excess');
// indicator-error magnified inset: the gap is sub-pixel at full scale, so zoom near equivalence
if (live.indError && (indicator.lag || 0) > 0 && Veq <= VtMax) {
const lag = indicator.lag, Vend = Veq + lag, w = Math.max(0.2, lag * 2.2);
const ix0 = W - mR - 112, iy0 = mT, iw = 112, ih = 74;
svgCurve.append('rect').attr('x', ix0).attr('y', iy0).attr('width', iw).attr('height', ih).attr('rx', 4)
.attr('fill', isDark ? '#11162a' : '#ffffff').attr('stroke', axisCol).attr('stroke-width', 1).attr('opacity', 0.97);
svgCurve.append('text').attr('x', ix0 + iw / 2).attr('y', iy0 + 12).attr('text-anchor', 'middle').attr('font-size', '7.5px').attr('fill', tickCol).text('near equivalence (zoom)');
const xi = d3.scaleLinear().domain([Veq - w, Veq + w]).range([ix0 + 14, ix0 + iw - 10]);
const baseY = iy0 + ih - 16, topY = iy0 + 22;
const endCol = isDark ? '#fbbf24' : '#d97706';
svgCurve.append('line').attr('x1', ix0 + 8).attr('y1', baseY).attr('x2', ix0 + iw - 6).attr('y2', baseY).attr('stroke', axisCol).attr('stroke-width', 0.8);
svgCurve.append('rect').attr('x', xi(Veq)).attr('y', topY).attr('width', Math.max(1.5, xi(Vend) - xi(Veq))).attr('height', baseY - topY).attr('fill', c.marker).attr('opacity', 0.16);
svgCurve.append('line').attr('x1', xi(Veq)).attr('y1', topY).attr('x2', xi(Veq)).attr('y2', baseY).attr('stroke', c.marker).attr('stroke-width', 1.2);
svgCurve.append('line').attr('x1', xi(Vend)).attr('y1', topY).attr('x2', xi(Vend)).attr('y2', baseY).attr('stroke', endCol).attr('stroke-width', 1.4);
svgCurve.append('text').attr('x', xi(Veq)).attr('y', baseY + 9).attr('text-anchor', 'middle').attr('font-size', '7px').attr('fill', c.marker).text('eq');
svgCurve.append('text').attr('x', xi(Vend)).attr('y', baseY + 9).attr('text-anchor', 'middle').attr('font-size', '7px').attr('fill', endCol).text('end');
svgCurve.append('text').attr('x', (xi(Veq) + xi(Vend)) / 2).attr('y', topY - 3).attr('text-anchor', 'middle').attr('font-size', '7px').attr('fill', labCol).text('+' + (+lag.toFixed(2)) + ' mL');
}
}
// ===================== WORKED-SOLUTION HELPERS =====================
const cp = k => k === 1 ? '' : `${k}~`;
const uC = '\\mathrm{mol~L^{-1}}', uML = '\\mathrm{mL}', uMol = '\\mathrm{mol}', uG = '\\mathrm{g}';
// explicit mL → L conversion factor; multiply (c·V) products by this so amounts come out in mol
const conv = '~\\left(\\dfrac{1~\\mathrm{L}}{10^{3}~\\mathrm{mL}}\\right)';
const mn = (...xs) => Math.max(1, Math.min(...xs));
// four-line working: symbol = substitution = barred intermediate = sig-fig answer
function w4(symbol, subst, val, unitTex, n) {
return `${symbol} \\\\[1ex] &= ${subst} \\\\[1ex] &= ${F.barTex(val, n)}~${unitTex} \\\\[1ex] &= ${F.sigfigStr(val, n)}~${unitTex}`;
}
function line(id, label, valStr, body) {
const open = live.open[id] ? ' open' : '';
return `<details class="tl-linedet" data-line="${id}"${open}>` +
`<summary><span class="tl-line-label">${label}</span><span class="tl-line-val">${valStr}</span></summary>` +
`<div class="tl-work">$$ \\begin{aligned} ${body} \\end{aligned} $$</div></details>`;
}
function plainLine(label, valStr) {
return `<div class="tl-line"><span class="tl-line-label">${label}</span><span class="tl-line-val">${valStr}</span></div>`;
}
function bin(id, name, head, inner) {
const open = live.open[id] ? ' open' : '';
return `<details class="tl-bin" data-bin="${id}"${open}>` +
`<summary><span class="tl-bin-name">${name}</span><span class="tl-bin-head">${head}</span></summary>` +
`<div class="tl-bin-body">${inner}</div></details>`;
}
// ===================== DYNAMIC UPDATE =====================
let mounted = false; // first render is deferred (DOM detached); later updates typeset synchronously
function updateDynamic() {
const a = sp.a, b = sp.b;
const ct = live.ct, ca = live.ca, Va = live.Va, Vt = live.Vt;
let q = F.calc(sp, live); // every number below comes from tlFmt.calc
const Veq = q.Veq, VtMax = q.VtMax;
vtSlider.max = VtMax; vtNum.max = VtMax;
veqMark.style.display = q.overBuret ? 'none' : '';
const _veqFrac = Math.min(1, Math.max(0, Veq / VtMax)); // align tick with the thumb centre (thumb is 16px + 2px border each side = 20px, so travel is inset 10px)
veqMark.style.left = `calc(10px + ${_veqFrac} * (100% - 20px))`;
if (Vt > VtMax) { live.Vt = VtMax; live.VtStr = (+VtMax).toFixed(2); vtSlider.value = VtMax; vtNum.value = live.VtStr; q = F.calc(sp, live); }
const Vtn = live.Vt;
const endpoint = q.endpoint; // true stoichiometric equivalence (drives the worked-solution chemistry)
const atEq = q.atEq;
const lag = live.indError ? (indicator.lag || 0) : 0;
const Vend = Veq + lag; // volume at the color change (endpoint)
const colorOn = Vtn >= Vend - 1e-9; // the flask color flips at the endpoint, ~one drop after equivalence
if (live.leftView === 'curve') drawCurve(Veq, VtMax);
else drawApparatus(Veq, VtMax, colorOn);
indicatorNote.innerHTML = `Indicator: <b>${indicator.name}</b> · ${indicator.low} → ${indicator.high}`;
snapBtn.textContent = live.indError ? 'Jump to color change' : 'Jump to endpoint';
snapBtn.disabled = q.overBuret;
buretNote.hidden = !q.overBuret;
const buretSay = q.overBuret ? `This titration needs ${F.sigfigStr(Veq, 4)} mL of titrant, more than one ${F.BURET} mL buret holds. Use a more concentrated titrant, a more dilute analyte, or a smaller sample.` : '';
if (buretNote.textContent !== buretSay) buretNote.textContent = buretSay;
if (live.indError) {
const pErr = Veq > 0 ? lag / Veq * 100 : 0;
errNote.style.display = '';
errNote.innerHTML = `True equivalence <b>${F.sigfigStr(Veq, 4)} mL</b> · color change <b>${F.sigfigStr(Vend, 4)} mL</b><br>` +
`recording the endpoint over-estimates the result by <b>+${pErr.toFixed(2)} %</b> (~one drop late).`;
} else {
errNote.style.display = 'none';
}
const statusSay = Vtn <= 0 ? 'Add titrant with the slider or box.'
: (atEq ? 'At the equivalence point.'
: (Vtn < Veq ? 'Before the equivalence point.' : 'Past the equivalence point.'));
if (statusNote.textContent !== statusSay) statusNote.textContent = statusSay; // written only on a change, so it is announced once
// sig figs of the measured inputs
const sfct = q.sf.ct, sfca = q.sf.ca, sfva = q.sf.Va, sfvt = q.sf.Vt, sfM = F.sigFigs(String(Manalyte));
// amounts in mol, masses in g
const ntMol = q.nt, nIonMol = q.nIon, nSpecMol = q.nSpec;
const nAnalyteMol = q.nAnalyte, nReactedMol = q.nReacted;
const remainingMol = q.remaining, excessMol = q.excess;
const massAnalyteG = q.nAnalyte * Manalyte;
const Vtot = q.Vtot, pct = q.pct;
// the solid, one per formula of titrant before equivalence and one per formula of analyte after
const nSolidMol = endpoint ? q.nAnalyte : q.nt, sfSolid = q.sfReacted;
const massSolidG = solid ? nSolidMol * solid.M : 0;
const sfSolidMass = solid ? mn(sfSolid, F.sigFigs(String(solid.M))) : 1;
// barred input strings
const ctB = F.barInput(live.ctStr), caB = F.barInput(live.caStr);
const VaB = F.barInput(live.VaStr), VtB = F.barInput(live.VtStr);
const MB = F.barInput(String(Manalyte));
const VeqStr = F.sigfigStr(Veq, 4), VeqB = F.barInput(VeqStr);
// ---------- BIN: Titrant added ----------
let titrant = plainLine('volume delivered', `${live.VtStr} mL`);
titrant += line('t-mol', 'moles of titrant', `${F.sigfigStr(ntMol, mn(sfct, sfvt))} mol`,
w4(`n_{\\mathrm{t}} &= c_{\\mathrm{t}}~V_{\\mathrm{t}}`,
`(${ctB}~${uC})(${VtB}~${uML})${conv}`, ntMol, uMol, mn(sfct, sfvt)));
titrant += line('t-ion', `moles of ${ionDelivLbl} added`, `${F.sigfigStr(nIonMol, mn(sfct, sfvt))} mol`,
w4(`n(${ionDelivTex}) &= ${cp(b)}c_{\\mathrm{t}}~V_{\\mathrm{t}}`,
`${cp(b)}(${ctB}~${uC})(${VtB}~${uML})${conv}`, nIonMol, uMol, mn(sfct, sfvt)));
titrant += line('t-spec', `moles of ${specLbl} added`, `${F.sigfigStr(nSpecMol, mn(sfct, sfvt))} mol`,
w4(`n(${specTex}) &= c_{\\mathrm{t}}~V_{\\mathrm{t}}`,
`(${ctB}~${uC})(${VtB}~${uML})${conv}`, nSpecMol, uMol, mn(sfct, sfvt)));
// ---------- BIN: Analyte ----------
const nCa = mn(sfct, sfva, 4);
const analyteHead = `${F.sigfigStr(ca, nCa)} mol L<sup>−1</sup>`;
let analyteInner = `<div class="tl-binnote">This is what the titration sets out to find. You don't read it off a slider; the <em>equivalence-point volume</em> determines it through the equivalence relation below. It is a fixed property of the sample, so it never changes as titrant is added (the live consumption and dilution appear under <em>Reaction progress</em>).</div>`;
// mole ratio r(A,T) = ν_A/ν_T (= b/a in the widget's proton/charge counts), formatted for display
const ratioTex = (b === a) ? '1' : (b % a === 0 ? String(b / a) : (a % b === 0 ? `\\tfrac{1}{${a / b}}` : `\\tfrac{${b}}{${a}}`));
analyteInner += line('a-conc', 'concentration', `${F.sigfigStr(ca, nCa)} mol L<sup>−1</sup>`,
`n_{\\mathrm{a}} &= n_{\\mathrm{t}}~r(\\mathrm{A,T}) \\\\[1ex]` +
`c_{\\mathrm{a}}~V_{\\mathrm{a}} &= c_{\\mathrm{t}}~V_{\\mathrm{eq}}~r(\\mathrm{A,T}) \\\\[1ex]` +
`c_{\\mathrm{a}} &= \\dfrac{c_{\\mathrm{t}}~V_{\\mathrm{eq}}~r(\\mathrm{A,T})}{V_{\\mathrm{a}}} \\\\[1ex]` +
`&= \\dfrac{(${ctB}~${uC})(${VeqB}~${uML})(${ratioTex})}{(${VaB}~${uML})} \\\\[1ex]` +
`&= ${F.barTex(ca, nCa)}~${uC} \\\\[1ex] &= ${F.sigfigStr(ca, nCa)}~${uC}`);
analyteInner += line('a-mol', 'moles of analyte in the sample', `${F.sigfigStr(nAnalyteMol, mn(sfca, sfva))} mol`,
w4(`n_{\\mathrm{a}} &= c_{\\mathrm{a}}~V_{\\mathrm{a}}`,
`(${caB}~${uC})(${VaB}~${uML})${conv}`, nAnalyteMol, uMol, mn(sfca, sfva)));
analyteInner += line('a-mass', 'mass of analyte in the sample', `${F.sigfigStr(massAnalyteG, mn(sfca, sfva, sfM))} g`,
w4(`m_{\\mathrm{a}} &= c_{\\mathrm{a}}~V_{\\mathrm{a}}~M`,
`(${caB}~${uC})(${VaB}~${uML})${conv}(${MB}~\\mathrm{g~mol^{-1}})`, massAnalyteG, uG, mn(sfca, sfva, sfM)));
// ---------- BIN: Reaction progress ----------
let prog = line('rp-pct', 'progress to equivalence', `${F.sigfigStr(pct, 3)} %`,
`\\text{progress} &= \\dfrac{V_{\\mathrm{t}}}{V_{\\mathrm{eq}}}\\times 100\\,\\% \\\\[1ex]` +
`&= \\dfrac{${VtB}~${uML}}{${VeqB}~${uML}}\\times 100\\,\\% \\\\[1ex]` +
`&= ${F.barTex(pct, 3)}\\,\\% \\\\[1ex] &= ${F.sigfigStr(pct, 3)}\\,\\%`);
if (atEq) {
prog += plainLine('in excess', 'none (at equivalence)');
} else if (!endpoint) {
const nrem = q.sfDiff, nremc = q.sfConc; // a difference keeps decimal places; see tlFmt.diffSf
prog += line('rp-rem', `${analyteIonLbl} remaining (unreacted analyte)`, `${F.sigfigStr(remainingMol, nrem)} mol`,
w4(`n(${analyteIonTex})_{\\mathrm{left}} &= ${cp(a)}c_{\\mathrm{a}}~V_{\\mathrm{a}} - ${cp(b)}c_{\\mathrm{t}}~V_{\\mathrm{t}}`,
`\\left[${cp(a)}(${caB}~${uC})(${VaB}~${uML}) - ${cp(b)}(${ctB}~${uC})(${VtB}~${uML})\\right]${conv}`, remainingMol, uMol, nrem));
prog += line('rp-remc', `${analyteIonLbl} concentration (consumed + diluted)`, `${F.sigfigStr(q.cRemaining, nremc)} mol L<sup>−1</sup>`,
w4(`c(${analyteIonTex}) &= \\dfrac{n(${analyteIonTex})_{\\mathrm{left}}}{V_{\\mathrm{a}} + V_{\\mathrm{t}}}`,
`\\dfrac{${F.barTex(remainingMol, nrem)}~${uMol}}{(${VaB} + ${VtB})~${uML}${conv}}`, q.cRemaining, uC, nremc));
} else {
const nexc = q.sfDiff, nexcc = q.sfConc;
prog += line('rp-exc', `${ionDelivLbl} in excess`, `${F.sigfigStr(excessMol, nexc)} mol`,
w4(`n(${ionDelivTex})_{\\mathrm{excess}} &= ${cp(b)}c_{\\mathrm{t}}~V_{\\mathrm{t}} - ${cp(a)}c_{\\mathrm{a}}~V_{\\mathrm{a}}`,
`\\left[${cp(b)}(${ctB}~${uC})(${VtB}~${uML}) - ${cp(a)}(${caB}~${uC})(${VaB}~${uML})\\right]${conv}`, excessMol, uMol, nexc));
prog += line('rp-excc', `${ionDelivLbl} concentration`, `${F.sigfigStr(q.cExcess, nexcc)} mol L<sup>−1</sup>`,
w4(`c(${ionDelivTex}) &= \\dfrac{n(${ionDelivTex})_{\\mathrm{excess}}}{V_{\\mathrm{a}} + V_{\\mathrm{t}}}`,
`\\dfrac{${F.barTex(excessMol, nexc)}~${uMol}}{(${VaB} + ${VtB})~${uML}${conv}}`, q.cExcess, uC, nexcc));
}
const progHead = atEq ? 'at equivalence' : `${F.sigfigStr(pct, 3)} %`;
// ---------- BIN: Products ----------
let products, prodHead;
const nRn = q.sfReacted;
const specLine = () => line('p-spec', `${specLbl} concentration`, `${F.sigfigStr(q.cSpec, q.sfSpec)} mol L<sup>−1</sup>`,
w4(`c(${specTex}) &= \\dfrac{c_{\\mathrm{t}}~V_{\\mathrm{t}}}{V_{\\mathrm{a}} + V_{\\mathrm{t}}}`,
`\\dfrac{(${ctB}~${uC})(${VtB}~${uML})}{(${VaB} + ${VtB})~${uML}}`, q.cSpec, uC, q.sfSpec));
const solidLines = () =>
line('p-ppt', `moles of ${solid.lbl}`, `${F.sigfigStr(nSolidMol, sfSolid)} mol`,
w4(`n(${solid.tex}) &= ${endpoint ? `c_{\\mathrm{a}}~V_{\\mathrm{a}}` : `c_{\\mathrm{t}}~V_{\\mathrm{t}}`}`,
endpoint ? `(${caB}~${uC})(${VaB}~${uML})${conv}` : `(${ctB}~${uC})(${VtB}~${uML})${conv}`, nSolidMol, uMol, sfSolid)) +
line('p-pptm', `mass of ${solid.lbl}`, `${F.sigfigStr(massSolidG, sfSolidMass)} g`,
w4(`m(${solid.tex}) &= n(${solid.tex})~M`,
`(${F.barTex(nSolidMol, sfSolid)}~${uMol})(${F.barInput(String(solid.M))}~\\mathrm{g~mol^{-1}})`, massSolidG, uG, sfSolidMass));
if (isPrecip) {
prodHead = `${F.sigfigStr(massSolidG, sfSolidMass)} g`;
products = solidLines() + specLine();
} else {
const waterSym = endpoint ? `${cp(a)}c_{\\mathrm{a}}~V_{\\mathrm{a}}` : `${cp(b)}c_{\\mathrm{t}}~V_{\\mathrm{t}}`;
const waterSub = endpoint ? `${cp(a)}(${caB}~${uC})(${VaB}~${uML})${conv}` : `${cp(b)}(${ctB}~${uC})(${VtB}~${uML})${conv}`;
products = line('p-h2o', 'moles of H<sub>2</sub>O(l) formed', `${F.sigfigStr(nReactedMol, nRn)} mol`,
w4(`n(\\mathrm{H_2O}) &= ${waterSym}`, waterSub, nReactedMol, uMol, nRn));
if (solid) {
// H2SO4 + Ba(OH)2: the cation is not a spectator, it precipitates, so it has no concentration line
prodHead = `${F.sigfigStr(massSolidG, sfSolidMass)} g ${solid.plain}`;
products += solidLines();
} else {
prodHead = `${F.sigfigStr(nReactedMol, nRn)} mol H<sub>2</sub>O`;
products += specLine();
}
}
// ---------- assemble right column ----------
const region = endpoint ? (atEq ? 'At equivalence' : 'Past equivalence') : 'Before equivalence';
const strip = `${region} · ${F.sigfigStr(pct, 3)} % titrated · ` +
`<i>V</i><sub>t</sub> = ${live.VtStr} mL · <i>V</i><sub>eq</sub> = ${VeqStr} mL`;
const keyHTML = '<i>a</i> = analyte (flask) · <i>t</i> = titrant (buret) · eq = equivalence';
rightCol.innerHTML =
`<div class="tl-eq">$$ ${sp.eq} $$</div>` +
`<div class="tl-strip">${strip}</div>` +
`<div class="tl-key">${keyHTML}</div>` +
`<div class="tl-bins">` +
bin('titrant', 'Titrant added', `${F.sigfigStr(ntMol, mn(sfct, sfvt))} mol`, titrant) +
bin('progress', 'Reaction progress', progHead, prog) +
bin('products', 'Products', prodHead, products) +
bin('analyte', 'Analyte (Unknown)', analyteHead, analyteInner) +
`</div>`;
rightCol.querySelectorAll('details[data-bin],details[data-line]').forEach(d => {
const id = d.dataset.bin || d.dataset.line;
d.addEventListener('toggle', () => { live.open[id] = d.open; typesetVisible(true); });
});
// synchronous typeset on updates so the raw $$...$$ never paints (no flash while sliding);
// first render is deferred because the widget DOM is still detached during cell evaluation
if (mounted) typesetVisible(true);
else setTimeout(() => { typesetVisible(true); mounted = true; }, 0);
}
function typesetVisible(sync) {
if (!window.MathJax) return;
const els = [];
const eqEl = rightCol.querySelector('.tl-eq');
if (eqEl) els.push(eqEl);
rightCol.querySelectorAll('.tl-work').forEach(el => { if (el.offsetParent !== null) els.push(el); });
if (!els.length) return;
// sync typeset renders before the browser paints (kills the raw-LaTeX flash); fall back to async
if (sync && window.MathJax.typeset) { try { window.MathJax.typeset(els); return; } catch (e) {} }
if (window.MathJax.typesetPromise) window.MathJax.typesetPromise(els);
}
setView(live.leftView); // sets toggle state + visibility, then renders via updateDynamic
return root;
}// ========== TITRATION LAB - CSS ==========
html`<style>
.tl-widget {
background: #f8f9fa; border-radius: 10px; padding: 14px 18px 18px;
font-family: system-ui, sans-serif; max-width: 1200px; margin: 12px auto 18px; position: relative;
}
.tl-fs-btn { position: absolute; top: 10px; right: 12px; width: 28px; height: 28px; border: 1px solid #cbd5e1;
border-radius: 6px; background: #ffffff; color: #475569; cursor: pointer; display: flex; align-items: center;
justify-content: center; font-size: 18px; line-height: 1; transition: all 0.15s ease; z-index: 5; }
.tl-fs-btn:hover { background: #eef2f7; color: #1f2937; border-color: #94a3b8; }
.tl-title { text-align: center; font-size: 19px; font-weight: 700; color: #1f2937; padding-bottom: 8px; }
/* the title is an h1 or h2 now: keep the old look, not the page theme's heading styles */
.tl-widget .tl-title { margin: 0; padding: 0 0 8px; border: none; line-height: 1.3; font-family: inherit; letter-spacing: normal;
background: none; -webkit-text-fill-color: currentColor; text-shadow: none !important; filter: none; }
.tl-widget .tl-title::before, .tl-widget .tl-title::after { display: none !important; content: none !important; }
.tl-tab-row { display: flex; gap: 18px; justify-content: center; flex-wrap: wrap; padding-bottom: 12px; }
.tl-tabs { display: inline-flex; border-radius: 8px; overflow: hidden; border: 1px solid #cbd5e1; }
.tl-tab { font-size: 15px; padding: 6px 14px; border: none; background: #ffffff; color: #475569; cursor: pointer; transition: all 0.15s ease; }
.tl-tab:hover { background: #f1f5f9; }
.tl-tab.active { background: #2563eb; color: #ffffff; font-weight: 600; }
.tl-body { display: flex; gap: 22px; flex-wrap: wrap; }
.tl-left { flex: 0 1 440px; min-width: 0; }
.tl-right { flex: 1 1 360px; min-width: 0; }
.tl-controls { display: flex; flex-direction: column; gap: 8px; margin-bottom: 10px; }
.tl-ctrl-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.tl-ctrl-label { font-size: 15px; color: #475569; }
.tl-select, .tl-number {
font-size: 15px; padding: 4px 8px; border: 1px solid #cbd5e1; border-radius: 6px;
background: #ffffff; color: #1f2937; min-width: 150px;
}
.tl-number { width: 112px; min-width: 0; text-align: right; padding-right: 8px; }
.tl-number, .tl-vtnum { -webkit-appearance: textfield !important; -moz-appearance: textfield !important; appearance: textfield !important; }
.tl-number::-webkit-inner-spin-button, .tl-number::-webkit-outer-spin-button,
.tl-vtnum::-webkit-inner-spin-button, .tl-vtnum::-webkit-outer-spin-button {
-webkit-appearance: none !important; appearance: none !important; display: none !important; margin: 0 !important; }
.tl-stepper { display: inline-flex; align-items: stretch; gap: 7px; }
.tl-stepbtns { display: flex; flex-direction: column; gap: 2px; }
.tl-stepbtn { width: 21px; flex: 1 1 0; min-height: 0; padding: 0; display: flex; align-items: center; justify-content: center;
font-size: 8.5px; line-height: 1; color: #475569; background: #f1f5f9; border: 1px solid #cbd5e1; border-radius: 4px; cursor: pointer; }
.tl-stepbtn:hover { background: #e2e8f0; color: #1f2937; }
.tl-stepbtn:active { background: #cbd5e1; }
.tl-vt-label { margin-top: 6px; }
.tl-slider-row { display: flex; align-items: center; gap: 10px; margin-top: 4px; min-width: 0; }
.tl-slider-wrap { position: relative; flex: 1 1 0; min-width: 0; display: flex; align-items: center; }
.tl-veq-mark { position: absolute; top: 50%; transform: translate(-50%, -50%); width: 2px; height: 18px;
background: #dc2626; border-radius: 1px; pointer-events: none; }
/* 6px of track inside a 24px-tall box: the padding is the pointer target (WCAG 2.5.8) */
.tl-slider { -webkit-appearance: none; appearance: none; flex: 1 1 0; min-width: 0; height: 6px; border-radius: 3px;
box-sizing: content-box; padding: 9px 0; background-clip: content-box !important;
background: linear-gradient(90deg, #dbeafe 0%, #3b82f6 100%); outline: none; cursor: pointer; margin: 0; }
.tl-slider::-webkit-slider-thumb { -webkit-appearance: none; width: 16px; height: 16px; border-radius: 50%;
background: #3b82f6; border: 2px solid #fff; box-shadow: 0 1px 3px rgba(59,130,246,0.4); cursor: pointer; }
.tl-slider::-moz-range-thumb { width: 16px; height: 16px; border-radius: 50%; background: #3b82f6; border: 2px solid #fff; cursor: pointer; }
.tl-vtnum { width: 96px; font-size: 14.5px; padding: 3px 8px; border: 1px solid #cbd5e1; border-radius: 6px;
background: #ffffff; color: #1f2937; text-align: right; font-variant-numeric: tabular-nums; }
.tl-unit { font-size: 14.5px; color: #6b7280; }
.tl-snap-btn { align-self: flex-start; font-size: 14px; padding: 4px 10px; border: 1px solid #cbd5e1;
border-radius: 6px; background: #ffffff; color: #475569; cursor: pointer; }
.tl-snap-btn:hover { background: #f1f5f9; }
.tl-snap-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.tl-buretnote[hidden] { display: none; }
.tl-status { font-size: 14px; color: #6b7280; font-style: italic; min-height: 16px; padding-top: 2px; }
.tl-chart { display: block; width: 100%; height: auto; max-width: 440px; margin: 4px auto 0; }
.tl-widget svg text { user-select: none; -webkit-user-select: none; }
.tl-viewtog { display: flex; justify-content: center; margin: 4px auto 2px; border: 1px solid #cbd5e1; border-radius: 7px; overflow: hidden; width: fit-content; }
.tl-viewbtn { font-size: 14px; padding: 4px 16px; border: none; background: #ffffff; color: #475569; cursor: pointer; transition: background 0.15s ease; }
.tl-viewbtn + .tl-viewbtn { border-left: 1px solid #cbd5e1; }
.tl-viewbtn:hover { background: #f1f5f9; }
.tl-viewbtn.active { background: #2563eb; color: #ffffff; font-weight: 600; }
.tl-indicator { font-size: 13px; color: #64748b; text-align: center; margin-top: 3px; line-height: 1.3; }
.tl-indicator b { color: #475569; }
.tl-widget .tl-check { display: flex !important; align-items: center; gap: 7px; font-size: 14px; color: #475569; cursor: pointer; margin-top: 4px; align-self: flex-start; font-weight: 400; }
.tl-widget .tl-check input { flex: none; margin: 0; width: 18px; height: 18px; }
.tl-widget .tl-check span { font-size: 14px; line-height: 1.2; }
.tl-errnote { font-size: 13px; color: #b45309; background: #fffbeb; border: 1px solid #fde68a; border-radius: 6px; padding: 5px 9px; margin-top: 6px; line-height: 1.35; text-align: center; }
.tl-errnote b { color: #92400e; }
.tl-eq { text-align: center; }
/* The site sets all math to 110% (assets/custom.scss): 18.7px beside this widget's 15px text.
16px keeps the worked lines level with their labels and lets the longest one fit. */
.tl-widget mjx-container { font-size: 16px !important; }
.tl-strip { font-size: 15.5px; color: #475569; background: #eef2f7; border-radius: 6px; padding: 6px 11px; margin: 6px 0 4px; }
.tl-key { font-size: 15px; color: #6b7280; padding-bottom: 8px; }
.tl-bins { display: flex; flex-direction: column; gap: 8px; }
.tl-bin { border: 1px solid #d6deea; border-radius: 10px; background: #ffffff; overflow: hidden; box-shadow: 0 1px 2px rgba(15,23,42,0.05); }
/* HEADER BAR: plain white like the card, bold, chevron on the left and the value at the right */
.tl-bin > summary {
cursor: pointer; display: flex; align-items: center; gap: 10px;
padding: 9px 14px; font-weight: 700; font-size: 16px; color: #1e293b;
background: #ffffff;
border-bottom: 1px solid transparent; list-style: none; transition: background 0.15s ease;
}
.tl-bin > summary:hover { background: #f6f9fc; }
.tl-bin[open] > summary { border-bottom-color: #e2e8f0; }
.tl-bin > summary::-webkit-details-marker { display: none; }
.tl-bin > summary::before {
content: ''; flex: none; width: 6px; height: 6px;
border-top: 2px solid #2563eb; border-right: 2px solid #2563eb;
transform: rotate(45deg); transition: transform 0.18s ease;
}
.tl-bin[open] > summary::before { transform: rotate(135deg); }
.tl-bin-name { flex: 1; letter-spacing: 0.01em; }
.tl-bin-head { font-weight: 600; font-size: 15px; color: #0f172a; font-variant-numeric: tabular-nums; white-space: nowrap; }
.tl-bin-body { padding: 3px 14px 9px; }
/* LINE ITEMS: quiet rows on the white card, subordinate to the header */
.tl-line, .tl-linedet { border-top: 1px solid #eef2f7; }
.tl-bin-body > .tl-line:first-child, .tl-bin-body > .tl-linedet:first-child { border-top: none; }
.tl-line { display: flex; justify-content: space-between; gap: 10px; padding: 7px 4px; font-size: 15px; color: #475569; }
.tl-linedet > summary { cursor: pointer; display: flex; align-items: center; gap: 8px;
padding: 7px 4px; font-size: 15px; color: #475569; list-style: none; border-radius: 5px; transition: background 0.12s ease; }
.tl-linedet > summary:hover { background: #f6f9fc; }
.tl-linedet > summary::-webkit-details-marker { display: none; }
.tl-linedet > summary::before { content: '▸'; flex: none; color: #94a3b8; font-size: 11px; transition: transform 0.15s ease; }
.tl-linedet[open] > summary::before { transform: rotate(90deg); color: #2563eb; }
.tl-linedet > summary:hover .tl-line-label { color: #1d4ed8; }
.tl-line-label { flex: 1; }
.tl-line-val { font-weight: 600; color: #0f172a; font-variant-numeric: tabular-nums; white-space: nowrap; }
.tl-work { padding: 2px 0 6px 17px; overflow-x: auto; color: #1e293b; }
.tl-binnote { font-size: 13px; color: #64748b; line-height: 1.4; padding: 2px 4px 6px; margin-bottom: 2px; }
.tl-binnote em { font-style: italic; color: #475569; }
/* ===== DARK MODE ===== */
[data-bs-theme="dark"] .tl-widget, body.quarto-dark .tl-widget, .quarto-dark .tl-widget {
background: linear-gradient(145deg, #0b0c14 0%, #0d1020 50%, #0b0c14 100%);
border: 1px solid rgba(0,217,255,0.2);
}
[data-bs-theme="dark"] .tl-fs-btn, body.quarto-dark .tl-fs-btn, .quarto-dark .tl-fs-btn {
background: rgba(11,12,20,0.8); border-color: rgba(0,217,255,0.2); color: #a8afc7; }
[data-bs-theme="dark"] .tl-fs-btn:hover, body.quarto-dark .tl-fs-btn:hover, .quarto-dark .tl-fs-btn:hover {
background: rgba(0,217,255,0.08); border-color: rgba(0,217,255,0.4); color: #00d9ff; }
[data-bs-theme="dark"] .tl-title, body.quarto-dark .tl-title, .quarto-dark .tl-title { color: #e8ecf8; }
[data-bs-theme="dark"] .tl-tabs, body.quarto-dark .tl-tabs, .quarto-dark .tl-tabs { border-color: rgba(0,217,255,0.2); }
[data-bs-theme="dark"] .tl-tab, body.quarto-dark .tl-tab, .quarto-dark .tl-tab { background: rgba(11,12,20,0.6); color: #a8afc7; }
[data-bs-theme="dark"] .tl-tab:hover, body.quarto-dark .tl-tab:hover, .quarto-dark .tl-tab:hover { background: rgba(0,217,255,0.08); }
[data-bs-theme="dark"] .tl-tab.active, body.quarto-dark .tl-tab.active, .quarto-dark .tl-tab.active { background: #00d9ff; color: #0b0c14; }
[data-bs-theme="dark"] .tl-ctrl-label, body.quarto-dark .tl-ctrl-label, .quarto-dark .tl-ctrl-label { color: #a8afc7; }
[data-bs-theme="dark"] .tl-select, [data-bs-theme="dark"] .tl-number, [data-bs-theme="dark"] .tl-vtnum,
body.quarto-dark .tl-select, body.quarto-dark .tl-number, body.quarto-dark .tl-vtnum,
.quarto-dark .tl-select, .quarto-dark .tl-number, .quarto-dark .tl-vtnum {
background: rgba(11,12,20,0.6); border-color: rgba(0,217,255,0.2); color: #e8ecf8;
}
[data-bs-theme="dark"] .tl-stepbtn, body.quarto-dark .tl-stepbtn, .quarto-dark .tl-stepbtn {
background: rgba(0,217,255,0.08); border-color: rgba(0,217,255,0.25); color: #a8afc7; }
[data-bs-theme="dark"] .tl-stepbtn:hover, body.quarto-dark .tl-stepbtn:hover, .quarto-dark .tl-stepbtn:hover {
background: rgba(0,217,255,0.18); color: #e8ecf8; }
[data-bs-theme="dark"] .tl-unit, body.quarto-dark .tl-unit, .quarto-dark .tl-unit { color: #8b949e; }
[data-bs-theme="dark"] .tl-slider, body.quarto-dark .tl-slider, .quarto-dark .tl-slider { background: linear-gradient(90deg, #1a1f35 0%, #00d9ff 100%); }
[data-bs-theme="dark"] .tl-slider::-webkit-slider-thumb, body.quarto-dark .tl-slider::-webkit-slider-thumb, .quarto-dark .tl-slider::-webkit-slider-thumb { background: #00d9ff; border-color: #0b0c14; box-shadow: 0 0 8px rgba(0,217,255,0.5); }
[data-bs-theme="dark"] .tl-slider::-moz-range-thumb, body.quarto-dark .tl-slider::-moz-range-thumb, .quarto-dark .tl-slider::-moz-range-thumb { background: #00d9ff; border-color: #0b0c14; }
[data-bs-theme="dark"] .tl-snap-btn, body.quarto-dark .tl-snap-btn, .quarto-dark .tl-snap-btn { background: rgba(11,12,20,0.6); border-color: rgba(0,217,255,0.2); color: #a8afc7; }
[data-bs-theme="dark"] .tl-snap-btn:hover, body.quarto-dark .tl-snap-btn:hover, .quarto-dark .tl-snap-btn:hover { background: rgba(0,217,255,0.08); color: #00d9ff; }
[data-bs-theme="dark"] .tl-status, body.quarto-dark .tl-status, .quarto-dark .tl-status { color: #8b949e; }
[data-bs-theme="dark"] .tl-strip, body.quarto-dark .tl-strip, .quarto-dark .tl-strip { background: rgba(0,217,255,0.06); color: #a8afc7; }
[data-bs-theme="dark"] .tl-key, body.quarto-dark .tl-key, .quarto-dark .tl-key { color: #8b949e; }
/* neutralize the global details summary theme rule (translateX slide, transition all, glow, margin) on our bins */
.tl-bin > summary, .tl-linedet > summary { transition: background 0.15s ease !important; text-shadow: none !important; margin-bottom: 0 !important; }
.tl-bin > summary:hover, .tl-linedet > summary:hover { transform: none !important; }
.tl-bin > summary > *, .tl-linedet > summary > * { text-shadow: none !important; }
/* bins: dark cards in dark mode (solid fills -> no translucent seams; neutral hover) */
[data-bs-theme="dark"] .tl-bin, body.quarto-dark .tl-bin, .quarto-dark .tl-bin {
background: #11162a; border-color: rgba(0,217,255,0.18); box-shadow: none;
}
[data-bs-theme="dark"] .tl-bin > summary, body.quarto-dark .tl-bin > summary, .quarto-dark .tl-bin > summary {
background: #11162a; color: #e8ecf8 !important;
}
[data-bs-theme="dark"] .tl-bin > summary:hover, body.quarto-dark .tl-bin > summary:hover, .quarto-dark .tl-bin > summary:hover { background: #1a2236; color: #e8ecf8 !important; }
[data-bs-theme="dark"] .tl-bin[open] > summary, body.quarto-dark .tl-bin[open] > summary, .quarto-dark .tl-bin[open] > summary { border-bottom-color: rgba(0,217,255,0.15); }
[data-bs-theme="dark"] .tl-bin > summary::before, body.quarto-dark .tl-bin > summary::before, .quarto-dark .tl-bin > summary::before { border-top-color: #00d9ff; border-right-color: #00d9ff; }
[data-bs-theme="dark"] .tl-bin-name, body.quarto-dark .tl-bin-name, .quarto-dark .tl-bin-name { color: #e8ecf8 !important; }
[data-bs-theme="dark"] .tl-bin-head, body.quarto-dark .tl-bin-head, .quarto-dark .tl-bin-head {
color: #e8ecf8 !important;
}
[data-bs-theme="dark"] .tl-line, body.quarto-dark .tl-line, .quarto-dark .tl-line,
[data-bs-theme="dark"] .tl-linedet > summary, body.quarto-dark .tl-linedet > summary, .quarto-dark .tl-linedet > summary { color: #a8afc7 !important; }
[data-bs-theme="dark"] .tl-line, body.quarto-dark .tl-line, .quarto-dark .tl-line,
[data-bs-theme="dark"] .tl-linedet, body.quarto-dark .tl-linedet, .quarto-dark .tl-linedet { border-top-color: rgba(255,255,255,0.07); }
[data-bs-theme="dark"] .tl-linedet > summary:hover, body.quarto-dark .tl-linedet > summary:hover, .quarto-dark .tl-linedet > summary:hover { background: rgba(255,255,255,0.05); color: #a8afc7 !important; }
[data-bs-theme="dark"] .tl-line-label, body.quarto-dark .tl-line-label, .quarto-dark .tl-line-label { color: #a8afc7 !important; }
[data-bs-theme="dark"] .tl-linedet > summary:hover .tl-line-label, body.quarto-dark .tl-linedet > summary:hover .tl-line-label, .quarto-dark .tl-linedet > summary:hover .tl-line-label { color: #00d9ff !important; }
[data-bs-theme="dark"] .tl-linedet[open] > summary::before, body.quarto-dark .tl-linedet[open] > summary::before, .quarto-dark .tl-linedet[open] > summary::before { color: #00d9ff; }
[data-bs-theme="dark"] .tl-line-val, body.quarto-dark .tl-line-val, .quarto-dark .tl-line-val { color: #e8ecf8 !important; }
[data-bs-theme="dark"] .tl-work, body.quarto-dark .tl-work, .quarto-dark .tl-work { color: #e8ecf8; }
[data-bs-theme="dark"] .tl-binnote, body.quarto-dark .tl-binnote, .quarto-dark .tl-binnote { color: #8b949e; }
[data-bs-theme="dark"] .tl-binnote em, body.quarto-dark .tl-binnote em, .quarto-dark .tl-binnote em { color: #a8afc7; }
[data-bs-theme="dark"] .tl-veq-mark, body.quarto-dark .tl-veq-mark, .quarto-dark .tl-veq-mark { background: #ff007c; }
[data-bs-theme="dark"] .tl-viewtog, body.quarto-dark .tl-viewtog, .quarto-dark .tl-viewtog { border-color: rgba(0,217,255,0.2); }
[data-bs-theme="dark"] .tl-viewbtn, body.quarto-dark .tl-viewbtn, .quarto-dark .tl-viewbtn { background: rgba(11,12,20,0.6); color: #a8afc7; }
[data-bs-theme="dark"] .tl-viewbtn + .tl-viewbtn, body.quarto-dark .tl-viewbtn + .tl-viewbtn, .quarto-dark .tl-viewbtn + .tl-viewbtn { border-left-color: rgba(0,217,255,0.2); }
[data-bs-theme="dark"] .tl-viewbtn:hover, body.quarto-dark .tl-viewbtn:hover, .quarto-dark .tl-viewbtn:hover { background: rgba(0,217,255,0.08); }
[data-bs-theme="dark"] .tl-viewbtn.active, body.quarto-dark .tl-viewbtn.active, .quarto-dark .tl-viewbtn.active { background: #00d9ff; color: #0b0c14; }
[data-bs-theme="dark"] .tl-indicator, body.quarto-dark .tl-indicator, .quarto-dark .tl-indicator { color: #8b949e; }
[data-bs-theme="dark"] .tl-indicator b, body.quarto-dark .tl-indicator b, .quarto-dark .tl-indicator b { color: #cbd5e1; }
[data-bs-theme="dark"] .tl-check, body.quarto-dark .tl-check, .quarto-dark .tl-check { color: #a8afc7; }
[data-bs-theme="dark"] .tl-errnote, body.quarto-dark .tl-errnote, .quarto-dark .tl-errnote { color: #fbbf24; background: rgba(251,191,36,0.08); border-color: rgba(251,191,36,0.25); }
[data-bs-theme="dark"] .tl-errnote b, body.quarto-dark .tl-errnote b, .quarto-dark .tl-errnote b { color: #fcd34d; }
/* visible keyboard focus on every interactive control (UA default is often suppressed by the theme) */
.tl-tab:focus-visible, .tl-snap-btn:focus-visible, .tl-stepbtn:focus-visible, .tl-fs-btn:focus-visible, .tl-viewbtn:focus-visible,
.tl-select:focus-visible, .tl-number:focus-visible, .tl-vtnum:focus-visible, .tl-slider:focus-visible,
.tl-bin > summary:focus-visible, .tl-linedet > summary:focus-visible {
outline: 2px solid #2563eb; outline-offset: 2px; border-radius: 4px;
}
[data-bs-theme="dark"] :is(.tl-tab,.tl-snap-btn,.tl-stepbtn,.tl-fs-btn,.tl-select,.tl-number,.tl-vtnum,.tl-slider):focus-visible,
[data-bs-theme="dark"] :is(.tl-bin,.tl-linedet) > summary:focus-visible,
body.quarto-dark :is(.tl-tab,.tl-snap-btn,.tl-stepbtn,.tl-fs-btn,.tl-select,.tl-number,.tl-vtnum,.tl-slider):focus-visible,
body.quarto-dark :is(.tl-bin,.tl-linedet) > summary:focus-visible {
outline-color: #00d9ff;
}
/* narrow: a long label and its value stack, value to the right, so nothing runs past the card */
@media (max-width: 480px) {
.tl-line, .tl-linedet > summary, .tl-bin > summary { flex-wrap: wrap; }
.tl-line-val, .tl-bin-head { margin-left: auto; }
.tl-bin-body { padding-left: 8px; padding-right: 8px; }
}
@media (prefers-reduced-motion: reduce) {
.tl-widget *, .tl-widget *::before, .tl-widget *::after { transition: none !important; }
}
</style>`