diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e08435..302cf41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The NOC charts have tooltips, on the dashboard and on the wallboard in the NOC window: hover (or touch) a chart to see every series on that day, with a total. Click an entry in the legend to hide or show that series, and the scale follows what is left. The "how it arrives" bars on the Traffic tab show the same kind of tooltip, and its legend picks which ways in (caches, PNIs, IX peering, transit) the table counts. ## [2.9.1] — 2026-11-04 - Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten. diff --git a/scripts/lib/mcp-game.js b/scripts/lib/mcp-game.js index 0de39b8..cf61800 100644 --- a/scripts/lib/mcp-game.js +++ b/scripts/lib/mcp-game.js @@ -11,7 +11,7 @@ const path = require('node:path'); const { load } = require('../../tests/harness'); const HEADLESS_JS = fs.readFileSync(path.join(__dirname, 'mcp-headless.js'), 'utf8'); -const ACT_DIR = path.join(__dirname, '..', '..', 'src', 'game', '90-actions'); +const ACT_DIRS = ['90-actions', '94-dashboard', '96-map'].map((d) => path.join(__dirname, '..', '..', 'src', 'game', d)); // The arguments of the actions the command tables do not type (the drafts), read from their source // (`dfSrc:({v})=>`): in the page the actions are wrapped for puzzle mode, so their own parameter lists are not visible. @@ -20,8 +20,8 @@ function actArgs() { if (ACT_ARGS) return ACT_ARGS; ACT_ARGS = {}; const re = /(?:^|[\s,{])([A-Za-z]\w*):\s*(?:async\s*)?\(\s*\{([^}]*)\}\s*(?:=\s*\{\s*\}\s*)?\)\s*=>/g; - for (const f of fs.readdirSync(ACT_DIR).filter((f) => f.endsWith('.js')).sort()) { - const src = fs.readFileSync(path.join(ACT_DIR, f), 'utf8'); + for (const [dir, f] of ACT_DIRS.flatMap((d) => fs.readdirSync(d).filter((f) => f.endsWith('.js')).sort().map((f) => [d, f]))) { + const src = fs.readFileSync(path.join(dir, f), 'utf8'); for (const m of src.matchAll(re)) if (!ACT_ARGS[m[1]]) ACT_ARGS[m[1]] = m[2].split(',').map((a) => a.split('=')[0].trim()).filter(Boolean); } return ACT_ARGS; diff --git a/site/i18n/de.js b/site/i18n/de.js index 7d8e371..a9c0de4 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1757,6 +1757,7 @@ "dashboard.all_n":"Alle ({n})", "dashboard.amp_huts_and_spares":"Verstärkerhütten und Ersatzteile", "dashboard.caches_pnis_and_ix":"Caches, PNIs und IX", +"dashboard.chart_total":"Gesamt", "dashboard.customers_are_upset":"Kunden sind verärgert", "dashboard.delivered_30_days":"Geliefert, 30 Tage", "dashboard.five_nines_ish":"fünf Neunen, so ungefähr", diff --git a/site/i18n/es.js b/site/i18n/es.js index 1acb3a7..b554085 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1755,6 +1755,7 @@ "dashboard.all_n":"Todo ({n})", "dashboard.amp_huts_and_spares":"Casetas de amplificación y repuestos", "dashboard.caches_pnis_and_ix":"cachés, PNIs e IX", +"dashboard.chart_total":"Total", "dashboard.customers_are_upset":"los clientes están molestos", "dashboard.delivered_30_days":"Entregado, 30 días", "dashboard.five_nines_ish":"casi cinco nueves", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b773527..a82034f 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1755,6 +1755,7 @@ "dashboard.all_n":"Toutes ({n})", "dashboard.amp_huts_and_spares":"Abris d’amplis et rechanges", "dashboard.caches_pnis_and_ix":"caches, PNI et IX", +"dashboard.chart_total":"Total", "dashboard.customers_are_upset":"les clients râlent", "dashboard.delivered_30_days":"Livré, 30 jours", "dashboard.five_nines_ish":"cinq neuf, ou presque", diff --git a/site/i18n/it.js b/site/i18n/it.js index b050b08..8ea4136 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1755,6 +1755,7 @@ "dashboard.all_n":"Tutte ({n})", "dashboard.amp_huts_and_spares":"Shelter amplificatori e ricambi", "dashboard.caches_pnis_and_ix":"cache, PNI e IX", +"dashboard.chart_total":"Totale", "dashboard.customers_are_upset":"clienti furiosi", "dashboard.delivered_30_days":"Consegnato, 30 giorni", "dashboard.five_nines_ish":"cinque nove, più o meno", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cf2987c..1117eac 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1755,6 +1755,7 @@ "dashboard.all_n":"Todos ({n})", "dashboard.amp_huts_and_spares":"Abrigos de amplificador e reservas", "dashboard.caches_pnis_and_ix":"caches, PNIs e IX", +"dashboard.chart_total":"Total", "dashboard.customers_are_upset":"clientes furiosos", "dashboard.delivered_30_days":"Entregue, 30 dias", "dashboard.five_nines_ish":"cinco noves, quase", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 275791e..d7e74ed 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -415,6 +415,7 @@ const API_CMD={ const API_VIEW={ traceMode:{args:[['m','string']],doc:'Redo the open traceroute in a routing mode: normal, fast or scenic.'}, + chartToggle:{args:[['c','string'],['k','string']],doc:'Hide or show one series of a dashboard chart (a legend click); hiding every series shows them all again.'}, help:{args:[],doc:'Open the how-to-play modal.'}, dash:{args:[],doc:'Open the NOC dashboard.'}, dashClose:{args:[],doc:'Close the NOC dashboard.'}, diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index f588fbb..8fcd742 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -161,8 +161,9 @@ function linkPanel(id){ return h; } const EGC={c:[tr('common.caches'),'#16A866'],p:[tr('common.pnis'),'#7B61FF'],ix:[tr('common.ix_peering_0631'),'#FFD23F'],t:[tr('common.transit'),'#FF8A3D'],l2:[tr('common.l2_circuits'),'#2F8CFF']}; -function svgChart(rows,stackKeys,lines,fmtY){ - const W=600,H=180,L=50,B=20,T=8,Rr=8;if(rows.length<2)return `

