A NOC screen in its own window, for a second display

A button next to the speed controls opens this page at ?noc=<slot> in a
noopener pop-up, so it runs on its own thread. The window never claims the
slot, saves or runs a day. The game sends it a copy of S and R over a
BroadcastChannel, at most once a second and only while a window is connected,
and runs its clicks through an allowlist of the same ACT.* a click uses.

The window opens on a dark wallboard: a live world map of links and POPs,
traffic and money graphs, alarms, and the hottest ports with the dashboard's
own upgrade buttons (connUp). Clicking a POP filters the ports. Details shows
the full dashboard. Phones do not show the button.
This commit is contained in:
Christopher Hawker 2026-11-04 20:01:37 +11:00
parent c04fbe88b8
commit 80f671953a
18 changed files with 752 additions and 6 deletions

View file

@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- A new button next to the speed controls opens a NOC screen in a window of its own, to keep on a second display beside the map. It is a dark wallboard with a live world map of your links and POPs, traffic and money graphs, alarms, and your hottest ports with their upgrade buttons, which work on the running game; click a POP to see its ports. Details has the full dashboard, and Full screen fills the display. The new window only shows and sends clicks: your network is still played and saved in the game window. Phones do not show the button.
- Every capital in Africa is on the map, which puts every capital of the world in the game: 33 new cities from Porto-Novo, Bamako and Niamey to Khartoum, Juba, Mogadishu, Brazzaville, Tripoli, Rabat and Pretoria. Each country brings its real telcos, Nigeria gets its wholesale backbone up to Abuja, and the island capitals of the Comoros, São Tomé and Equatorial Guinea sit on their real cables.
- Every capital in South, East and Southeast Asia and the Pacific is on the map: Thimphu, Kathmandu, Bandar Seri Begawan, Phnom Penh, Vientiane, Ulaanbaatar, Naypyidaw, Pyongyang, Dili, Hanoi and Wellington, with the island capitals Tarawa, Palikir, Yaren, Funafuti and Port Vila. Each country brings its real telcos, North Korea reaches the world only through China and Russia, and the islands hang on their real cables.
- Every capital in the Middle East, the Caucasus and Central Asia is on the map, from Yerevan and Baku to Kabul, Tehran, Baghdad, Jerusalem, Amman, Kuwait City, Beirut, Damascus, Sanaa and Manama, with Ankara and Islamabad. Each country brings its real telcos, and Bahrain is an island on the Gulf's cables.

View file

