← Commit history
0.4.0: wiki page runs the live calculator (README.html loads the current source from the page repo), UI static mode, shared settings spec
10 files changed
+164−16
CHANGELOG.md+8@@ -1,5 +1,13 @@ # Changelog +## 0.4.0 — 2026-09-25+- The wiki page runs the calculator itself, no install: README.html fetches public/index.html, calcs.js and schematics.js+ from the page repo on every visit (served no-store) and runs them inline in a nested frame, so the page always runs the+ latest pushed source. A status bar shows the version and commit it loaded.+- UI static mode (window.HWCALC_STATIC): in-memory settings, no server calls, Copy link gives a wiki deep link+ (wiki.adom.inc/adom/hardware-calculator#<calc>?k=v), clipboard fallback for sandboxed frames.+- Settings spec moved into calcs.js (SETTINGS_SPEC) so the server and the page build share defaults.+ ## 0.3.0 — 2026-09-25 - Crystal load capacitors upgraded to a full Pierce oscillator CL calculator: caps for a rated CL or CL from C1/C2 (asymmetric), gm_crit and gain margin ≥ 5, drive level from a measured Vpp, frequency pulling and trim sensitivity.
README.htmladded+100@@ -0,0 +1,100 @@+<!doctype html>+<html lang="en"><head>+<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="readme-max-height" content="32000">+<title>Hardware Calculator</title>+<style>+:root { --bg:#0d1117; --panel:#161b22; --line:#262d38; --ink:#e6edf3; --dim:#8b949e; --teal:#00b8b0; }+* { box-sizing: border-box; margin: 0; padding: 0; }+html, body { background: var(--bg); color: var(--ink); font: 15px/1.6 -apple-system, 'Segoe UI', Inter, sans-serif; }+#page { padding: 22px 22px 30px; max-width: 1400px; margin: 0 auto; }+h1 { font-size: 26px; letter-spacing: .01em; } h2 { font-size: 18px; margin: 28px 0 8px; }+p, li { color: #c9d1d9; } p { margin: 6px 0; } ul { margin: 6px 0 6px 20px; } li { margin: 3px 0; }+code { font: 13px ui-monospace, Menlo, monospace; background: var(--panel); border: 1px solid var(--line); border-radius: 5px; padding: 1px 5px; color: #d2dae4; }+pre { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; margin: 8px 0; overflow-x: auto; }+pre code { border: 0; background: none; padding: 0; }+a { color: #58a6ff; }+.lead { font-size: 16px; color: #dfe6ee; max-width: 900px; }+.live { margin-top: 18px; border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--panel); }+.bar { display: flex; align-items: center; gap: 10px; padding: 8px 14px; border-bottom: 1px solid var(--line); font-size: 12.5px; color: var(--dim); }+.bar .dot { width: 8px; height: 8px; border-radius: 50%; background: #3fb950; box-shadow: 0 0 6px #3fb950; }+.bar .dot.wait { background: #d29922; box-shadow: none; } .bar .dot.bad { background: #f85149; box-shadow: none; }+#app { display: block; width: 100%; height: 880px; border: 0; background: var(--bg); }+#app[hidden] { display: none; }+#msg { padding: 40px; text-align: center; color: var(--dim); }+</style></head>+<body><div id="page">+<h1>Hardware Calculator</h1>+<p class="lead">40 hardware design calculators whose every number traces to a standard, with a live schematic of the circuit you are sizing.+Trace width to IPC-2152, clearance to IPC-2221C, impedance to IPC-2141, crystal load caps and oscillator start-up margin to ST AN2867,+I²C pull-ups to NXP UM10204. Try it right here: this is the real app, loaded live from this page's source.</p>++<div class="live">+ <div class="bar"><span class="dot wait" id="dot"></span><span id="status">Loading the calculator from the page repo…</span></div>+ <div id="msg">Loading…</div>+ <iframe id="app" title="Hardware Calculator" hidden></iframe>+</div>++<h2>Install it for your AI and terminal</h2>+<p>The page above runs in your browser with no install. Install the app to let your AI open and fill calculations for you, use the CLI, and keep your settings.</p>+<pre><code>adom-wiki pkg install adom/hardware-calculator+hwcalc --ai-thread "<name>" start # opens the calculator in a Hydrogen tab</code></pre>++<h2>Say it to your AI</h2>+<ul>+ <li>"with the hardware calculator, what trace width for 3 A at 20 °C rise on 2 oz?"</li>+ <li>"size the load caps for a 12 pF crystal and check the gain margin with 25 mA/V gm"</li>+ <li>"hardware calculator: clearance for 300 V on an external coated layer"</li>+ <li>"open the hardware calculator on a buck from 12 V to 3.3 V at 2 A, 500 kHz"</li>+</ul>+<p>Or from the terminal, no server needed: <code>hwcalc calc trace I=3 dT=20 oz=2</code>, <code>hwcalc calc crystal CL=12p Cs=4p --svg osc.svg</code>.</p>++<h2>Why you can trust it</h2>+<ul>+ <li><b>Standards checked for currency.</b> IPC-2221 is Rev C (Dec 2023), IPC-2152 is still Rev 0 (2009), and so on. Every source, its revision and the date it was checked is in <a href="https://wiki.adom.inc/adom/hardware-calculator/files/SOURCES.md" target="_blank">SOURCES.md</a>.</li>+ <li><b>No undisclosed fits.</b> Where a standard is chart-only (IPC-2152) the published curve fit is named; where a table is paywalled (IPC-2221 Table 6-1) the values were cross-checked against two independent reproductions.</li>+ <li><b>Tested against the sources' own worked examples</b>, for example AN2867's 8 MHz crystal: gm_crit 0.23 mA/V and gain margin 107. 140 automated checks run on every change.</li>+ <li><b>Honest limits.</b> Closed-form impedance says ±5–10 % and to confirm with your fab's field solver; unmodelled effects are stated under each result.</li>+</ul>++<h2>Contributing</h2>+<p>Anyone in the adom org can publish. Every change follows the <code>hwcalc-calculator-standards</code> skill (Skills tab, Dev): source fetched and revision+confirmed, a test reproducing the source's worked example, a labelled drawing for any circuit, and the sources register updated. Releases follow+<code>hwcalc-release</code> (Skills tab, Publish). A change pushed to this page's source shows up in the calculator above on the next page load.</p>+</div>++<script>+// Loads the app's own UI and formula modules from this page's repo on every visit (served no-store), so the embedded+// calculator is always the latest pushed source. The sandbox serves .js as octet-stream (no <script src>), so the code is+// fetched as text and inlined into a srcdoc frame (inline scripts are allowed; eval is not needed).+(async () => {+ const PAGE = 'https://wiki.adom.inc/adom/hardware-calculator', RAW = PAGE + '/render/';+ const $ = s => document.querySelector(s), setStatus = (t, cls) => { $('#status').textContent = t; $('#dot').className = 'dot' + (cls ? ' ' + cls : ''); };+ let pendingHash = '';+ addEventListener('message', e => {+ const m = e.data || {};+ if (m.type === 'readme-hash' && m.hash) { pendingHash = m.hash; const f = $('#app'); if (f.contentWindow) f.contentWindow.postMessage({ type: 'hwcalc-open', hash: m.hash }, '*'); }+ });+ try {+ const get = p => fetch(RAW + p, { cache: 'no-store' }).then(r => { if (!r.ok) throw new Error(p + ' ' + r.status); return r.text(); });+ const [html, calcs, schem, pkg] = await Promise.all([get('public/index.html'), get('calcs.js'), get('schematics.js'), get('package.json')]);+ let commit = ''; try { commit = (await (await fetch('https://wiki.adom.inc/api/pages/adom/hardware-calculator')).json()).page.last_commit_hash || ''; } catch {}+ const version = JSON.parse(pkg).version;+ const boot = { version, commit, pageUrl: PAGE, hash: pendingHash };+ const inline = code => '<script>' + code.replace(/<\/script/gi, '<\\/script') + '<\/script>';+ let doc = html.replace('<script src="calcs.js"></scr' + 'ipt>', () => '<script>window.HWCALC_STATIC = ' + JSON.stringify(boot) + '<\/script>' + inline(calcs))+ .replace('<script src="schematics.js"></scr' + 'ipt>', () => inline(schem));+ if (!doc.includes('HWCALC_STATIC')) throw new Error('unexpected index.html layout');+ const f = $('#app'); f.srcdoc = doc; f.hidden = false; $('#msg').remove();+ f.addEventListener('load', () => { if (pendingHash) f.contentWindow.postMessage({ type: 'hwcalc-open', hash: pendingHash }, '*'); }, { once: true });+ setStatus(`Live: v${version}${commit ? ' @ ' + commit.slice(0, 7) : ''}, loaded from this page's source just now. Runs entirely in your browser.`);+ } catch (err) {+ setStatus('Could not load the calculator: ' + err.message, 'bad');+ $('#msg').textContent = 'The live calculator could not be loaded here. Install it instead: adom-wiki pkg install adom/hardware-calculator';+ }+})();+// Size the wiki frame to the content (measure the wrapper, never documentElement: that ratchets).+const fit = () => parent.postMessage({ type: 'readme-height', height: Math.ceil(document.getElementById('page').getBoundingClientRect().height) + 8 }, '*');+addEventListener('load', fit); new ResizeObserver(fit).observe(document.getElementById('page')); fit();+</script>+</body></html>
SOURCES.md+1−1@@ -1,6 +1,6 @@ # Hardware Calculator — sources register -Generated by `node scripts/sources.js` for v0.3.0. Do not edit the calculator table by hand;+Generated by `node scripts/sources.js` for v0.4.0. Do not edit the calculator table by hand; edit `ref` / `formula` in calcs.js and regenerate. The standards register above it is maintained by hand in `docs/standards.md`.
calcs.js+11−1@@ -890,5 +890,15 @@ inputs: c.inputs.map(f => ({ key: f.key, label: f.label, unit: f.unit || '', type: f.type || 'number', options: f.options, def: f.def, show: f.show, si: f.si !== false, setting: f.setting })) })); } - return { CALCS, run, catalog, parseNum, fmtSI, fmtN, eNearest, eValuesInRange, E_BASE, colourBands, eia96, visible, inputsFor };+ // Settings shared by the server (validated, persisted) and the static wiki build (in memory). ui: shown on the wiki page.+ const SETTINGS_SPEC = {+ e_series: { type: 'enum', values: ['E6', 'E12', 'E24', 'E48', 'E96', 'E192'], def: 'E24', label: 'Default E-series for resistor picks', ui: true },+ trace_dT: { type: 'number', min: 1, max: 100, def: 10, label: 'Default trace temperature rise (°C)', ui: true },+ show_formulas: { type: 'bool', def: true, label: 'Show formula and reference under results', ui: true },+ show_schematics: { type: 'bool', def: true, label: 'Show the schematic / cross-section drawing', ui: true },+ ttl_hours: { type: 'number', min: 1, max: 720, def: 24, label: 'Shut the server down after this many idle hours' },+ default_surface: { type: 'enum', values: ['wv', 'pup'], def: 'wv', label: 'Where "hwcalc show" opens the app' },+ };++ return { CALCS, SETTINGS_SPEC, run, catalog, parseNum, fmtSI, fmtN, eNearest, eValuesInRange, E_BASE, colourBands, eia96, visible, inputsFor }; });
dev-skills/hwcalc-calculator-standards/SKILL.md+7@@ -115,6 +115,13 @@ adom-cli hydrogen screenshot panel --name "Hardware Calculator" --reason "verify Read the screenshot: the results, the warning and note boxes, and the drawing under Results. +The wiki page runs the same UI with no server (README.html inlines `public/index.html`, `calcs.js` and `schematics.js`+from the page repo in a sandboxed frame, `window.HWCALC_STATIC` set). So a calculator must work entirely in the browser:+no server-only data, no `fetch` from `compute`. Keep the two exact tags `<script src="calcs.js"></script>` and+`<script src="schematics.js"></script>` in `public/index.html` (the page build replaces them; `test.js` guards this).+After the release push, open https://wiki.adom.inc/adom/hardware-calculator and confirm the status bar shows the new+commit and the changed calculator works there too.+ ## Gate 6 — record it - `docs/standards.md`: add or update the source's row (revision, date checked, how it is used).
package.json+2−2@@ -2,7 +2,7 @@ "slug": "hardware-calculator", "title": "Hardware Calculator", "name": "hardware-calculator",- "version": "0.3.0",+ "version": "0.4.0", "type": "app", "description": "40 hardware design calculators whose every number traces to a standard (IPC-2152/2221C/2141, ST AN2867, NXP UM10204, IEC 60063), with live labelled schematics and PCB cross-sections. Hydrogen UI, CLI and HTTP API.", "dependencies": {},@@ -46,7 +46,7 @@ "SOURCES.md", "CHANGELOG.md" ],- "changelog": "0.3.0: AN2867-verified crystal oscillator CL calculator; live schematics for 26 calculators; sources register",+ "changelog": "0.4.0: the wiki page runs the live calculator (README.html loads the current source from the page repo); static mode in the UI", "discovery_triggers": [ "hardware calculator", "hwcalc",
public/index.html+22−4@@ -104,6 +104,15 @@ tbody tr:first-child td { color: var(--teal); } const H = window.HWCALC, $ = s => document.querySelector(s); const CAT = H.catalog(); let settings = {}, spec = {}, cur = 'divider', vals = {}, lastRes = null, usedHash = false, seenRev = 0;+// STATIC: the wiki page build (no server). The host sets window.HWCALC_STATIC = { version, commit, pageUrl, hash }.+const STATIC = window.HWCALC_STATIC || null;+function copyText(text, msg) {+ const done = () => toast(msg), fallback = () => {+ const t = document.createElement('textarea'); t.value = text; t.style.position = 'fixed'; t.style.opacity = '0'; document.body.appendChild(t); t.select();+ let ok = false; try { ok = document.execCommand('copy'); } catch {} t.remove(); ok ? done() : toast('Copy blocked here. Select and copy: ' + text); };+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, fallback); else fallback();+}+const openHash = hs => { const [hc, hq] = String(hs || '').replace(/^#/, '').split('?'); if (hc && CAT.find(c => c.id === hc)) { select(hc, Object.fromEntries(new URLSearchParams(hq || ''))); return true; } return false; }; const toast = m => { const t = $('#toast'); t.textContent = m; t.classList.add('on'); clearTimeout(t._h); t._h = setTimeout(() => t.classList.remove('on'), 1600); }; const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); @@ -164,17 +173,17 @@ function compute() { const svg = settings.show_schematics !== false && window.HWSCHEM ? HWSCHEM.draw(cur, vals, settings) : null; $('#schemCard').hidden = !svg; if (svg) { $('#schem').innerHTML = svg; $('#schemH').textContent = cur === 'spiral' ? 'Layout' : /impedance|diffpair|trace|via|spacing/.test(cur) ? 'Cross-section' : 'Schematic'; } }-$('#out').addEventListener('click', e => { if (e.target.classList.contains('v')) { navigator.clipboard?.writeText(e.target.textContent); toast('Copied ' + e.target.textContent); } });+$('#out').addEventListener('click', e => { if (e.target.classList.contains('v')) copyText(e.target.textContent, 'Copied ' + e.target.textContent); }); $('#copy').onclick = () => { const r = lastRes; if (!r) return; const lines = [r.title, ...Object.entries(vals).map(([k, v]) => ` ${k} = ${v}`), ...(r.outputs || []).map(o => `${o.label}: ${o.text}`), `Formula: ${r.formula}`, `Ref: ${r.ref}`];- navigator.clipboard?.writeText(lines.join('\n')); toast('Results copied');+ copyText(lines.join('\n'), 'Results copied'); };-$('#link').onclick = () => { navigator.clipboard?.writeText(location.href); toast('Link copied (opens this calculation with these inputs)'); };+$('#link').onclick = () => { const h = '#' + cur + '?' + new URLSearchParams(vals).toString(); copyText(STATIC ? STATIC.pageUrl + h : location.href, 'Link copied (opens this calculation with these inputs)'); }; $('#reset').onclick = () => { select(cur); toast('Defaults restored'); }; let pushT = null; const pushSoon = () => { clearTimeout(pushT); pushT = setTimeout(pushState, 500); };-function pushState() { fetch('ui/state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ calc: cur, inputs: vals }) }).catch(() => {}); }+function pushState() { if (STATIC) return; fetch('ui/state', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ calc: cur, inputs: vals }) }).catch(() => {}); } // settings function renderSettings() {@@ -186,6 +195,7 @@ function renderSettings() { $('#sets').addEventListener('change', async e => { const k = e.target.dataset.s; if (!k) return; let v = e.target.value; if (spec[k].type === 'bool') v = v === 'on'; if (spec[k].type === 'number') v = Number(v);+ if (STATIC) { settings[k] = v; toast('Applied (this page only)'); compute(); return; } const r = await (await fetch('settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ [k]: v, aiThread: 'ui (human)' }) })).json(); if (r.ok) { settings = r.settings; toast('Saved'); compute(); } else { toast(r.error); renderSettings(); } });@@ -194,6 +204,14 @@ $('#close').onclick = () => $('#modal').classList.remove('on'); $('#modal').onclick = e => { if (e.target.id === 'modal') $('#modal').classList.remove('on'); }; (async () => {+ if (STATIC) {+ spec = Object.fromEntries(Object.entries(H.SETTINGS_SPEC).filter(([, s]) => s.ui));+ settings = Object.fromEntries(Object.entries(spec).map(([k, s]) => [k, s.def]));+ $('#ver').textContent = 'v' + STATIC.version; $('#sver').textContent = `Hardware Calculator ${STATIC.version} · live from the page repo${STATIC.commit ? ' @ ' + STATIC.commit.slice(0, 7) : ''} · settings last for this visit`;+ if (!openHash(STATIC.hash)) select('crystal');+ addEventListener('message', e => { const m = e.data || {}; if (m.type === 'hwcalc-open' && m.hash) openHash(m.hash); });+ return;+ } try { const s = await (await fetch('settings')).json(); settings = s.settings; spec = s.spec; const st = await (await fetch('state')).json(); seenRev = st.openRev || 0; $('#ver').textContent = 'v' + st.version; $('#sver').textContent = `hwcalc ${st.version} · port ${st.port}`;
publish-skills/hwcalc-release/SKILL.md+4@@ -21,6 +21,10 @@ adom-wiki pkg publish --org adom # the installable: CLI, server, UI, u adom-wiki repo push adom/hardware-calculator -m "<version>: <what changed and which source verified it>" ``` +The wiki page body is `README.html` (it wins over README.md): hand-maintained prose plus the live calculator, which+loads the pushed source on every visit, so a `repo push` of `calcs.js` / `schematics.js` / `public/index.html` updates the+page's calculator immediately. Keep README.html's prose in step with README.md (README.md ships in the tarball).+ `pkg publish` ships only the user skill (`skills/`); `repo push` puts the whole source on the page, including `dev-skills/` and `publish-skills/`. Do both on every release, or the Files tab and the installable drift apart.
server.js+1−8@@ -16,14 +16,7 @@ fs.mkdirSync(path.join(HOME, 'snapshots'), { recursive: true }); const REG = path.join(HOME, slug(THREAD) + '.json'), SNAP = path.join(HOME, 'snapshots', slug(THREAD) + '.json'), SETF = path.join(HOME, 'settings.json'); // ---------------------------------------------------------------- settings (server-side, persisted)-const SETTINGS_SPEC = {- e_series: { type: 'enum', values: ['E6', 'E12', 'E24', 'E48', 'E96', 'E192'], def: 'E24', label: 'Default E-series for resistor picks' },- trace_dT: { type: 'number', min: 1, max: 100, def: 10, label: 'Default trace temperature rise (°C)' },- show_formulas: { type: 'bool', def: true, label: 'Show formula and reference under results' },- show_schematics: { type: 'bool', def: true, label: 'Show the schematic / cross-section drawing' },- ttl_hours: { type: 'number', min: 1, max: 720, def: 24, label: 'Shut the server down after this many idle hours' },- default_surface: { type: 'enum', values: ['wv', 'pup'], def: 'wv', label: 'Where "hwcalc show" opens the app' },-};+const SETTINGS_SPEC = H.SETTINGS_SPEC; let settings = Object.fromEntries(Object.entries(SETTINGS_SPEC).map(([k, s]) => [k, s.def])); try { Object.assign(settings, JSON.parse(fs.readFileSync(SETF, 'utf8'))); } catch {} const argTtl = arg('--ttl'); if (argTtl) settings.ttl_hours = Number(argTtl);
test.js+8@@ -111,4 +111,12 @@ for (const c of H.CALCS) { const rr = H.run(c.id, {}); if (!rr.ok) { n++; fail++ const variants = [{}]; for (const f of c.inputs) if (f.type === 'select') for (const opt of f.options) variants.push({ [f.key]: opt }); for (const v of variants) { const svg = S.draw(id, v); n++; if (!svg || !svg.startsWith('<svg') || /undefined|NaN/.test(svg)) bad.push(id + ' ' + JSON.stringify(v)); } } check(`schematics render (${n} variants, ${S.ids.length} drawings)`, bad.length, 0); if (bad.length) console.log(' bad:', bad.join('; ')); }++// wiki page build: README.html inlines calcs.js / schematics.js by replacing these exact tags in public/index.html+{ const fs = require('fs'), html = fs.readFileSync(__dirname + '/public/index.html', 'utf8'), readme = fs.readFileSync(__dirname + '/README.html', 'utf8');+ check('index.html has the calcs.js tag README.html replaces', html.includes('<script src="calcs.js"></script>') ? 1 : 0, 1);+ check('index.html has the schematics.js tag README.html replaces', html.includes('<script src="schematics.js"></script>') ? 1 : 0, 1);+ check('index.html supports static mode', html.includes('window.HWCALC_STATIC') ? 1 : 0, 1);+ const hostJs = readme.slice(readme.indexOf('<script>'), readme.lastIndexOf('</script>') + 1);+ check('README.html host script has no literal closing script tag', (hostJs.match(/<\/script/gi) || []).length, 0); } console.log(`${n - fail}/${n} checks passed`); process.exit(fail ? 1 : 0);