${tr('link_panels.collecting_data_check_back_in_a')}

`; +const CHBOX={W:600,H:180,L:50,B:20,T:8,R:8}; +function svgChart(rows,stackKeys,lines,fmtY,id){ + const {W,H,L,B,T,R:Rr}=CHBOX,off=(id&&UI.chartOff&&UI.chartOff[id])||{};stackKeys=stackKeys.filter(k=>!off[k]);lines=lines.filter(ln=>!off[ln.k]);if(rows.length<2)return `

${tr('link_panels.collecting_data_check_back_in_a')}

`; let ymax=1;for(const r of rows){let s=0;for(const k of stackKeys)s+=r[k]||0;ymax=Math.max(ymax,s);for(const ln of lines)ymax=Math.max(ymax,r[ln.k]||0);}ymax*=1.1; const x=i=>L+(W-L-Rr)*i/(rows.length-1),y=v=>T+(H-T-B)*(1-v/ymax);let g=''; for(let j=0;j<=3;j++){const v=ymax*j/3,yy=y(v);g+=`${fmtY(v)}`;} @@ -170,7 +171,7 @@ function svgChart(rows,stackKeys,lines,fmtY){ for(const k of stackKeys){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`;for(let i=1;i=0;i--)d+=`L${x(i)},${y(base[i])}`;g+=``;top.forEach((v,i)=>base[i]=v);} for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;const last=rows[rows.length-1][ln.k]||0;g+=``;} g+=`${dateStr(rows[0].d)}${dateStr(rows[rows.length-1].d)}`; - return `${g}`;} + return `${g}`;} // For a network you currently reach over transit: the cheapest way to move it to peering. // Exchange members as sets, rebuilt once per routing pass: hints are asked for many networks at a time. let IXMR=null,IXMC={};const ixHas=(x,id)=>{if(IXMR!==R){IXMR=R;IXMC={};}return (IXMC[x]||(IXMC[x]=new Set(ixMembers(x)))).has(id);}; diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 269f689..4ea4fae 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -7,20 +7,22 @@ function renderDash(){checkLayer(); const tile=(l,v,sub)=>`
${l}
${v}
${sub?`
${sub}
`:''}
`; let h=`
AS${S.asn} · ${esc(S.name)} · ${tierLabel()}

${tr('common.noc_dashboard')}

