From 3a1abbb2587b651cada03e66a3dae9c6a195fad5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 1 Aug 2026 02:40:04 +0000 Subject: [PATCH 1/3] Move what-if, compare and CSV export off the critical path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ran the Lighthouse audit. Performance reads 97 against the 98 recorded earlier; one run in five reported 77 with 740ms TBT, which the medians say is this machine rather than the app. The real finding was in the bundles. The README has described app-extra.js as holding "what-if, compare, quote, onboarding" for some time, but only quote, Quick mode and the wizard were actually there. renderWhatIf (7.5KB), renderCompare (5.5KB) and exportHistoryCSV (1.4KB) had drifted into the core bundle — two dialogs and a download behind a button, none reachable on first paint. Moved, using acorn boundaries rather than brace matching. Critical path 96.0KB -> 92.4KB gzipped; deferred share 20.0% -> 25.8%. Onboarding stayed put. It moved cleanly but obRender and OB_STEP did not come with it, and half-moving a cluster for 1.9KB is not worth the entanglement. Verified the cold path in a real browser rather than trusting jsdom, where both bundles are inlined and the shims are never exercised. The first attempt proved nothing: the service worker served app-extra.js from cache, bypassing route interception, so the implementation was already present. With service workers blocked it reads undefined at load, the what-if grid is empty while the bundle is in flight, and fills to three cards with figures once it lands. Compare and CSV export both work. No page errors. Added a guard naming each moved function, so a future move back fails here rather than quietly costing 14KB, plus a ceiling on the gzipped critical path. Two audits score zero by choice and the README now says so: unminified JS is the no-build-step trade, and unused JS is mostly the deferred bundle being warmed during idle so first use is instant. The dominant main-thread cost is Style & Layout at ~325ms against 70ms of scripting — 1,043 nodes, 809 CSS rules and thirteen :has() selectors, which exist to show a keyboard-only focus ring. 1387 assertions. --- assets/app-extra.js | 331 ++++++++++++++++++++++++++++++++++++ assets/app.js | 374 ++++++----------------------------------- tests/features.test.js | 18 ++ 3 files changed, 400 insertions(+), 323 deletions(-) diff --git a/assets/app-extra.js b/assets/app-extra.js index 83518ee..0f36159 100644 --- a/assets/app-extra.js +++ b/assets/app-extra.js @@ -1358,3 +1358,334 @@ function _toggleFeatureImpl(k){ 'The setting and its values are removed. This can be undone.', 'Turn off and clear',turnOff); } + +/* ── What-if, compare, onboarding and CSV export (deferred) ───────────────── + None is reachable on first paint: two are dialogs, one runs on a first + visit, one is a download behind a button. They had drifted into the core + bundle even though the README described them as deferred. + ─────────────────────────────────────────────────────────────────────────── */ +var WI_CHEVRON_SVG=''; + +function resolveWiSP(sc){ + if(sc.spMode==='manual'){ + var v=parseFloat(String(sc.spVal).replace(/,/g,'')); + return priceFromManual(v,sc.spManualSub); + } + var d=parseFloat(sc.spDisc); + return(!isNaN(d)&&sc.spDisc!=='')?priceFromDisc(d,sc.spMode):null; +} + +function _updateWiResultsImpl(){ + if(!LAST_CP)return; + var inc=getIncentiveInr(LAST_CP),eff=effectiveCP(LAST_CP),floor=getFloor(); + + // Recalculate best GP + var bestGP=-Infinity,bestIdx=-1; + WI_SCENES.forEach(function(sc,i){ + var sp=resolveWiSP(sc);if(!sp)return; + var gp=(sp.e>0)?((sp.e-eff)/sp.e)*100:null; + if(gp!==null&&gp>bestGP){bestGP=gp;bestIdx=i} + }); + + WI_SCENES.forEach(function(sc,i){ + // update card highlight + var card=el('wi-card-'+i); + if(card)card.className='wi-card'+(i===bestIdx?' wi-best':''); + + var sp=resolveWiSP(sc); + var KEYS=['spe','spi','pr','gp','mg']; + + if(sp){ + var pr=sp.e-eff,gp=(sp.e>0)?(pr/sp.e)*100:null,mg=(eff>0)?(pr/eff)*100:null; + var vals=[ + {v:SINR(sp.e),c:''}, + {v:SINR(sp.i),c:''}, + {v:SINR(pr),c:pr>=0?'pos':'neg'}, + {v:PCT(gp),c:gpCls(gp,floor)}, + {v:PCT(mg),c:mgCls(mg,floor)} + ]; + vals.forEach(function(row,k){ + var cell=el('wi-'+i+'-'+KEYS[k]); + if(cell){cell.textContent=row.v;cell.className='wi-val '+row.c} + }); + } else { + KEYS.forEach(function(k){ + var cell=el('wi-'+i+'-'+k); + if(cell){cell.textContent='—';cell.className='wi-val dim'} + }); + } + }); +} + +function _renderWhatIfImpl(cp){ + var info=el('wi-cp-info'),grid=el('wi-grid'); + if(!cp){info.innerHTML='Enter CP and incentives on the main screen first.';grid.innerHTML='';return} + var inc=getIncentiveInr(cp),eff=effectiveCP(cp),floor=getFloor(); + var incTxt=inc>0?' · Incentives: '+CINR(inc)+' · Eff CP: '+CINR(eff):''; + info.innerHTML='MRP: '+INR(MI)+'CP excl GST: '+CINR(cp.e)+''+incTxt; + + var bestGP=-Infinity,bestIdx=-1; + WI_SCENES.forEach(function(sc,i){ + var sp=resolveWiSP(sc);if(!sp)return; + var gp=(sp.e>0)?((sp.e-eff)/sp.e)*100:null; + if(gp!==null&&gp>bestGP){bestGP=gp;bestIdx=i} + }); + + grid.innerHTML=''; + WI_SCENES.forEach(function(sc,i){ + var isManual=sc.spMode==='manual'; + var card=document.createElement('div'); + card.className='wi-card'+(i===bestIdx?' wi-best':''); + card.id='wi-card-'+i; + + // header + var hd=document.createElement('div');hd.className='wi-card-head'; + var ttl=document.createElement('span');ttl.className='wi-card-title'; + ttl.textContent='Scenario '+['A','B','C'][i]; + hd.appendChild(ttl);card.appendChild(hd); + + // 3-way mode tabs — mode change does full rebuild (no input is focused) + var tabs=document.createElement('div');tabs.className='sub-tabs'; + [{key:'excl',label:'Discount + GST %'},{key:'incl',label:'Nett Discount %'},{key:'manual',label:'Enter ₹ directly'}] + .forEach(function(m){ + var btn=document.createElement('button'); + btn.className='stab'+(sc.spMode===m.key?' on':''); + btn.textContent=m.label; + btn.onclick=(function(mode,idx){return function(){WI_SCENES[idx].spMode=mode;renderWhatIf(LAST_CP)}})(m.key,i); + tabs.appendChild(btn); + }); + card.appendChild(tabs); + + if(isManual){ + var subWrap=document.createElement('div');subWrap.style.cssText='display:flex;flex-direction:column;gap:6px'; + // sub-tabs for incl/excl GST — also full rebuild (no input focused) + var subTabs=document.createElement('div');subTabs.className='sub-tabs'; + [{key:'incl',label:'SP incl GST'},{key:'excl',label:'SP excl GST'}].forEach(function(s){ + var b=document.createElement('button');b.className='stab'+(sc.spManualSub===s.key?' on':''); + b.textContent=s.label; + b.onclick=(function(sub,idx){return function(){WI_SCENES[idx].spManualSub=sub;renderWhatIf(LAST_CP)}})(s.key,i); + subTabs.appendChild(b); + }); + subWrap.appendChild(subTabs); + + // ₹ input — oninput stores value + calls updateWiResults() ONLY (never rebuilds) + var fldM=document.createElement('div');fldM.className='field'; + var symM=document.createElement('span');symM.className='sym';symM.textContent='₹'; + var inpM=document.createElement('input');inpM.type='text';inpM.inputMode='decimal'; + inpM.placeholder=sc.spManualSub==='incl'?'SP incl GST':'SP excl GST'; + inpM.autocomplete='off'; + if(sc.spVal!==''){var nv=parseFloat(sc.spVal);inpM.value=isNaN(nv)?sc.spVal:fmtINDIAN(nv)} + inpM.oninput=(function(idx){return function(){ + var raw=this.value.replace(/[^0-9.]/g,''); + var pts=raw.split('.');if(pts.length>2)raw=pts[0]+'.'+pts.slice(1).join(''); + WI_SCENES[idx].spVal=raw; + var num=parseFloat(raw); + if(!isNaN(num)&&raw!==''&&raw!=='.'){ + var fmt=fmtINDIAN(num); + if(raw.indexOf('.')!==-1){var dec=raw.split('.')[1];fmt=fmtINDIAN(parseFloat(raw.split('.')[0])||0).split('.')[0]+'.'+(dec||'')} + this.value=fmt; + } else if(raw===''||raw==='.'){this.value=raw} + _updateWiResultsImpl(); // ← results only, keyboard stays open + }})(i); + var btnM=document.createElement('button');btnM.className='field-next';btnM.tabIndex=-1;btnM.title='Done'; + btnM.innerHTML=WI_CHEVRON_SVG;btnM.onclick=function(){inpM.blur()}; + fldM.appendChild(symM);fldM.appendChild(inpM);fldM.appendChild(btnM); + subWrap.appendChild(fldM); + card.appendChild(subWrap); + + } else { + // disc % input — oninput stores + updateWiResults() only + var fld=document.createElement('div');fld.className='field'; + var sym=document.createElement('span');sym.className='sym';sym.textContent='Disc %'; + var inp=document.createElement('input');inp.type='number';inp.inputMode='decimal';inp.placeholder='e.g. 20'; + inp.min='0';inp.max='100';inp.step='0.01';inp.value=sc.spDisc;inp.autocomplete='off'; + inp.oninput=(function(idx){return function(){ + WI_SCENES[idx].spDisc=this.value; + _updateWiResultsImpl(); // ← results only, keyboard stays open + }})(i); + var btnD=document.createElement('button');btnD.className='field-next';btnD.tabIndex=-1;btnD.title='Done'; + btnD.innerHTML=WI_CHEVRON_SVG;btnD.onclick=function(){inp.blur()}; + fld.appendChild(sym);fld.appendChild(inp);fld.appendChild(btnD);card.appendChild(fld); + } + + // result rows with stable IDs + var rows=document.createElement('div');rows.className='wi-rows'; + var LBLS=['SP excl GST','SP incl GST','Profit ₹','GP %','Margin %']; + var KEYS=['spe','spi','pr','gp','mg']; + var sp=resolveWiSP(sc); + LBLS.forEach(function(lbl,k){ + var r=document.createElement('div');r.className='wi-row'; + var l=document.createElement('span');l.className='wi-lbl';l.textContent=lbl; + var v=document.createElement('span'); + v.id='wi-'+i+'-'+KEYS[k]; + v.className='wi-val dim';v.textContent='—'; + r.appendChild(l);r.appendChild(v);rows.appendChild(r); + }); + card.appendChild(rows);grid.appendChild(card); + }); + + // Populate results after the DOM is built. This used to need an + // elClearCache() first: the grid is rebuilt with the same wi-*-* ids, so + // every node the old el() cache held was detached and updateWiResults wrote + // into nodes that were no longer displayed — the cards showed '—' on every + // re-render after the first. el() no longer caches, so the ids resolve to + // whatever is currently in the document. + _updateWiResultsImpl(); +} + +function _exportHistoryCSVImpl(){ + if(HISTORY.length===0){ + logWarn('exportHistoryCSV called with an empty history'); + toast('No history entries to export.'); + return; + } + var headers=['Time','Tag','MRP (incl GST)','CP excl GST','CP incl GST','SP excl GST','SP incl GST','Eff CP excl GST','CP Incentives INR','Eff SP excl GST','SP Incentives INR','Profit INR','GP %','Margin %','GST Rate %','Qty','Total Profit INR']; + var rows=[headers.join(',')]; + HISTORY.forEach(function(h){ + rows.push([ + '"'+h.time+'"', + '"'+String(h.tag||'').replace(/"/g,'""')+'"', + h.mrp.toFixed(2), + h.cpE.toFixed(2), + h.cpI.toFixed(2), + h.spE.toFixed(2), + h.spI.toFixed(2), + h.effCPE.toFixed(2), + h.incInr>0?h.incInr.toFixed(2):'', + (h.effSPE||h.spE).toFixed(2), + (h.spIncInr||0)>0?(h.spIncInr||0).toFixed(2):'', + h.pr.toFixed(2), + h.gp!==null?h.gp.toFixed(2):'', + h.mg!==null?h.mg.toFixed(2):'', + h.gst, + h.qty||1, + (h.totalPr!=null?h.totalPr:h.pr*(h.qty||1)).toFixed(2) + ].join(',')); + }); + var csv=rows.join('\r\n'); + var blob=new Blob([csv],{type:'text/csv;charset=utf-8;'}); + var url=URL.createObjectURL(blob); + var a=document.createElement('a'); + a.href=url; + a.download='pricing-history-'+new Date().toISOString().slice(0,10)+'.csv'; + document.body.appendChild(a);a.click(); + setTimeout(function(){document.body.removeChild(a);URL.revokeObjectURL(url)},200); +} + +function _openCompareImpl(idx){ + COMPARE_IDX=idx; + renderCompare(); + openModal('compare'); +} + +function _renderCompareImpl(){ + var floor=getFloor(); + var hist=HISTORY[COMPARE_IDX]; + if(!hist){el('cmp-grid').innerHTML='
No entry selected.
';return} + + // Build current snapshot + var cur=null; + if(LAST_CP&&LAST_SP){ + var inc=getIncentiveInr(LAST_CP),eff=effectiveCP(LAST_CP); + var spInc=getSPIncentiveInr(LAST_SP),effSP=effectiveSP(LAST_SP); + var pr=effSP-eff; + cur={ + mrp:MI,cpE:LAST_CP.e,cpI:LAST_CP.i,spE:LAST_SP.e,spI:LAST_SP.i, + effCPE:eff,effSPE:effSP,incInr:inc,spIncInr:spInc,pr:pr, + gp:(effSP>0)?(pr/effSP)*100:null, + mg:(eff>0)?(pr/eff)*100:null, + gst:G*100 + }; + } + + // meta + var meta=el('cmp-meta'); + var histTimeDisp=hist.ts?relTime(hist.ts):hist.time; + var histTimeFull=hist.ts?fmtTime(hist.ts):hist.time; + meta.innerHTML='Comparing current calculation vs history entry from '+histTimeDisp+''; + if(!cur) meta.innerHTML+=' — Enter CP & SP on main screen to populate Current column'; + + // delta helper + function delta(curV,histV,isPercent,higherIsBetter){ + if(curV===null||histV===null||curV===undefined||histV===undefined)return''; + var d=curV-histV; + if(Math.abs(d)<0.005)return '—'; + var sign=d>0?'+':''; + var cls=(higherIsBetter?(d>0):(d<0))?'up':'dn'; + var txt=isPercent?(sign+d.toFixed(2)+'pp'):(sign+d.toFixed(2)); + return ''+txt+''; + } + function deltaINR(curV,histV,higher,side){ + if(curV===null||histV===null)return''; + var d=curV-histV;if(Math.abs(d)<0.005)return'—'; + // Math.abs() strips the sign, so a fall has to be signed explicitly — + // otherwise -₹50 and +₹50 render identically and only the colour differs. + var sign=d>0?'+':'−'; + var cls=(higher?(d>0):(d<0))?'up':'dn'; + // The delta wears the same symbol as the two cells it sits between. + return ''+sign+symFor(side||'base')+Math.abs(d).toFixed(2)+''; + } + + // cell builders + function hd(txt,cls){return '
'+(txt||'')+'
'} + function lbl(txt){return '
'+txt+'
'} + + function valCell(v,fmt,cls){ + var disp=v===null||v===undefined?'—':(fmt==='inr'?INR(v):PCT(v)); + return '
'+(disp||'—')+'
'; + } + function inrCell(v,posNeg,side){ + if(v===null||v===undefined)return'
—
'; + var cls=posNeg?(v>=0?'cmp-pos':'cmp-neg'):''; + return'
'+money(v,side||'base')+'
'; + } + function pctCell(v,floor,isGP){ + if(v===null||v===undefined)return'
—
'; + var f=isGP?floor.gp:floor.mg; + var cls=belowFloor(v,f)?'cmp-warn':(v>=0?'cmp-pos':'cmp-neg'); + return'
'+PCT(v)+'
'; + } + function deltaCell(html){return'
'+(html||'—')+'
'} + + var rows=[ + {label:'MRP (incl GST)', cur:cur?cur.mrp:null, hist:hist.mrp, fmt:'inr', higher:null, side:'base'}, + {label:'CP excl GST', cur:cur?cur.cpE:null, hist:hist.cpE, fmt:'inr', higher:false, side:'cost'}, + {label:'CP incl GST', cur:cur?cur.cpI:null, hist:hist.cpI, fmt:'inr', higher:false, side:'cost'}, + {label:'SP excl GST', cur:cur?cur.spE:null, hist:hist.spE, fmt:'inr', higher:true, side:'sale'}, + {label:'SP incl GST', cur:cur?cur.spI:null, hist:hist.spI, fmt:'inr', higher:true, side:'sale'}, + {label:'Eff. SP excl GST', cur:cur?cur.effSPE:null, hist:hist.effSPE||hist.spE, fmt:'inr', higher:true, side:'sale'}, + {label:'SP Incentives', cur:cur?cur.spIncInr:null,hist:hist.spIncInr||0,fmt:'inr', higher:true, side:'sale'}, + {label:'Eff. CP excl GST', cur:cur?cur.effCPE:null,hist:hist.effCPE,fmt:'inr', higher:false, side:'cost'}, + {label:'Incentives', cur:cur?cur.incInr:null,hist:hist.incInr,fmt:'inr', higher:true, side:'cost'}, + {label:'Profit', cur:cur?cur.pr:null, hist:hist.pr, fmt:'inr', higher:true, posNeg:true, side:'sale'}, + {label:'GP %', cur:cur?cur.gp:null, hist:hist.gp, fmt:'pct', higher:true, isGP:true}, + {label:'Margin %', cur:cur?cur.mg:null, hist:hist.mg, fmt:'pct', higher:true, isMG:true}, + {label:'GST Rate', cur:cur?cur.gst:null, hist:hist.gst, fmt:'gst', higher:null} + ]; + + var html=hd('')+hd('Current','cur')+hd('Selected','sel')+hd('Change'); + + rows.forEach(function(r){ + html+=lbl(r.label); + if(r.fmt==='pct'){ + html+=pctCell(r.cur,floor,r.isGP); + html+=pctCell(r.hist,floor,r.isGP); + html+=deltaCell(delta(r.cur,r.hist,true,r.higher)); + } else if(r.fmt==='gst'){ + html+='
'+(r.cur!==null?r.cur+'%':'—')+'
'; + html+='
'+r.hist+'%
'; + html+=deltaCell(delta(r.cur,r.hist,false,null)); + } else { + var c=r.posNeg?inrCell(r.cur,true,r.side):(r.cur===null?'
—
':inrCell(r.cur,false,r.side)); + var s=r.posNeg?inrCell(r.hist,true,r.side):inrCell(r.hist,false,r.side); + html+=c+s; + html+=deltaCell(deltaINR(r.cur,r.hist,r.higher,r.side)); + } + }); + + el('cmp-grid').innerHTML=html; +} + + + + diff --git a/assets/app.js b/assets/app.js index 063ff9c..f9418ab 100644 --- a/assets/app.js +++ b/assets/app.js @@ -3482,181 +3482,20 @@ function updateMiniResult(pr,gp,mg){ /* ── What-if modal renderer ── */ /* ── What-if helpers ── */ -var WI_CHEVRON_SVG=''; + /** * Selling price for one what-if scenario. * @param {Object} sc scenario record from WI_SCENES * @returns {{e:number,i:number}|null} */ -function resolveWiSP(sc){ - if(sc.spMode==='manual'){ - var v=parseFloat(String(sc.spVal).replace(/,/g,'')); - return priceFromManual(v,sc.spManualSub); - } - var d=parseFloat(sc.spDisc); - return(!isNaN(d)&&sc.spDisc!=='')?priceFromDisc(d,sc.spMode):null; -} + // Update only the result rows — never touches inputs so keyboard stays open -function updateWiResults(){ - if(!LAST_CP)return; - var inc=getIncentiveInr(LAST_CP),eff=effectiveCP(LAST_CP),floor=getFloor(); - - // Recalculate best GP - var bestGP=-Infinity,bestIdx=-1; - WI_SCENES.forEach(function(sc,i){ - var sp=resolveWiSP(sc);if(!sp)return; - var gp=(sp.e>0)?((sp.e-eff)/sp.e)*100:null; - if(gp!==null&&gp>bestGP){bestGP=gp;bestIdx=i} - }); - WI_SCENES.forEach(function(sc,i){ - // update card highlight - var card=el('wi-card-'+i); - if(card)card.className='wi-card'+(i===bestIdx?' wi-best':''); - - var sp=resolveWiSP(sc); - var KEYS=['spe','spi','pr','gp','mg']; - - if(sp){ - var pr=sp.e-eff,gp=(sp.e>0)?(pr/sp.e)*100:null,mg=(eff>0)?(pr/eff)*100:null; - var vals=[ - {v:SINR(sp.e),c:''}, - {v:SINR(sp.i),c:''}, - {v:SINR(pr),c:pr>=0?'pos':'neg'}, - {v:PCT(gp),c:gpCls(gp,floor)}, - {v:PCT(mg),c:mgCls(mg,floor)} - ]; - vals.forEach(function(row,k){ - var cell=el('wi-'+i+'-'+KEYS[k]); - if(cell){cell.textContent=row.v;cell.className='wi-val '+row.c} - }); - } else { - KEYS.forEach(function(k){ - var cell=el('wi-'+i+'-'+k); - if(cell){cell.textContent='—';cell.className='wi-val dim'} - }); - } - }); -} // Full render — rebuilds the entire grid (called on modal open, mode change, CP change) -function renderWhatIf(cp){ - var info=el('wi-cp-info'),grid=el('wi-grid'); - if(!cp){info.innerHTML='Enter CP and incentives on the main screen first.';grid.innerHTML='';return} - var inc=getIncentiveInr(cp),eff=effectiveCP(cp),floor=getFloor(); - var incTxt=inc>0?' · Incentives: '+CINR(inc)+' · Eff CP: '+CINR(eff):''; - info.innerHTML='MRP: '+INR(MI)+'CP excl GST: '+CINR(cp.e)+''+incTxt; - - var bestGP=-Infinity,bestIdx=-1; - WI_SCENES.forEach(function(sc,i){ - var sp=resolveWiSP(sc);if(!sp)return; - var gp=(sp.e>0)?((sp.e-eff)/sp.e)*100:null; - if(gp!==null&&gp>bestGP){bestGP=gp;bestIdx=i} - }); - - grid.innerHTML=''; - WI_SCENES.forEach(function(sc,i){ - var isManual=sc.spMode==='manual'; - var card=document.createElement('div'); - card.className='wi-card'+(i===bestIdx?' wi-best':''); - card.id='wi-card-'+i; - - // header - var hd=document.createElement('div');hd.className='wi-card-head'; - var ttl=document.createElement('span');ttl.className='wi-card-title'; - ttl.textContent='Scenario '+['A','B','C'][i]; - hd.appendChild(ttl);card.appendChild(hd); - - // 3-way mode tabs — mode change does full rebuild (no input is focused) - var tabs=document.createElement('div');tabs.className='sub-tabs'; - [{key:'excl',label:'Discount + GST %'},{key:'incl',label:'Nett Discount %'},{key:'manual',label:'Enter ₹ directly'}] - .forEach(function(m){ - var btn=document.createElement('button'); - btn.className='stab'+(sc.spMode===m.key?' on':''); - btn.textContent=m.label; - btn.onclick=(function(mode,idx){return function(){WI_SCENES[idx].spMode=mode;renderWhatIf(LAST_CP)}})(m.key,i); - tabs.appendChild(btn); - }); - card.appendChild(tabs); - - if(isManual){ - var subWrap=document.createElement('div');subWrap.style.cssText='display:flex;flex-direction:column;gap:6px'; - // sub-tabs for incl/excl GST — also full rebuild (no input focused) - var subTabs=document.createElement('div');subTabs.className='sub-tabs'; - [{key:'incl',label:'SP incl GST'},{key:'excl',label:'SP excl GST'}].forEach(function(s){ - var b=document.createElement('button');b.className='stab'+(sc.spManualSub===s.key?' on':''); - b.textContent=s.label; - b.onclick=(function(sub,idx){return function(){WI_SCENES[idx].spManualSub=sub;renderWhatIf(LAST_CP)}})(s.key,i); - subTabs.appendChild(b); - }); - subWrap.appendChild(subTabs); - - // ₹ input — oninput stores value + calls updateWiResults() ONLY (never rebuilds) - var fldM=document.createElement('div');fldM.className='field'; - var symM=document.createElement('span');symM.className='sym';symM.textContent='₹'; - var inpM=document.createElement('input');inpM.type='text';inpM.inputMode='decimal'; - inpM.placeholder=sc.spManualSub==='incl'?'SP incl GST':'SP excl GST'; - inpM.autocomplete='off'; - if(sc.spVal!==''){var nv=parseFloat(sc.spVal);inpM.value=isNaN(nv)?sc.spVal:fmtINDIAN(nv)} - inpM.oninput=(function(idx){return function(){ - var raw=this.value.replace(/[^0-9.]/g,''); - var pts=raw.split('.');if(pts.length>2)raw=pts[0]+'.'+pts.slice(1).join(''); - WI_SCENES[idx].spVal=raw; - var num=parseFloat(raw); - if(!isNaN(num)&&raw!==''&&raw!=='.'){ - var fmt=fmtINDIAN(num); - if(raw.indexOf('.')!==-1){var dec=raw.split('.')[1];fmt=fmtINDIAN(parseFloat(raw.split('.')[0])||0).split('.')[0]+'.'+(dec||'')} - this.value=fmt; - } else if(raw===''||raw==='.'){this.value=raw} - updateWiResults(); // ← results only, keyboard stays open - }})(i); - var btnM=document.createElement('button');btnM.className='field-next';btnM.tabIndex=-1;btnM.title='Done'; - btnM.innerHTML=WI_CHEVRON_SVG;btnM.onclick=function(){inpM.blur()}; - fldM.appendChild(symM);fldM.appendChild(inpM);fldM.appendChild(btnM); - subWrap.appendChild(fldM); - card.appendChild(subWrap); - - } else { - // disc % input — oninput stores + updateWiResults() only - var fld=document.createElement('div');fld.className='field'; - var sym=document.createElement('span');sym.className='sym';sym.textContent='Disc %'; - var inp=document.createElement('input');inp.type='number';inp.inputMode='decimal';inp.placeholder='e.g. 20'; - inp.min='0';inp.max='100';inp.step='0.01';inp.value=sc.spDisc;inp.autocomplete='off'; - inp.oninput=(function(idx){return function(){ - WI_SCENES[idx].spDisc=this.value; - updateWiResults(); // ← results only, keyboard stays open - }})(i); - var btnD=document.createElement('button');btnD.className='field-next';btnD.tabIndex=-1;btnD.title='Done'; - btnD.innerHTML=WI_CHEVRON_SVG;btnD.onclick=function(){inp.blur()}; - fld.appendChild(sym);fld.appendChild(inp);fld.appendChild(btnD);card.appendChild(fld); - } - - // result rows with stable IDs - var rows=document.createElement('div');rows.className='wi-rows'; - var LBLS=['SP excl GST','SP incl GST','Profit ₹','GP %','Margin %']; - var KEYS=['spe','spi','pr','gp','mg']; - var sp=resolveWiSP(sc); - LBLS.forEach(function(lbl,k){ - var r=document.createElement('div');r.className='wi-row'; - var l=document.createElement('span');l.className='wi-lbl';l.textContent=lbl; - var v=document.createElement('span'); - v.id='wi-'+i+'-'+KEYS[k]; - v.className='wi-val dim';v.textContent='—'; - r.appendChild(l);r.appendChild(v);rows.appendChild(r); - }); - card.appendChild(rows);grid.appendChild(card); - }); - // Populate results after the DOM is built. This used to need an - // elClearCache() first: the grid is rebuilt with the same wi-*-* ids, so - // every node the old el() cache held was detached and updateWiResults wrote - // into nodes that were no longer displayed — the cards showed '—' on every - // re-render after the first. el() no longer caches, so the ids resolve to - // whatever is currently in the document. - updateWiResults(); -} /* ── Auto-save ── */ var _autoSaveTimer=null; @@ -3839,44 +3678,7 @@ function renderHistory(){ } /* ── History export ── */ -function exportHistoryCSV(){ - if(HISTORY.length===0){ - logWarn('exportHistoryCSV called with an empty history'); - toast('No history entries to export.'); - return; - } - var headers=['Time','Tag','MRP (incl GST)','CP excl GST','CP incl GST','SP excl GST','SP incl GST','Eff CP excl GST','CP Incentives INR','Eff SP excl GST','SP Incentives INR','Profit INR','GP %','Margin %','GST Rate %','Qty','Total Profit INR']; - var rows=[headers.join(',')]; - HISTORY.forEach(function(h){ - rows.push([ - '"'+h.time+'"', - '"'+String(h.tag||'').replace(/"/g,'""')+'"', - h.mrp.toFixed(2), - h.cpE.toFixed(2), - h.cpI.toFixed(2), - h.spE.toFixed(2), - h.spI.toFixed(2), - h.effCPE.toFixed(2), - h.incInr>0?h.incInr.toFixed(2):'', - (h.effSPE||h.spE).toFixed(2), - (h.spIncInr||0)>0?(h.spIncInr||0).toFixed(2):'', - h.pr.toFixed(2), - h.gp!==null?h.gp.toFixed(2):'', - h.mg!==null?h.mg.toFixed(2):'', - h.gst, - h.qty||1, - (h.totalPr!=null?h.totalPr:h.pr*(h.qty||1)).toFixed(2) - ].join(',')); - }); - var csv=rows.join('\r\n'); - var blob=new Blob([csv],{type:'text/csv;charset=utf-8;'}); - var url=URL.createObjectURL(blob); - var a=document.createElement('a'); - a.href=url; - a.download='pricing-history-'+new Date().toISOString().slice(0,10)+'.csv'; - document.body.appendChild(a);a.click(); - setTimeout(function(){document.body.removeChild(a);URL.revokeObjectURL(url)},200); -} + /* ── Comparison modal ── */ var COMPARE_IDX=null; @@ -3885,122 +3687,12 @@ var COMPARE_IDX=null; * Open the comparison modal for one history entry. * @param {number} idx index into HISTORY */ -function openCompare(idx){ - COMPARE_IDX=idx; - renderCompare(); - openModal('compare'); -} + /** * Draw the current-vs-saved comparison table with per-row deltas. */ -function renderCompare(){ - var floor=getFloor(); - var hist=HISTORY[COMPARE_IDX]; - if(!hist){el('cmp-grid').innerHTML='
No entry selected.
';return} - // Build current snapshot - var cur=null; - if(LAST_CP&&LAST_SP){ - var inc=getIncentiveInr(LAST_CP),eff=effectiveCP(LAST_CP); - var spInc=getSPIncentiveInr(LAST_SP),effSP=effectiveSP(LAST_SP); - var pr=effSP-eff; - cur={ - mrp:MI,cpE:LAST_CP.e,cpI:LAST_CP.i,spE:LAST_SP.e,spI:LAST_SP.i, - effCPE:eff,effSPE:effSP,incInr:inc,spIncInr:spInc,pr:pr, - gp:(effSP>0)?(pr/effSP)*100:null, - mg:(eff>0)?(pr/eff)*100:null, - gst:G*100 - }; - } - - // meta - var meta=el('cmp-meta'); - var histTimeDisp=hist.ts?relTime(hist.ts):hist.time; - var histTimeFull=hist.ts?fmtTime(hist.ts):hist.time; - meta.innerHTML='Comparing current calculation vs history entry from '+histTimeDisp+''; - if(!cur) meta.innerHTML+=' — Enter CP & SP on main screen to populate Current column'; - - // delta helper - function delta(curV,histV,isPercent,higherIsBetter){ - if(curV===null||histV===null||curV===undefined||histV===undefined)return''; - var d=curV-histV; - if(Math.abs(d)<0.005)return '—'; - var sign=d>0?'+':''; - var cls=(higherIsBetter?(d>0):(d<0))?'up':'dn'; - var txt=isPercent?(sign+d.toFixed(2)+'pp'):(sign+d.toFixed(2)); - return ''+txt+''; - } - function deltaINR(curV,histV,higher,side){ - if(curV===null||histV===null)return''; - var d=curV-histV;if(Math.abs(d)<0.005)return'—'; - // Math.abs() strips the sign, so a fall has to be signed explicitly — - // otherwise -₹50 and +₹50 render identically and only the colour differs. - var sign=d>0?'+':'−'; - var cls=(higher?(d>0):(d<0))?'up':'dn'; - // The delta wears the same symbol as the two cells it sits between. - return ''+sign+symFor(side||'base')+Math.abs(d).toFixed(2)+''; - } - - // cell builders - function hd(txt,cls){return '
'+(txt||'')+'
'} - function lbl(txt){return '
'+txt+'
'} - - function valCell(v,fmt,cls){ - var disp=v===null||v===undefined?'—':(fmt==='inr'?INR(v):PCT(v)); - return '
'+(disp||'—')+'
'; - } - function inrCell(v,posNeg,side){ - if(v===null||v===undefined)return'
—
'; - var cls=posNeg?(v>=0?'cmp-pos':'cmp-neg'):''; - return'
'+money(v,side||'base')+'
'; - } - function pctCell(v,floor,isGP){ - if(v===null||v===undefined)return'
—
'; - var f=isGP?floor.gp:floor.mg; - var cls=belowFloor(v,f)?'cmp-warn':(v>=0?'cmp-pos':'cmp-neg'); - return'
'+PCT(v)+'
'; - } - function deltaCell(html){return'
'+(html||'—')+'
'} - - var rows=[ - {label:'MRP (incl GST)', cur:cur?cur.mrp:null, hist:hist.mrp, fmt:'inr', higher:null, side:'base'}, - {label:'CP excl GST', cur:cur?cur.cpE:null, hist:hist.cpE, fmt:'inr', higher:false, side:'cost'}, - {label:'CP incl GST', cur:cur?cur.cpI:null, hist:hist.cpI, fmt:'inr', higher:false, side:'cost'}, - {label:'SP excl GST', cur:cur?cur.spE:null, hist:hist.spE, fmt:'inr', higher:true, side:'sale'}, - {label:'SP incl GST', cur:cur?cur.spI:null, hist:hist.spI, fmt:'inr', higher:true, side:'sale'}, - {label:'Eff. SP excl GST', cur:cur?cur.effSPE:null, hist:hist.effSPE||hist.spE, fmt:'inr', higher:true, side:'sale'}, - {label:'SP Incentives', cur:cur?cur.spIncInr:null,hist:hist.spIncInr||0,fmt:'inr', higher:true, side:'sale'}, - {label:'Eff. CP excl GST', cur:cur?cur.effCPE:null,hist:hist.effCPE,fmt:'inr', higher:false, side:'cost'}, - {label:'Incentives', cur:cur?cur.incInr:null,hist:hist.incInr,fmt:'inr', higher:true, side:'cost'}, - {label:'Profit', cur:cur?cur.pr:null, hist:hist.pr, fmt:'inr', higher:true, posNeg:true, side:'sale'}, - {label:'GP %', cur:cur?cur.gp:null, hist:hist.gp, fmt:'pct', higher:true, isGP:true}, - {label:'Margin %', cur:cur?cur.mg:null, hist:hist.mg, fmt:'pct', higher:true, isMG:true}, - {label:'GST Rate', cur:cur?cur.gst:null, hist:hist.gst, fmt:'gst', higher:null} - ]; - - var html=hd('')+hd('Current','cur')+hd('Selected','sel')+hd('Change'); - - rows.forEach(function(r){ - html+=lbl(r.label); - if(r.fmt==='pct'){ - html+=pctCell(r.cur,floor,r.isGP); - html+=pctCell(r.hist,floor,r.isGP); - html+=deltaCell(delta(r.cur,r.hist,true,r.higher)); - } else if(r.fmt==='gst'){ - html+='
'+(r.cur!==null?r.cur+'%':'—')+'
'; - html+='
'+r.hist+'%
'; - html+=deltaCell(delta(r.cur,r.hist,false,null)); - } else { - var c=r.posNeg?inrCell(r.cur,true,r.side):(r.cur===null?'
—
':inrCell(r.cur,false,r.side)); - var s=r.posNeg?inrCell(r.hist,true,r.side):inrCell(r.hist,false,r.side); - html+=c+s; - html+=deltaCell(deltaINR(r.cur,r.hist,r.higher,r.side)); - } - }); - - el('cmp-grid').innerHTML=html; -} /** * Build the plain-text summary used by copy, WhatsApp and email. * @returns {string|null} null when CP or SP is missing @@ -4845,6 +4537,37 @@ if(typeof requestIdleCallback === 'function'){ } +/* ── Deferred-feature entry points ────────────────────────────────────────── + What-if, comparison and the CSV export live in app-extra.js. None is + reachable on first paint — two are dialogs, one is a download behind a + button — but they had drifted into the core bundle, which the README already + described as not carrying them. Each entry point is a thin shim so callers + do not each have to know about the split. + ─────────────────────────────────────────────────────────────────────────── */ +/** Draw the what-if grid. @param {Object} cp */ +function renderWhatIf(cp){ + if(typeof _renderWhatIfImpl==='function')return _renderWhatIfImpl(cp); + withExtras(function(){ _renderWhatIfImpl(cp) }); +} +/** Refresh the what-if figures without rebuilding the grid. */ +function updateWiResults(){ + if(typeof _updateWiResultsImpl==='function')return _updateWiResultsImpl(); +} +/** Open the comparison dialog against a history entry. @param {number} i */ +function openCompare(i){ + if(typeof _openCompareImpl==='function')return _openCompareImpl(i); + withExtras(function(){ _openCompareImpl(i) }); +} +/** Redraw the comparison, if it happens to be open. */ +function renderCompare(){ + if(typeof _renderCompareImpl==='function')return _renderCompareImpl(); +} +/** Download the history as CSV. */ +function exportHistoryCSV(){ + if(typeof _exportHistoryCSVImpl==='function')return _exportHistoryCSVImpl(); + withExtras(function(){ _exportHistoryCSVImpl() }); +} + /* ── Share-link payload validation ────────────────────────────────────────── ?s= is unauthenticated base64 JSON from whoever sends you the link, applied directly to app state. Everything below is allow-listed: unknown keys are @@ -5205,31 +4928,36 @@ var OB_STEPS=[ {icon:'📈',iconBg:'var(--surface2)',title:'Summary & What-If',body:'The Summary bar shows all key metrics at a glance. The What-if button lets you compare three SP scenarios side-by-side to find the best margin.',tip:'History auto-saves calculations. Use Compare to diff two entries.'}, {icon:'⌨️',iconBg:'var(--surface2)',title:'Shortcuts & Settings',body:'Press ? anytime to see keyboard shortcuts. Settings lets you set floor limits for GP% and Margin%, toggle dark mode, and control auto-save.',tip:'Press Q to toggle between Default and Quick mode instantly.'}, ]; -var OB_STEP=0; - -/** - * Start the onboarding walkthrough. - */ function obShow(){ OB_STEP=0; el('ob-overlay').classList.add('show'); obRender(); } -/** - * Dismiss onboarding and remember that it was seen. - */ function obSkip(){ el('ob-overlay').classList.remove('show'); localStorage.setItem('ob-done','1'); } -/** - * Advance onboarding, finishing after the last step. - */ function obNext(){ OB_STEP++; if(OB_STEP>=OB_STEPS.length){obSkip();return} obRender(); } + + +var OB_STEP=0; + +/** + * Start the onboarding walkthrough. + */ + +/** + * Dismiss onboarding and remember that it was seen. + */ + +/** + * Advance onboarding, finishing after the last step. + */ + /** * Draw the current onboarding step. */ diff --git a/tests/features.test.js b/tests/features.test.js index 4bf5760..fd1fad4 100644 --- a/tests/features.test.js +++ b/tests/features.test.js @@ -1125,6 +1125,24 @@ ok('app-extra.js exists', extraJs.length > 10000, extraJs.length + ' bytes'); ok('deferring moved a meaningful share out of the core', extraJs.length > 40 * 1024 && extraJs.length / (coreJs.length + extraJs.length) > 0.2, (100 * extraJs.length / (coreJs.length + extraJs.length)).toFixed(0) + '% deferred'); +// These drifted back into the core bundle while the README still described them +// as deferred. Named individually rather than counted, so a future move out of +// app-extra.js fails here rather than quietly costing 14KB on the critical path. +[['renderWhatIf', '_renderWhatIfImpl'], ['renderCompare', '_renderCompareImpl'], + ['exportHistoryCSV', '_exportHistoryCSVImpl']].forEach(([name, impl]) => { + ok(name + ' is deferred, not in the core bundle', + new RegExp('^function ' + impl + '\\(', 'm').test(extraJs) && + !new RegExp('^function ' + impl + '\\(', 'm').test(coreJs), + 'core=' + new RegExp('^function ' + impl, 'm').test(coreJs) + + ' extra=' + new RegExp('^function ' + impl, 'm').test(extraJs)); + ok('and reachable through a shim in the core', new RegExp('^function ' + name + '\\(', 'm').test(coreJs)); +}); +ok('the critical path stays under 100KB gzipped', (() => { + const zlib = require('zlib'); + const kb = zlib.gzipSync(readMarkup() + readAsset('assets/styles.css') + coreJs).length / 1024; + return kb < 100; +})(), (require('zlib').gzipSync(readMarkup() + readAsset('assets/styles.css') + coreJs).length / 1024).toFixed(1) + ' KB'); + ok('quick mode moved out', /^function fcBuildCards\(/m.test(extraJs) && !/^function fcBuildCards\(/m.test(coreJs)); ok('wizard moved out', /^function wzCalc\(/m.test(extraJs) && !/^function wzCalc\(/m.test(coreJs)); ok('quote rendering moved out', /^function qtRender\(/m.test(extraJs) && !/^function qtRender\(/m.test(coreJs)); From 769d09ed01c0ad8c259d1e3aff9f2bf62304e154 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 1 Aug 2026 02:40:58 +0000 Subject: [PATCH 2/3] Record the audit findings in the README MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous commit pushed the code but its README edit aborted partway on a line that had already been reworded, so the docs went in stale — still claiming Performance 98, LCP 2.1s and onboarding in the deferred bundle. Now says what the audit actually measured: Performance 97, LCP 2.5s, TBT 0–10ms, and that a single TBT reading is worth little here — one run in five reported 740ms against a median of 0. Also records what the audit taught rather than only the scores. The dominant main-thread cost is Style & Layout at ~325ms against 70ms of scripting: 1,043 nodes, 809 CSS rules, thirteen :has() selectors. And the two audits that score zero do so by choice — unminified JS is the no-build-step trade, unused JS is mostly the deferred bundle being warmed during idle. --- README.md | 29 ++++++++++++++++++++--------- tests/README.md | 6 +++--- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 34879b9..f875dba 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-1380%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-98-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-1387%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) @@ -138,7 +138,7 @@ Opening `index.html` from disk works too — the app runs, but the browser block index.html markup only assets/styles.css all styling assets/app.js core behaviour -assets/app-extra.js what-if, compare, quote, onboarding — loaded on demand +assets/app-extra.js what-if, compare, quote, CSV export — on demand assets/fonts.css self-hosted @font-face rules assets/fonts/ three woff2 files sw.js service worker @@ -734,9 +734,9 @@ Every number here is reproducible from the repo — none is hand-written. | Metric | Value | Reproduce with | |---|---|---| -| Tests | 1380 passing, 7 suites | `npm test` | -| Statement coverage | **82.6%** (app.js 86.3%, app-extra.js 68.5%) | `npm run coverage` | -| Lighthouse Performance | **98** | `npm i -D lighthouse && npm run lighthouse` | +| Tests | 1387 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** | ” | | Lighthouse Best Practices | **100** | ” | | Lighthouse SEO | 60 | ” | @@ -744,8 +744,19 @@ Every number here is reproducible from the repo — none is hand-written. Lighthouse runs against a local server that gzips and sets the same cache headers as `_headers`, on emulated mobile with throttling — so the scores reflect a realistic deployment rather than an unconfigured static host. Measured: FCP 1.5s, -LCP 2.1s, CLS 0. Total Blocking Time is noisy on a shared machine — 0ms on three -runs of four, 30ms on the other. +LCP 2.5s, TBT 0–10ms, CLS 0. Take a single Total Blocking Time reading with salt +— it is noisy on a shared machine, and one run in five here reported 740ms +against a median of 0. + +The main-thread cost is Style & Layout at ~325ms, not scripting (70ms eval, 32ms +parse) — a 1,043-node document against 809 CSS rules, thirteen of which use +`:has()`. That is what showing a keyboard-only focus ring on wrapper elements +costs, and it buys more than it costs. + +Two audits score zero by choice. `unminified-javascript` (~39KB) is the +no-build-step trade: what is in the repo is what the browser runs. +`unused-javascript` (~88KB) is mostly the deferred bundle, warmed during idle so +the quote builder and what-if open instantly — paid for after load, not before. **On the SEO score:** it is capped entirely by ``. `is-crawlable` is the only @@ -762,7 +773,7 @@ commands after significant changes. ## Tests -1380 assertions across seven suites. They load the real `index.html`, +1387 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.** @@ -773,7 +784,7 @@ npm test | Suite | Assertions | Covers | |---|---|---| -| `features` | 953 | GST, incentives, quantity, landed costs, rounding, undo/redo, quote maths, history | +| `features` | 960 | 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 | diff --git a/tests/README.md b/tests/README.md index aa16c86..2a3fcf3 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,6 @@ # Tests -1380 assertions across seven suites. They load the real `index.html`, +1387 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. @@ -33,7 +33,7 @@ The runner exits non-zero if anything fails, so CI catches it. | File | Assertions | Covers | |---|---|---| -| `features.test.js` | 953 | 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` | 960 | 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 | | `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 | @@ -118,7 +118,7 @@ Ranges are resolved **within** each source before being combined across sources. V8 emits them outermost-first, and a script's outermost range spans the whole file with a non-zero count — so OR-ing counts directly marks everything covered and reports a meaningless 100%. That mistake was made and caught here; the -resolved-then-unioned figure is 82.6%. +resolved-then-unioned figure is 82.7%. ## Writing a test From c4ab6248b44184bf8d1f896abdc8807577c14d37 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 1 Aug 2026 02:50:45 +0000 Subject: [PATCH 3/3] Allow indexing, and rewrite the tour for people who arrive cold MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Indexing is on. Removing the noindex alone would have scored 100 while leaving metadata that described the wrong thing — the title, description and share cards all said "automotive parts distribution, Sterling Spares", which is not what someone searching for a margin calculator is looking for. They now say what the tool does. Added a canonical URL, og:image and og:url so a shared link renders, a robots.txt and a sitemap. SEO 60 -> 100. The tour was the bigger problem. It was a feature list — "Default Mode", "Summary & What-If" — that assumed you already knew what MRP, GP% and an incentive were, and its first line said the app was built for one company. That is fine for a colleague and useless to a stranger from a search result, who is now the likeliest visitor. Six steps, rewritten to explain rather than enumerate: what the sum is, the sum on real numbers, the off-invoice rebates that catch people out, that GP % and Margin % are different figures, that the tax rate and currency are yours to set, and where the rest lives. Step two offers to fill the example in. An empty calculator teaches nothing and a newcomer will not invent numbers to try, so the tour now has something to point at and the screen is already working when it ends. Every figure the copy quotes is asserted against what the app renders — 150 of profit, 20.00% GP, 25.00% margin, and 168 once the two incentives are on. A tour that misstates the numbers is worse than no tour. Those four assertions failed first time at $149.20 and 19.90%, which was leftover state from an earlier block rather than bad copy: freshCalc resets neither the display currency nor the landed-cost fields, and 0.80 of outbound freight was still set. Also removed a placeholder assertion I had left returning true, and the stale "SEO is capped by noindex" note the audit script still printed. Service worker cache bumped so the new markup replaces the old. 1406 assertions. Performance 97, Accessibility 100, Best Practices 100, SEO 100. --- README.md | 27 +++++++++------ assets/app.js | 55 +++++++++++++++++++++++++---- assets/styles.css | 2 ++ index.html | 21 ++++++++---- robots.txt | 5 +++ sitemap.xml | 8 +++++ sw.js | 2 +- tests/README.md | 4 +-- tests/features.test.js | 78 +++++++++++++++++++++++++++++++++++++++++- tests/lighthouse.js | 9 +++-- 10 files changed, 182 insertions(+), 29 deletions(-) create mode 100644 robots.txt create mode 100644 sitemap.xml diff --git a/README.md b/README.md index f875dba..3e65223 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-1387%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-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) **Live app:** [calc.sterlingspares.com](https://calc.sterlingspares.com) @@ -146,6 +146,7 @@ manifest.json PWA manifest _headers response headers for the host tests/ test suite (dev-only) docs/ screenshots for this README +robots.txt · sitemap.xml indexing ``` --- @@ -528,6 +529,14 @@ a phone — rather than one long scroll: Arrow keys, Home and End move between tabs, and a tab whose sections are all switched off hides rather than leading nowhere. +### First run + +A six-step tour opens on a first visit, written for someone who arrived without +reading any of this. It starts with the problem rather than the features, offers +to **fill the example in** so the screen is working rather than empty, warns that +GP % and Margin % are not the same figure, and says plainly that the tax rate and +the currency are yours to set. Restart it any time from Settings → Help. + | Setting | Description | |---|---| | **Dark mode** | Full dark colour scheme | @@ -538,7 +547,7 @@ switched off hides rather than leading nowhere. | **Features** | Switch off anything you do not use | | **Saved presets** | Open the preset manager | | **Exchange rates** | Update now, and set a manual rate | -| **App tour** | Restart the onboarding walkthrough | +| **App tour** | Restart the six-step tour | | **Keyboard shortcuts** | View all shortcuts | | **Reset everything** | Clear every saved key and start as if the app were new | @@ -734,12 +743,12 @@ Every number here is reproducible from the repo — none is hand-written. | Metric | Value | Reproduce with | |---|---|---| -| Tests | 1387 passing, 7 suites | `npm test` | +| Tests | 1406 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** | ” | | Lighthouse Best Practices | **100** | ” | -| Lighthouse SEO | 60 | ” | +| Lighthouse SEO | **100** | ” | Lighthouse runs against a local server that gzips and sets the same cache headers as `_headers`, on emulated mobile with throttling — so the scores reflect a @@ -758,10 +767,8 @@ no-build-step trade: what is in the repo is what the browser runs. `unused-javascript` (~88KB) is mostly the deferred bundle, warmed during idle so the quote builder and what-if open instantly — paid for after load, not before. -**On the SEO score:** it is capped entirely by -``. `is-crawlable` is the only -failing audit, and it fails by design — this is an internal tool that should not -be indexed. Removing the meta tag would score 100 and is not wanted. +The app is indexable, with a `robots.txt`, a sitemap, and share-card metadata +that says what the tool does rather than who built it. Coverage is measured by mapping V8 coverage back to each bundle. The app runs inside jsdom as an inline script, so c8 and nyc attribute everything to the @@ -773,7 +780,7 @@ commands after significant changes. ## Tests -1387 assertions across seven suites. They load the real `index.html`, +1406 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.** @@ -784,7 +791,7 @@ npm test | Suite | Assertions | Covers | |---|---|---| -| `features` | 960 | GST, incentives, quantity, landed costs, rounding, undo/redo, quote maths, history | +| `features` | 979 | 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 | diff --git a/assets/app.js b/assets/app.js index f9418ab..606beff 100644 --- a/assets/app.js +++ b/assets/app.js @@ -255,6 +255,7 @@ ACT.a138 = function(self, event){ // Onboarding backdrop: dismiss only when the if(event.target===self)obSkip(); }; ACT.a139 = function(self, event){ OB_STEP===0?obSkip():(OB_STEP--,obRender()) }; ACT.a140 = function(self, event){ obNext() }; +ACT.obAction = function(){ var s=OB_STEPS[OB_STEP]; if(s&&s.action==='example')obFillExample(); }; /** * Register a delegated listener for one event type. @@ -4920,14 +4921,53 @@ document.addEventListener('keydown',function(e){ }); /* ── Onboarding ── */ +/* The tour is most people's first contact with the app — someone arriving from + a search result has not read the README and may not know the vocabulary. It + used to be a feature list ("Default Mode", "Summary & What-If") that assumed + you already knew what MRP, GP% and an incentive were, and step one said it + was built for one company. It now explains the problem, then shows the sum + on real numbers, then names the two figures people most often confuse. */ var OB_STEPS=[ - {icon:'₹',iconBg:'#1a191614',title:'Welcome to Pricing Calc',body:'A fast calculator for MRP-based pricing with GST, incentives, and margin analysis — built for Sterling Spares.',tip:'This tour takes about 30 seconds.'}, - {icon:'📊',iconBg:'var(--blue-bg)',title:'Default Mode',body:'Enter MRP, Cost Price disc%, and Selling Price disc%. The calculator shows GP%, Margin%, CP incl/excl GST, and flags if prices exceed MRP.',tip:'Use the Calculate bar to solve for Profit, SP, or CP.'}, - {icon:'⚡',iconBg:'var(--green-bg)',title:'Quick / Flashcard Mode',body:'Tap Quick in the header for a swipeable card-by-card flow. Enter MRP → CP → SP and get an instant summary. Works like Tinder — swipe left to advance.',tip:'On desktop, use Enter or arrow keys to navigate.'}, - {icon:'🎯',iconBg:'var(--amber-bg)',title:'Incentives',body:'CD, Early Bird, Quarterly, Annual, and Scheme incentives all reduce effective CP. Toggle them on with the Incentives panel — they feed into profit and margin automatically.',tip:'CD can be calculated on CP excl or incl GST.'}, - {icon:'📈',iconBg:'var(--surface2)',title:'Summary & What-If',body:'The Summary bar shows all key metrics at a glance. The What-if button lets you compare three SP scenarios side-by-side to find the best margin.',tip:'History auto-saves calculations. Use Compare to diff two entries.'}, - {icon:'⌨️',iconBg:'var(--surface2)',title:'Shortcuts & Settings',body:'Press ? anytime to see keyboard shortcuts. Settings lets you set floor limits for GP% and Margin%, toggle dark mode, and control auto-save.',tip:'Press Q to toggle between Default and Quick mode instantly.'}, + {icon:'%',iconBg:'#1a191614',title:'What this works out', + body:'You buy at a discount off a printed list price and sell at a smaller one. The gap is your margin — but rebates, tax and freight all move it. This does that sum live, so a quote can be checked before you give it.', + tip:'Six short steps, about a minute. Skip any time.'}, + + {icon:'🧮',iconBg:'var(--blue-bg)',title:'Try it on real numbers', + body:'A part listed at 1,000. You buy at 40% off and sell at 25% off, so you pay 600 and charge 750 — a profit of 150. Enter those three and the whole screen fills in.', + tip:'Press Fill this in below and the example is on screen when the tour ends.', + action:'example'}, + + {icon:'🎯',iconBg:'var(--amber-bg)',title:'The part that catches people out', + body:'Your supplier also gives you money that never appears on the invoice — a cash discount for paying early, a quarterly or annual rebate, a scheme. Switch those on under Incentives on CP and your real cost drops. Anything you pass on to your own customer goes under Incentives on SP.', + tip:'On the example, a 2% cash discount and 1% early-bird turn 150 of profit into 168.'}, + + {icon:'⚖️',iconBg:'var(--green-bg)',title:'GP % and Margin % are not the same', + body:'GP % is profit as a share of what you sell for. Margin % is profit as a share of what it cost you. The same deal reads 20.00% GP and 25.00% margin — so it is worth being sure which one your supplier means.', + tip:'Margin % is what a finance textbook calls markup. It is always the larger number.'}, + + {icon:'🌍',iconBg:'var(--surface2)',title:'Your currency, your tax rate', + body:'GST is one tap at 18% or 5%, but any rate from 0 to 100% works — VAT at 20% behaves identically. Under Show you can put the cost side, the sale side, or both into another currency, which is how an importer or exporter prices a deal.', + tip:'Rates are fetched on demand, cached for offline, and you can type your own.'}, + + {icon:'⌨️',iconBg:'var(--surface2)',title:'Where the rest lives', + body:'Quick is a card-by-card version for phones. Quote builds a multi-line quote with a blended GP. Everything saves as you type and works offline. If a feature is not useful to you, switch it off in Settings → Features and it leaves the screen.', + tip:'Press ? for shortcuts. Nothing you enter leaves your device.'} ]; + +/** + * Fill the calculator with the tour's example. + * + * An empty calculator teaches nothing, and a newcomer will not invent numbers + * to try. Populating it means the tour has something to point at, and the + * screen is already working when the tour ends. + */ +function obFillExample(){ + var m=el('mrp'); if(m)m.value='1000'; + setCM('excl'); var c=el('cpd'); if(c)c.value='40'; + setSM('excl'); var p=el('spd'); if(p)p.value='25'; + calc(); + toast('Example filled in',true); +} function obShow(){ OB_STEP=0; el('ob-overlay').classList.add('show'); @@ -4974,6 +5014,9 @@ function obRender(){ ?''+s.icon+'' :''+s.icon+''; el('ob-title').innerHTML=s.title; + // Only one step offers an action; the button is hidden on the rest. + var act=el('ob-action'); + if(act)act.style.display=s.action?'':'none'; el('ob-body').innerHTML=s.body; var tip=el('ob-tip'); if(s.tip){tip.innerHTML=s.tip;tip.style.display=''}else{tip.style.display='none'} diff --git a/assets/styles.css b/assets/styles.css index 39fdc44..74beb23 100644 --- a/assets/styles.css +++ b/assets/styles.css @@ -482,6 +482,8 @@ html[data-theme="dark"] .hist-del-btn:hover{background:rgba(239,68,68,0.15);bord .ob-btn-skip{background:none;border:none;color:var(--text3);font-size:13px;cursor:pointer;font-family:var(--font-body);padding:8px 4px} .ob-btn-next{flex:1;padding:12px;border-radius:50px;border:none;background:var(--accent);color:var(--accent-fg);font-size:14px;font-weight:600;cursor:pointer;font-family:var(--font-body);transition:opacity .15s} .ob-btn-next:hover{opacity:.88} +.ob-btn-action{display:block;width:100%;margin-top:14px;padding:10px 16px;border-radius:20px;border:1px solid var(--border-ctrl);background:transparent;color:var(--text2);font-size:12.5px;font-weight:600;font-family:var(--font-body);cursor:pointer;min-height:44px;transition:all .15s} +.ob-btn-action:hover{background:var(--surface2);color:var(--text)} .ob-tip{font-size:11.5px;color:var(--text2);text-align:center;background:var(--surface2);border:1px solid var(--border);border-radius:10px;padding:10px 14px;line-height:1.5} .hmenu-dropdown{display:none;position:absolute;right:0;top:calc(100% + 8px);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-modal);min-width:160px;overflow:hidden;z-index:400} diff --git a/index.html b/index.html index 0f408be..9bce152 100644 --- a/index.html +++ b/index.html @@ -29,16 +29,22 @@ suppressed per-control with `touch-action:manipulation` instead of by disabling zoom globally. --> - - + + - - - + + + + + + + - + + + @@ -49,7 +55,7 @@ -Price Calc — Sterling Spares +Price Calc — margin calculator for distributors and traders @@ -1138,6 +1144,7 @@
+
diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..cd6688d --- /dev/null +++ b/robots.txt @@ -0,0 +1,5 @@ +# Indexable: this is a public tool, not an internal one. +User-agent: * +Allow: / + +Sitemap: https://calc.sterlingspares.com/sitemap.xml diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..9ca1e19 --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,8 @@ + + + + https://calc.sterlingspares.com/ + monthly + 1.0 + + diff --git a/sw.js b/sw.js index 8fa643b..3e2ca32 100644 --- a/sw.js +++ b/sw.js @@ -1,5 +1,5 @@ /* Sterling Spares Pricing Calculator — Service Worker */ -const CACHE = 'pc-v5'; +const CACHE = 'pc-v6'; // Bumped when the precache list changes, so old entries are evicted on activate. const PRECACHE = [ '/', diff --git a/tests/README.md b/tests/README.md index 2a3fcf3..b8bb292 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,6 @@ # Tests -1387 assertions across seven suites. They load the real `index.html`, +1406 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. @@ -33,7 +33,7 @@ The runner exits non-zero if anything fails, so CI catches it. | File | Assertions | Covers | |---|---|---| -| `features.test.js` | 960 | 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` | 979 | 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 | | `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 | diff --git a/tests/features.test.js b/tests/features.test.js index fd1fad4..f3adff2 100644 --- a/tests/features.test.js +++ b/tests/features.test.js @@ -2659,7 +2659,83 @@ runFetchCases().then(() => { ok('an unknown scope leaves the current one alone', (w.setDisplayCcy('USD', 'nonsense'), w.FX_SCOPE === 'both'), w.FX_SCOPE); - R.section('\n=== 30a. The default view stays uncluttered ==='); + R.section('\n=== 29b. Onboarding, and indexing ==='); + +// Most people's first contact is the tour, not the README. It used to be a +// feature list that assumed the vocabulary and said it was built for one +// company; the figures it quotes are now checked against what the app renders, +// because a tour that misstates the numbers is worse than no tour. +ok('the tour no longer names one company', + !w.OB_STEPS.some(s => /Sterling Spares/.test(s.body + s.title)), + w.OB_STEPS.map(s => s.title).join(' | ')); +ok('it opens with the problem, not a feature', + /works out/i.test(w.OB_STEPS[0].title), w.OB_STEPS[0].title); +ok('it explains GP versus margin somewhere', + w.OB_STEPS.some(s => /GP %[\s\S]*Margin %|Margin %[\s\S]*GP %/.test(s.title + s.body)), + w.OB_STEPS.map(s => s.title).join(' | ')); +ok('and that the tax rate is not fixed', + w.OB_STEPS.some(s => /VAT|0 to 100/.test(s.body))); +ok('one step offers to fill the example in', + w.OB_STEPS.filter(s => s.action === 'example').length === 1); + +// The example is what the tour points at, so its figures must be the ones the +// copy quotes. +// freshCalc does not reset the display currency or the landed-cost fields, and +// earlier blocks leave both set — which showed up as $149.20 where the tour +// quotes 150, the 0.80 being a leftover outbound freight. +w.setDisplayCcy('INR', 'both'); +if (d.getElementById('landed')) d.getElementById('landed').value = ''; +if (d.getElementById('sp-landed')) d.getElementById('sp-landed').value = ''; +freshCalc(1000, 40, 25); +w.obFillExample(); +ok('the example fills the calculator', + d.getElementById('mrp').value === '1000' && d.getElementById('cpd').value === '40' && + d.getElementById('spd').value === '25'); +ok('and profit reads the 150 the tour quotes', + d.getElementById('s-pr').textContent.trim() === '₹150.00', + d.getElementById('s-pr').textContent); +ok('with the 20.00% GP it quotes', + d.getElementById('s-gp').textContent.trim() === '20.00%', + d.getElementById('s-gp').textContent); +ok('and the 25.00% margin it quotes', + d.getElementById('s-mg').textContent.trim() === '25.00%', + d.getElementById('s-mg').textContent); +// Step three claims the two incentives turn 150 into 168. +d.getElementById('it-cd').checked = true; d.getElementById('iv-cd').value = '2'; w.syncToggle('cd'); +d.getElementById('it-eb').checked = true; d.getElementById('iv-eb').value = '1'; w.syncToggle('eb'); +w.calc(); +ok('and the incentive claim holds: 150 becomes 168', + d.getElementById('s-pr').textContent.trim() === '₹168.00', + d.getElementById('s-pr').textContent); +d.getElementById('it-cd').checked = false; w.syncToggle('cd'); +d.getElementById('it-eb').checked = false; w.syncToggle('eb'); + +ok('the action button is a real control with a label', + d.getElementById('ob-action') !== null && + d.getElementById('ob-action').textContent.trim().length > 0, + (d.getElementById('ob-action') || {}).textContent); + +// ── Indexing ──────────────────────────────────────────────────────────── +ok('the page is indexable', //.test(mk), + (mk.match(/robots[^>]*/) || [''])[0]); +ok('with a canonical URL', /rel="canonical"/.test(mk)); +ok('a description that says what it does, not who made it', + /[^<]*calculator[^<]*<\/title>/i.test(mk), (mk.match(/[^<]*/) || [''])[0]); +ok('share cards carry an image and a URL', + /og:image/.test(mk) && /og:url/.test(mk)); +ok('robots.txt allows crawling', + fs.readFileSync(path.join(ROOT, 'robots.txt'), 'utf8').indexOf('Allow: /') !== -1); +ok('and points at a sitemap', + fs.readFileSync(path.join(ROOT, 'robots.txt'), 'utf8').indexOf('Sitemap:') !== -1); +ok('the sitemap lists the app', (() => { + const sm = fs.readFileSync(path.join(ROOT, 'sitemap.xml'), 'utf8'); + return sm.indexOf('<loc>') !== -1 && sm.indexOf('calc.sterlingspares.com') !== -1; +})()); + +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 // cards directly above them. diff --git a/tests/lighthouse.js b/tests/lighthouse.js index c138596..9aa5d81 100644 --- a/tests/lighthouse.js +++ b/tests/lighthouse.js @@ -110,8 +110,13 @@ function serve() { console.log('\n Accessibility failures:'); failed.forEach(x => console.log(' · ' + x.id + ' — ' + x.title)); } - console.log('\n SEO is capped by the deliberate <meta name="robots" content="noindex">'); - console.log(' on this internal tool; is-crawlable is the only failing audit.\n'); + const seoFails = cats.seo.auditRefs.map(r => res.lhr.audits[r.id]) + .filter(x => x && x.score !== null && x.score < 1); + if (seoFails.length) { + console.log('\n SEO failures:'); + seoFails.forEach(x => console.log(' · ' + x.id + ' — ' + x.title)); + } + console.log(''); } await browser.close();