@ -37,7 +37,7 @@ hoisted across files, and top-level statements run in path order. Find code by n
| `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers |
| `91-save.js`, `92-audio.js` | Save, export and import; sound effects |
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning |
| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, lease swaps, the NOC dashboard, the bank, hints |
| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=<slot>`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints |
| `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals |
| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, `draw()`, the world layer, cities, input and click delegation |
| `99-loop.js` | `frame()` and `boot()` |

View file

@ -512,6 +512,7 @@ const API_VIEW={
help:{args:[],doc:'Open the how-to-play modal.'},
dash:{args:[],doc:'Open the NOC dashboard.'},
dashClose:{args:[],doc:'Close the NOC dashboard.'},
nocWindow:{args:[],doc:'Open the NOC dashboard in a window of its own, for a second display.'},
dashTab:{args:[['k','dashTab']],doc:'Switch the NOC dashboard tab.'},
dashSort:{args:[['k','dashSortKey']],doc:'Flip a dashboard column\'s sort.'},
dashLink:{args:[['id','entityId']],doc:'Jump from the dashboard to a link\'s panel.'},

View file

@ -3027,6 +3027,33 @@
"networks.waves_goodbye_to_latency_across_the":"Winkt der Latenz quer über den Indischen Ozean zum Abschied.",
"networks.western_canada_s_incumbent_tell_us":"Der Platzhirsch Westkanadas. Sag uns, was du brauchst, und wir sagen dir den Preis.",
"networks.will_peer_with_anyone_anywhere":"Peert mit jedem, überall. Angeblich verschickt er IPv6-Torten per Post.",
"noc.alarms":"Alarme",
"noc.all_pops":"Alle POPs",
"noc.details":"Details",
"noc.full_screen":"Vollbild",
"noc.hottest_ports":"Heißeste Ports",
"noc.legend_down":"Ausgefallen",
"noc.legend_hot":"Über 90 %",
"noc.legend_ok":"Unter 65 %",
"noc.legend_warm":"Über 65 %",
"noc.n_alarms":{"one":"{n} Alarm","other":"{n} Alarme"},
"noc.n_pops_n_links":"{pops} POPs · {links} Links",
"noc.n_ports_over_90_full":{"one":"{n} Port über 90 %","other":"{n} Ports über 90 %"},
"noc.n_unhappy_customers":{"one":"{n} unzufriedener Kunde","other":"{n} unzufriedene Kunden"},
"noc.n_warnings":{"one":"{n} Warnung","other":"{n} Warnungen"},
"noc.net_per_month":"Netto pro Monat",
"noc.no_ports_here":"Hier gibt es noch keine Ports. Kauf Transit oder geh an ein Exchange.",
"noc.nothing_on_fire":"Nichts brennt. Genieß es, solange es hält.",
"noc.open_in_its_own_window":"NOC-Dashboard in einem eigenen Fenster öffnen",
"noc.the_game_has_a_dialog_open":"Im Spielfenster ist ein Dialog offen. Schließ ihn zuerst dort.",
"noc.the_game_is_paused":"Das Spiel ist pausiert.",
"noc.the_game_window_is_closed":"Das Spielfenster ist geschlossen oder antwortet nicht, diese Zahlen sind also nicht live. Öffne dort dein Netz, dann verbindet sich dieses Fenster wieder.",
"noc.the_game_window_is_hidden":"Das Spielfenster ist verdeckt, darum steht seine Uhr. Hol es zurück auf den Bildschirm, um weiterzuspielen.",
"noc.under_attack":"{who} wird angegriffen: {g}",
"noc.waiting_for_the_game_window":"Warte auf das Spielfenster…",
"noc.wallboard":"Wallboard",
"noc.your_browser_blocked_the_window":"Dein Browser hat das NOC-Fenster vielleicht blockiert. Erlaube Pop-ups für diese Seite und versuch es nochmal.",
"noc.your_network":"Dein Netz",
"notifications.last_10_minutes":"letzte 10 Minuten",
"notifications.n_min_ago":{"one":"vor {n} Min.","other":"vor {n} Min."},
"notifications.nothing_in_the_last_10_minutes":"Nichts in den letzten 10 Minuten.",

View file

@ -3025,6 +3025,33 @@
"networks.waves_goodbye_to_latency_across_the":"Le dice adiós a la latencia a través del Océano Índico.",
"networks.western_canada_s_incumbent_tell_us":"El operador histórico del oeste de Canadá. Dinos qué necesitas y te diremos el precio.",
"networks.will_peer_with_anyone_anywhere":"Hace peering con cualquiera, en cualquier lugar. Se rumorea que manda pasteles de IPv6 por correo.",
"noc.alarms":"Alarmas",
"noc.all_pops":"Todos los POP",
"noc.details":"Detalles",
"noc.full_screen":"Pantalla completa",
"noc.hottest_ports":"Puertos más cargados",
"noc.legend_down":"Caído",
"noc.legend_hot":"Más del 90 %",
"noc.legend_ok":"Menos del 65 %",
"noc.legend_warm":"Más del 65 %",
"noc.n_alarms":{"one":"{n} alarma","other":"{n} alarmas"},
"noc.n_pops_n_links":"{pops} POP · {links} enlaces",
"noc.n_ports_over_90_full":{"one":"{n} puerto por encima del 90 %","other":"{n} puertos por encima del 90 %"},
"noc.n_unhappy_customers":{"one":"{n} cliente descontento","other":"{n} clientes descontentos"},
"noc.n_warnings":{"one":"{n} aviso","other":"{n} avisos"},
"noc.net_per_month":"Neto al mes",
"noc.no_ports_here":"Aún no hay puertos aquí. Compra tránsito o únete a un exchange.",
"noc.nothing_on_fire":"Nada en llamas. Disfrútalo mientras dure.",
"noc.open_in_its_own_window":"Abrir el panel del NOC en su propia ventana",
"noc.the_game_has_a_dialog_open":"La ventana del juego tiene un diálogo abierto. Ciérralo allí primero.",
"noc.the_game_is_paused":"El juego está en pausa.",
"noc.the_game_window_is_closed":"La ventana del juego está cerrada o no responde, así que estas cifras no están en directo. Abre tu red allí y esta ventana se vuelve a conectar.",
"noc.the_game_window_is_hidden":"La ventana del juego está oculta, así que su reloj se ha parado. Vuelve a ponerla en pantalla para seguir jugando.",
"noc.under_attack":"{who} bajo ataque: {g}",
"noc.waiting_for_the_game_window":"Esperando a la ventana del juego…",
"noc.wallboard":"Panel mural",
"noc.your_browser_blocked_the_window":"Puede que tu navegador haya bloqueado la ventana del NOC. Permite las ventanas emergentes en este sitio y vuelve a intentarlo.",
"noc.your_network":"Tu red",
"notifications.last_10_minutes":"últimos 10 minutos",
"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.",

View file

@ -3025,6 +3025,33 @@
"networks.waves_goodbye_to_latency_across_the":"Fait un signe d’adieu à la latence à travers l’océan Indien.",
"networks.western_canada_s_incumbent_tell_us":"L’opérateur historique de l’Ouest canadien. Dis-nous ce qu’il te faut, et on te dira le prix.",
"networks.will_peer_with_anyone_anywhere":"Fait du peering avec tout le monde, partout. Il paraît qu’il envoie des gâteaux IPv6 par la poste.",
"noc.alarms":"Alarmes",
"noc.all_pops":"Tous les POP",
"noc.details":"Détails",
"noc.full_screen":"Plein écran",
"noc.hottest_ports":"Ports les plus chargés",
"noc.legend_down":"Hors service",
"noc.legend_hot":"Plus de 90 %",
"noc.legend_ok":"Moins de 65 %",
"noc.legend_warm":"Plus de 65 %",
"noc.n_alarms":{"one":"{n} alarme","other":"{n} alarmes"},
"noc.n_pops_n_links":"{pops} POP · {links} liens",
"noc.n_ports_over_90_full":{"one":"{n} port à plus de 90 %","other":"{n} ports à plus de 90 %"},
"noc.n_unhappy_customers":{"one":"{n} client mécontent","other":"{n} clients mécontents"},
"noc.n_warnings":{"one":"{n} avertissement","other":"{n} avertissements"},
"noc.net_per_month":"Net par mois",
"noc.no_ports_here":"Pas encore de port ici. Achète du transit ou rejoins un exchange.",
"noc.nothing_on_fire":"Rien ne brûle. Profites-en tant que ça dure.",
"noc.open_in_its_own_window":"Ouvrir le tableau de bord NOC dans sa propre fenêtre",
"noc.the_game_has_a_dialog_open":"La fenêtre du jeu a une boîte de dialogue ouverte. Ferme-la d'abord là-bas.",
"noc.the_game_is_paused":"Le jeu est en pause.",
"noc.the_game_window_is_closed":"La fenêtre du jeu est fermée ou ne répond pas : ces chiffres ne sont plus en direct. Rouvre ton réseau là-bas et cette fenêtre se reconnecte.",
"noc.the_game_window_is_hidden":"La fenêtre du jeu est masquée, son horloge est donc arrêtée. Remets-la à l'écran pour continuer à jouer.",
"noc.under_attack":"{who} attaqué : {g}",
"noc.waiting_for_the_game_window":"En attente de la fenêtre du jeu…",
"noc.wallboard":"Mur d'écrans",
"noc.your_browser_blocked_the_window":"Ton navigateur a peut-être bloqué la fenêtre NOC. Autorise les pop-ups pour ce site et réessaie.",
"noc.your_network":"Ton réseau",
"notifications.last_10_minutes":"10 dernières minutes",
"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.",

View file

@ -3025,6 +3025,33 @@
"networks.waves_goodbye_to_latency_across_the":"Manda una wave d’addio alla latenza attraverso l’Oceano Indiano.",
"networks.western_canada_s_incumbent_tell_us":"L'incumbent del Canada occidentale. Dicci cosa ti serve e noi ti diremo il prezzo.",
"networks.will_peer_with_anyone_anywhere":"Fa peering con chiunque, ovunque. Si dice spedisca torte IPv6 per posta.",
"noc.alarms":"Allarmi",
"noc.all_pops":"Tutti i POP",
"noc.details":"Dettagli",
"noc.full_screen":"Schermo intero",
"noc.hottest_ports":"Porte più calde",
"noc.legend_down":"Giù",
"noc.legend_hot":"Oltre il 90%",
"noc.legend_ok":"Sotto il 65%",
"noc.legend_warm":"Oltre il 65%",
"noc.n_alarms":{"one":"{n} allarme","other":"{n} allarmi"},
"noc.n_pops_n_links":"{pops} POP · {links} link",
"noc.n_ports_over_90_full":{"one":"{n} porta oltre il 90%","other":"{n} porte oltre il 90%"},
"noc.n_unhappy_customers":{"one":"{n} cliente scontento","other":"{n} clienti scontenti"},
"noc.n_warnings":{"one":"{n} avviso","other":"{n} avvisi"},
"noc.net_per_month":"Netto al mese",
"noc.no_ports_here":"Ancora nessuna porta qui. Compra transit o entra in un exchange.",
"noc.nothing_on_fire":"Niente in fiamme. Goditela finché dura.",
"noc.open_in_its_own_window":"Apri la dashboard NOC in una finestra separata",
"noc.the_game_has_a_dialog_open":"La finestra di gioco ha una finestra di dialogo aperta. Chiudila prima lì.",
"noc.the_game_is_paused":"Il gioco è in pausa.",
"noc.the_game_window_is_closed":"La finestra di gioco è chiusa o non risponde, quindi questi numeri non sono in tempo reale. Riapri lì la tua rete e questa finestra si ricollega.",
"noc.the_game_window_is_hidden":"La finestra di gioco è nascosta, quindi il suo orologio è fermo. Riportala sullo schermo per continuare a giocare.",
"noc.under_attack":"{who} sotto attacco: {g}",
"noc.waiting_for_the_game_window":"In attesa della finestra di gioco…",
"noc.wallboard":"Wallboard",
"noc.your_browser_blocked_the_window":"Il browser potrebbe aver bloccato la finestra NOC. Consenti i pop-up per questo sito e riprova.",
"noc.your_network":"La tua rete",
"notifications.last_10_minutes":"ultimi 10 minuti",
"notifications.n_min_ago":{"one":"{n} min fa","other":"{n} min fa"},
"notifications.nothing_in_the_last_10_minutes":"Niente negli ultimi 10 minuti.",

View file

@ -3025,6 +3025,33 @@
"networks.waves_goodbye_to_latency_across_the":"Dá tchau pra latência com uma wave pelo Oceano Índico.",
"networks.western_canada_s_incumbent_tell_us":"O incumbente do oeste do Canadá. Diga do que você precisa, e nós diremos o preço.",
"networks.will_peer_with_anyone_anywhere":"Faz peering com qualquer um, em qualquer lugar. Dizem que manda bolos IPv6 pelo correio.",
"noc.alarms":"Alarmes",
"noc.all_pops":"Todos os POPs",
"noc.details":"Detalhes",
"noc.full_screen":"Tela cheia",
"noc.hottest_ports":"Portas mais quentes",
"noc.legend_down":"Fora do ar",
"noc.legend_hot":"Acima de 90%",
"noc.legend_ok":"Abaixo de 65%",
"noc.legend_warm":"Acima de 65%",
"noc.n_alarms":{"one":"{n} alarme","other":"{n} alarmes"},
"noc.n_pops_n_links":"{pops} POPs · {links} links",
"noc.n_ports_over_90_full":{"one":"{n} porta acima de 90%","other":"{n} portas acima de 90%"},
"noc.n_unhappy_customers":{"one":"{n} cliente insatisfeito","other":"{n} clientes insatisfeitos"},
"noc.n_warnings":{"one":"{n} aviso","other":"{n} avisos"},
"noc.net_per_month":"Líquido por mês",
"noc.no_ports_here":"Ainda não há portas aqui. Compre trânsito ou entre num exchange.",
"noc.nothing_on_fire":"Nada pegando fogo. Aproveite enquanto dura.",
"noc.open_in_its_own_window":"Abrir o painel do NOC numa janela própria",
"noc.the_game_has_a_dialog_open":"A janela do jogo tem uma caixa de diálogo aberta. Feche-a lá primeiro.",
"noc.the_game_is_paused":"O jogo está em pausa.",
"noc.the_game_window_is_closed":"A janela do jogo está fechada ou não responde, por isso estes números não estão ao vivo. Abra a sua rede lá e esta janela volta a ligar-se.",
"noc.the_game_window_is_hidden":"A janela do jogo está oculta, por isso o relógio parou. Traga-a de volta ao ecrã para continuar a jogar.",
"noc.under_attack":"{who} sob ataque: {g}",
"noc.waiting_for_the_game_window":"À espera da janela do jogo…",
"noc.wallboard":"Painel de parede",
"noc.your_browser_blocked_the_window":"O navegador pode ter bloqueado a janela do NOC. Permita pop-ups neste site e tente de novo.",
"noc.your_network":"A sua rede",
"notifications.last_10_minutes":"últimos 10 minutos",
"notifications.n_min_ago":{"one":"há {n} min","other":"há {n} min"},
"notifications.nothing_in_the_last_10_minutes":"Nada nos últimos 10 minutos.",

View file

@ -8,7 +8,7 @@ const RELEASE_NOTES=/*__RELEASE_NOTES__*/[];
const RELEASE_STORY=/*__RELEASE_STORY__*/[];
const IS_DEV=APP_VERSION.startsWith('__');
// Only report from the real site; previews, localhost and the Claude viewer stay silent.
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
const ANALYTICS={host:/(^|\.)seriesoftub\.es$/.test(location.hostname)&&!/[?&]noc=/.test(location.search)?'https://stats.seriesoftub.es':'',site:'seriesoftub.es'};
(function(){
try{
window.ridiculytics=window.ridiculytics||function(){const q=window.ridiculytics.q=window.ridiculytics.q||[];if(q.length<100)q.push(arguments);};

View file

@ -33,7 +33,7 @@ function bbCost(c){return 15000+CITY[c].P*20;}
const RK_SKIP=new Set(['name','log','offers','usedNames','stats','cash','seen','tut','ach','achP','won','loanOffers','loanStrikes','uiSpeed','cam','richTold','demo','nextEvent','nextFail','done','confReg','auNews','calV','solWon','seatOff','chartSet','t1Now','ltv','capDeal','auV','pdeskRep','sv']);
function routeKey(){const o={};for(const k in S)if(!RK_SKIP.has(k))o[k]=S[k];return JSON.stringify(o);}
function routeIfChanged(){const k=S&&!pzOn()?routeKey():null;if(k&&k===UI.rk&&R===UI.rkR)return false;compute();UI.rk=k;UI.rkR=R;return true;}
function after(){if(pzOn()){pzAfter();return;}if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}
function after(){if(pzOn()){pzAfter();return;}NOC.dirty=true;if(S)purgeInc();routeIfChanged();checkGoals();renderAll();if(S&&!$('dash').hidden)renderDash();save();}
const isTablet=()=>innerWidth>760&&innerWidth<=1200;
function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();}
// Frame the whole drawn line (cables bend far from the straight one) in the part of the map the panel leaves free:

View file

@ -0,0 +1,77 @@
/* ---------- The NOC window ----------
The dashboard in a window of its own, for a second display: this page again, at ?noc=<slot>. It never claims the slot,
saves or runs a day: the game window stays the only writer, sends it a copy of S and R, and runs its clicks.
The control channel is small messages, always open so a reloaded game finds its window again; the copies go on a channel
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_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;}}
if(!RW_IN)try{if(typeof BroadcastChannel==='function'){NOC.ctl=new BroadcastChannel('sot-noc');NOC.ctl.onmessage=e=>{const m=e.data;if(!m||typeof m!=='object'||!slotOkId(m.id))return;if(NOC.win)nocWinMsg(m);else nocGameMsg(m);};}}catch(e){}
const nocPost=m=>{try{if(NOC.ctl)NOC.ctl.postMessage(m);}catch(e){console.error('[tubes] NOC window',e);}};
const nocHid=()=>document.visibilityState==='hidden';
// ---------- in the game window ----------
// R as plain data: the routing tables are left out (the dashboard does not read them), an attack names its attack in S by id.
const NOC_SKIP={ef:1,fl:1,efp:1,flc:1,efg:1};
function nocR(){const o={};for(const k in R)if(!NOC_SKIP[k])o[k]=k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k];return o;}
// Half a day (its routing still in the worker) is never sent, like it is never saved: it stays due.
function nocSend(now){if(!NOC.peer||!S||S.lost||pzOn()||RW.job||!UI.slot)return;
try{if(NOC.stId!==UI.slot){if(NOC.st)NOC.st.close();NOC.stId=UI.slot;NOC.st=new BroadcastChannel('sot-noc:'+UI.slot);}
NOC.st.postMessage({S,R:nocR(),speed:UI.speed,hid:nocHid()});NOC.dirty=false;NOC.sent=now;}
catch(e){console.error('[tubes] NOC window',e);NOC.peer=false;}}
// Every frame while a window is connected: at most one copy a second, whatever the game's speed.
function nocPump(now){if(now>NOC.until){NOC.peer=false;return;}if(NOC.dirty&&now-NOC.sent>=NOC_GAP)nocSend(now);}
function nocGameMsg(m){if(m.id!==UI.slot)return;const now=performance.now();
if(m.t==='hello'||m.t==='hi'){const was=NOC.peer;NOC.peer=true;NOC.until=now+NOC_LOST;nocPost({t:'yo',id:m.id,speed:UI.speed,hid:nocHid()});
if(m.t==='hello'||!was){NOC.dirty=true;nocSend(now);}}
else if(m.t==='bye')NOC.peer=false;
else if(m.t==='act')nocRun(m,now);}
// A click from the window: the same rules as a click here. A window open in the game comes first, like any click outside it.
function nocRun(m,now){const ts=[],t=toast;
if(!NOC_GO.includes(m.act)||typeof ACT[m.act]!=='function'||!S||S.lost||pzOn())return;
if(!$('modal').hidden){nocPost({t:'res',id:m.id,ts:[[tr('noc.the_game_has_a_dialog_open'),'bad']]});return;}
const a=m.args&&typeof m.args==='object'?m.args:{};
toast=(h,k,x,o)=>{ts.push([h,k]);return t(h,k,x,o);};
try{if(m.act==='connCancel')UI.confirm='cc:'+a.k+':'+a.id;ACT[m.act](a);}catch(e){console.error('[tubes] NOC window action',m.act,e);}finally{toast=t;}
NOC.dirty=true;nocSend(now);nocPost({t:'res',id:m.id,ts});}
// ---------- in the NOC window ----------
function nocWinMsg(m){if(m.id!==NOC.id)return;
if(m.t==='yo'){NOC.yoAt=performance.now();NOC.gone=false;NOC.speed=m.speed;NOC.hid=!!m.hid;nocBar();}
else if(m.t==='bye'){NOC.gone=true;nocBar();}
else if(m.t==='focus'){try{window.focus();}catch(e){}}
else if(m.t==='res')for(const [h,k] of m.ts||[])toast(h,k);}
function nocWinState(d){if(!d||!d.S||!d.R)return;S=d.S;R=Object.assign(emptyR(),d.R);const as=ddosAll(S,false);for(const m of R.ddos||[]){m.attack=as.find(a=>a.id===m.attack)||null;m.ports=new Map();}
UI.started=true;NOC.speed=d.speed;NOC.hid=!!d.hid;NOC.gone=false;NOC.yoAt=performance.now();document.title=tr('common.noc_dashboard')+' · '+S.name;nocRender();}
// Not under a finger: a button that moves during a press never gets its click.
function nocRender(){if(pressing){setTimeout(nocRender,150);return;}document.body.classList.toggle('noc-still',!NOC.speed||NOC.gone||!animOn());try{if(S){if(NOCW.view==='wall')nocWall();else renderDash();}}catch(e){console.error('[tubes] NOC window render',e);}nocBar();}
function nocBar(){const b=$('nocBar');if(!b)return;
const why=NOC.gone?tr('noc.the_game_window_is_closed'):!S?tr('noc.waiting_for_the_game_window'):NOC.hid?tr('noc.the_game_window_is_hidden'):!NOC.speed?tr('noc.the_game_is_paused'):'';
const {bad,warn}=NOCW.sum,tab=(v,l)=>`<button data-nc="${v}" class="${NOCW.view===v?'on':''}" aria-pressed="${NOCW.view===v}">${esc(l)}</button>`;
const h=`<div class="nb-id">${S?`<span class="nb-as">AS${S.asn} · ${esc(S.name)} · ${esc(tierLabel())}</span>`:''}<div class="nb-title">${esc(tr('common.noc_dashboard'))}</div></div>`
+(S?`<span class="nb-pill ${bad?'bad':warn?'warn':''}">${esc(bad?trn('noc.n_alarms',bad):warn?trn('noc.n_warnings',warn):tr('common.all_quiet'))}</span><span class="nb-now"><b>${esc(dateStr(S.day))}</b><span>${esc(fmt$(S.cash))}</span><span>${NOC.speed?NOC.speed+'×':'❚❚'}</span></span>`:'')
+`<div class="nb-tabs">${tab('wall',tr('noc.wallboard'))}${tab('details',tr('noc.details'))}${document.documentElement.requestFullscreen?`<button data-nc="fs">${esc(tr('noc.full_screen'))}</button>`:''}</div>`
+(why?`<div class="nb-why">${esc(why)}</div>`:'');
if(b._h!==h){b._h=h;morph(b,h);}}
function nocBeat(now=performance.now()){nocPost({t:'hi',id:NOC.id});if(now-NOC.yoAt>NOC_LOST&&!NOC.gone){NOC.gone=true;nocBar();}}
function nocFwd(act,a){if(NOC_GO.includes(act))nocPost({t:'act',id:NOC.id,act,args:a||{}});}
function nocWinBoot(){i18nDom();document.body.classList.add('noc-window');UI.dtab='conn';try{UI.anim=localStorage.getItem('sot-anim')||'auto';}catch(e){}$('dash').hidden=true;$('dash').insertAdjacentHTML('beforebegin','<div id="nocBoard"><header id="nocBar"></header><main id="nocWall"></main></div>');
const bd=$('nocBoard');bd.addEventListener('click',nocUiClick);bd.addEventListener('change',e=>{if(e.target.hasAttribute&&e.target.hasAttribute('data-nc-city')){NOCW.city=e.target.value;nocRender();}});bd.addEventListener('pointerdown',e=>{if(e.target.closest('#nocWall'))pressing=true;});
// The game's keyboard shortcuts are for the map, which is not here. Tab and the browser's own keys still work.
addEventListener('keydown',e=>e.stopImmediatePropagation(),true);
for(const k of Object.keys(ACT))if(!NOC_LOCAL.includes(k))ACT[k]=a=>nocFwd(k,a);
ACT.dashClose=()=>{try{window.close();}catch(e){}};
ACT.connCancel=a=>{const key='cc:'+a.k+':'+a.id;if(UI.confirm!==key){UI.confirm=key;renderDash();return;}UI.confirm=null;nocFwd('connCancel',a);};
try{NOC.st=new BroadcastChannel('sot-noc:'+NOC.id);NOC.st.onmessage=e=>nocWinState(e.data);}catch(e){}
addEventListener('pagehide',()=>nocPost({t:'bye',id:NOC.id}));
// A hidden window's timers slow right down, so the game stops sending; coming back asks for the latest.
document.addEventListener('visibilitychange',()=>{if(!nocHid()){NOC.yoAt=performance.now();nocPost({t:'hello',id:NOC.id});}});
NOC.yoAt=performance.now();nocBar();nocPost({t:'hello',id:NOC.id});if(!window.__TUBES_TEST__)setInterval(nocBeat,NOC_HB);}
addEventListener('pagehide',()=>{if(!NOC.win&&NOC.peer&&UI.slot)nocPost({t:'bye',id:UI.slot});});
Object.assign(ACT,{
// A second click finds the window that is already there. A blocked pop-up can only be told by its silence (noopener gives no handle).
nocWindow:()=>{if(!S||pzOn()||!UI.slot)return;const id=UI.slot;if(NOC.peer){nocPost({t:'focus',id});return;}
window.open(location.pathname+'?noc='+id,'_blank','noopener,popup,width=1320,height=860');
if(!window.__TUBES_TEST__)setTimeout(()=>{if(!NOC.peer&&UI.slot===id)toast(tr('noc.your_browser_blocked_the_window'),'bad');},4000);},
});

View file

@ -0,0 +1,93 @@
/* ---------- The NOC window's wallboard ----------
The first thing the window shows: a dark board to glance at from across the room. Everything is drawn from the copy of S
and R (90-noc-window.js) with the game's own helpers, and the upgrade buttons are the dashboard's (connUp), so prices
and rules cannot drift. Each section is patched with morph(): a flow on the map keeps running and a button stays put.
Only the window runs any of this. */
const NOCW={view:'wall',city:'',built:false,sum:{bad:0,warn:0}};
const NW_HOT=0.9,NW_WARM=0.65,NW_FLOWS=40,NW_PORTS=8;
const NW_COL={ok:'#2DD4A7',warn:'#FFB547',bad:'#FF5C6C',idle:'#5A6B94'};
const nwCol=u=>u>=NW_HOT?NW_COL.bad:u>=NW_WARM?NW_COL.warn:NW_COL.ok;
const nwG=v=>v>=1000?(+(v/1000).toFixed(1))+'T':(v>=10||v===0?Math.round(v):+v.toFixed(1))+'G';
// ---------- the land: built once, it never changes ----------
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 `<p class="nw-empty">${tr('link_panels.collecting_data_check_back_in_a')}</p>`;
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+=`<line class="nw-grid" x1="${L}" x2="${CW-Rr}" y1="${yy}" y2="${yy}"/><text class="nw-ax" x="${L-6}" y="${yy+3}" text-anchor="end">${esc(fmtY(v))}</text>`;}
const base=rows.map(()=>0);
for(const k of stack){const top=rows.map((r,i)=>base[i]+(r[k]||0));let d=`M${x(0)},${y(top[0])}`,e=d;for(let i=1;i<rows.length;i++){d+=`L${x(i)},${y(top[i])}`;e+=`L${x(i)},${y(top[i])}`;}for(let i=rows.length-1;i>=0;i--)d+=`L${x(i)},${y(base[i])}`;
g+=`<path d="${d}Z" fill="${EGC[k][1]}" fill-opacity=".55"/><path d="${e}" fill="none" stroke="${EGC[k][1]}" stroke-width="1.5"/>`;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+=`<path d="${d}" fill="none" stroke="${ln.col}" stroke-width="2" ${ln.dash?'stroke-dasharray="5 4"':''} stroke-linejoin="round"/><circle cx="${x(rows.length-1)}" cy="${y(rows[rows.length-1][ln.k]||0)}" r="3.5" fill="${ln.col}"/>`;}
g+=`<text class="nw-ax" x="${L}" y="${CH-6}">${esc(dateStr(rows[0].d))}</text><text class="nw-ax" x="${CW-Rr}" y="${CH-6}" text-anchor="end">${esc(dateStr(rows[rows.length-1].d))}</text>`;
return `<svg class="nw-chart" viewBox="0 0 ${CW} ${CH}" role="img">${g}</svg>`;}
function nwSpark(vals,col){if(vals.length<2)return '';let a=Infinity,b=-Infinity;for(const v of vals){if(v<a)a=v;if(v>b)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 `<svg class="nw-spark" viewBox="0 0 100 28" preserveAspectRatio="none" aria-hidden="true"><polyline points="${pts}" fill="none" stroke="${col}" stroke-width="2" vector-effect="non-scaling-stroke"/></svg>`;}
// ---------- what is wrong ----------
function nwAlarms(){const A=[];
for(const a of ddosAll()){const t=tr('noc.under_attack',{who:ddosWho(a),g:fmtG(a.gbps)});A.push({k:'bad',t:esc(t.charAt(0).toUpperCase()+t.slice(1)),m:''});}
for(const i of S.inc)if(i.type!=='ddos'&&i.until>S.day)A.push({k:'bad',t:incTitle(i.type),m:esc(i.msg||''),s:shipSea(i)?'🚢 '+esc(shipStatus(i)):esc(trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day))});
const hot=hotPorts().filter(h=>h.k==='t'||h.k==='p'||h.k==='ix').length,sad=custStats().unhappy;
if(hot)A.push({k:'warn',t:esc(trn('noc.n_ports_over_90_full',hot)),m:''});
if(sad)A.push({k:'warn',t:esc(trn('noc.n_unhappy_customers',sad)),m:''});
return A;}
// ---------- sections ----------
function nwTiles(){const H=(S.hist||[]).slice(-60),last30=(S.hist||[]).slice(-30),net=R.revMo-R.costMo;
const up=last30.length?last30.reduce((a,r)=>a+(r.dem?Math.min(1,r.srv/r.dem):1),0)/last30.length:1;
const tile=(l,v,sub,sp,cls='')=>`<div class="nw-tile ${cls}"><div class="nw-l">${l}</div><div class="nw-v num">${v}</div><div class="nw-s">${sub||'&nbsp;'}</div>${sp||''}</div>`;
return tile(tr('common.traffic_now'),esc(fmtG(R.served)),esc(tr('dashboard.of_g_wanted',{g:fmtG(R.demand)})),nwSpark(H.map(r=>r.srv),NW_COL.ok))
+tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%','',nwSpark(H.map(r=>r.dem?Math.min(1,r.srv/r.dem):1),NW_COL.ok),up<0.99?'warn':'')
+tile(tr('common.peering_ratio'),pct(R.peerShare||0),'',nwSpark(H.map(r=>r.srv?(r.c+r.p+r.ix)/r.srv:0),'#7B8CFF'))
+tile(tr('noc.net_per_month'),esc(fmt$(net)),'',nwSpark(H.map(r=>r.rev-r.cost),net<0?NW_COL.bad:NW_COL.ok),net<0?'bad':'')
+tile(tr('common.peak'),esc(fmtG(S.stats.peak)),esc(tr('common.reach'))+' '+reachPct(R.reach||0))
+tile(tr('common.bgp_sessions'),String(R.sessions||0),esc(tr('noc.n_pops_n_links',{pops:Object.keys(S.pops).length,links:S.links.length})));}
// Parallel links between two cities are one line on so small a map: their load over their capacity, down only when all are.
function nwMap(){const by=new Map();
for(const l of S.links){const k=edgeKey(l);let e=by.get(k);if(!e)by.set(k,e={k,a:l.a,b:l.b,load:0,cap:0,up:0});if(!linkDown(l)&&!l.standby){e.up++;e.load+=(R.load&&R.load[l.id])||0;e.cap+=capOf(l)||0;}}
const E=[...by.values()],fl=new Set(E.filter(e=>e.load>0&&e.up).sort((a,b)=>b.load-a.load).slice(0,NW_FLOWS).map(e=>e.k));let g='';
for(const e of E){const A=CITY[e.a],B=CITY[e.b],dx=wrapDx(A.x,B.x),bx=A.x+dx,u=e.cap>0?e.load/e.cap:0,len=Math.hypot(dx,B.y-A.y);
const arc=o=>`M${Math.round(A.x+o)} ${Math.round(A.y)}Q${Math.round(A.x+o+dx/2)} ${Math.round((A.y+B.y)/2-len*0.09)} ${Math.round(bx+o)} ${Math.round(B.y)}`;
const d=arc(0)+(bx<0?arc(W):bx>W?arc(-W):''),col=e.up?nwCol(u):NW_COL.bad,wd=e.up?(1.5+Math.min(4,Math.log10(1+e.cap)*0.9)).toFixed(1):'2.5';
g+=`<path class="nw-link${e.up?'':' down'}" d="${d}" stroke="${col}" stroke-width="${wd}"/>`;
if(fl.has(e.k))g+=`<path class="nw-flow" d="${d}" stroke-width="${wd}"/>`;}
const inc=new Set();for(const i of S.inc)if(i.until>S.day&&isCity(i.ref))inc.add(i.ref);for(const a of ddosAll())inc.add(a.city);
let dots='',labs='';
for(const c of Object.keys(S.pops)){const C=CITY[c],up=popUp(c),u=(R.nodeLoad[c]||0)/(R.nodeCap[c]||1),on=NOCW.city===c,alarm=!up||inc.has(c),col=!up?NW_COL.bad:nwCol(u);
dots+=`<g class="nw-pop${alarm?' alarm':''}${on?' on':''}" data-nc="pop:${c}"><title>${esc(CITY[c].name)} · ${pct(u)}</title><circle class="nw-hit" cx="${Math.round(C.x)}" cy="${Math.round(C.y)}" r="24"/>${alarm?`<circle class="nw-ring" cx="${Math.round(C.x)}" cy="${Math.round(C.y)}" r="14" stroke="${NW_COL.bad}"/>`:''}${on?`<circle class="nw-sel" cx="${Math.round(C.x)}" cy="${Math.round(C.y)}" r="17"/>`:''}<circle class="nw-dot" cx="${Math.round(C.x)}" cy="${Math.round(C.y)}" r="${on?10:8}" fill="${col}"/></g>`;
if(on||alarm||u>=NW_HOT)labs+=`<text class="nw-lab" x="${Math.round(C.x+14)}" y="${Math.round(C.y+9)}">${esc(CITY[c].name)}</text>`;}
const v=NOCW.box.join(' ');return `<svg class="nw-over" viewBox="${v}" role="img" aria-label="${esc(tr('noc.your_network'))}">${g}${dots}${labs}</svg>`;}
// An exchange port's row only knows about the exchange: its POP going dark takes it down as well. A remote port has no POP here.
const nwDown=r=>r.down||(!!S.pops[r.city]&&!popUp(r.city));
function nwPorts(){const all=conns().filter(r=>r.k==='t'||r.k==='p'||r.k==='ix'),city=NOCW.city&&all.some(r=>r.city===NOCW.city)||S.pops[NOCW.city]?NOCW.city:'';NOCW.city=city;
const cities=[...new Set(all.map(r=>r.city))].sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));
const sel=`<label class="nw-pick"><span class="sr-only">${tr('common.your_pop')}</span><select data-nc-city="1"><option value="">${esc(tr('noc.all_pops'))}</option>${cities.map(c=>`<option value="${c}"${c===city?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label>`;
const rows=all.filter(r=>city?r.city===city:!nwDown(r)).map(r=>({r,u:r.cap>0?r.use/r.cap:0})).sort((a,b)=>(nwDown(b.r)?1:0)-(nwDown(a.r)?1:0)||b.u-a.u).slice(0,city?60:NW_PORTS);
const row=({r,u})=>`<div class="nw-port"><span class="nw-k" style="background:${CONN_COL[r.k]}">${esc(tr(CONN_K[r.k]))}</span><div class="nw-pm"><div class="nw-pt"><b>${esc(CITY[r.city].name)}</b> ${esc(r.name)}</div><div class="nw-bar"><i style="width:${Math.min(100,u*100).toFixed(1)}%;background:${nwDown(r)?NW_COL.bad:nwCol(u)}"></i></div><div class="nw-s num">${esc(fmtG(r.use))} / ${esc(r.port)}</div></div><b class="nw-pc num" style="color:${nwDown(r)?NW_COL.bad:nwCol(u)}">${nwDown(r)?esc(tr('noc.legend_down')):pct(u)}</b><div class="nw-btns">${connUp(r)}${btn(tr('common.open'),'goConn',{city:r.city,k:r.k},'ghost sm')}</div></div>`;
return `<div class="nw-h"><h3>${esc(tr('noc.hottest_ports'))}</h3>${sel}</div>${rows.length?rows.map(row).join(''):`<p class="nw-empty">${esc(tr('noc.no_ports_here'))}</p>`}`;}
function nwAlarmsHtml(A){return `<div class="nw-h"><h3>${esc(tr('noc.alarms'))}</h3></div>`+(A.length?A.map(a=>`<div class="nw-al ${a.k}"><b>${a.t}</b>${a.m?`<div class="nw-s">${a.m}</div>`:''}${a.s?`<div class="nw-s">${a.s}</div>`:''}</div>`).join(''):`<p class="nw-quiet">${esc(tr('noc.nothing_on_fire'))}</p>`);}
const nwBars=(title,rows)=>`<div class="nw-h"><h3>${esc(title)}</h3></div>`+rows.map(([n,m,u])=>`<div class="nw-row"><div class="nw-pm"><div class="nw-pt"><b>${esc(n)}</b> <span class="nw-s">${esc(m)}</span></div><div class="nw-bar"><i style="width:${Math.min(100,u*100).toFixed(1)}%;background:${nwCol(u)}"></i></div></div><b class="nw-pc num" style="color:${nwCol(u)}">${pct(u)}</b></div>`).join('');
function nwBuild(){const w=$('nocWall');NOCW.box=nwMapBox();
w.innerHTML=`<div class="nw-tiles" id="nwTiles"></div>
<div class="nw-col"><section class="nw-panel nw-map"><div class="nw-h"><h3>${esc(tr('noc.your_network'))}</h3><div class="nw-legend"><span><i style="background:${NW_COL.ok}"></i>${esc(tr('noc.legend_ok'))}</span><span><i style="background:${NW_COL.warn}"></i>${esc(tr('noc.legend_warm'))}</span><span><i style="background:${NW_COL.bad}"></i>${esc(tr('noc.legend_hot'))}</span></div></div>
<div class="nw-world" style="aspect-ratio:${NOCW.box[2]}/${NOCW.box[3]}"><svg class="nw-land" viewBox="${NOCW.box.join(' ')}" aria-hidden="true"><path d="${nwLand()}"/></svg><div id="nwOver"></div></div></section>
<section class="nw-panel" id="nwTraffic"></section></div>
<div class="nw-col"><section class="nw-panel nw-alarms" id="nwAlarms"></section>
<section class="nw-panel" id="nwPorts"></section></div>
<div class="nw-low"><section class="nw-panel" id="nwRouters"></section><section class="nw-panel" id="nwLinks"></section><section class="nw-panel" id="nwMoney"></section></div>`;NOCW.built=true;}
function nocWall(){if(!NOCW.built)nwBuild();const rows=(S.hist||[]).slice(-90),A=nwAlarms();
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',`<div class="nw-h"><h3>${esc(tr('dashboard.traffic_by_way_out'))}</h3><div class="nw-legend">${Object.keys(EGC).filter(k=>(R.egT[k]||0)>0.01||rows.some(r=>(r[k]||0)>0)).map(k=>`<span><i style="background:${EGC[k][1]}"></i>${esc(EGC[k][0])} <b class="num">${esc(fmtG(R.egT[k]||0))}</b></span>`).join('')}<span><i class="dash"></i>${esc(tr('common.demand'))}</span></div></div>${nwChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#E8EEFA',dash:true}],nwG)}`);
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',`<div class="nw-h"><h3>${esc(tr('dashboard.money_per_month'))}</h3><div class="nw-legend"><span><i style="background:${NW_COL.ok}"></i>${esc(tr('common.revenue'))}</span><span><i style="background:${NW_COL.bad}"></i>${esc(tr('common.costs'))}</span></div></div>${nwChart(rows,[],[{k:'rev',col:NW_COL.ok},{k:'cost',col:NW_COL.bad}],fmt$,520,220,74)}`);}
// 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);
else if(v==='fs'){try{if(document.fullscreenElement)document.exitFullscreen();else document.documentElement.requestFullscreen();}catch(err){}}
else if(v.startsWith('pop:')){const c=v.slice(4);NOCW.city=NOCW.city===c?'':c;nocRender();}}
function nocView(v){NOCW.view=v;$('dash').hidden=v==='wall';$('nocWall').hidden=v!=='wall';UI._dh=null;nocRender();try{scrollTo(0,0);}catch(e){}}

View file

@ -7,7 +7,8 @@ function frame(now){
if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);}
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
if(UI.panelsDue){NOC.dirty=true;UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
if(NOC.peer)nocPump(now);
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0;
// With the route worker one day is in flight at a time; time does not pile up behind it.
if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
@ -50,4 +51,4 @@ function boot(data){
window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}}));
if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);}
}
if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));
if(NOC.win)nocWinBoot();else if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {}));

View file

@ -3026,6 +3026,33 @@
"networks.waves_goodbye_to_latency_across_the":"Waves goodbye to latency across the Indian Ocean.",
"networks.western_canada_s_incumbent_tell_us":"Western Canada’s incumbent. Tell us what you need, and we will tell you the price.",
"networks.will_peer_with_anyone_anywhere":"Will peer with anyone, anywhere. Rumored to mail out IPv6 cakes.",
"noc.alarms":"Alarms",
"noc.all_pops":"All POPs",
"noc.details":"Details",
"noc.full_screen":"Full screen",
"noc.hottest_ports":"Hottest ports",
"noc.legend_down":"Down",
"noc.legend_hot":"Over 90% full",
"noc.legend_ok":"Under 65% full",
"noc.legend_warm":"Over 65% full",
"noc.n_alarms":{"one":"{n} alarm","other":"{n} alarms"},
"noc.n_pops_n_links":"{pops} POPs · {links} links",
"noc.n_ports_over_90_full":{"one":"{n} port over 90% full","other":"{n} ports over 90% full"},
"noc.n_unhappy_customers":{"one":"{n} unhappy customer","other":"{n} unhappy customers"},
"noc.n_warnings":{"one":"{n} warning","other":"{n} warnings"},
"noc.net_per_month":"Net per month",
"noc.no_ports_here":"No ports here yet. Buy transit or join an exchange.",
"noc.nothing_on_fire":"Nothing on fire. Enjoy it while it lasts.",
"noc.open_in_its_own_window":"Open the NOC dashboard in its own window",
"noc.the_game_has_a_dialog_open":"The game window has a dialog open. Close it there first.",
"noc.the_game_is_paused":"The game is paused.",
"noc.the_game_window_is_closed":"The game window is closed or not answering, so these numbers are not live. Open your network there and this window picks it up again.",
"noc.the_game_window_is_hidden":"The game window is hidden, so its clock has stopped. Bring it back on screen to keep playing.",
"noc.under_attack":"{who} under attack: {g}",
"noc.waiting_for_the_game_window":"Waiting for the game window…",
"noc.wallboard":"Wallboard",
"noc.your_browser_blocked_the_window":"Your browser may have blocked the NOC window. Allow pop-ups for this site and try again.",
"noc.your_network":"Your network",
"notifications.last_10_minutes":"last 10 minutes",
"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.",

View file

@ -126,6 +126,7 @@
<button data-act="speed" data-args='{"v":4}' id="sp4">4×</button>
<button data-act="speed" data-args='{"v":8}' id="sp8">8×</button>
<button data-act="dash" aria-label="NOC dashboard" data-i18n-aria-label="common.noc_dashboard" title="NOC dashboard" data-i18n-title="common.noc_dashboard"><svg width="16" height="14" viewBox="0 0 16 14" aria-hidden="true"><path d="M1 13h14M2 10l4-5 3 3 5-6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
<button class="hide-sm" data-act="nocWindow" aria-label="Open the NOC dashboard in its own window" data-i18n-aria-label="noc.open_in_its_own_window" title="Open the NOC dashboard in its own window" data-i18n-title="noc.open_in_its_own_window"><svg width="17" height="14" viewBox="0 0 17 14" aria-hidden="true"><rect x="1" y="1" width="9" height="7" rx="1.5" fill="none" stroke="currentColor" stroke-width="2"/><rect x="7" y="6" width="9" height="7" rx="1.5" fill="currentColor"/></svg></button>
<button data-act="help" aria-label="How to play" data-i18n-aria-label="common.how_to_play">?</button>
<button data-act="mute" id="muteBtn" aria-label="Toggle sound" data-i18n-aria-label="common.toggle_sound">♪</button>
</div>

View file

@ -0,0 +1,95 @@
/* The NOC window (?noc=<slot>): 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 #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}
#nocBar{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;padding:10px 16px;background:#0F1830;border-bottom:1px solid #2A3658;position:sticky;top:0;z-index:5}
.nb-id{min-width:0;margin-right:auto}
.nb-as{display:block;font-size:11px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:#9FB0D3;overflow-wrap:anywhere}
.nb-title{font-family:var(--display);font-weight:800;font-size:22px;line-height:1.1}
.nb-pill{font-family:var(--display);font-weight:800;font-size:14px;padding:4px 12px;border-radius:99px;color:#07101F;background:#2DD4A7;white-space:nowrap}
.nb-pill.warn{background:#FFB547}
.nb-pill.bad{background:#FF5C6C}
.nb-now{font-family:var(--display);font-weight:800;font-size:17px;font-variant-numeric:tabular-nums;white-space:nowrap}
.nb-now span{color:#9FB0D3;font-weight:700;margin-left:10px}
.nb-why{flex-basis:100%;order:9;color:#FFD08A;font-weight:700;font-size:13px}
.nb-tabs{display:flex;gap:4px}
.nb-tabs button{background:none;border:1px solid #2A3658;color:#C9D5EE;border-radius:9px;padding:5px 11px;font-weight:800;font-size:12.5px;cursor:pointer}
.nb-tabs button.on{background:#E8EEFA;color:#0B1224;border-color:#E8EEFA}
#nocWall{display:grid;grid-template-columns:minmax(0,1.55fr) minmax(0,1fr);gap:10px;padding:10px 12px 16px}
.nw-tiles{grid-column:1/-1;display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px}
.nw-col{display:flex;flex-direction:column;gap:10px;min-width:0}
.nw-low{grid-column:1/-1;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
.nw-tile,.nw-panel{background:#121B33;border:1px solid #2A3658;border-radius:14px;min-width:0}
.nw-tile{padding:8px 12px;position:relative;overflow:hidden}
.nw-l{font-size:10.5px;font-weight:900;letter-spacing:.07em;text-transform:uppercase;color:#9FB0D3}
.nw-v{font-family:var(--display);font-weight:800;font-size:25px;line-height:1.15;white-space:nowrap}
.nw-tile.bad .nw-v{color:#FF5C6C}
.nw-tile.warn .nw-v{color:#FFB547}
.nw-s{font-size:11.5px;font-weight:700;color:#9FB0D3}
.nw-spark{display:block;width:100%;height:22px;margin-top:3px}
.nw-panel{padding:10px 12px}
.nw-h{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:4px 12px;margin-bottom:6px}
.nw-h h3{font-size:15px;color:#E8EEFA}
.nw-legend{display:flex;flex-wrap:wrap;gap:3px 10px;font-size:11.5px;font-weight:700;color:#C9D5EE}
.nw-legend i{display:inline-block;width:9px;height:9px;border-radius:3px;margin-right:4px}
.nw-legend i.dash{width:12px;height:0;border-top:2px dashed #E8EEFA;border-radius:0;vertical-align:middle}
.nw-empty{color:#9FB0D3;font-weight:700;margin:14px 0}
.nw-quiet{color:#2DD4A7;font-weight:800;margin:10px 0}
.nw-world{position:relative;width:100%;border-radius:10px;background:#0A1A33;overflow:hidden}
.nw-world svg{position:absolute;inset:0;width:100%;height:100%;display:block}
.nw-land path{fill:#233459;stroke:#34497A;stroke-width:1.5;stroke-linejoin:round}
#nwOver{position:absolute;inset:0}
.nw-link{fill:none;stroke-linecap:round;opacity:.85}
.nw-link.down{stroke-dasharray:10 10}
.nw-flow{fill:none;stroke:#fff;stroke-linecap:round;stroke-dasharray:3 34;opacity:.75;pointer-events:none}
.nw-dot{stroke:#0A1A33;stroke-width:3}
.nw-hit{fill:transparent}
.nw-pop{cursor:pointer}
.nw-sel{fill:none;stroke:#fff;stroke-width:3}
.nw-ring{fill:none;stroke-width:4}
.nw-lab{font-family:var(--body);font-weight:800;font-size:28px;fill:#fff;paint-order:stroke;stroke:#0A1A33;stroke-width:7px;stroke-linejoin:round;pointer-events:none}
@media (prefers-reduced-motion:no-preference){
body.noc-window:not(.noc-still) .nw-flow{animation:nwFlow 1.6s linear infinite}
body.noc-window:not(.noc-still) .nw-ring{animation:nwPing 1.4s ease-out infinite;transform-box:fill-box;transform-origin:center}
}
@keyframes nwFlow{to{stroke-dashoffset:-37}}
@keyframes nwPing{from{transform:scale(.7);opacity:1}to{transform:scale(2.2);opacity:0}}
.nw-chart{display:block;width:100%;height:auto}
.nw-grid{stroke:#2A3658;stroke-width:1}
.nw-ax{font-size:13px;font-weight:700;fill:#9FB0D3}
.nw-al{border-left:4px solid #FFB547;padding:4px 8px;margin-bottom:6px;background:#19233F;border-radius:0 8px 8px 0;font-size:13px}
.nw-al.bad{border-left-color:#FF5C6C}
.nw-alarms{max-height:min(44vh,430px);overflow:auto}
.nw-pick select{background:#0F1830;color:#E8EEFA;border:1px solid #2A3658;border-radius:8px;padding:4px 6px;font-weight:700;font-size:12.5px;max-width:170px}
.nw-port{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:2px 8px;align-items:center;padding:7px 0;border-top:1px solid #222E4E}
.nw-k{font-size:10px;font-weight:900;color:#07101F;padding:2px 6px;border-radius:6px;white-space:nowrap}
.nw-pm{min-width:0}
.nw-pt{font-size:13px;overflow-wrap:anywhere}
.nw-bar{height:7px;border-radius:9px;background:#26324F;overflow:hidden;margin:3px 0}
.nw-bar i{display:block;height:100%;border-radius:9px}
.nw-pc{font-family:var(--display);font-size:16px;min-width:42px;text-align:right}
.nw-btns{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:4px;--ink:#1E2640;--paper:#fff;color:#1E2640}
.nw-btns .meta{color:#9FB0D3}
.nw-row{display:flex;align-items:center;gap:8px;padding:4px 0}
.nw-row .nw-pm{flex:1}
@media (max-width:1000px){
#nocWall{grid-template-columns:minmax(0,1fr)}
.nw-low{grid-template-columns:minmax(0,1fr)}
.nw-tiles{grid-template-columns:repeat(3,minmax(0,1fr))}
}
@media (max-width:520px){
.nw-tiles{grid-template-columns:repeat(2,minmax(0,1fr))}
.nw-v{font-size:21px}
.nw-lab{display:none}
#nocBar{padding:8px 10px}
#nocWall{padding:8px}
.nb-now span{margin-left:6px}
}

View file

@ -19,7 +19,7 @@ function load(opts = {}) {
if (!/getContext|Not implemented/.test(e.message)) errors.push(e.message);
});
const dom = new JSDOM(html, {
url: 'https://tests.invalid/',
url: opts.url || 'https://tests.invalid/',
runScripts: 'dangerously',
pretendToBeVisual: true,
virtualConsole: vc,

315
tests/noc-window.test.js Normal file
View file

@ -0,0 +1,315 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load, browser } = require('./harness');
// A game window and its NOC window in one fake browser: shared localStorage, broadcast channels and locks.
const settle = async (ev, cond, what) => { for (let i = 0; i < 400 && !ev(cond); i++) await new Promise((r) => setTimeout(r, 5)); assert.ok(ev(cond), what || cond); };
const wait = (ms = 30) => new Promise((r) => setTimeout(r, ms));
const START = "UI.pitched=true;ACT.pickStart({city:'fra'});ACT.start({});closeModal();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
"ACT.launchBB({city:'fra'});S.pops.fra.bb.d=300;S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:0,signed:true});S.pni.push({id:'p1',city:'fra',net:'drz',tier:0,ready:0});compute();save(true)";
const closeAll = (t, ...hs) => t.after(() => { for (const h of hs) h.dom.window.close(); });
async function pair(t) {
const b = browser();
const G = load({ browser: b });
G.ev(START);
const id = G.ev('UI.slot');
const W = load({ browser: b, url: 'https://tests.invalid/?noc=' + id });
closeAll(t, G, W);
await settle(W.ev, 'UI.started===true', 'the window got its first copy');
return { b, G, W, id };
}
const pump = (G) => G.ev('NOC.sent=-1e9;nocPump(performance.now())');
const click = (h, sel) => h.ev(`document.querySelector(${JSON.stringify(sel)}).click()`);
test('with no NOC window nothing is sent and nothing is scheduled', (t) => {
const b = browser();
const G = load({ browser: b });
closeAll(t, G);
G.ev(START);
G.ev("window.__posts=0;{const P=BroadcastChannel.prototype.postMessage;BroadcastChannel.prototype.postMessage=function(m){__posts++;return P.call(this,m);};}");
G.ev('after();after();nocPump(performance.now()+1e6);nocSend(performance.now());frame(performance.now());dayTick()');
assert.equal(G.ev('__posts'), 0);
assert.equal(G.ev('NOC.peer'), false);
assert.deepEqual(G.errors, []);
});
test('the window never claims the network and never writes to localStorage', async (t) => {
const b = browser();
const G = load({ browser: b });
G.ev(START);
const id = G.ev('UI.slot'), before = JSON.stringify([...b.ls.entries()].filter(([k]) => !k.startsWith('sot-open:')));
const W = load({ browser: b, url: 'https://tests.invalid/?noc=' + id });
closeAll(t, G, W);
await settle(W.ev, 'UI.started===true');
assert.equal(W.ev('NOC.win'), true);
assert.ok(!W.ev('UI.slot'), 'the window holds no network');
assert.equal(G.ev('UI.slot'), id, 'the game keeps its network');
W.ev('S.cash=1;save(true)');
await wait();
assert.equal(JSON.stringify([...b.ls.entries()].filter(([k]) => !k.startsWith('sot-open:'))), before);
assert.equal(G.ev('SLOT.no.has(UI.slot)'), false, 'and the game was not told it lost it');
assert.deepEqual(W.errors, []); assert.deepEqual(G.errors, []);
});
test('a malformed ?noc= is just the game', (t) => {
const b = browser();
const G = load({ browser: b, url: 'https://tests.invalid/?noc=../evil' });
closeAll(t, G);
assert.equal(G.ev('NOC.win'), false);
});
test('every dashboard tab draws the same from the copy as in the game, also during a flood', async (t) => {
const { G, W } = await pair(t);
const html = (h) => h.ev("(()=>{const o={};for(const k of DTABS){UI.dtab=k;UI._dh=null;renderDash();o[k]=document.getElementById('dashCard').innerHTML;}return JSON.stringify(o)})()");
G.ev("$('dash').hidden=false");
G.ev('NOC.dirty=true'); pump(G); await wait();
// uid-free views: the same state must render the same.
assert.deepEqual(JSON.parse(html(W)), JSON.parse(html(G)));
G.ev("S.day=60;S.ev.ddos={id:'a',city:'fra',tgt:'bb:fra',vec:'http',gbps:20,start:S.day,until:S.day+3};compute();NOC.dirty=true"); pump(G); await wait();
assert.equal(W.ev('S.day'), 60);
assert.equal(W.ev("R.ddos.length&&R.ddos[0].attack&&R.ddos[0].attack.id"), 'a', 'the attack points at its copy again');
assert.deepEqual(JSON.parse(html(W)), JSON.parse(html(G)));
assert.deepEqual(W.errors, []); assert.deepEqual(G.errors, []);
});
test('every button the dashboard draws is in exactly one list', async (t) => {
const { G, W } = await pair(t);
const local = JSON.parse(G.ev('JSON.stringify(NOC_LOCAL)')), go = JSON.parse(G.ev('JSON.stringify(NOC_GO)'));
assert.deepEqual(local.filter((x) => go.includes(x)), []);
for (const k of [...local, ...go]) assert.equal(G.ev(`typeof ACT[${JSON.stringify(k)}]`), 'function', k);
const seen = JSON.parse(G.ev("(()=>{$('dash').hidden=false;S.biz.push({id:'b1',type:Object.keys(BIZ_T)[0],city:'fra',reqs:[],mood:50,name:'x',g:1,mo:1,day:0});const o=new Set();for(const k of DTABS){UI.dtab=k;UI._dh=null;renderDash();for(const e of document.querySelectorAll('#dashCard [data-act],#dashCard [data-chg]'))o.add(e.dataset.act||e.dataset.chg);}S.biz.pop();return JSON.stringify([...o])})()"));
assert.ok(seen.includes('lagP') && seen.includes('buyIx'), 'the upgrade buttons are there');
assert.deepEqual(seen.filter((x) => !local.includes(x) && !go.includes(x)), [], 'a new dashboard button must be sorted into a list');
assert.deepEqual(W.errors, []);
});
test('an upgrade clicked in the window costs what the click costs and lands in the game', async (t) => {
const twin = load(); closeAll(t, twin); twin.ev(START);
const { G, W } = await pair(t);
const c0 = G.ev('S.cash'), t0 = twin.ev('S.cash');
W.ev("UI.dtab='conn';UI._dh=null;renderDash()");
click(W, '#dashCard [data-act="buyIx"]');
await settle(W.ev, 'S.ixp.fra===1', 'the copy shows the bigger port');
assert.equal(G.ev('S.ixp.fra'), 1);
twin.ev("ACT.buyIx({city:'fra',tier:1})");
assert.equal(c0 - G.ev('S.cash'), t0 - twin.ev('S.cash'));
assert.equal(W.ev('S.cash'), G.ev('S.cash'), 'the window was told at once');
assert.deepEqual(W.errors, []); assert.deepEqual(G.errors, []);
});
test('view clicks stay in the window; the game ignores anything off its list', async (t) => {
const { G, W, id } = await pair(t);
const c0 = G.ev('S.cash');
W.ev("nocView('details')");
click(W, '#dashCard [data-act="dashTab"][data-args*="infra"]');
assert.equal(W.ev('UI.dtab'), 'infra'); assert.notEqual(G.ev('UI.dtab'), 'infra');
W.ev(`NOC.ctl.postMessage({t:'act',id:${JSON.stringify(id)},act:'newgame',args:{}});NOC.ctl.postMessage({t:'act',id:${JSON.stringify(id)},act:'takeLoan',args:{id:'x'}});ACT.newgame({});ACT.buildPop({city:'ams'})`);
await wait();
assert.equal(G.ev('S.cash'), c0);
assert.equal(G.ev('!!S.pops.ams'), false, 'buildPop is not on the list');
W.ev(`NOC.ctl.postMessage({t:'act',id:'someoneelse',act:'lagIx',args:{city:'fra',d:1}})`);
await wait();
assert.equal(G.ev('(S.ixn||{}).fra||1'), 1, "another network's click");
assert.deepEqual(G.errors, []);
});
test('remove keeps its Really? step in the window, and a dialog in the game blocks clicks with a note', async (t) => {
const { G, W } = await pair(t);
W.ev("UI.dtab='conn';UI._dh=null;renderDash()");
W.ev("ACT.connCancel({k:'p',id:'p1'})");
await wait();
assert.equal(G.ev("S.pni.some(p=>p.id==='p1')"), true, 'one click only asks');
assert.equal(W.ev('UI.confirm'), 'cc:p:p1');
W.ev("ACT.connCancel({k:'p',id:'p1'})");
await settle(G.ev, "!S.pni.some(p=>p.id==='p1')", 'the second click removes it');
G.ev("openModal('<p>hi</p>')");
W.ev("ACT.lagIx({city:'fra',d:1})");
await settle(W.ev, "document.getElementById('toasts').textContent.includes('dialog open')", 'told why');
assert.equal(G.ev('(S.ixn||{}).fra||1'), 1);
assert.deepEqual(W.errors, []); assert.deepEqual(G.errors, []);
});
test('copies go out at most once a second, only when something changed, never mid-day, and stop with the window', async (t) => {
const { G, W } = await pair(t);
G.ev("window.__n=0;{const f=nocSend;nocSend=function(n){__n++;return f(n);};}window.__tx=0;{const P=NOC.st.postMessage;NOC.st.postMessage=function(m){__tx++;return P.call(this,m);};}");
G.ev('NOC.dirty=false;NOC.sent=1000;NOC.until=1e12;nocPump(5000)');
assert.equal(G.ev('__tx'), 0, 'nothing changed');
G.ev('NOC.sent=1000;NOC.dirty=true;nocPump(1500)');
assert.equal(G.ev('__tx'), 0, 'too soon');
G.ev('nocPump(2000)');
assert.equal(G.ev('__tx'), 1);
assert.equal(G.ev('NOC.dirty'), false);
assert.deepEqual(JSON.parse(G.ev(`JSON.stringify(Object.keys(nocR()).filter(k=>['ef','fl','efp','flc'].includes(k)))`)), [], 'the routing tables stay home');
assert.ok(G.ev("Object.keys(nocR()).includes('usePni')"));
G.ev('after();RW.job={seq:0};nocPump(9000)');
assert.equal(G.ev('__tx'), 1, 'half a day is not sent');
assert.equal(G.ev('NOC.dirty'), true, 'and stays due');
G.ev('RW.job=null;nocPump(9000)');
assert.equal(G.ev('__tx'), 2);
G.ev('NOC.until=10000;NOC.dirty=true;nocPump(20000)');
assert.equal(G.ev('NOC.peer'), false, 'no sign of the window for a while');
assert.equal(G.ev('__tx'), 2);
W.ev('nocBeat()');
await settle(G.ev, 'NOC.peer===true', 'its next heartbeat reconnects it');
W.ev("dispatchEvent(new Event('pagehide'))");
await settle(G.ev, 'NOC.peer===false', 'closing says bye');
assert.deepEqual(G.errors, []);
});
test('the bar says when the game is paused, hidden or gone, and clears when the game answers', async (t) => {
const { G, W } = await pair(t);
const bar = () => W.ev("document.getElementById('nocBar').textContent");
assert.match(bar(), /paused/);
assert.match(bar(), /Y1/);
G.ev('UI.speed=1;NOC.dirty=true'); pump(G); await wait();
assert.doesNotMatch(bar(), /paused/);
W.ev('NOC.hid=true;nocBar()'); assert.match(bar(), /hidden/); W.ev('NOC.hid=false');
W.ev('nocBeat(performance.now()+1e6)');
assert.match(bar(), /closed or not answering/);
G.ev("dispatchEvent(new Event('pagehide'))");
await wait();
W.ev('nocBeat()'); await wait();
assert.doesNotMatch(bar(), /closed or not answering/, 'the game answered again');
assert.deepEqual(W.errors, []);
});
test('the button is in the speed group, asks for a noopener pop-up with the network, and a second click only focuses', async (t) => {
const { G } = await pair(t);
assert.equal(G.ev(`!!document.querySelector('.speed [data-act="nocWindow"]')`), true);
// Only phones lose it: fitHud() hides .hide-md and .hide-md2 when the HUD is crowded, which a big network always is.
assert.equal(G.ev(`document.querySelector('[data-act="nocWindow"]').className`), 'hide-sm');
G.ev("window.__open=[];window.open=(...a)=>{__open.push(a);return null;};NOC.peer=false;ACT.nocWindow()");
const a = JSON.parse(G.ev('JSON.stringify(__open[0])'));
assert.equal(a[0], '/?noc=' + G.ev('UI.slot'));
assert.match(a[2], /noopener/); assert.match(a[2], /popup/);
G.ev('__open.length=0;NOC.peer=true;ACT.nocWindow()');
assert.equal(G.ev('__open.length'), 0);
G.ev('__open.length=0;NOC.peer=false;UI.pz=0;S=null;ACT.nocWindow()');
assert.equal(G.ev('__open.length'), 0, 'no network, no window');
});
test('the window speaks the game\'s language and fits a 360 px screen without the map', async (t) => {
const b = browser();
const G = load({ browser: b, lang: 'it' });
G.ev(START);
const W = load({ browser: b, lang: 'it', url: 'https://tests.invalid/?noc=' + G.ev('UI.slot') });
closeAll(t, G, W);
await settle(W.ev, 'UI.started===true');
assert.equal(W.ev("document.body.classList.contains('noc-window')"), true);
assert.equal(W.ev("$('dash').hidden"), true, 'the wallboard comes first');
assert.equal(W.ev("$('nocWall').hidden"), false);
assert.match(W.ev("document.getElementById('nocBar').textContent"), /pausa/);
assert.doesNotMatch(W.ev("$('nocBoard').innerHTML"), /\b(common|noc|dashboard|connections|hud_and_panels)\.[a-z_]+\b/, 'no raw labels');
W.ev("nocView('details')");
assert.doesNotMatch(W.ev("$('dashCard').innerHTML"), /\b(common|noc|connections)\.[a-z_]+\b/, 'no raw labels');
assert.deepEqual(W.errors, []);
});
test('the wallboard opens first, with graphs, the world map, alarms and the hottest ports', async (t) => {
const { G, W } = await pair(t);
G.ev("S.pops.fra.bb.d=1;S.caches.push({id:'c1',city:'fra',net:NETS.find(n=>n.cache).id,site:'a'});compute();NOC.dirty=true"); pump(G); await wait();
assert.ok(W.ev("document.querySelector('.nw-land path').getAttribute('d').length") > 5000, 'land');
assert.equal(W.ev("document.querySelectorAll('.nw-pop').length"), G.ev('Object.keys(S.pops).length'), 'a dot per POP');
assert.equal(W.ev("document.querySelectorAll('.nw-tile').length"), 6);
assert.match(W.ev("$('nwAlarms').textContent"), /Nothing on fire/);
assert.match(W.ev("$('nocBar').textContent"), /All quiet/);
assert.equal(W.ev("document.querySelectorAll('.nw-port').length"), 3, 'transit, PNI and IX, no more');
// Not enough history: the charts say so instead of drawing nothing.
assert.match(W.ev("$('nwTraffic').textContent"), /ollecting/);
G.ev('for(let i=0;i<5;i++)dayTick();NOC.dirty=true'); pump(G); await wait();
assert.ok(W.ev("document.querySelectorAll('#nwTraffic svg path').length") > 0, 'a traffic graph');
assert.ok(W.ev("document.querySelectorAll('#nwMoney svg path').length") > 0, 'a money graph');
assert.deepEqual(W.errors, []); assert.deepEqual(G.errors, []);
});
test('links are coloured by how full they are, an antimeridian link wraps, a dead one is dashed', async (t) => {
const { G, W } = await pair(t);
G.ev("for(const c of ['ams','tok','sjc'])ACT.buildPop({city:c});for(const [id,a,b] of [['L1','fra','ams'],['L2','tok','sjc']])S.links.push({id,a,b,kind:'wave',tier:1,km:500,sub:false,cable:null,mo:1,mult:1,trench:id,cut:0,day:0});compute();R.load.L1=capOf(S.links[0])*0.95;R.load.L2=0.01;NOC.dirty=true"); pump(G); await wait();
const links = () => JSON.parse(W.ev("JSON.stringify([...document.querySelectorAll('.nw-link')].map(e=>[e.getAttribute('stroke'),e.getAttribute('d').split('M').length-1,e.classList.contains('down')]))"));
let L = links();
assert.equal(L[0][0], W.ev('NW_COL.bad'), '95% is red');
assert.equal(L[1][0], W.ev('NW_COL.ok'), 'an idle link is green');
assert.equal(L[1][1], 2, 'Tokyo to San Jose is drawn on both edges of the map');
assert.equal(L[0][1], 1);
G.ev('S.links[0].cut=S.day+5;compute();NOC.dirty=true'); pump(G); await wait();
L = links();
assert.equal(L[0][2], true, 'a cut link is dashed');
assert.equal(L[0][0], W.ev('NW_COL.bad'));
assert.deepEqual(W.errors, []); assert.deepEqual(G.errors, []);
});
test('an incident and a flood raise the alarm, and hot ports only warn', async (t) => {
const { G, W } = await pair(t);
G.ev("S.pops.fra.bb.d=1;compute();R.useIx.fra=9.8;NOC.dirty=true"); pump(G); await wait();
assert.match(W.ev("$('nwAlarms').textContent"), /1 port over 90%/);
assert.equal(W.ev("document.querySelector('.nb-pill').className.includes('warn')"), true);
G.ev("S.ev.ddos={id:'a',city:'fra',tgt:'bb:fra',vec:'http',gbps:20,start:S.day,until:S.day+3};compute();S.inc.push({id:'i1',type:'power',ref:'fra',until:S.day+3,msg:'<img src=x onerror=alert(1)>',cost:0});NOC.dirty=true"); pump(G); await wait();
const A = W.ev("$('nwAlarms').textContent");
assert.match(A, /under attack/);
assert.match(A, /<img src=x/, 'the message is shown as text');
assert.equal(W.ev("document.querySelector('#nwAlarms img')"), null);
assert.equal(W.ev("document.querySelector('.nb-pill').className.includes('bad')"), true);
assert.match(W.ev("$('nocBar').textContent"), /2 alarms/);
assert.ok(W.ev("document.querySelector('.nw-pop.alarm .nw-ring')"), 'the POP rings on the map');
assert.deepEqual(W.errors, []);
});
test('an upgrade from the wallboard runs in the game; a POP filters the list; the map keeps its elements between updates', async (t) => {
const { G, W } = await pair(t);
const c0 = G.ev('S.cash');
click(W, '#nwPorts [data-act="buyIx"]');
await settle(W.ev, 'S.ixp.fra===1');
assert.equal(G.ev('S.ixp.fra'), 1);
assert.equal(c0 - G.ev('S.cash'), G.ev('ixPortMo("fra",1)'));
G.ev("ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams',tier:0});compute();NOC.dirty=true"); pump(G); await wait();
assert.equal(W.ev("[...document.querySelectorAll('.nw-port b')].some(e=>e.textContent==='Amsterdam')"), true);
W.ev(`document.querySelector('[data-nc="pop:ams"]').dispatchEvent(new MouseEvent('click',{bubbles:true}))`);
assert.equal(W.ev('NOCW.city'), 'ams');
assert.equal(W.ev("[...document.querySelectorAll('.nw-port b')].some(e=>e.textContent==='Frankfurt')"), false);
assert.equal(W.ev("document.querySelector('[data-nc-city]').value"), 'ams');
assert.notEqual(G.ev('UI.sel&&UI.sel.id'), 'ams', 'that click stays in the window');
W.ev("window.__dot=document.querySelector('.nw-pop .nw-dot')");
G.ev('NOC.dirty=true;S.cash+=1'); pump(G); await wait();
assert.equal(W.ev("__dot===document.querySelector('.nw-pop .nw-dot')"), true, 'patched, not rebuilt: animations keep running');
W.ev(`document.querySelector('[data-nc="details"]').click()`);
assert.equal(W.ev("$('dash').hidden"), false);
assert.equal(W.ev("$('nocWall').hidden"), true);
assert.ok(W.ev("$('dashCard').textContent.length") > 100, 'Details is the dashboard');
assert.deepEqual(W.errors, []); assert.deepEqual(G.errors, []);
});
test('every button the wallboard draws is on a list, and its motion stops when the game does', async (t) => {
const { G, W } = await pair(t);
const seen = JSON.parse(W.ev("JSON.stringify([...new Set([...document.querySelectorAll('#nocBoard [data-act]')].map(e=>e.dataset.act))])"));
const lists = JSON.parse(G.ev('JSON.stringify([...NOC_LOCAL,...NOC_GO])'));
assert.ok(seen.length >= 3);
assert.deepEqual(seen.filter((x) => !lists.includes(x)), []);
assert.equal(W.ev("document.body.classList.contains('noc-still')"), true, 'paused');
G.ev('UI.speed=1;NOC.dirty=true'); pump(G); await wait();
assert.equal(W.ev("document.body.classList.contains('noc-still')"), false);
W.ev("UI.anim='off';nocRender()");
assert.equal(W.ev("document.body.classList.contains('noc-still')"), true, 'the Animations setting is respected');
assert.deepEqual(W.errors, []);
});
test('a dead POP is an alarm, not a list full of Down: the hot ports stay, and picking that POP shows its own', async (t) => {
const { G, W } = await pair(t);
G.ev("ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams',tier:0});S.pops.ams.down=S.day+5;compute();NOC.dirty=true"); pump(G); await wait();
const rows = () => JSON.parse(W.ev("JSON.stringify([...document.querySelectorAll('.nw-port .nw-pt b')].map(e=>e.textContent))"));
assert.equal(rows().includes('Amsterdam'), false);
assert.equal(rows().includes('Frankfurt'), true);
W.ev("NOCW.city='ams';nocRender()");
assert.deepEqual(rows(), ['Amsterdam']);
assert.match(W.ev("$('nwPorts').textContent"), /Down/);
// A remote port at an exchange with no POP of ours is not down just because there is no POP.
W.ev("NOCW.city=''");
assert.equal(W.ev("nwDown({city:'syd',down:false})"), false);
assert.deepEqual(W.errors, []);
});
test('the board\'s light text stays on the board: Details is the game\'s own dashboard on its own card', () => {
const css = require('node:fs').readFileSync(require('node:path').join(__dirname, '..', 'src', 'styles', '45-noc-window.css'), 'utf8');
const body = css.match(/body\.noc-window\{([^}]*)\}/)[1];
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:/);
});