`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=`
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}
-

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)))}
${Object.keys(EGC).map(k=>`${EGC[k][0]} ${pct((R.egT[k]||0)/tot)}`).join('')}${tr('common.demand')}
-

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v))}
${tr('common.revenue')}${tr('common.costs')}
+

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}
+

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')}

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; const tT=(R.egT.t||0)||1; - const row=(n,e,want)=>{const t=e.c+e.p+e.ix+e.t;return {n,e,t,want,cost:(R.cost.transit||0)*e.t/tT,lost:want>0.01?Math.max(0,1-t/want):0};}; + const offMix=(UI.chartOff&&UI.chartOff.mix)||{},filt=Object.keys(offMix).length>0; + // The legend above the table picks which ways in count; "lost" still looks at everything the network gets. + const row=(n,e0,want)=>{const e={};for(const k of ['c','p','ix','t'])e[k]=offMix[k]?0:e0[k];const t=e.c+e.p+e.ix+e.t,all=e0.c+e0.p+e0.ix+e0.t;return {n,e,t,want,cost:(R.cost.transit||0)*e.t/tT,lost:want>0.01?Math.max(0,1-all/want):0};}; const nets=NETS.filter(n=>!n.tail).map(n=>row(n,R.netEg[n.id]||{c:0,p:0,ix:0,t:0},R.demTo[n.id]||0)); {const e={c:0,p:0,ix:0,t:0};let w=0;for(const n of NETS)if(n.tail){const x=R.netEg[n.id];if(x)for(const k in e)e[k]+=x[k]||0;w+=R.demTo[n.id]||0;}nets.push(row({id:'_tail',name:tr('dashboard.the_long_tail_n_small_networks',{n:NETS.filter(n=>n.tail).length}),asn:'many',type:'eye',col:'#8A93B8'},e,w));} - for(let i=nets.length-1;i>=0;i--)if(!(nets[i].t>0.01||nets[i].want>0.01))nets.splice(i,1); + for(let i=nets.length-1;i>=0;i--)if(!(nets[i].t>0.01||(!filt&&nets[i].want>0.01)))nets.splice(i,1); {const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||b.t-a.t;});} if(DT==='cust')h+=custSection(); if(DT==='conn')h+=connSection(); if(DT==='traffic')h+=`
${btn(tr('ops.standing_orders'),'opsOpen',{},'sm')}
`; - if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${['c','p','ix','t'].map(k=>`${EGC[k][0]}`).join('')}
${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>``).join('')} - ${nets.map(({n,e,t,want})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm pall'):''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${t?['c','p','ix','t'].filter(k=>e[k]>0).map(k=>``).join(''):''}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}
`; + if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${chartLegend('mix')}
${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>``).join('')} + ${nets.map(({n,e,t,want,lost})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm pall'):''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(lost):'—'}
`; if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`

${tr('dashboard.who_your_transit_carries')}

${tr('dashboard.the_networks_you_pay_transit_to')}

${top.map(([id,v])=>`
${logo(NET[id])}
${esc(NET[id].name)} AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}
${esc(offTransitHint(id))}
${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}
`).join('')}
`;} const ls=S.links.filter(l=>capOf(l)>0).map(l=>({l,u:(R.load[l.id]||0)/capOf(l)})).sort((a,b)=>b.u-a.u).slice(0,8); const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6); diff --git a/src/game/94-dashboard/65-chart-legend.js b/src/game/94-dashboard/65-chart-legend.js new file mode 100644 index 0000000..63cfdfa --- /dev/null +++ b/src/game/94-dashboard/65-chart-legend.js @@ -0,0 +1,44 @@ +/* The NOC charts: legend entries switch a series on and off (the scale follows what is left), and hovering or + touching a chart shows every visible series on that day. View state only: UI.chartOff is never saved. */ +const CHARTS={ + traffic:{stack:['c','p','ix','t','l2'],lines:['dem'],fmt:v=>fmtG(v),name:k=>k==='dem'?tr('common.demand'):EGC[k][0],col:k=>k==='dem'?'#1E2640':EGC[k][1]}, + mix:{stack:['c','p','ix','t'],lines:[],fmt:v=>fmtG(v),name:k=>EGC[k][0],col:k=>EGC[k][1]}, // the Traffic tab's table + money:{stack:[],lines:['rev','cost'],fmt:v=>fmt$(v),name:k=>k==='rev'?tr('common.revenue'):tr('common.costs'),col:k=>k==='rev'?'#16A866':'#FF4D5E'} +}; +const chartKeys=C=>[...C.stack,...C.lines]; +function chartLegend(id,label){const C=CHARTS[id],off=(UI.chartOff&&UI.chartOff[id])||{}; + return `
${chartKeys(C).map(k=>``).join('')}
`;} +Object.assign(ACT,{ + chartToggle:({c,k})=>{const C=CHARTS[c];if(!C||!chartKeys(C).includes(k))return; + const off=((UI.chartOff=UI.chartOff||{})[c]=UI.chartOff[c]||{});if(off[k])delete off[k];else off[k]=1; + if(chartKeys(C).every(x=>off[x]))UI.chartOff[c]={}; // nothing left to draw: show everything again + renderDash();}, +}); +// The tooltip and its cursor line sit on , outside the dashboard, so the per-tick redraw never removes them. +// Pointer moves are frequent: the tip is only rebuilt (and measured) when what it shows changes, not on every pixel. +let chartTip=null,chartCur=null,chartKey='',chartTw=0,chartTh=0; +function chartHide(){if(chartTip&&!chartTip.hidden){chartTip.hidden=chartCur.hidden=true;chartKey='';}} +function chartEnsure(){if(!chartTip){chartTip=document.createElement('div');chartTip.className='chtip';chartCur=document.createElement('div');chartCur.className='chcur';document.body.append(chartCur,chartTip);}} +// Fill the tip when its content key changes; measure it once, so moving inside the same content reads no layout. +function chartFill(key,html,showCur){if(key===chartKey&&!chartTip.hidden)return false;chartKey=key;chartTip.innerHTML=html;chartTip.hidden=false;chartCur.hidden=!showCur;chartTw=chartTip.offsetWidth;chartTh=chartTip.offsetHeight;return true;} +// Keep the tip inside the window, beside x and above y (below it when there is no room). +function chartPlace(x,cy){const tw=chartTw,th=chartTh; + chartTip.style.left=Math.max(4,Math.min(innerWidth-tw-4,x+12>innerWidth-tw-4?x-tw-12:x+12))+'px'; + chartTip.style.top=Math.max(4,Math.min(innerHeight-th-4,cy-th-8<4?cy+14:cy-th-8))+'px';} +function chartShow(svg,cx,cy){const id=svg.dataset.ch,C=CHARTS[id],H=S&&S.hist||[],n=Math.min(90,H.length),r=svg.getBoundingClientRect(),[bW,bH,bL,bT,bB,bR]=svg.dataset.box?svg.dataset.box.split(',').map(Number):[CHBOX.W,CHBOX.H,CHBOX.L,CHBOX.T,CHBOX.B,CHBOX.R]; + if(!C||n<2||!r.width)return chartHide(); + chartEnsure(); + const sx=r.width/bW,i=Math.max(0,Math.min(n-1,Math.round(((cx-r.left)/sx-bL)/(bW-bL-bR)*(n-1)))),row=H[H.length-n+i],off=(UI.chartOff&&UI.chartOff[id])||{}; + const x=r.left+(bL+(bW-bL-bR)*i/(n-1))*sx; + const key=id+'|'+row.d+'|'+Object.keys(off).join(); + if(chartFill(key,chartHtml(C,row,off),true)||chartCur.dataset.x!==String(x)){chartCur.dataset.x=x;chartCur.style.cssText=`left:${x}px;top:${r.top+bT*sx}px;height:${(bH-bT-bB)*sx}px`;} + chartPlace(x,cy);} +function chartHtml(C,row,off){const ks=chartKeys(C).filter(k=>!off[k]),st=C.stack.filter(k=>!off[k]); + return `${dateStr(row.d)}`+ks.map(k=>`
${C.name(k)}${C.fmt(row[k]||0)}
`).join('')+(st.length>1?`
${tr('dashboard.chart_total')}${C.fmt(st.reduce((a,k)=>a+(row[k]||0),0))}
`:'');} +// The "how it arrives" bars of the Traffic tab: the same tip, with each way in and its share. +function mixShow(el,cx,cy){const raw=el.dataset.mix;chartEnsure(); + if(chartKey!=='mix|'+raw||chartTip.hidden){let m;try{m=JSON.parse(raw);}catch(e){return chartHide();} + const ks=['c','p','ix','t'].filter(k=>m[k]>0),tot=ks.reduce((a,k)=>a+m[k],0); + chartFill('mix|'+raw,ks.length?ks.map(k=>`
${EGC[k][0]}${fmtG(m[k])} · ${pct(m[k]/tot)}
`).join(''):tr('common.nothing_yet'),false);} + chartPlace(cx,cy);} +for(const t of ['pointermove','pointerdown'])document.addEventListener(t,e=>{const c=e.target.closest&&e.target.closest('svg[data-ch],.mix[data-mix]');if(!c)chartHide();else if(c.dataset.mix!==undefined)mixShow(c,e.clientX,e.clientY);else chartShow(c,e.clientX,e.clientY);}); diff --git a/src/game/94-dashboard/90-noc-window.js b/src/game/94-dashboard/90-noc-window.js index 82b45fc..83d8189 100644 --- a/src/game/94-dashboard/90-noc-window.js +++ b/src/game/94-dashboard/90-noc-window.js @@ -5,7 +5,7 @@ per network, opened once a window says hello, so other games' tabs never unpack them. With no window nothing is sent. */ const NOC_HB=3000,NOC_LOST=10000,NOC_GAP=1000; // What a click in the window does: changes only its own view, or runs in the game. Every button the dashboard draws is in one list. -const NOC_LOCAL=['connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore']; +const NOC_LOCAL=['chartToggle','connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore']; const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagP','lagT','leaseSwap','netFocus','opsOpen','pni','pniAllOpen']; const NOC={win:false,id:null,ctl:null,st:null,stId:null,peer:false,until:0,dirty:false,sent:0,speed:1,hid:false,yoAt:0,gone:false}; {const id=RW_IN?null:new URLSearchParams(location.search).get('noc');if(slotOkId(id)){NOC.win=true;NOC.id=id;}} diff --git a/src/game/94-dashboard/91-noc-wall.js b/src/game/94-dashboard/91-noc-wall.js index c990415..5025513 100644 --- a/src/game/94-dashboard/91-noc-wall.js +++ b/src/game/94-dashboard/91-noc-wall.js @@ -12,7 +12,7 @@ const nwG=v=>v>=1000?(+(v/1000).toFixed(1))+'T':(v>=10||v===0?Math.round(v):+v.t const nwMapBox=()=>{let y0=Infinity,y1=-Infinity;for(const p of COAST){const b=polyBox(p);if(ringArea(p)>=600){y0=Math.min(y0,b[1]);y1=Math.max(y1,b[3]);}}return [0,Math.floor(y0),W,Math.ceil(y1-y0)];}; function nwLand(){let d='';for(const p of COAST){if(ringArea(p)<600&&!CITIES.some(c=>inPoly(c.x,c.y,p)))continue;d+='M'+p.map(q=>Math.round(q[0])+' '+Math.round(q[1])).join('L')+'Z';}return d;} // ---------- charts ---------- -function nwChart(rows,stack,lines,fmtY,CW=900,CH=260,L=62){if(rows.length<2)return `

${tr('link_panels.collecting_data_check_back_in_a')}

`; +function nwChart(rows,stack,lines,fmtY,CW=900,CH=260,L=62,id=''){if(rows.length<2)return `

${tr('link_panels.collecting_data_check_back_in_a')}

`; const B=22,T=8,Rr=8;let ymax=1;for(const r of rows){let s=0;for(const k of stack)s+=r[k]||0;ymax=Math.max(ymax,s);for(const ln of lines)ymax=Math.max(ymax,r[ln.k]||0);}ymax*=1.1; const x=i=>+(L+(CW-L-Rr)*i/(rows.length-1)).toFixed(1),y=v=>+(T+(CH-T-B)*(1-v/ymax)).toFixed(1);let g=''; for(let j=0;j<=4;j++){const v=ymax*j/4,yy=y(v);g+=`${esc(fmtY(v))}`;} @@ -21,7 +21,7 @@ function nwChart(rows,stack,lines,fmtY,CW=900,CH=260,L=62){if(rows.length<2)retu g+=``;top.forEach((v,i)=>base[i]=v);} for(const ln of lines){let d='';rows.forEach((r,i)=>{d+=(i?'L':'M')+x(i)+','+y(r[ln.k]||0);});g+=``;} g+=`${esc(dateStr(rows[0].d))}${esc(dateStr(rows[rows.length-1].d))}`; - return `${g}`;} + return `${g}`;} function nwSpark(vals,col){if(vals.length<2)return '';let a=Infinity,b=-Infinity;for(const v of vals){if(vb)b=v;}const sp=b-a||1; const pts=vals.map((v,i)=>(100*i/(vals.length-1)).toFixed(1)+','+(26-22*(v-a)/sp).toFixed(1)).join(' '); return ``;} @@ -80,11 +80,11 @@ function nocWall(){if(!NOCW.built)nwBuild();const rows=(S.hist||[]).slice(-90),A NOCW.sum={bad:A.filter(a=>a.k==='bad').length,warn:A.filter(a=>a.k==='warn').length}; const put=(id,h)=>{const e=$(id);if(e._h!==h){e._h=h;morph(e,h);}}; put('nwTiles',nwTiles());put('nwOver',nwMap());put('nwAlarms',nwAlarmsHtml(A)); - put('nwTraffic',`

${esc(tr('dashboard.traffic_by_way_out'))}

${Object.keys(EGC).filter(k=>(R.egT[k]||0)>0.01||rows.some(r=>(r[k]||0)>0)).map(k=>`${esc(EGC[k][0])} ${esc(fmtG(R.egT[k]||0))}`).join('')}${esc(tr('common.demand'))}
${nwChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#E8EEFA',dash:true}],nwG)}`); + put('nwTraffic',`

${esc(tr('dashboard.traffic_by_way_out'))}

${Object.keys(EGC).filter(k=>(R.egT[k]||0)>0.01||rows.some(r=>(r[k]||0)>0)).map(k=>`${esc(EGC[k][0])} ${esc(fmtG(R.egT[k]||0))}`).join('')}${esc(tr('common.demand'))}
${nwChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#E8EEFA',dash:true}],nwG,900,260,62,'traffic')}`); put('nwPorts',nwPorts()); put('nwRouters',nwBars(tr('common.router_load'),Object.keys(S.pops).map(c=>[CITY[c].name,`${S.pops[c].routers||1} × ${RG[S.pops[c].rgen||0].n}`,(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)]).sort((a,b)=>b[2]-a[2]).slice(0,6))); put('nwLinks',nwBars(tr('common.busiest_links'),S.links.filter(l=>capOf(l)>0).map(l=>[`${CITY[l.a].name} ⇄ ${CITY[l.b].name}`,capName(l),(R.load[l.id]||0)/capOf(l)]).sort((a,b)=>b[2]-a[2]).slice(0,6))); - put('nwMoney',`

${esc(tr('dashboard.money_per_month'))}

${esc(tr('common.revenue'))}${esc(tr('common.costs'))}
${nwChart(rows,[],[{k:'rev',col:NW_COL.ok},{k:'cost',col:NW_COL.bad}],fmt$,520,220,74)}`);} + put('nwMoney',`

${esc(tr('dashboard.money_per_month'))}

${esc(tr('common.revenue'))}${esc(tr('common.costs'))}
${nwChart(rows,[],[{k:'rev',col:NW_COL.ok},{k:'cost',col:NW_COL.bad}],fmt$,520,220,74,'money')}`);} // The window's own controls never reach the game: they change what this screen shows. function nocUiClick(e){const b=e.target.closest&&e.target.closest('[data-nc]');if(!b)return;const v=b.getAttribute('data-nc'); if(v==='wall'||v==='details')nocView(v); diff --git a/src/i18n/en.js b/src/i18n/en.js index 2345643..e63c90e 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1756,6 +1756,7 @@ "dashboard.all_n":"All ({n})", "dashboard.amp_huts_and_spares":"Amp huts and spares", "dashboard.caches_pnis_and_ix":"caches, PNIs and IX", +"dashboard.chart_total":"Total", "dashboard.customers_are_upset":"customers are upset", "dashboard.delivered_30_days":"Delivered, 30 days", "dashboard.five_nines_ish":"five nines-ish", diff --git a/src/styles/42-chart-tooltips.css b/src/styles/42-chart-tooltips.css new file mode 100644 index 0000000..34334c6 --- /dev/null +++ b/src/styles/42-chart-tooltips.css @@ -0,0 +1,15 @@ +.legend .lg{font:inherit;color:inherit;background:none;border:0;padding:2px 4px;margin:-2px -4px;border-radius:6px;cursor:pointer} +.legend .lg:hover{background:rgba(30,38,64,.08)} +.legend .lg.off{opacity:.45;text-decoration:line-through} +.chart[data-ch]{touch-action:pan-y;cursor:crosshair} +.chtip{position:fixed;z-index:60;pointer-events:none;background:var(--ink);color:#fff;border-radius:8px;padding:6px 9px;font-size:11.5px;font-weight:700;box-shadow:0 4px 14px rgba(0,0,0,.3);min-width:130px} +.chtip[hidden],.chcur[hidden]{display:none} +.chtip div{display:flex;align-items:center;gap:6px;margin-top:2px} +.chtip div span{margin-left:auto;padding-left:10px;font-variant-numeric:tabular-nums} +.chtip i{width:9px;height:9px;border-radius:3px;border:1px solid #fff} +.chtip .tot{border-top:1px solid rgba(255,255,255,.35);margin-top:4px;padding-top:3px} +.chcur{position:fixed;z-index:59;pointer-events:none;width:0;border-left:1px dashed var(--ink)} +.mix[data-mix]{cursor:help} +.nw-chart[data-ch]{touch-action:pan-y;cursor:crosshair} +.noc-window .chtip{border:1px solid #3A4A78} +.noc-window .chcur{border-left-color:#E8EEFA} diff --git a/src/styles/45-noc-window.css b/src/styles/45-noc-window.css index 6b953fc..e215a87 100644 --- a/src/styles/45-noc-window.css +++ b/src/styles/45-noc-window.css @@ -1,7 +1,7 @@ /* The NOC window (?noc=): a dark wallboard for a second display, and the dashboard's own tabs under Details. */ body.noc-window{background:#0B1224;overflow:auto} #nocBoard{color:#E8EEFA} -body.noc-window>*:not(#nocBoard):not(#dash):not(#toasts):not(script){display:none !important} +body.noc-window>*:not(#nocBoard):not(#dash):not(#toasts):not(.chtip):not(.chcur):not(script){display:none !important} body.noc-window #dash{position:static;background:none;overflow:visible;padding:0 12px 16px} body.noc-window #toasts{z-index:20} body.noc-window [data-act="dashClose"]{display:none} diff --git a/tests/chart-legend.test.js b/tests/chart-legend.test.js new file mode 100644 index 0000000..309c5f8 --- /dev/null +++ b/tests/chart-legend.test.js @@ -0,0 +1,95 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.nextFail=1e9;S.nextEvent=1e9;S.hist=[];for(let d=1;d<=40;d++)S.hist.push({d,dem:100+d,srv:90+d,c:10,p:20,ix:30,t:40+d,l2:5,rev:1000+d*10,cost:900+d*5})"; +const dash = ev => ev("(renderDash(),$('dash').innerHTML)"); + +test('NOC legend entries hide and show a series, and the scale follows the rest', () => { + const { ev, errors } = load(); + ev(start); ev("$('dash').hidden=false"); + let h = dash(ev); + assert.match(h, /data-ch="traffic"/); + assert.match(h, /data-ch="money"/); + assert.equal((h.match(/class="lg"/g) || []).length, 8, 'six traffic entries and two money ones, all on'); + const stacked = html => (html.match(/fill-opacity="\.85"/g) || []).length; + assert.equal(stacked(h), 5); + ev("ACT.chartToggle({c:'traffic',k:'t'})"); + h = ev("$('dash').innerHTML"); + assert.equal(stacked(h), 4, 'transit is gone from the stack'); + assert.match(h, /class="lg off" aria-pressed="false"[^>]*data-args="[^"]*"k":"t"/); + ev("ACT.chartToggle({c:'traffic',k:'ix'})"); + assert.equal(stacked(ev("$('dash').innerHTML")), 3, 'several at once'); + ev("ACT.chartToggle({c:'traffic',k:'t'})"); + assert.equal(stacked(ev("$('dash').innerHTML")), 4, 'a second click brings it back'); + // Hiding the last visible series shows everything again instead of an empty chart. + ev("UI.chartOff={}"); + for (const k of ['c', 'p', 'ix', 'l2', 'dem']) ev(`ACT.chartToggle({c:'traffic',k:'${k}'})`); + assert.equal(stacked(ev("$('dash').innerHTML")), 1, 'only transit left'); + ev("ACT.chartToggle({c:'traffic',k:'t'})"); + assert.equal(stacked(ev("$('dash').innerHTML")), 5); + // Nonsense is ignored, and the other chart is untouched. + ev("ACT.chartToggle({c:'nope',k:'t'});ACT.chartToggle({c:'money',k:'zzz'})"); + assert.equal(ev("JSON.stringify(UI.chartOff.money||{})"), '{}'); + assert.deepEqual(errors, []); +}); + +test('hovering a NOC chart shows the day and every visible series; leaving hides it', () => { + const { ev, dom, errors } = load(); + const doc = dom.window.document; + ev(start); ev("$('dash').hidden=false;renderDash()"); + const svg = doc.querySelector('svg.chart[data-ch="traffic"]'); + svg.getBoundingClientRect = () => ({ left: 0, top: 0, width: 600, height: 180, right: 600, bottom: 180 }); + const move = (t, x) => t.dispatchEvent(new dom.window.MouseEvent('pointermove', { clientX: x, clientY: 60, bubbles: true })); + move(svg, 50 + 542); // the right edge of the plot: the newest day + const tip = doc.querySelector('.chtip'); + assert.ok(tip && !tip.hidden, 'tooltip appears'); + assert.match(tip.textContent, /Y1 · /); + assert.match(tip.textContent, /Transit/); + assert.match(tip.textContent, /Demand/); + assert.match(tip.textContent, /Total/); + assert.equal(tip.textContent.includes('80.0 Gbps'), true, 'newest transit 40+40 Gbps'); + ev("ACT.chartToggle({c:'traffic',k:'t'})"); + move(doc.querySelector('svg.chart[data-ch="traffic"]'), 50); + assert.doesNotMatch(tip.textContent, /Transit/, 'hidden series are left out'); + assert.match(tip.textContent, /Gbps/); + move(doc.body, 10); + assert.equal(tip.hidden, true, 'moving away hides it'); + assert.deepEqual(errors, []); +}); + +test('the "how it arrives" bars on the Traffic tab show the same tip with each way in and its share', () => { + const { ev, dom, errors } = load(); + const doc = dom.window.document; + ev("ACT.start({});S.cash=1e8;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();UI.dtab='traffic';$('dash').hidden=false;renderDash()"); + const bars = [...doc.querySelectorAll('.mix[data-mix]')].filter(b => Object.keys(JSON.parse(b.dataset.mix)).length); + assert.ok(bars.length, 'a network with traffic has a bar'); + assert.equal(bars[0].hasAttribute('title'), false, 'no plain browser tooltip next to ours'); + assert.match(bars[0].getAttribute('aria-label'), /Gbps/); + bars[0].dispatchEvent(new dom.window.MouseEvent('pointermove', { clientX: 100, clientY: 100, bubbles: true })); + const tip = doc.querySelector('.chtip'); + assert.ok(tip && !tip.hidden); + assert.match(tip.textContent, /Transit.*Gbps · \d+%/); + assert.equal(doc.querySelector('.chcur').hidden, true, 'no cursor line for a bar'); + doc.body.dispatchEvent(new dom.window.MouseEvent('pointermove', { clientX: 5, clientY: 5, bubbles: true })); + assert.equal(tip.hidden, true); + assert.deepEqual(errors, []); +}); + +test('the Traffic tab legend picks which ways in count, and the table follows', () => { + const { ev, dom, errors } = load(); + const doc = dom.window.document; + ev("ACT.start({});S.cash=1e8;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute();UI.dtab='traffic';$('dash').hidden=false;renderDash()"); + const rows = () => doc.querySelectorAll('.tbl tbody tr').length; + const kinds = () => new Set([...doc.querySelectorAll('.tbl .mix[data-mix]')].flatMap(b => Object.keys(JSON.parse(b.dataset.mix)))); + const all = rows(); + assert.ok(kinds().has('t'), 'transit carries something'); + assert.equal(doc.querySelectorAll('.legend .lg').length, 4, 'one entry per way in'); + ev("ACT.chartToggle({c:'mix',k:'t'})"); + assert.equal(kinds().has('t'), false, 'transit is out of every bar'); + assert.ok(rows() < all, 'networks that only came in over transit are gone'); + assert.equal(doc.querySelectorAll('.legend .lg.off').length, 1); + ev("ACT.chartToggle({c:'mix',k:'t'})"); + assert.equal(rows(), all, 'switching it back restores the table'); + assert.deepEqual(errors, []); +}); diff --git a/tests/noc-window.test.js b/tests/noc-window.test.js index 1595df1..3534bcd 100644 --- a/tests/noc-window.test.js +++ b/tests/noc-window.test.js @@ -313,3 +313,34 @@ test('the board\'s light text stays on the board: Details is the game\'s own das assert.doesNotMatch(body, /(^|;)\s*color:/, 'a colour on body would be inherited by the white dashboard card and its toasts'); assert.match(css, /#nocBoard\{color:/); }); + +test('the wallboard charts have the same tooltip, and the Details legend works in the window', async (t) => { + const { G, W } = await pair(t); + G.ev("S.hist=[];for(let d=1;d<=40;d++)S.hist.push({d,dem:100+d,srv:90+d,c:10,p:20,ix:30,t:40+d,l2:5,rev:1000+d*10,cost:900+d*5})"); + G.ev('NOC.dirty=true');pump(G); + await settle(W.ev, '(S.hist||[]).length===40', 'the window got the history'); + W.ev('nocRender()'); + const doc = W.dom.window.document; + const svg = doc.querySelector('svg.nw-chart[data-ch="traffic"]'); + assert.ok(svg, 'the wallboard traffic chart is tagged'); + assert.ok(doc.querySelector('svg.nw-chart[data-ch="money"]'), 'and so is the money chart'); + svg.getBoundingClientRect = () => ({ left: 0, top: 0, width: 900, height: 260, right: 900, bottom: 260 }); + svg.dispatchEvent(new W.dom.window.MouseEvent('pointermove', { clientX: 900 - 8, clientY: 100, bubbles: true })); // the newest day + const tip = doc.querySelector('.chtip'); + assert.ok(tip && !tip.hidden, 'the tooltip appears in the window'); + assert.match(tip.textContent, /Transit/); + assert.equal(tip.textContent.includes('80.0 Gbps'), true, 'newest transit 40+40 Gbps'); + W.ev("nocView('details')"); + W.ev("UI.dtab='traffic';renderDash()"); + W.ev("ACT.chartToggle({c:'traffic',k:'t'})"); + assert.equal(W.ev("!!(UI.chartOff&&UI.chartOff.traffic&&UI.chartOff.traffic.t)"), true, "the legend changes the window's own view"); + assert.equal(G.ev("!!(UI.chartOff&&UI.chartOff.traffic)"), false, 'and does not travel to the game'); +}); + +test('the stylesheet of the window leaves the chart tooltip and its cursor line alone', () => { + const css = require('node:fs').readFileSync(require('node:path').join(__dirname, '..', 'src', 'styles', '45-noc-window.css'), 'utf8'); + const hide = css.split('\n').find((l) => l.startsWith('body.noc-window>*:not(#nocBoard)')); + assert.ok(hide, 'the rule that hides the game page is there'); + assert.ok(hide.includes(':not(.chtip)'), 'the tooltip stays'); + assert.ok(hide.includes(':not(.chcur)'), 'and so does its cursor line'); +});