From 66ae4be72d5bfaa8a47dfef372ed3ca5beca395a Mon Sep 17 00:00:00 2001
From: LookedPath <2457111+LookedPath@users.noreply.github.com>
Date: Tue, 27 Oct 2026 20:30:20 +0000
Subject: [PATCH] Add editable optic counts to fiber link panels
---
CHANGELOG.md | 2 +
site/i18n/es.js | 4 ++
site/i18n/fr.js | 4 ++
site/i18n/it.js | 4 ++
site/i18n/pt.js | 4 ++
src/game/90-actions/88-optic-counts.js | 27 +++++++++
src/game/93-ui/70-link-panels.js | 2 +-
src/game/93-ui/75-optic-counts.js | 20 +++++++
src/i18n/en.js | 4 ++
src/styles/35-optic-counts.css | 4 ++
tests/optic-counts.test.js | 81 ++++++++++++++++++++++++++
11 files changed, 155 insertions(+), 1 deletion(-)
create mode 100644 src/game/90-actions/88-optic-counts.js
create mode 100644 src/game/93-ui/75-optic-counts.js
create mode 100644 src/styles/35-optic-counts.css
create mode 100644 tests/optic-counts.test.js
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3465c68..5a1b699 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
+- Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf.
+
- Yellow progress bars are slim again, like the green and red ones, instead of padded boxes.
- São Paulo's exchange is now called IX.brrr São Paulo, like every other Brazilian exchange (#166).
- Sponsor a conference: some peering meetings sell sponsorships, and while the glow lasts more customers from that region come knocking (#168).
diff --git a/site/i18n/es.js b/site/i18n/es.js
index f7dea85..23f66b0 100644
--- a/site/i18n/es.js
+++ b/site/i18n/es.js
@@ -2348,6 +2348,10 @@
"notifications.n_min_ago":{"one":"hace {n} min","other":"hace {n} min"},
"notifications.nothing_in_the_last_10_minutes":"Nada en los últimos 10 minutos.",
"notifications.show_all_n":"Mostrar las {n}",
+"optic_counts.apply_price":"Aplicar · {price}",
+"optic_counts.count_for_model":"Número de canales {model}",
+"optic_counts.only_n_channels_free":"Solo quedan {n} canales libres en esta fibra.",
+"optic_counts.target_count":"Cantidad deseada",
"own_cable.a_and_b":"{a} y {b}",
"own_cable.a_fishing_fleet_is_trawling_exactly":"Una flota pesquera está faenando justo donde necesitas tender.",
"own_cable.a_leased_wave_wave_on_this":"Una onda {wave} alquilada en esta ruta cuesta {price}/mes.",
diff --git a/site/i18n/fr.js b/site/i18n/fr.js
index 4342c28..d9a31c3 100644
--- a/site/i18n/fr.js
+++ b/site/i18n/fr.js
@@ -2348,6 +2348,10 @@
"notifications.n_min_ago":{"one":"il y a {n} min","other":"il y a {n} min"},
"notifications.nothing_in_the_last_10_minutes":"Rien ces 10 dernières minutes.",
"notifications.show_all_n":"Tout afficher ({n})",
+"optic_counts.apply_price":"Appliquer · {price}",
+"optic_counts.count_for_model":"Nombre de canaux {model}",
+"optic_counts.only_n_channels_free":"Il ne reste que {n} canaux libres sur cette fibre.",
+"optic_counts.target_count":"Quantité souhaitée",
"own_cable.a_and_b":"{a} et {b}",
"own_cable.a_fishing_fleet_is_trawling_exactly":"Une flotte de chalutiers drague pile là où tu dois poser.",
"own_cable.a_leased_wave_wave_on_this":"Une longueur d’onde {wave} louée sur ce parcours coûte {price}/mois.",
diff --git a/site/i18n/it.js b/site/i18n/it.js
index db5ff27..1054518 100644
--- a/site/i18n/it.js
+++ b/site/i18n/it.js
@@ -2348,6 +2348,10 @@
"notifications.n_min_ago":{"one":"{n} min fa","other":"{n} min fa"},
"notifications.nothing_in_the_last_10_minutes":"Niente negli ultimi 10 minuti.",
"notifications.show_all_n":"Mostra tutte e {n}",
+"optic_counts.apply_price":"Applica · {price}",
+"optic_counts.count_for_model":"Numero di canali {model}",
+"optic_counts.only_n_channels_free":"Su questa fibra sono liberi solo {n} canali.",
+"optic_counts.target_count":"Quantità desiderata",
"own_cable.a_and_b":"{a} e {b}",
"own_cable.a_fishing_fleet_is_trawling_exactly":"Una flotta di pescherecci sta strascicando proprio dove devi posare.",
"own_cable.a_leased_wave_wave_on_this":"Una wave da {wave} in affitto su questa tratta costa {price}/mese.",
diff --git a/site/i18n/pt.js b/site/i18n/pt.js
index b474374..f0f4baf 100644
--- a/site/i18n/pt.js
+++ b/site/i18n/pt.js
@@ -2348,6 +2348,10 @@
"notifications.n_min_ago":{"one":"há {n} min","other":"há {n} min"},
"notifications.nothing_in_the_last_10_minutes":"Nada nos últimos 10 minutos.",
"notifications.show_all_n":"Mostrar todas as {n}",
+"optic_counts.apply_price":"Aplicar · {price}",
+"optic_counts.count_for_model":"Número de canais {model}",
+"optic_counts.only_n_channels_free":"Só há {n} canais livres nesta fibra.",
+"optic_counts.target_count":"Quantidade desejada",
"own_cable.a_and_b":"{a} e {b}",
"own_cable.a_fishing_fleet_is_trawling_exactly":"Uma frota pesqueira está arrastando redes bem onde você precisa lançar.",
"own_cable.a_leased_wave_wave_on_this":"Uma wave de {wave} alugada nesta rota custa {price}/mês.",
diff --git a/src/game/90-actions/88-optic-counts.js b/src/game/90-actions/88-optic-counts.js
new file mode 100644
index 0000000..62d1e91
--- /dev/null
+++ b/src/game/90-actions/88-optic-counts.js
@@ -0,0 +1,27 @@
+// Quote the whole change before spending: shelf optics still need regen cards.
+function opticCountCost(l,o,n){
+ const add=Math.max(0,n-(l.ch||[]).filter(k=>k===o).length),sp=Math.min(add,spareN(o)),r=REGEN_CH*(l.regen|0),c=optCost(o);
+ return sp*Math.round(c*r)+(add-sp)*Math.round(c*(1+r));
+}
+Object.assign(ACT,{
+ setChCount:({id,o,n})=>{
+ const l=S.links.find(x=>x.id===id);
+ if(!l||l.kind!=='df'||!own(OPT,o)||!Number.isSafeInteger(n)||n<0||n>chMax(l))return;
+ const old=(l.ch||[]).filter(k=>k===o).length,d=n-old;
+ if(!d)return;
+ if(d>0){
+ const why=chWhy(l,o);
+ if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;}
+ const free=chMax(l)-(l.ch||[]).length-soldSlots(l);
+ if(d>free){toast(tr('optic_counts.only_n_channels_free',{n:free}),'bad');sfx('err');return;}
+ if(!portGate(l.a,d)||!portGate(l.b,d)||!spend(opticCountCost(l,o,n)))return;
+ const sp=Math.min(d,spareN(o));if(sp)S.spares[o]-=sp;
+ (l.ch=l.ch||[]).push(...Array(d).fill(o));
+ }else{
+ let left=-d;l.ch=l.ch.filter(k=>k!==o||left--<=0);
+ S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)-d;
+ }
+ if(UI.opticCounts)delete UI.opticCounts[JSON.stringify([id,o])];
+ after();
+ },
+});
diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js
index 19b6eb7..e37ea26 100644
--- a/src/game/93-ui/70-link-panels.js
+++ b/src/game/93-ui/70-link-panels.js
@@ -81,7 +81,7 @@ function dfPanel(l){
if(l.own&&l.sub)h+=subUpgradePanel(l);
for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k);
const md=optMode(k,l),cc=chCost(l,k),sp=spareN(k);
- h+=`
${O.n} ${optModes(k,l).map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}
${esc(O.blurb)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${sp?` · ${trn('link_panels.n_spare_on_the_shelf',sp)}`:''}
${md&&!md.full?`
⚠️ ${tr('link_panels.runs_at_g_per_channel_on',{g:fmtG(md.g)})} ${!l.sub&®enNeed(k,l)>(l.regen|0)?trn('link_panels.n_regen_site_would_bring_it',regenNeed(k,l),{g:fmtG(O.g)}):''}
`:''}${why?`
${esc(why)}
`:''}
${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+
${cc?tr('link_panels.spare_price',{price:fmt$(cc)}):tr('common.spare')}`:`+
${fmt$(cc)}`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash
`;}
+ h+=`${O.n} ${optModes(k,l).map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}
${esc(O.blurb)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${sp?` · ${trn('link_panels.n_spare_on_the_shelf',sp)}`:''}
${md&&!md.full?`
⚠️ ${tr('link_panels.runs_at_g_per_channel_on',{g:fmtG(md.g)})} ${!l.sub&®enNeed(k,l)>(l.regen|0)?trn('link_panels.n_regen_site_would_bring_it',regenNeed(k,l),{g:fmtG(O.g)}):''}
`:''}${why?`
${esc(why)}
`:''}${opticCountControl(l,k,n)}
${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+
${cc?tr('link_panels.spare_price',{price:fmt$(cc)}):tr('common.spare')}`:`+
${fmt$(cc)}`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash
`;}
{const st=Object.keys(OPT).filter(k=>spareN(k)>0);h+=`${tr('link_panels.unplugged_optics_go_on_the_spares')}
`;
{const used=[...new Set(l.ch||[])].filter(k=>OPT[k]&&OPT[k].lvl<=lvl());if(used.length)h+=`${used.map(k=>btn(tr('link_panels.stock_a_spare_optic_price',{optic:OPT[k].n,price:fmt$(optCost(k))}),'buySpare',{o:k},'ghost sm',S.cash=64)).join('')}
${tr('link_panels.spares_bought_now_are_already_paid')}
`;}if(st.length)h+=`${tr('common.spares_shelf')}
`+st.map(k=>`${spareN(k)} × ${OPT[k].n}
${btn(tr('link_panels.sell_one_price',{price:fmt$(spareValue(k))}),'sellSpare',{o:k},'ghost sm')}
`).join('');}
const rg=l.regen|0,rgAdd=REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH);
diff --git a/src/game/93-ui/75-optic-counts.js b/src/game/93-ui/75-optic-counts.js
new file mode 100644
index 0000000..35fe1cf
--- /dev/null
+++ b/src/game/93-ui/75-optic-counts.js
@@ -0,0 +1,20 @@
+function opticCountControl(l,o,n){
+ const key=JSON.stringify([l.id,o]);let draft=UI.opticCounts&&UI.opticCounts[key];
+ if(draft&&draft.base!==n){delete UI.opticCounts[key];draft=null;}
+ const v=draft?draft.n:n,value=draft?draft.value:n;
+ const price=Number.isSafeInteger(v)&&v>=0&&v<=chMax(l)?opticCountCost(l,o,v):0;
+ return ``;
+}
+document.addEventListener('input',e=>{
+ const f=e.target.closest('form.optic-count');if(!f||!S)return;
+ const l=S.links.find(x=>x.id===f.dataset.link),o=f.dataset.optic,n=f.elements.count.valueAsNumber;
+ if(!l||!own(OPT,o))return;
+ UI.opticCounts=UI.opticCounts||{};UI.opticCounts[JSON.stringify([l.id,o])]={base:(l.ch||[]).filter(k=>k===o).length,n,value:e.target.value};
+ e.target.setAttribute('value',e.target.value);
+ f.querySelector('button').textContent=tr('optic_counts.apply_price',{price:fmt$(Number.isSafeInteger(n)&&n>=0&&n<=chMax(l)?opticCountCost(l,o,n):0)});
+});
+document.addEventListener('submit',e=>{
+ const f=e.target.closest('form.optic-count');if(!f)return;e.preventDefault();
+ if(!S||!f.reportValidity()||!$('modal').hidden)return;
+ ACT.setChCount({id:f.dataset.link,o:f.dataset.optic,n:f.elements.count.valueAsNumber});
+});
diff --git a/src/i18n/en.js b/src/i18n/en.js
index 86aae1c..2d9cd0b 100644
--- a/src/i18n/en.js
+++ b/src/i18n/en.js
@@ -2349,6 +2349,10 @@
"notifications.n_min_ago":{"one":"{n} min ago","other":"{n} min ago"},
"notifications.nothing_in_the_last_10_minutes":"Nothing in the last 10 minutes.",
"notifications.show_all_n":"Show all {n}",
+"optic_counts.apply_price":"Apply · {price}",
+"optic_counts.count_for_model":"Number of {model} channels",
+"optic_counts.only_n_channels_free":"Only {n} channels are free on this fiber.",
+"optic_counts.target_count":"Target count",
"own_cable.a_and_b":"{a} and {b}",
"own_cable.a_fishing_fleet_is_trawling_exactly":"A fishing fleet is trawling exactly where you need to lay.",
"own_cable.a_leased_wave_wave_on_this":"A leased {wave} wave on this route costs {price}/mo.",
diff --git a/src/styles/35-optic-counts.css b/src/styles/35-optic-counts.css
new file mode 100644
index 0000000..6690821
--- /dev/null
+++ b/src/styles/35-optic-counts.css
@@ -0,0 +1,4 @@
+.optic-count{display:flex;flex-wrap:wrap;align-items:end;gap:8px;margin-top:8px}
+.optic-count label{display:flex;flex-direction:column;gap:3px;font-size:12px;font-weight:800}
+.optic-count input.t{width:88px;font-size:16px;min-height:44px}
+.optic-count .b{min-height:44px}
diff --git a/tests/optic-counts.test.js b/tests/optic-counts.test.js
new file mode 100644
index 0000000..1e85f3f
--- /dev/null
+++ b/tests/optic-counts.test.js
@@ -0,0 +1,81 @@
+const test=require('node:test');
+const assert=require('node:assert/strict');
+const {load}=require('./harness');
+function setup(ev,sub=false){ev(`ACT.start({});S.cash=1e9;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0;
+ S.pops.fra.rgen=mainRG(4);S.pops.fra.routers=16;S.pops.ams={...S.pops.fra};
+ S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sub:${sub},sys:'roadm',km:400,ch:[],ready:0,day:0,cut:0,mo:1}];
+ UI.sel={type:'link',id:'fiber'};renderPanel();`);}
+const count=ev=>ev('S.links[0].ch.length');
+for(const sub of [false,true])test(`typed counts buy and remove optics on ${sub?'subsea':'land'} fiber`,()=>{
+ const {ev,dom,errors}=load();try{
+ setup(ev,sub);const doc=dom.window.document;
+ const f=doc.querySelector('form.optic-count[data-optic="zr4"]'),input=f.elements.count;
+ input.focus();input.value='5';input.dispatchEvent(new dom.window.Event('input',{bubbles:true}));
+ const cost=ev("5*chCost(S.links[0],'zr4')"),cash=ev('S.cash');
+ assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`)));
+ ev('S.day++;renderPanel()');
+ assert.equal(doc.activeElement,input,'tick preserves the focused field');assert.equal(input.value,'5');
+ assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`)));
+ f.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true}));
+ assert.equal(count(ev),5);assert.equal(cash-ev('S.cash'),cost);
+ ev("ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),2);assert.equal(ev('S.spares.zr4'),3);
+ const before=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),5);assert.equal(ev('S.cash'),before);assert.equal(ev('S.spares.zr4'),0);
+ ev("ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(count(ev),0);assert.equal(ev('S.spares.zr4'),5);
+ assert.deepEqual(errors,[]);
+ }finally{dom.window.close();}
+});
+test('batch price matches individual channel purchases with spares, regen cards and tariffs',()=>{
+ const {ev,dom}=load();try{setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");
+ const expected=ev("2*Math.round(optCost('zr4')*REGEN_CH*2)+3*Math.round(optCost('zr4')*(1+REGEN_CH*2))");
+ assert.equal(ev("opticCountCost(S.links[0],'zr4',5)"),expected);
+ const cash=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(cash-ev('S.cash'),expected);
+ setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");const cash2=ev('S.cash');
+ ev("for(let i=0;i<5;i++)ACT.addCh({id:'fiber',o:'zr4'})");assert.equal(cash2-ev('S.cash'),expected);
+ }finally{dom.window.close();}
+});
+test('unaffordable batches, port limits and invalid input never partially change state',()=>{
+ const {ev,dom}=load();try{setup(ev);ev('S.cash=1');
+ ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),0);assert.equal(ev('S.cash'),1);
+ ev('S.cash=1e9;S.pops.ams.routers=1');const max=ev("Math.floor(portsMax('ams')-portsUsed('ams'))");
+ ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${max+1}})`);assert.equal(count(ev),0);assert.equal(ev('S.cash'),1e9);
+ ev('S.pops.ams.routers=16');
+ for(const n of ['NaN','Infinity','-1','1.5','65',"'3'"]){ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${n}})`);assert.equal(count(ev),0);}
+ ev("ACT.setChCount({id:'missing',o:'zr4',n:2});ACT.setChCount({id:'fiber',o:'missing',n:2})");assert.equal(ev('S.cash'),1e9);
+ }finally{dom.window.close();}
+});
+test('channel reservations and reach, line-system, level and router compatibility still apply',()=>{
+ const {ev,dom}=load();try{setup(ev);
+ ev("S.links[0].ch=Array(63).fill('zr8');ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),63);
+ setup(ev);ev("S.biz.push({type:'wwave',link:'fiber',slots:63});ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0);
+ setup(ev);ev("S.links[0].km=20000;ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0);
+ setup(ev);ev("S.links[0].sys='lite';ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0);
+ setup(ev);ev("S.lvl=1;S.done={};ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0);
+ setup(ev);ev("S.pops.ams.rgen=0;ACT.setChCount({id:'fiber',o:'tp32',n:2})");assert.equal(count(ev),0);
+ setup(ev);ev("S.links[0].ch=['zr4','zr8','zr4'];ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(ev("JSON.stringify(S.links[0].ch)"),'["zr8"]');
+ }finally{dom.window.close();}
+});
+test('plus and minus buttons work alongside typed counts',()=>{
+ const {ev,dom,errors}=load();try{setup(ev);const doc=dom.window.document;
+ const plus=()=>[...doc.querySelectorAll('[data-act="addCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4');
+ const minus=()=>[...doc.querySelectorAll('[data-act="rmCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4');
+ const input=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input');
+ plus().click();assert.equal(count(ev),1);assert.equal(input().value,'1');
+ input().value='4';input().dispatchEvent(new dom.window.Event('input',{bubbles:true}));
+ input().form.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true}));
+ assert.equal(count(ev),4);minus().click();assert.equal(count(ev),3);assert.equal(input().value,'3');
+ plus().click();assert.equal(count(ev),4);assert.equal(input().value,'4');assert.deepEqual(errors,[]);
+ }finally{dom.window.close();}
+});
+
+test('draft counts and quotes stay together when reopening a panel or using shortcuts',()=>{
+ const {ev,dom}=load();try{setup(ev);const doc=dom.window.document;
+ const field=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input');
+ field().value='5';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));
+ ev("UI.sel=null;renderPanel();$('panelBody').innerHTML='';UI.sel={type:'link',id:'fiber'};renderPanel()");
+ assert.equal(field().value,'5');
+ ev("ACT.addCh({id:'fiber',o:'zr4'});ACT.rmCh({id:'fiber',o:'zr4'})");
+ assert.equal(field().value,'0');assert.ok(field().form.querySelector('button').textContent.includes(ev('fmt$(0)')));
+ field().value='';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));ev('S.day++;renderPanel()');
+ assert.equal(field().value,'','empty in-progress entry survives a tick');
+ }finally{dom.window.close();}
+});