From 4db4957113d55ab82b53c17761bbdaa77891d3bd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 1 Aug 2026 03:26:38 +0000 Subject: [PATCH 1/2] Add a GP % / markup % converter to the header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A supplier offering "25%" and a customer expecting "25%" can mean different money: same profit, different denominator. GP divides it by the selling price, markup by the cost. The button sits beside Quote and opens a two-field dialog where either value drives the other. markup = GP / (100 - GP) GP = markup / (100 + markup) Named to match what is already on screen. This app calls profit÷CP "Margin %", which is markup, so the field says so rather than introducing a third word for the same number. The result is also shown as money — buy at ₹100.00, sell at ₹125.00, profit ₹25.00 — because a percentage on its own is easy to nod along to without picturing it. "Use this calculation" seeds it from whatever is on screen, and hides itself when there is nothing to seed from. Both ends where there is no finite answer are handled rather than left to produce Infinity: a GP of 100% would mean the goods cost nothing, and a markup of -100% would mean selling for nothing. Each says which, in words. Given a switch in Settings → Features like the other header entry points. It is the only stateless feature there — it reads two numbers and stores none — so it has nothing to report or clear when switched off. 36 assertions, including seven GP/markup pairs each checked in both directions, the two undefined ends, and that the seeded markup equals the Margin % the app is showing at the time. Contrast swept in both themes, axe extended to the new dialog. 1442 assertions. --- README.md | 31 +++++++++++-- assets/app.js | 103 ++++++++++++++++++++++++++++++++++++++++- assets/styles.css | 17 +++++++ index.html | 40 ++++++++++++++++ tests/README.md | 6 +-- tests/a11y.test.js | 7 +-- tests/features.test.js | 93 +++++++++++++++++++++++++++++++++---- 7 files changed, 276 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 3e65223..7060a81 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Pricing Calculator -[![Tests](https://github.com/sterlingspares/calc/actions/workflows/tests.yml/badge.svg)](https://github.com/sterlingspares/calc/actions/workflows/tests.yml) ![Tests](https://img.shields.io/badge/tests-1406%20passing-brightgreen?style=flat-square) ![Coverage](https://img.shields.io/badge/coverage-80%25-green?style=flat-square) ![Lighthouse Performance](https://img.shields.io/badge/Lighthouse%20Perf-97-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Accessibility](https://img.shields.io/badge/Lighthouse%20A11y-100-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Best Practices](https://img.shields.io/badge/Best%20Practices-100-brightgreen?style=flat-square&logo=lighthouse) ![a11y](https://img.shields.io/badge/WCAG%202.1-AA-brightgreen?style=flat-square) ![PWA](https://img.shields.io/badge/PWA-offline--ready-brightgreen?style=flat-square&logo=pwa) ![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square) ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) +[![Tests](https://github.com/sterlingspares/calc/actions/workflows/tests.yml/badge.svg)](https://github.com/sterlingspares/calc/actions/workflows/tests.yml) ![Tests](https://img.shields.io/badge/tests-1442%20passing-brightgreen?style=flat-square) ![Coverage](https://img.shields.io/badge/coverage-80%25-green?style=flat-square) ![Lighthouse Performance](https://img.shields.io/badge/Lighthouse%20Perf-97-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Accessibility](https://img.shields.io/badge/Lighthouse%20A11y-100-brightgreen?style=flat-square&logo=lighthouse) ![Lighthouse Best Practices](https://img.shields.io/badge/Best%20Practices-100-brightgreen?style=flat-square&logo=lighthouse) ![a11y](https://img.shields.io/badge/WCAG%202.1-AA-brightgreen?style=flat-square) ![PWA](https://img.shields.io/badge/PWA-offline--ready-brightgreen?style=flat-square&logo=pwa) ![License](https://img.shields.io/badge/license-MIT-blue?style=flat-square) ![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) **Live app:** [calc.sterlingspares.com](https://calc.sterlingspares.com) @@ -449,6 +449,26 @@ takes its own SP input (discount % or manual ₹) and shows SP, Profit ₹, GP % Margin %. The highest-GP scenario is highlighted automatically, and everything updates live. +### GP % / markup % converter + +Two ways of quoting the same profit, over different denominators — which is why +a supplier offering "25%" and a customer expecting "25%" can mean different +money. **GP ⇄ Markup** in the header takes either and returns the other: + +| GP % | Markup % | +|---:|---:| +| 20.00 | 25.00 | +| 25.00 | 33.33 | +| 50.00 | 100.00 | + +`markup = GP ÷ (100 − GP)` and `GP = markup ÷ (100 + markup)`. It shows the +result as money as well — *buy at ₹100.00, sell at ₹125.00* — because a +percentage on its own is easy to nod along to. **Use this calculation** seeds it +from whatever is on screen, and the two ends with no finite answer (100% GP, +−100% markup) say so rather than blanking. + +Markup % is what this app calls **Margin %** elsewhere. + ### Quote builder A multi-line quoting tool — press `M`, or use **Quote** in the header / menu. @@ -562,6 +582,7 @@ and it disappears from the screen: | | | |---|---| | **Presets** | the header button, menu entry and the manager | +| **GP / markup converter** | the header button | | **Quote builder** | the header button, menu item and bottom-nav tab | | **What-if scenarios** | the button on the summary | | **Landed costs** | both fields in the MRP bar | @@ -743,7 +764,7 @@ Every number here is reproducible from the repo — none is hand-written. | Metric | Value | Reproduce with | |---|---|---| -| Tests | 1406 passing, 7 suites | `npm test` | +| Tests | 1442 passing, 7 suites | `npm test` | | Statement coverage | **82.7%** (app.js 86.3%, app-extra.js 72.3%) | `npm run coverage` | | Lighthouse Performance | **97** | `npm i -D lighthouse && npm run lighthouse` | | Lighthouse Accessibility | **100** | ” | @@ -780,7 +801,7 @@ commands after significant changes. ## Tests -1406 assertions across seven suites. They load the real `index.html`, +1442 assertions across seven suites. They load the real `index.html`, `assets/styles.css` and both script bundles, and drive the actual application functions — no application code is mocked. **Node 22 or newer.** @@ -791,12 +812,12 @@ npm test | Suite | Assertions | Covers | |---|---|---| -| `features` | 979 | GST, incentives, quantity, landed costs, rounding, undo/redo, quote maths, history | +| `features` | 1014 | GST, incentives, quantity, landed costs, rounding, undo/redo, quote maths, history | | `errors` | 33 | every failure path logs; a clean run stays silent; storage and payload recovery | | `mobile` | 78 | modal layering, touch targets, sticky result bar, responsive quote layouts | | `fab` | 50 | floating action button behaviour and z-index ordering | | `modes` | 85 | solve modes, price input modes, what-if, comparison, Quick mode, wizard, share-link round trip, theming, auto-save | -| `a11y` | 103 | contrast ratios, structure, names, keyboard operability, focus trap, live regions, reduced motion, axe-core | +| `a11y` | 104 | contrast ratios, structure, names, keyboard operability, focus trap, live regions, reduced motion, axe-core | | `browser` | 78 | real Chromium over HTTP: asset loading, CSS cascade, `defer` timing, clicks, dialogs, mobile viewport, axe with layout | Individual suites: `npm run test:features`, `test:errors`, `test:mobile`, diff --git a/assets/app.js b/assets/app.js index 606beff..838f6b1 100644 --- a/assets/app.js +++ b/assets/app.js @@ -1139,7 +1139,7 @@ function closeModal(id){ * @param {string} id overlay suffix */ function overlayClick(e,id){if(e.target===el('overlay-'+id))closeModal(id)} -document.addEventListener('keydown',function(e){if(e.key==='Escape'){closeModal('settings');closeModal('whatif');closeModal('quote');closeModal('presets');closeConfirm();closePrompt();closeFab()}}); +document.addEventListener('keydown',function(e){if(e.key==='Escape'){closeModal('settings');closeModal('whatif');closeModal('quote');closeModal('presets');closeConfirm();closePrompt();closeConvert();closeFab()}}); /** * Handler for the custom GST box. Rejects anything outside 0–100 and says so, @@ -1174,7 +1174,7 @@ function onCustomGST(inp){ adding a feature is one entry rather than edits in four places, and the tests can walk the registry rather than naming elements by hand. ─────────────────────────────────────────────────────────────────────────── */ -var FEATURES={presets:true,quote:true,whatif:true,landed:true,solver:true,inccp:true,incsp:true}; +var FEATURES={presets:true,convert:true,quote:true,whatif:true,landed:true,solver:true,inccp:true,incsp:true}; /** True when the named feature is switched on. Unknown keys read as on. */ function featOn(k){ return FEATURES[k]!==false } @@ -1185,6 +1185,11 @@ var FEATURE_DEFS=[ values:function(){ var n=Object.keys(PRESETS).length; return n?[n+' saved preset'+(n===1?'':'s')]:[] }, clear:function(){ PRESETS={}; savePresets(); renderPresetList(); renderPresetManager(); }}, + {k:'convert',name:'GP / markup converter',hint:'Translate between the two ways of quoting a margin.', + els:['hbtn-convert'], + values:function(){ return [] }, + clear:function(){ closeConvert(); }}, + {k:'quote',name:'Quote builder',hint:'Multi-line quotes with blended GP.', els:['hbtn-quote','hmenu-quote','bnav-quote'], values:function(){ return QUOTE.length?[QUOTE.length+' quote line'+(QUOTE.length===1?'':'s')]:[] }, @@ -1305,6 +1310,100 @@ function factoryReset(){ } ACT.factoryReset = function(){ factoryReset() }; +/* ── GP % / markup % converter ────────────────────────────────────────────── + The same profit over two different denominators, which is why a supplier + offering "25%" and a customer expecting "25%" can mean different money. + GP = profit / selling price + markup = profit / cost price (what this app calls Margin %) + so markup = GP / (100 - GP) and GP = markup / (100 + markup). + ─────────────────────────────────────────────────────────────────────────── */ +/** + * @param {number} gp gross profit percentage + * @returns {number|null} markup %, or null where it has no finite answer + */ +function gpToMarkup(gp){ + if(isNaN(gp)||gp>=100)return null; // at 100% GP the cost is zero + return (gp/(100-gp))*100; +} +/** + * @param {number} mk markup percentage + * @returns {number|null} GP %, or null where it has no finite answer + */ +function markupToGp(mk){ + if(isNaN(mk)||mk<=-100)return null; // at -100% markup the sale is zero + return (mk/(100+mk))*100; +} +/** + * Recompute the other field and the worked line beneath. + * @param {'gp'|'mk'} from which field the user is typing in + */ +function renderConvert(from){ + var gpEl=el('cv-gp'), mkEl=el('cv-mk'), out=el('cv-out'); + if(!gpEl||!mkEl||!out)return; + var raw=(from==='gp'?gpEl:mkEl).value; + if(String(raw).trim()===''){ + (from==='gp'?mkEl:gpEl).value=''; + out.textContent='';out.className='cv-out'; + return; + } + var v=parseFloat(raw); + var other=(from==='gp')?gpToMarkup(v):markupToGp(v); + if(other===null){ + (from==='gp'?mkEl:gpEl).value=''; + out.textContent=(from==='gp') + ? 'A GP of 100% or more would mean the goods cost nothing — there is no markup that matches.' + : 'A markup of −100% or less would mean selling for nothing — there is no GP that matches.'; + out.className='cv-out bad'; + return; + } + (from==='gp'?mkEl:gpEl).value=String(+other.toFixed(4)); + // Ground it in money: percentages either way are easy to nod along to. + var gp=(from==='gp')?v:other; + var cost=100, sale=(gp>=100)?null:(cost/(1-gp/100)); + if(sale===null||!isFinite(sale)){ out.textContent='';out.className='cv-out'; return } + out.textContent='Buy at '+INR_RS(cost)+', sell at '+INR_RS(sale)+' — profit '+ + INR_RS(sale-cost)+', which is '+PCT(gp)+' of the sale and '+ + PCT((from==='gp')?other:v)+' of the cost.'; + out.className='cv-out'; +} +/** Open the converter, seeded from the calculation on screen when there is one. */ +function openConvert(){ + if(!featOn('convert'))return; + var o=el('overlay-convert'); + if(!o)return; + _lastFocused=document.activeElement; + o.classList.add('open'); + document.body.style.overflow='hidden'; + pushOverlay(o); + var use=el('cv-use'); + if(use)use.style.display=(LAST_CP&&LAST_SP)?'':'none'; + setTimeout(function(){ var f=el('cv-gp'); if(f){f.focus();if(f.select)f.select()} },30); +} +/** Close it. */ +function closeConvert(){ + var o=el('overlay-convert'); + if(o&&o.classList.contains('open')){ + o.classList.remove('open'); + popOverlay(o); + if(_lastFocused&&_lastFocused.focus)_lastFocused.focus(); + } +} +/** Pull the GP the calculator is currently showing into the converter. */ +function convertUseCurrent(){ + if(!LAST_CP||!LAST_SP)return; + var effSP=effectiveSP(LAST_SP), effCP=effectiveCP(LAST_CP); + if(!effSP||effSP<=0)return; + var gp=((effSP-effCP)/effSP)*100; + var f=el('cv-gp'); + if(f){ f.value=String(+gp.toFixed(4)); renderConvert('gp'); } +} +ACT.openConvert = function(){ openConvert() }; +ACT.convertClose = function(){ closeConvert() }; +ACT.convertOverlay = function(self,event){ if(event.target===el('overlay-convert'))closeConvert() }; +ACT.convertFromGp = function(){ renderConvert('gp') }; +ACT.convertFromMk = function(){ renderConvert('mk') }; +ACT.convertUseCurrent = function(){ convertUseCurrent() }; + /* ── Settings tabs ────────────────────────────────────────────────────────── Eight stacked sections became a long scroll that was hard to find anything in. They are grouped into four panes behind a nav rail, which becomes a diff --git a/assets/styles.css b/assets/styles.css index 74beb23..dbc2ad1 100644 --- a/assets/styles.css +++ b/assets/styles.css @@ -856,6 +856,20 @@ html[data-theme="dark"] .lbl-field:focus-within{box-shadow:0 0 0 3px rgba(240,23 /* The last section in a pane has nothing under it to separate from. */ .settings-pane .modal-section:last-child{border-bottom:none;margin-bottom:0;padding-bottom:0} +/* ── GP / markup converter ── */ +.cv-intro{font-size:12px;color:var(--text2);line-height:1.55;margin:0 0 16px} +.cv-pair{display:flex;align-items:flex-start;gap:12px} +.cv-field{flex:1;min-width:0;display:flex;flex-direction:column;gap:5px;cursor:text} +.cv-lbl{font-size:10px;letter-spacing:.09em;text-transform:uppercase;color:var(--text3);font-weight:600} +.cv-input{display:flex;align-items:center;border:1.5px solid var(--border-ctrl);border-radius:var(--radius-sm);background:var(--surface2);padding:0 10px} +.cv-input:focus-within{border-color:var(--text2)} +.cv-input input{flex:1;min-width:0;border:none;background:transparent;outline:none;padding:10px 0;font-family:var(--font-mono);font-size:17px;font-weight:600;color:var(--text);-moz-appearance:textfield} +.cv-input input::-webkit-outer-spin-button,.cv-input input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0} +.cv-input::after{content:'%';font-size:12px;color:var(--text3);margin-left:4px} +.cv-hint{font-size:10.5px;color:var(--text3);line-height:1.4} +.cv-swap{align-self:center;margin-top:14px;font-size:16px;color:var(--text3);flex-shrink:0} +.cv-out{font-size:11.5px;line-height:1.55;color:var(--text2);min-height:34px;margin:14px 0 0} +.cv-out.bad{color:var(--amber)} .feat-intro{font-size:12px;color:var(--text2);line-height:1.55;margin:0 0 12px} .feat-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px} .feat-chip{display:flex;flex-direction:column;gap:2px;text-align:left;padding:10px 12px;border-radius:var(--radius-sm);border:1px solid var(--border-ctrl);background:transparent;cursor:pointer;font-family:var(--font-body);transition:all .15s;min-height:44px} @@ -949,6 +963,9 @@ html[data-theme="dark"] .qt-del:hover{background:rgba(239,68,68,0.15)} sits before the base rules they override — so .pm-btn kept its 30px height and .fx-note kept nowrap. Same specificity, later wins. */ .inc-pair{grid-template-columns:1fr;gap:10px} + .cv-pair{flex-direction:column;gap:14px} + .cv-swap{align-self:flex-start;margin-top:0;transform:rotate(90deg)} + .cv-input input{min-height:44px} .solver{grid-column:1/-1;padding-top:10px;border-top:1px solid rgba(255,255,255,0.16)} .fx-note{white-space:normal;width:100%} .fx-manual-wrap input{min-height:44px} diff --git a/index.html b/index.html index 9bce152..2209206 100644 --- a/index.html +++ b/index.html @@ -106,6 +106,10 @@

Price Calc

Presets + + + + + +
- Disc + Discount % + 18% GST
diff --git a/package.json b/package.json index 8b34019..94be98e 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,8 @@ "test:browser": "node tests/browser.test.js", "test:modes": "node tests/modes.test.js", "coverage": "node tests/coverage.js", - "lighthouse": "node tests/lighthouse.js" + "lighthouse": "node tests/lighthouse.js", + "screenshots": "node tests/screenshots.js" }, "devDependencies": { "acorn": "^8.18.0", diff --git a/tests/README.md b/tests/README.md index aae6d0f..ad8a85f 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,6 @@ # Tests -1442 assertions across seven suites. They load the real `index.html`, +1479 assertions across seven suites. They load the real `index.html`, `assets/styles.css` and `assets/app.js` into [jsdom](https://github.com/jsdom/jsdom) and drive the actual application functions — no application code is mocked. @@ -25,6 +25,7 @@ npm test # run everything | `npm run test:browser` | real Chromium (skips if none is installed) | | `npm run coverage` | statement coverage of both bundles | | `npm run lighthouse` | Lighthouse audit (needs `npm i -D lighthouse`) | +| `npm run screenshots` | regenerate the two screenshots the README embeds | Failing suites print their full output; passing ones print a single line. The runner exits non-zero if anything fails, so CI catches it. @@ -33,11 +34,11 @@ The runner exits non-zero if anything fails, so CI catches it. | File | Assertions | Covers | |---|---|---| -| `features.test.js` | 1014 | GST (presets, custom, decimal), incentive edit mode, add/delete/rename, %/₹ modes, quantity and order totals, rounding, undo/redo, quote maths, history search/filter/tags, share-state round trips | +| `features.test.js` | 1041 | GST (presets, custom, decimal), incentive edit mode, add/delete/rename, %/₹ modes, quantity and order totals, rounding, undo/redo of typed values and every control, quote maths, history search/filter/tags, share-state round trips | | `errors.test.js` | 33 | every failure path logs; a clean run logs nothing; storage-quota and corrupt-payload recovery; global handlers | | `mobile.test.js` | 78 | modal layering vs the bottom nav, touch-target sizes, viewport zoom policy, type scale, sticky result bar states, quote table vs card layouts | | `fab.test.js` | 50 | FAB visibility rules, open/close and dismissal, ARIA state, deferred dispatch, error containment, z-index ordering | -| `browser.test.js` | 78 | serves the repo over HTTP and drives real Chromium: asset loading, CSS cascade and media queries, `defer` timing, clicks, dialog focus, mobile viewport and z-index layering | +| `browser.test.js` | 88 | serves the repo over HTTP and drives real Chromium: asset loading, CSS cascade and media queries, `defer` timing, clicks, dialog focus, control-bar spacing, mobile viewport and z-index layering | | `modes.test.js` | 85 | price maths, the three solve modes, input and profit modes, what-if scenarios, comparison, Quick mode, wizard, share-link URL round trip, summary text, theming, auto-save, floor limits | | `a11y.test.js` | 104 | contrast ratios computed from the palette, document structure, accessible names, keyboard operability, dialog focus trap and restore, live regions, reduced motion, plus axe-core over every visible state | @@ -149,3 +150,17 @@ Discount modes are easy to get wrong when writing assertions. In the price *excl* GST — so MRP 1000 at 40% gives CP excl 600, not `1000 / 1.18 × 0.6`. Several assertions were initially written against the wrong formula. If a test disagrees with the app, check the formula before changing the code. + +## Screenshots + +```bash +npm run screenshots +``` + +The two images the README embeds are generated, not captured by hand. They had +drifted twice — once when labels were renamed, once when a header button was +added — and nothing tied them to the app. `screenshots.js` drives the real page +through the same worked example the README's own table walks through, so the +picture and the prose describe the same numbers. It skips the first-run tour, +reads under `reducedMotion: 'reduce'` so the count-up figures are final, and +collapses the History panel that the 900ms auto-save would otherwise expand. diff --git a/tests/browser.test.js b/tests/browser.test.js index 6c22ce4..3c415bc 100644 --- a/tests/browser.test.js +++ b/tests/browser.test.js @@ -713,6 +713,101 @@ async function launchChromium(chromium) { await p5.close(); } + /* ── 7h. Control-bar spacing (measured) ───────────────────────────── */ + R.section('\n=== 7h. The control bar breathes ==='); + // The chips were 3px apart, which read as one blurred block rather than + // three separate choices. Measured, because a gap can be collapsed by + // wrapping, a later rule, or a mismatched box on the neighbour. + const bar = await page.evaluate(() => { + const boxes = sel => [...document.querySelectorAll(sel)] + .map(e => e.getBoundingClientRect()); + const gaps = rects => rects.slice(1) + .map((r, i) => Math.round((r.left - rects[i].right) * 10) / 10); + const gst = boxes('#g18, #g5, #gst-custom-wrap'); + const calcChips = boxes('#tprofit, #tsp, #tcp'); + const groups = boxes('.control-bar .ctrl-group'); + return { + gstGaps: gaps(gst), calcGaps: gaps(calcChips), + groupGap: Math.round(groups[1].left - groups[0].right), + heights: gst.map(r => Math.round(r.height * 10) / 10), + oneRow: new Set(gst.concat(calcChips).map(r => Math.round(r.top))).size === 1 + }; + }); + ok('GST chips are clearly separated', + bar.gstGaps.every(g => g >= 6), 'gaps ' + bar.gstGaps.join(', ')); + ok('so are the Calculate chips', + bar.calcGaps.every(g => g >= 6), 'gaps ' + bar.calcGaps.join(', ')); + ok('the two groups are further apart than the chips within them', + bar.groupGap > Math.max(...bar.gstGaps, ...bar.calcGaps), + 'group gap ' + bar.groupGap); + // The custom-rate box is a different element type sitting in the same row. + ok('the custom-rate box matches the chips it sits beside', + Math.max(...bar.heights) - Math.min(...bar.heights) <= 1, + 'heights ' + bar.heights.join(', ')); + ok('and the whole bar is still one row on desktop', bar.oneRow); + + // "Disc" was the only abbreviation left on the main screen. The longer word + // has to fit the narrowest phone without pushing the input out of the field. + await page.setViewportSize({ width: 320, height: 720 }); + await page.waitForTimeout(150); + const disc = await page.evaluate(() => { + const f = document.getElementById('cpf-disc'); + const box = f.getBoundingClientRect(), inp = document.getElementById('cpd').getBoundingClientRect(); + return { + label: f.querySelector('.sym').textContent, + inputWidth: Math.round(inp.width), + overflow: Math.round(f.scrollWidth - f.clientWidth), + bodyOverflow: document.body.scrollWidth - document.body.clientWidth, + boxWidth: Math.round(box.width) + }; + }); + ok('the field says Discount, not Disc', disc.label === 'Discount', disc.label); + ok('the input still has room to type in at 320px', disc.inputWidth >= 40, + 'input ' + disc.inputWidth + 'px of ' + disc.boxWidth + 'px'); + ok('and nothing overflows the field or the page', + disc.overflow <= 0 && disc.bodyOverflow <= 0, + 'field ' + disc.overflow + 'px, page ' + disc.bodyOverflow + 'px'); + await page.setViewportSize({ width: 1280, height: 900 }); + await page.waitForTimeout(150); + + // Quick mode prints its prefix at 20px heading weight, sized for a ₹ or a %. + // The longer word took the input from ~180px down to 76px — enough for two + // digits, but the hint was sliced to "e.g". + { + const q = await browser.newPage({ viewport: { width: 390, height: 900 } }); + await q.goto(origin + '/', { waitUntil: 'load' }); + await q.waitForFunction(() => typeof window.calc === 'function'); + await q.evaluate(() => document.getElementById('mode-quick').click()); + // Quick mode lives in the deferred bundle; without this the next evaluate + // races the fetch and throws on whichever run loses. + await q.waitForFunction(() => typeof window.fcNext === 'function'); + await q.evaluate(() => { + document.getElementById('fc-mrp').value = '1000'; + window.fcNext(); + }); + await q.waitForTimeout(400); + const fc = await q.evaluate(() => { + const inp = document.getElementById('fc-cpd'); + const sym = inp.previousElementSibling; + // Width the placeholder needs, measured in the font actually rendering it + const ph = getComputedStyle(inp, '::placeholder'); + const box = getComputedStyle(inp); // padding lives here, not on ::placeholder + const c = document.createElement('canvas').getContext('2d'); + c.font = ph.fontWeight + ' ' + ph.fontSize + ' ' + ph.fontFamily; + return { + prefix: sym.textContent, + input: Math.round(inp.getBoundingClientRect().width), + hint: Math.ceil(c.measureText(inp.placeholder).width), + pad: Math.round(parseFloat(box.paddingLeft) + parseFloat(box.paddingRight)) + }; + }); + ok('Quick mode says Discount too', fc.prefix === 'Discount', fc.prefix); + ok('and the example still fits inside the field', + fc.hint + fc.pad <= fc.input, + 'hint ' + fc.hint + 'px + ' + fc.pad + 'px padding in ' + fc.input + 'px'); + await q.close(); + } + /* ── 8. Mobile viewport ───────────────────────────────────────────── */ R.section('\n=== 8. Mobile viewport ==='); await page.setViewportSize({ width: 390, height: 780 }); diff --git a/tests/features.test.js b/tests/features.test.js index 5bf8ce1..46f6a6b 100644 --- a/tests/features.test.js +++ b/tests/features.test.js @@ -2803,6 +2803,138 @@ ok('and it can be switched off like the others', w.featureDef('convert') !== null && w.featureDef('convert').els.indexOf('hbtn-convert') !== -1); +R.section('\n=== 29d. Undo covers typed values, and every other control ==='); +// Undo used to cover only the handful of actions whose code remembered to call +// pushUndo. Typing — the thing people do most — was not one of them. + +// A real edit: focus, keystrokes, then leave. The snapshot is taken on focus, +// so writing .value directly (as the rest of this suite does) records nothing. +const typeInto = (id, val) => { + const i = d.getElementById(id); + i.focus(); + i.value = val; + i.dispatchEvent(new w.Event('input', { bubbles: true })); + i.blur(); +}; +const undoDepth = () => w.UNDO.length; +const lastUndo = () => w.UNDO[w.UNDO.length - 1].label; + +freshCalc(1000, 40, 25); +d.getElementById('mrp').value = ''; +w.UNDO.length = 0; w.REDO.length = 0; + +typeInto('mrp', '1000'); +ok('typing a value is one undo entry', undoDepth() === 1, 'got ' + undoDepth()); +ok('and it is named after the field', lastUndo() === 'MRP', 'got ' + lastUndo()); + +const beforeIdle = undoDepth(); +d.getElementById('mrp').focus(); d.getElementById('mrp').blur(); +ok('focusing and leaving records nothing', undoDepth() === beforeIdle); + +w.undo(); +// The field started empty. numStr used to fold '' into "field absent", so a +// restore could put a number into a box but never take one back out. +ok('undo empties a box that started empty', d.getElementById('mrp').value === '', + 'got "' + d.getElementById('mrp').value + '"'); +w.redo(); +// Restored through the same grouping the box shows while you type in it +ok('redo puts the typed value back', d.getElementById('mrp').value === '1,000', + 'got "' + d.getElementById('mrp').value + '"'); + +typeInto('cpd', '35'); +typeInto('spd', '22'); +ok('each field is its own step', undoDepth() === 3, 'got ' + undoDepth()); +w.undo(); +ok('undo steps back one field at a time', d.getElementById('spd').value === '25' && + d.getElementById('cpd').value === '35', + d.getElementById('cpd').value + ' / ' + d.getElementById('spd').value); +w.undo(); +ok('and then the one before it', d.getElementById('cpd').value === '40'); +ok('undo is not itself undoable', undoDepth() === 1, 'got ' + undoDepth()); + +// Ctrl+Z never leaves the field first, so the edit in progress has not been +// committed by a blur when undo runs. +w.UNDO.length = 0; w.REDO.length = 0; +const mrpEl = d.getElementById('mrp'); +mrpEl.focus(); +mrpEl.value = '2500'; +mrpEl.dispatchEvent(new w.Event('input', { bubbles: true })); +w.undo(); +ok('undo from inside the field still reverts it', mrpEl.value === '1,000', + 'got "' + mrpEl.value + '"'); +mrpEl.blur(); + +// Clicks: recorded generically by comparing state around the handler, so a +// control does not have to know undo exists. +freshCalc(1000, 40, 25); +w.UNDO.length = 0; w.REDO.length = 0; + +d.getElementById('g5').click(); +ok('a GST chip is undoable', undoDepth() === 1 && lastUndo() === '5%', lastUndo()); +w.undo(); +ok('and undo puts the rate back', Math.abs(w.G - 0.18) < 1e-9, 'got ' + w.G); + +w.UNDO.length = 0; +d.getElementById('cmi').click(); +ok('a two-line chip reads as words', lastUndo() === 'Nett Discount %', lastUndo()); + +w.UNDO.length = 0; +d.querySelector('.qty-box button:last-child').click(); +ok('a symbol-only button uses its accessible name', + lastUndo() === 'Increase quantity', lastUndo()); + +w.UNDO.length = 0; +d.getElementById('it-cd').click(); +ok('an incentive toggle is undoable', undoDepth() === 1, 'got ' + undoDepth()); +ok('under the incentive\'s own name', lastUndo() === w.INC_LABELS.cd, lastUndo()); +const cdOn = d.getElementById('it-cd').checked; +w.undo(); +ok('and undo flips it back', d.getElementById('it-cd').checked === !cdOn); + +// Handlers that already push their own entry must not get a second one. +w.UNDO.length = 0; +d.getElementById('cp-inc-add-btn').click(); +ok('an action with its own undo entry records once', undoDepth() === 1, + 'got ' + undoDepth()); +ok('keeping its own wording', lastUndo() === 'add incentive', lastUndo()); +w.undo(); + +// Clicking a chip while a field edit is still open: two separate steps, in the +// order they happened. The pending edit is committed first, and the bump that +// causes must not be read as "this handler recorded its own entry". +freshCalc(1000, 40, 25); +w.UNDO.length = 0; w.REDO.length = 0; +const mrpLive = d.getElementById('mrp'); +mrpLive.focus(); +mrpLive.value = '4000'; +mrpLive.dispatchEvent(new w.Event('input', { bubbles: true })); +d.getElementById('g5').click(); // no blur in between +ok('an unfinished edit and the click after it are both recorded', + undoDepth() === 2, 'got ' + undoDepth()); +ok('in the order they happened', + w.UNDO[0].label === 'MRP' && w.UNDO[1].label === '5%', + w.UNDO.map(e => e.label).join(' | ')); +w.undo(); +ok('undo takes back the click first', Math.abs(w.G - 0.18) < 1e-9, 'got ' + w.G); +w.undo(); +ok('and the typing after it', d.getElementById('mrp').value === '1,000', + 'got "' + d.getElementById('mrp').value + '"'); +mrpLive.blur(); + +// Nothing that leaves the saved state alone should reach the stack. +freshCalc(1000, 40, 25); +w.UNDO.length = 0; +d.querySelector('[data-click="a10"]').click(); // open Settings +ok('opening a dialog is not an undoable action', undoDepth() === 0, 'got ' + undoDepth()); +const tabs = d.querySelectorAll('.settings-tab'); +tabs[1].click(); +ok('nor is switching settings tabs', undoDepth() === 0, 'got ' + undoDepth()); +d.querySelector('#overlay-settings .modal-close').click(); +ok('nor is closing it again', undoDepth() === 0, 'got ' + undoDepth()); +typeInto('hist-search', 'brake'); +ok('nor is typing in the history search box', undoDepth() === 0, 'got ' + undoDepth()); +w.setHistQuery(''); + R.section('\n=== 30a. The default view stays uncluttered ==='); // The main screen had grown to a control bar of 13, five derived rows per price // card, and a 17-cell summary in which five cells repeated numbers shown in the diff --git a/tests/screenshots.js b/tests/screenshots.js new file mode 100644 index 0000000..6b0e407 --- /dev/null +++ b/tests/screenshots.js @@ -0,0 +1,135 @@ +/** + * Regenerate the two screenshots the README embeds. + * + * npm run screenshots + * + * These had drifted twice — labels renamed, a header button added — because + * they were produced by hand and nothing tied them to the app. Driving the real + * page through the same worked example the README walks through keeps the + * picture and the prose describing the same numbers. + * + * Needs Chromium (`npx playwright install chromium`). + */ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const http = require('http'); + +const ROOT = path.join(__dirname, '..'); +const OUT = path.join(ROOT, 'docs'); + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.woff2': 'font/woff2', +}; + +/** Serve the repo root so fonts and both bundles load exactly as they ship. */ +function serveRepo() { + const server = http.createServer((req, res) => { + let p = decodeURIComponent(req.url.split('?')[0]); + if (p === '/') p = '/index.html'; + const file = path.join(ROOT, p); + if (!file.startsWith(ROOT) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) { + res.writeHead(404); + return res.end('not found'); + } + res.writeHead(200, { 'Content-Type': MIME[path.extname(file)] || 'application/octet-stream' }); + res.end(fs.readFileSync(file)); + }); + return new Promise(resolve => { + server.listen(0, '127.0.0.1', () => + resolve({ server, origin: 'http://127.0.0.1:' + server.address().port })); + }); +} + +/** Same fallback the browser suite uses when the bundled revision is absent. */ +async function launchChromium(chromium) { + try { return await chromium.launch(); } catch (firstError) { + const base = process.env.PLAYWRIGHT_BROWSERS_PATH; + if (!base || !fs.existsSync(base)) throw firstError; + for (const dir of fs.readdirSync(base)) { + for (const rel of ['chrome-linux/chrome', 'chrome-linux/headless_shell', + 'chrome-mac/Chromium.app/Contents/MacOS/Chromium']) { + const exe = path.join(base, dir, rel); + if (fs.existsSync(exe)) return await chromium.launch({ executablePath: exe }); + } + } + throw firstError; + } +} + +/** + * MRP ₹1,000 at 18% GST, bought at 40% off, sold at 25% off, with a 2% cash + * discount and 1% early-bird rebate — the example in the README's own table. + * Runs in the page. + */ +function workedExample() { + window.setGST(18); + const mrp = document.getElementById('mrp'); + mrp.value = '1000'; + // Through the input handler, so the figure is grouped the way a typed one is + mrp.dispatchEvent(new Event('input', { bubbles: true })); + window.setCM('excl'); document.getElementById('cpd').value = '40'; + window.setSM('excl'); document.getElementById('spd').value = '25'; + ['cd', 'eb'].forEach(k => { + const cb = document.getElementById('it-' + k); + if (cb && !cb.checked) { cb.checked = true; window.syncToggle(k); } + }); + document.getElementById('iv-cd').value = '2'; + document.getElementById('iv-eb').value = '1'; + window.calc(); +} + +/** Put the page back to how a first-time visitor finds it, post-calculation. */ +function tidyUp() { + // Auto-save fires 900ms after a calculation, which expands History and pushes + // the footer off a full-page shot. + window.HISTORY.length = 0; + window.renderHistory(); + const h = document.getElementById('phdr-hist'); + if (h && h.getAttribute('aria-expanded') === 'true') h.click(); +} + +const SHOTS = [ + { file: 'screenshot.png', width: 1200, height: 820, fullPage: true }, + { file: 'screenshot-mobile.png', width: 390, height: 900, fullPage: false }, +]; + +(async () => { + let chromium; + try { ({ chromium } = require('playwright')); } + catch (e) { console.error('playwright is not installed — npm install'); process.exit(1); } + + const { server, origin } = await serveRepo(); + const browser = await launchChromium(chromium); + + for (const shot of SHOTS) { + const page = await browser.newPage({ + viewport: { width: shot.width, height: shot.height }, + deviceScaleFactor: 2, + }); + // Skip the first-run tour, which would cover the whole page + await page.addInitScript(() => { try { localStorage.setItem('ob-done', '1') } catch (e) {} }); + await page.goto(origin + '/', { waitUntil: 'load' }); + await page.waitForFunction(() => typeof window.calc === 'function'); + // Count-up animations settle instantly here, so the figures are final + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.evaluate(workedExample); + await page.waitForTimeout(1300); + await page.evaluate(tidyUp); + await page.waitForTimeout(200); + const file = path.join(OUT, shot.file); + await page.screenshot({ path: file, fullPage: shot.fullPage }); + console.log(' wrote docs/' + shot.file); + await page.close(); + } + + await browser.close(); + await new Promise(r => server.close(r)); +})();