From 7756d89d4120043f56a726d51d993881b1bb59d5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 31 Oct 2026 13:57:35 +0100 Subject: [PATCH] Find a city: a search box in the HUD and on / that jumps the map there (closes #218) --- CHANGELOG.md | 1 + site/i18n/de.js | 7 +++ site/i18n/es.js | 7 +++ site/i18n/fr.js | 7 +++ site/i18n/it.js | 7 +++ site/i18n/pt.js | 7 +++ src/game/90-actions/10-interface.js | 2 + src/game/93-ui/80-find-city.js | 30 ++++++++++++ src/i18n/en.js | 7 +++ src/index.html | 1 + src/styles/10-hud.css | 2 + src/styles/40-modal.css | 6 +++ src/styles/50-tablet.css | 5 ++ src/styles/60-phone.css | 2 + tests/find-city.test.js | 71 +++++++++++++++++++++++++++++ 15 files changed, 162 insertions(+) create mode 100644 src/game/93-ui/80-find-city.js create mode 100644 tests/find-city.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bfdebd..148958c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - The intern's PNI order now counts the traffic the PNI list shows at each POP, so it no longer orders a PNI where a network's own cache boxes already serve most of its traffic (#244). +- Find any city with the new 🔍 button in the top bar, or press / on a keyboard (#218). Type a city, a country (in your language or in English) or an exchange, and the map jumps there. - Cities on the map now show how big they are: zoomed out, bigger cities are bigger dots and megacities glow; zoomed in, a city's skyline grows from a hut to a megacity's towers. When cities crowd together, the smaller ones step back to a dot until you zoom in, so the map stays readable, and exchanges you haven't joined are quieter tags. - DDoS attacks are realistic now: most are small, the big ones are rare, and their size no longer grows with your network, so a big network is no longer hit by floods larger than the internet's record. Attacks go after one customer (gamers and hosting attract the most) or one city's subscribers, last one to three days, and On-call sees about one a month (#242). - A flood now arrives on every port the internet reaches you on, so more POPs and more exits spread it thinner, and a port it fills slows every customer on it. Flowspec and scrubbing behind a full port can no longer empty it (#242). diff --git a/site/i18n/de.js b/site/i18n/de.js index 43c548b..259c2d3 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2030,6 +2030,13 @@ "fiber_modals.you_need_a_fabric_port_at":"Du brauchst zuerst einen Fabric-Port an einem deiner POPs. Öffne den Tab Infra eines POPs und kauf einen Port auf {list}.", "fiber_modals.your_own_trench_almost_no_rent":"Dein eigener Graben: fast keine Miete, aber Genehmigungen und Graben dauern ewig, und Verzögerungen kommen vor.", "fiber_modals.your_pop_needs_a_fabric_port":"Dein POP · braucht dort einen Fabric-Port", +"find.city_country_or_exchange":"Stadt, Land oder Austauschknoten", +"find.find_a_city":"Stadt finden", +"find.find_a_city_slash":"Stadt finden (/)", +"find.no_city_matches_q":"Keine Stadt passt zu „{q}“.", +"find.press_slash_to_search_from":"Tipp: Drück irgendwo auf der Karte /, um zu suchen.", +"find.type_a_city_a_country":"Gib eine Stadt, ein Land oder einen Austauschknoten ein.", +"find.your_pop":"dein POP", "game_and_settings.delete_and_start_over":"Löschen und neu anfangen", "game_and_settings.export_save_download_a_file":"Spielstand exportieren Datei herunterladen", "game_and_settings.import_failed_that_save_is_damaged":"Import fehlgeschlagen.
Dieser Spielstand ist beschädigt und konnte nicht geladen werden. Dein aktuelles Spiel ist unberührt.", diff --git a/site/i18n/es.js b/site/i18n/es.js index cc07e43..a93046b 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2028,6 +2028,13 @@ "fiber_modals.you_need_a_fabric_port_at":"Primero necesitas un puerto de fabric en uno de tus POPs. Abre la pestaña Infra de un POP y compra un puerto en {list}.", "fiber_modals.your_own_trench_almost_no_rent":"Tu propia zanja: casi sin alquiler, pero los permisos y la excavación tardan una eternidad, y hay retrasos.", "fiber_modals.your_pop_needs_a_fabric_port":"Tu POP · necesita un puerto de fabric allí", +"find.city_country_or_exchange":"Ciudad, país o punto de intercambio", +"find.find_a_city":"Buscar una ciudad", +"find.find_a_city_slash":"Buscar una ciudad (/)", +"find.no_city_matches_q":"Ninguna ciudad coincide con «{q}».", +"find.press_slash_to_search_from":"Consejo: pulsa / en cualquier parte del mapa para buscar.", +"find.type_a_city_a_country":"Escribe una ciudad, un país o un punto de intercambio.", +"find.your_pop":"tu POP", "game_and_settings.delete_and_start_over":"Borrar y empezar de nuevo", "game_and_settings.export_save_download_a_file":"Exportar partida descargar un archivo", "game_and_settings.import_failed_that_save_is_damaged":"Falló la importación.
Esa partida está dañada y no se pudo cargar. Tu partida actual sigue intacta.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 6f4acc0..714e6c6 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2028,6 +2028,13 @@ "fiber_modals.you_need_a_fabric_port_at":"Il te faut d’abord un port fabric dans un de tes POP. Ouvre l’onglet Infra d’un POP et achète un port sur {list}.", "fiber_modals.your_own_trench_almost_no_rent":"Ta propre tranchée : presque pas de loyer, mais les permis et les travaux prennent une éternité, et les retards arrivent.", "fiber_modals.your_pop_needs_a_fabric_port":"Ton POP · il y faut un port fabric", +"find.city_country_or_exchange":"Ville, pays ou point d'échange", +"find.find_a_city":"Trouver une ville", +"find.find_a_city_slash":"Trouver une ville (/)", +"find.no_city_matches_q":"Aucune ville ne correspond à « {q} ».", +"find.press_slash_to_search_from":"Astuce : appuyez sur / n'importe où sur la carte pour chercher.", +"find.type_a_city_a_country":"Tapez une ville, un pays ou un point d'échange.", +"find.your_pop":"votre POP", "game_and_settings.delete_and_start_over":"Supprimer et recommencer", "game_and_settings.export_save_download_a_file":"Exporter la sauvegarde télécharger un fichier", "game_and_settings.import_failed_that_save_is_damaged":"Échec de l’import.
Cette sauvegarde est endommagée et n’a pas pu être chargée. Ta partie en cours est intacte.", diff --git a/site/i18n/it.js b/site/i18n/it.js index a1e613f..43ec801 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2028,6 +2028,13 @@ "fiber_modals.you_need_a_fabric_port_at":"Prima ti serve una porta fabric in uno dei tuoi POP. Apri la scheda Infra di un POP e compra una porta su {list}.", "fiber_modals.your_own_trench_almost_no_rent":"Uno scavo tutto tuo: quasi nessun affitto, ma permessi e scavi durano un’eternità, e i ritardi capitano.", "fiber_modals.your_pop_needs_a_fabric_port":"Il tuo POP · serve una porta fabric lì", +"find.city_country_or_exchange":"Città, paese o exchange", +"find.find_a_city":"Trova una città", +"find.find_a_city_slash":"Trova una città (/)", +"find.no_city_matches_q":"Nessuna città corrisponde a “{q}”.", +"find.press_slash_to_search_from":"Suggerimento: premi / ovunque sulla mappa per cercare.", +"find.type_a_city_a_country":"Scrivi una città, un paese o un exchange.", +"find.your_pop":"il tuo POP", "game_and_settings.delete_and_start_over":"Cancella e ricomincia", "game_and_settings.export_save_download_a_file":"Esporta salvataggio scarica un file", "game_and_settings.import_failed_that_save_is_damaged":"Importazione fallita.
Quel salvataggio è danneggiato e non si può caricare. La partita in corso non è stata toccata.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 6b7099f..05e0c28 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2028,6 +2028,13 @@ "fiber_modals.you_need_a_fabric_port_at":"Primeiro você precisa de uma porta de fabric em um dos seus POPs. Abra a aba Infra de um POP e compre uma porta em {list}.", "fiber_modals.your_own_trench_almost_no_rent":"Sua própria vala: quase nenhum aluguel, mas licenças e escavação levam uma eternidade, e atrasos acontecem.", "fiber_modals.your_pop_needs_a_fabric_port":"Seu POP · precisa de uma porta de fabric lá", +"find.city_country_or_exchange":"Cidade, país ou exchange", +"find.find_a_city":"Encontrar uma cidade", +"find.find_a_city_slash":"Encontrar uma cidade (/)", +"find.no_city_matches_q":"Nenhuma cidade corresponde a “{q}”.", +"find.press_slash_to_search_from":"Dica: pressione / em qualquer lugar do mapa para pesquisar.", +"find.type_a_city_a_country":"Digite uma cidade, um país ou um exchange.", +"find.your_pop":"seu POP", "game_and_settings.delete_and_start_over":"Apagar e recomeçar", "game_and_settings.export_save_download_a_file":"Exportar save baixar um arquivo", "game_and_settings.import_failed_that_save_is_damaged":"Falha na importação.
Esse save está corrompido e não pôde ser carregado. Seu jogo atual não foi mexido.", diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 3f6dc89..696ad90 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -45,6 +45,8 @@ const ACT={ if(o.a==='cust'){if(S.biz.some(b=>b.id===o.v)){ACT.custGo({id:o.v});return;}toast(tr('interface.that_customer_is_gone_the_contract'),'');return;} if(o.a==='bank'){ACT.bank({});return;}if(o.a==='ops'){ACT.opsOpen();return;}if(o.a==='tab'&&LOG_TABS.includes(o.v))ACT.leftTab({t:o.v});}, logAll:()=>{UI.logAll=!UI.logAll;renderLeft();}, + findOpen:()=>findOpen(), + findGo:({city})=>{if(!isCity(city))return;closeModal();$('dash').hidden=true;ACT.focusCity({city});}, focusCity:({city})=>{selectCity(city);const C=CITY[city];cam.x=C.x;cam.y=C.y;cam.z=Math.max(cam.z,1.2);if(innerWidth<760)UI.leftOpen=false;renderLeft();}, selLink:({id})=>selectLink(id), }; diff --git a/src/game/93-ui/80-find-city.js b/src/game/93-ui/80-find-city.js new file mode 100644 index 0000000..4f14971 --- /dev/null +++ b/src/game/93-ui/80-find-city.js @@ -0,0 +1,30 @@ +/* ---------- Find a city (#218): a search box that jumps the map there ---------- + Matches the city's name, its country (in the player's language and in English) and its exchange and data center + names, so "Deutschland", "Germany" or "DE-CIX" all find Frankfurt. Press / anywhere, or the 🔍 chip in the HUD. */ +const FIND_N=8; +const fold=s=>String(s||'').normalize('NFD').replace(/[̀-ͯ]/g,'').toLowerCase().trim(); +// Country names, built once per page: they never change while playing. +let FIND_IX=null; +function findIndex(){if(FIND_IX)return FIND_IX;let dn=null,en=null;try{dn=new Intl.DisplayNames([LANG],{type:'region'});en=new Intl.DisplayNames(['en'],{type:'region'});}catch(e){} + const cn=(d,cc)=>{try{return d?d.of(cc)||'':'';}catch(e){return '';}}; + FIND_IX=Object.values(CITY).map(C=>{const land=cn(dn,C.cc)||C.cc||'';return {id:C.id,name:fold(C.name),land,ctry:fold(land+' '+cn(en,C.cc)+' '+(C.cc||'')),xtra:fold((C.ix||'')+' '+(C.dc||''))};});return FIND_IX;} +// Best matches first: the name starts with it, a word of the name does, the name has it, then country, then exchange or DC. +function findCities(q){q=fold(q);const mine=c=>S&&S.pops&&S.pops[c]?0:1; + if(!q)return S&&S.pops?Object.keys(S.pops).filter(isCity).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)).slice(0,FIND_N):[]; + const out=[];for(const e of findIndex()){const n=e.name; + const s=n.startsWith(q)?0:n.split(/[\s\-.'()]+/).some(w=>w.startsWith(q))?1:n.includes(q)?2:e.ctry.includes(q)?3:e.xtra.includes(q)?4:-1; + if(s>=0)out.push([s,mine(e.id),-(CITY[e.id].P||0),e.id]);} + return out.sort((a,b)=>a[0]-b[0]||a[1]-b[1]||a[2]-b[2]).slice(0,FIND_N).map(r=>r[3]);} +function findRows(q){const ids=findCities(q),land=c=>(findIndex().find(e=>e.id===c)||{}).land||''; + if(!ids.length)return `

${q.trim()?tr('find.no_city_matches_q',{q:esc(q.trim())}):tr('find.type_a_city_a_country')}

`; + return ids.map((c,i)=>{const C=CITY[c],p=S&&S.pops&&S.pops[c]; + return ``;}).join('');} +function findOpen(){if(!S||!UI.started)return; + openModal(`

🔍 ${tr('find.find_a_city')}

+
${findRows('')}
${isPhone()?'':`

${tr('find.press_slash_to_search_from')}

`}`,'find'); + const el=$('findIn');if(el)el.focus();} +document.addEventListener('input',e=>{if(e.target.id!=='findIn')return;const L=$('findList');if(L)L.innerHTML=findRows(e.target.value);}); +document.addEventListener('keydown',e=>{ + if(e.target.id==='findIn'){if(e.key==='Escape'){closeModal();return;}if(e.key==='Enter'){e.preventDefault();const c=findCities(e.target.value)[0];if(c)ACT.findGo({city:c});}return;} + if(e.key!=='/'||e.ctrlKey||e.metaKey||e.altKey||(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]')))return; + if(!S||!UI.started||!$('modal').hidden)return;e.preventDefault();findOpen();}); diff --git a/src/i18n/en.js b/src/i18n/en.js index ec53666..abec28b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2029,6 +2029,13 @@ "fiber_modals.you_need_a_fabric_port_at":"You need a fabric port at one of your POPs first. Open a POP's Infra tab and buy a port on {list}.", "fiber_modals.your_own_trench_almost_no_rent":"Your own trench: almost no rent, but permits and digging take forever, and delays happen.", "fiber_modals.your_pop_needs_a_fabric_port":"Your POP · needs a fabric port there", +"find.city_country_or_exchange":"City, country or exchange", +"find.find_a_city":"Find a city", +"find.find_a_city_slash":"Find a city (/)", +"find.no_city_matches_q":"No city matches “{q}”.", +"find.press_slash_to_search_from":"Tip: press / anywhere on the map to search.", +"find.type_a_city_a_country":"Type a city, a country or an exchange.", +"find.your_pop":"your POP", "game_and_settings.delete_and_start_over":"Delete and start over", "game_and_settings.export_save_download_a_file":"Export save download a file", "game_and_settings.import_failed_that_save_is_damaged":"Import failed.
That save is damaged and could not be loaded. Your current game is untouched.", diff --git a/src/index.html b/src/index.html index 4b97816..490d3db 100644 --- a/src/index.html +++ b/src/index.html @@ -117,6 +117,7 @@
Date
Y1 · Jan 1
+
diff --git a/src/styles/10-hud.css b/src/styles/10-hud.css index ffb4977..e00a535 100644 --- a/src/styles/10-hud.css +++ b/src/styles/10-hud.css @@ -29,3 +29,5 @@ .minibar{height:6px;border-radius:4px;background:var(--line);overflow:hidden;margin-top:2px;width:100%} .minibar i{display:block;height:100%;background:var(--ok)} +/* Find a city: a square chip with just the magnifier. */ +#hud .chip.find{justify-content:center;align-items:center;padding:0;width:44px;min-width:44px;font-size:19px;cursor:pointer} diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index c22be16..75cfd1b 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -196,3 +196,9 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .menu-links .lnk{background:none;border:0;padding:4px 2px;font-weight:700;font-size:14px;font-family:inherit;color:var(--ink2);text-decoration:underline;text-underline-offset:3px;cursor:pointer} .menu-plugs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:12px} .mplug{border:2px solid var(--line);border-radius:12px;padding:8px 10px;font-weight:700;font-size:13px;line-height:1.25;color:var(--ink);text-decoration:none;background:var(--soft);display:flex;align-items:center} +/* Find a city: big tap targets, the first result (what Enter picks) highlighted. */ +.findlist{margin-top:8px} +.findrow{width:100%;text-align:left;background:none;border:0;border-top:1px solid var(--line);font:inherit;color:var(--ink);min-height:48px;padding:6px 8px;cursor:pointer;border-radius:0} +.findrow .nm,.findrow .meta{display:block} +.findrow.on{background:var(--soft);border-radius:10px} +.findrow:hover{background:var(--soft)} diff --git a/src/styles/50-tablet.css b/src/styles/50-tablet.css index 3d86fd1..80a7ac2 100644 --- a/src/styles/50-tablet.css +++ b/src/styles/50-tablet.css @@ -36,3 +36,8 @@ .chip{padding:2px 7px} } +/* Narrow tablets: a slim find chip and slimmer speed buttons keep the HUD on one row. */ +@media (min-width:761px) and (max-width:860px){ + #hud .chip.find{width:32px;min-width:32px;font-size:15px} + .speed button{min-width:23px;padding-left:2px;padding-right:2px} +} diff --git a/src/styles/60-phone.css b/src/styles/60-phone.css index 39cbe7f..b8d02e6 100644 --- a/src/styles/60-phone.css +++ b/src/styles/60-phone.css @@ -119,3 +119,5 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar } @media (prefers-reduced-motion:reduce){:root:not(.anim-force) *{animation:none !important;transition:none !important}} :root.no-anim *{animation:none !important;transition:none !important} +/* The narrowest phones: a slimmer find chip so the date still fits. */ +@media (max-width:340px){#hud .chip.find{width:34px;min-width:34px;font-size:15px}#hud .menubtn .caret{display:none}} diff --git a/tests/find-city.test.js b/tests/find-city.test.js new file mode 100644 index 0000000..4c59753 --- /dev/null +++ b/tests/find-city.test.js @@ -0,0 +1,71 @@ +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"; + +test('find a city by its name, without accents, by country or by its exchange (#218)', () => { + const { ev, errors } = load(); + ev(start); + const find = q => ev(`findCities(${JSON.stringify(q)}).join()`).split(','); + assert.equal(find('amster')[0], 'ams', 'the start of a name'); + assert.equal(find('AMSTERDAM')[0], 'ams', 'any case'); + assert.equal(find('sao paulo')[0], 'sao', 'accents are optional'); + assert.equal(find('paulo')[0], 'sao', 'a word inside the name'); + assert.ok(find('germany').includes('fra'), 'the country in English'); + assert.ok(find('germany').includes('muc')); + assert.ok(find('Brezn')[0] === 'muc', 'the exchange'); + assert.ok(find('germany').length <= ev('FIND_N'), 'a short list'); + assert.equal(ev("findCities('zzqqxx').length"), 0); + // Names first, then countries: "san" finds San José before cities in some country with "san" in it. + assert.equal(ev("findCities('san').every((c,i,a)=>i===0||fold(CITY[a[i-1]].name).includes('san')||!fold(CITY[c].name).includes('san'))"), true); + // An empty box lists your own POPs. + assert.equal(ev("findCities('').join()"), ev("Object.keys(S.pops).join()")); + assert.deepEqual(errors, []); +}); + +test('the search box opens with / or the HUD button, Enter jumps to the first city, Escape closes', () => { + const { ev, dom, errors } = load(); + const doc = dom.window.document; + ev(start); + const key = (k, t) => (t || doc.body).dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: k, bubbles: true })); + key('/'); + assert.equal(ev("$('modal').hidden"), false, '/ opens it'); + assert.ok(doc.getElementById('findIn'), 'with a search field'); + const inp = doc.getElementById('findIn'); + inp.value = 'tokyo'; + inp.dispatchEvent(new dom.window.Event('input', { bubbles: true })); + assert.match(doc.getElementById('findList').textContent, /Tokyo/); + key('Enter', inp); + assert.equal(ev("$('modal').hidden"), true, 'Enter jumps'); + assert.equal(ev('UI.sel&&UI.sel.id||UI.sel'), 'tok', 'and selects Tokyo'); + assert.equal(ev('cam.x'), ev('CITY.tok.x'), 'with the map on it'); + // The HUD button, then a tap on a result. + doc.querySelector('#hud .chip.find').click(); + assert.equal(ev("$('modal').hidden"), false); + const i2 = doc.getElementById('findIn'); + i2.value = 'nowhere at all'; + i2.dispatchEvent(new dom.window.Event('input', { bubbles: true })); + assert.match(doc.getElementById('findList').textContent, /No city matches/); + key('Escape', i2); + assert.equal(ev("$('modal').hidden"), true, 'Escape closes'); + ev("ACT.findOpen();ACT.findGo({city:'syd'})"); + assert.equal(ev('cam.x'), ev('CITY.syd.x')); + ev("ACT.findGo({city:'atlantis'})"); + assert.equal(ev('cam.x'), ev('CITY.syd.x'), 'unknown ids are ignored'); + // Typing / in another text field types a slash. + ev("ACT.rename()"); + key('/', doc.getElementById('rnIn')); + assert.equal(ev("!!$('findIn')"), false); + assert.deepEqual(errors, []); +}); + +test('in German, a German country name finds the city, and the search works on a phone', () => { + const { ev, dom, errors } = load({ lang: 'de' }); + ev(start + ";if(ACT.pitchSkip)ACT.pitchSkip();window.innerWidth=360;ACT.findOpen()"); + assert.ok(ev("findCities('deutschland').includes('fra')"), 'Deutschland'); + assert.ok(ev("findCities('germany').includes('fra')"), 'and Germany still works'); + assert.match(dom.window.document.getElementById('modalCard').textContent, /Stadt finden/); + assert.doesNotMatch(dom.window.document.getElementById('modalCard').textContent, /\/ /, 'no keyboard tip on a phone'); + assert.deepEqual(errors, []); +});