/* ============================================================ ConcreteQuantity: unit-toggle patch for the water-cement ratio and evaporation-rate pages ONLY ------------------------------------------------------------ THE BUG (verified live 26 Oct 2026) On these two pages the header toggle (Feet/Inches vs Meters/CM, buttons #p4uImp / #p4uMet) multiplies EVERY input by 0.3048 when switching to metric, including temperatures, wind, humidity, water and cement, and toggling back does NOT restore the original values. Example: evaporation at 30 C / 30 C / 50% / 15 km/h = 0.76 kg/m2/h became 9.144 / 9.144 / 50 / 4.572 = 0.08 kg/m2/h, and stayed wrong after toggling back. A visitor following those numbers gets a wrong risk band, so this is a data-corrupting bug, not a cosmetic one. WHY CAPTURE INTERCEPTION (not clone-and-replace) The buggy handlers are attached by the P4 script, which loads after this patch and wires its buttons at its own boot time. Clone-and-replace at patch time would be undone when P4 wires the fresh clones afterwards. Instead this patch listens on document in the CAPTURE phase: a capture listener on an ancestor runs before any listener on the button itself, no matter when that listener was attached, and stopPropagation() there prevents the buggy handler from ever firing. This holds regardless of P4's load order. CORRECT BEHAVIOUR (this patch) - Temperatures convert C <-> F (F = C x 9/5 + 32). - Wind converts km/h <-> mph (mph = km/h x 0.621371). - Humidity, water and cement values NEVER change. - Unknown fields are NEVER scaled (safe default: skip). - Toggling back restores the EXACT original value and unit: when leaving a unit system the patch saves the current value + select value on the input itself; returning restores the saved pair verbatim. Any manual edit (or manual unit-select change) clears the saved pair, so a stale value can never come back. - Per-input state is read from each input's own unit select at click time, so clicking the already-active system is a no-op and a conversion can never be applied twice. - The patch never dispatches events on the unit selects, so P4's own per-field select converter (if any) cannot double convert; it dispatches 'input' on the changed inputs only, so P4 recalculates with the new values and units. PLACEMENT: this script tag goes AFTER the V6 tag on the two pages only (water-cement-ratio-calculator, concrete-evaporation-rate-calculator). It is inert on every other page: it checks window.CC_SINGLE first. ============================================================ */ (function(){ "use strict"; var KMH_TO_MPH = 0.621371; /* ---------- pure conversions (unit tested) ---------- */ function cToF(c){ return c * 9 / 5 + 32; } function fToC(f){ return (f - 32) * 5 / 9; } function kmhToMph(k){ return k * KMH_TO_MPH; } function mphToKmh(m){ return m / KMH_TO_MPH; } function fmtTrim(v, dp){ var r = Math.round(v * Math.pow(10, dp)) / Math.pow(10, dp); var s = String(r); return s; } /* Classify a field by its data-fid, falling back to label text. Returns 'temp', 'wind', 'never', or null (unknown -> skip). */ function classifyFid(fid){ if(fid === 'airT' || fid === 'concT') return 'temp'; if(fid === 'wind') return 'wind'; if(fid === 'rh' || fid === 'water' || fid === 'cement') return 'never'; return null; } function classifyLabel(text){ text = (text || '').toLowerCase(); if(text.indexOf('temperature') >= 0) return 'temp'; if(text.indexOf('wind') >= 0) return 'wind'; if(text.indexOf('humidity') >= 0 || text.indexOf('water') >= 0 || text.indexOf('cement') >= 0) return 'never'; return null; } /* Pure toggle decision. state: {value, unit, saved} where unit is canonical ('C'|'F' for temp, 'kmh'|'mph' for wind) and saved is {value, unit, system, selectValue} or null. Returns {value, unit, saved, changed, restored}. */ function toggleField(state, targetSystem, kind){ var unit = state.unit; var currentSystem = (unit === 'F' || unit === 'mph') ? 'imp' : 'met'; if(currentSystem === targetSystem){ return { value: state.value, unit: unit, saved: state.saved, changed: false, restored: false }; } var saved = state.saved || null; if(saved && saved.system === targetSystem){ return { value: saved.value, unit: saved.unit, saved: null, changed: true, restored: true, selectValue: saved.selectValue }; } var v = parseFloat(state.value) || 0; var newUnit, newValue; if(kind === 'temp'){ if(targetSystem === 'imp'){ newUnit = 'F'; newValue = cToF(v); } else { newUnit = 'C'; newValue = fToC(v); } } else { if(targetSystem === 'imp'){ newUnit = 'mph'; newValue = kmhToMph(v); } else { newUnit = 'kmh'; newValue = mphToKmh(v); } } return { value: String(newValue), unit: newUnit, saved: { value: state.value, unit: unit, system: currentSystem }, changed: true, restored: false }; } /* ---------- DOM layer ---------- */ function getPanel(){ var c = document.getElementById('ccSingle'); if(!c) return null; var p = null; try { p = c.querySelector('.cc-panel'); } catch(e){ p = null; } return p || c; } function getInputs(panel){ var list = []; try { list = panel.querySelectorAll('input[data-fid]'); } catch(e){ list = []; } if(list.length) return list; try { return panel.querySelectorAll('input[type="number"]'); } catch(e){ return []; } } function getSelect(panel, fid, input){ var sel = null; try { sel = panel.querySelector('select.cc-funit[data-funit="' + fid + '"]'); } catch(e){ sel = null; } if(sel) return sel; var row = null; if(input.closest){ try { row = input.closest('.cc-unitrow'); } catch(e){ row = null; } } if(row){ try { sel = row.querySelector('select'); } catch(e){ sel = null; } } return sel; } function getLabelText(input){ var t = input.getAttribute('aria-label'); if(t) return t; var field = null; if(input.closest){ try { field = input.closest('.cc-field'); } catch(e){ field = null; } } if(field){ var lab = null; try { lab = field.querySelector('label'); } catch(e){ lab = null; } if(lab) return lab.textContent || ''; } return ''; } function canonicalUnit(selectValue, kind){ if(kind === 'temp') return (selectValue === 'F') ? 'F' : 'C'; return (selectValue === 'mph') ? 'mph' : 'kmh'; } /* Find the select option value to use for a target canonical unit. For imperial the values are exact ('F', 'mph', confirmed from P4's own toImp checks). For metric, prefer the saved value on restore, else the first option that is not the imperial one (covers 'C', 'kmh', 'km/h' and any other spelling). */ function targetOptionValue(select, kind, targetSystem, savedSelectValue){ if(savedSelectValue !== undefined && savedSelectValue !== null) return savedSelectValue; if(targetSystem === 'imp') return (kind === 'temp') ? 'F' : 'mph'; var impVal = (kind === 'temp') ? 'F' : 'mph'; var opts = select.options || []; var fallback = null; for(var i = 0; i < opts.length; i++){ var v = opts[i].value; if(v === 'C' && kind === 'temp') return 'C'; if(v !== impVal && fallback === null) fallback = v; } return fallback; } function fireInput(input){ var ev = null; try { ev = new Event('input', { bubbles: true }); } catch(e){ try { ev = document.createEvent('Event'); ev.initEvent('input', true, false); } catch(e2){ ev = null; } } if(ev && input.dispatchEvent) input.dispatchEvent(ev); } function readSave(input){ var raw = input.getAttribute('data-cc-toggle-save'); if(!raw) return null; try { return JSON.parse(raw); } catch(e){ return null; } } function paintButtons(targetSystem){ var ui = document.getElementById('p4uImp'), um = document.getElementById('p4uMet'); if(ui) ui.classList.toggle('on', targetSystem === 'imp'); if(um) um.classList.toggle('on', targetSystem === 'met'); } function doToggle(targetSystem){ paintButtons(targetSystem); var panel = getPanel(); if(!panel) return; var inputs = getInputs(panel); for(var i = 0; i < inputs.length; i++){ var input = inputs[i]; var fid = input.getAttribute('data-fid') || ''; var kind = classifyFid(fid); if(!kind) kind = classifyLabel(getLabelText(input)); if(!kind || kind === 'never') continue; var sel = getSelect(panel, fid, input); if(!sel) continue; /* cannot determine or flip the unit: skip, never guess */ if(input.value === '' || input.value === null) continue; var currentUnit = canonicalUnit(sel.value, kind); var saved = readSave(input); var res = toggleField({ value: input.value, unit: currentUnit, saved: saved }, targetSystem, kind); if(!res.changed) continue; var newSelectValue; if(res.restored){ newSelectValue = res.selectValue; } else { newSelectValue = targetOptionValue(sel, kind, targetSystem, null); } if(newSelectValue === null || newSelectValue === undefined) continue; /* Verify the option exists; a missing option means a blank select, which is worse than leaving the field alone. */ var hasOpt = false; var opts = sel.options || []; for(var j = 0; j < opts.length; j++){ if(opts[j].value === newSelectValue){ hasOpt = true; break; } } if(!hasOpt) continue; var oldSelectValue = sel.value; if(res.restored){ input.value = res.value; } else { var num = parseFloat(res.value) || 0; input.value = (kind === 'temp') ? fmtTrim(num, 1) : fmtTrim(num, 2); } sel.value = newSelectValue; if(res.saved){ res.saved.selectValue = oldSelectValue; try { input.setAttribute('data-cc-toggle-save', JSON.stringify(res.saved)); } catch(e){} } else { try { input.removeAttribute('data-cc-toggle-save'); } catch(e){} } fireInput(input); } } function clearSaveFor(fid, panel){ if(!panel || !fid) return; var inp = null; try { inp = panel.querySelector('input[data-fid="' + fid + '"]'); } catch(e){ inp = null; } if(inp){ try { inp.removeAttribute('data-cc-toggle-save'); } catch(e){} } } function wireDelegation(){ var c = document.getElementById('ccSingle'); if(!c || c.getAttribute('data-cc-toggle-wired')) return; c.setAttribute('data-cc-toggle-wired', '1'); /* Any manual edit or manual unit change invalidates the saved pair for that field, so a stale value can never return. */ c.addEventListener('input', function(e){ var t = e.target; if(t && t.getAttribute && t.getAttribute('data-fid')) clearSaveFor(t.getAttribute('data-fid'), c); }); c.addEventListener('change', function(e){ var t = e.target; if(!t || !t.getAttribute) return; var fid = t.getAttribute('data-fid') || t.getAttribute('data-funit'); if(fid) clearSaveFor(fid, c); }); } function closestButton(el){ var n = el; while(n){ if(n.id === 'p4uImp' || n.id === 'p4uMet') return n; n = n.parentNode; } return null; } function init(){ if(typeof document === 'undefined') return; if(typeof window !== 'undefined' && window.CC_SINGLE !== 'wcratio' && window.CC_SINGLE !== 'evaporation') return; /* Capture-phase interception: runs before any handler on the button itself, whenever that handler was attached. */ document.addEventListener('click', function(e){ var t = e.target; if(!t) return; var btn = null; if(t.closest){ try { btn = t.closest('#p4uImp,#p4uMet'); } catch(err){ btn = null; } } if(!btn) btn = closestButton(t); if(!btn) return; if(typeof window !== 'undefined' && window.CC_SINGLE !== 'wcratio' && window.CC_SINGLE !== 'evaporation') return; if(e.preventDefault) e.preventDefault(); if(e.stopPropagation) e.stopPropagation(); doToggle(btn.id === 'p4uMet' ? 'met' : 'imp'); }, true); wireDelegation(); if(document.readyState === 'loading'){ document.addEventListener('DOMContentLoaded', wireDelegation); } } init(); if(typeof module !== 'undefined' && module.exports){ module.exports = { cToF: cToF, fToC: fToC, kmhToMph: kmhToMph, mphToKmh: mphToKmh, toggleField: toggleField, classifyFid: classifyFid, classifyLabel: classifyLabel, /* Test-only DOM entry point (not used by the live page). */ _doToggle: doToggle }; } })();