Move a network to another device with QR codes or a link (#263)

No server and no account: the network travels gzipped in the fragment of a
link, which browsers never send anywhere. One link carries all of it, to copy
or share; QR codes carry it in parts that a phone's own camera app opens one
after another, and the receiving page collects them in any order, then imports
the network like a save file. To keep the codes few they leave out the charts'
history and the news log (a year-old network: 4 codes instead of 10); the link
carries everything. The QR encoder is a small built-in one, checked against the
reference implementation for every mask.
This commit is contained in:
Frederic Jung 2026-11-10 11:50:36 +01:00
parent b892dcd923
commit 79426f7a00
No known key found for this signature in database
21 changed files with 465 additions and 10 deletions

View file

@ -637,8 +637,8 @@ const API_WHY={
const API_DENY={
speed:'time',phonePlay:'time',phoneSpeed:'time',
start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start',
exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',
exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPage:'files',xferPaste:'files',xferRecv:'files',xferReset:'files',
slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots',
animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs',
install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',
install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser',
};

View file

@ -0,0 +1,59 @@
/* ---------- QR codes (#263) ----------
A small QR encoder: byte mode, error correction L or M, versions 1 to 40, the standard mask penalty. The game has no
dependencies and no server, so moving a network to a phone is codes the phone's own camera app can open.
Follows ISO/IEC 18004 (and Project Nayuki's reference implementation, MIT). */
const QR_ECC={L:[1,[7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25]],
M:[0,[10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49]]};
const qrRaw=v=>{let r=(16*v+128)*v+64;if(v>=2){const n=Math.floor(v/7)+2;r-=(25*n-10)*n-55;if(v>=7)r-=36;}return r;};
const qrDataCw=(v,e)=>Math.floor(qrRaw(v)/8)-QR_ECC[e][1][v-1]*QR_ECC[e][2][v-1];
// The most bytes one code of this version holds (byte mode).
const qrCap=(v,e='L')=>qrDataCw(v,e)-(v<10?2:3);
function qrMul(x,y){let z=0;for(let i=7;i>=0;i--){z=(z<<1)^((z>>>7)*0x11D);z^=((y>>>i)&1)*x;}return z;}
function qrRs(data,n){const d=new Array(n).fill(0);d[n-1]=1;let root=1;
for(let i=0;i<n;i++){for(let j=0;j<n;j++){d[j]=qrMul(d[j],root);if(j+1<n)d[j]^=d[j+1];}root=qrMul(root,2);}
const r=new Array(n).fill(0);for(const b of data){const f=b^r.shift();r.push(0);for(let i=0;i<n;i++)r[i]^=qrMul(d[i],f);}return r;}
const qrAlign=v=>{if(v===1)return [];const n=Math.floor(v/7)+2,step=v===32?26:Math.ceil((v*4+4)/(n*2-2))*2,r=[6];
for(let p=v*4+10;r.length<n;p-=step)r.splice(1,0,p);return r;};
const QR_MASK=[(x,y)=>(x+y)%2===0,(x,y)=>y%2===0,(x,y)=>x%3===0,(x,y)=>(x+y)%3===0,(x,y)=>(Math.floor(x/3)+Math.floor(y/2))%2===0,
(x,y)=>x*y%2+x*y%3===0,(x,y)=>(x*y%2+x*y%3)%2===0,(x,y)=>((x+y)%2+x*y%3)%2===0];
/* bytes (Uint8Array or array) → {size, m: rows of booleans (true = dark)}, or null when it does not fit in version 40.
o.ecc 'L' (default) or 'M'; o.mask 0-7 to force one (tests); o.min/o.max bound the version. */
function qrEncode(bytes,o={}){const e=o.ecc||'L',len=bytes.length;let v=o.min||1;
while(v<=(o.max||40)&&len>qrCap(v,e))v++;if(v>(o.max||40))return null;
const cap=qrDataCw(v,e),bits=[],put=(x,n)=>{for(let i=n-1;i>=0;i--)bits.push((x>>>i)&1);};
put(4,4);put(len,v<10?8:16);for(const b of bytes)put(b,8);
put(0,Math.min(4,cap*8-bits.length));put(0,(8-bits.length%8)%8);for(let p=0xEC;bits.length<cap*8;p^=0xEC^0x11)put(p,8);
const data=[];for(let i=0;i<bits.length;i+=8){let b=0;for(let j=0;j<8;j++)b=b<<1|bits[i+j];data.push(b);}
// Split into blocks, add Reed-Solomon to each, interleave.
const nb=QR_ECC[e][2][v-1],ne=QR_ECC[e][1][v-1],raw=Math.floor(qrRaw(v)/8),ns=nb-raw%nb,sl=Math.floor(raw/nb),blocks=[];
for(let i=0,k=0;i<nb;i++){const d=data.slice(k,k+sl-ne+(i<ns?0:1));k+=d.length;const ec=qrRs(d,ne);if(i<ns)d.push(0);blocks.push(d.concat(ec));}
const cw=[];for(let i=0;i<blocks[0].length;i++)for(let j=0;j<nb;j++)if(i!==sl-ne||j>=ns)cw.push(blocks[j][i]);
const n=v*4+17,m=[],fn=[];for(let y=0;y<n;y++){m.push(new Array(n).fill(false));fn.push(new Array(n).fill(false));}
const set=(x,y,d)=>{m[y][x]=d;fn[y][x]=true;};
for(let i=0;i<n;i++){set(6,i,i%2===0);set(i,6,i%2===0);}
for(const [cx,cy] of [[3,3],[n-4,3],[3,n-4]])for(let dy=-4;dy<=4;dy++)for(let dx=-4;dx<=4;dx++){const x=cx+dx,y=cy+dy,d=Math.max(Math.abs(dx),Math.abs(dy));if(x>=0&&x<n&&y>=0&&y<n)set(x,y,d!==2&&d!==4);}
const al=qrAlign(v);for(let i=0;i<al.length;i++)for(let j=0;j<al.length;j++){if(i===0&&j===0||i===0&&j===al.length-1||i===al.length-1&&j===0)continue;
for(let dy=-2;dy<=2;dy++)for(let dx=-2;dx<=2;dx++)set(al[i]+dx,al[j]+dy,Math.max(Math.abs(dx),Math.abs(dy))!==1);}
const fmt=mk=>{const d=QR_ECC[e][0]<<3|mk;let r=d;for(let i=0;i<10;i++)r=(r<<1)^((r>>>9)*0x537);const b=(d<<10|r)^0x5412,bit=i=>((b>>>i)&1)===1;
for(let i=0;i<=5;i++)set(8,i,bit(i));set(8,7,bit(6));set(8,8,bit(7));set(7,8,bit(8));for(let i=9;i<15;i++)set(14-i,8,bit(i));
for(let i=0;i<8;i++)set(n-1-i,8,bit(i));for(let i=8;i<15;i++)set(8,n-15+i,bit(i));set(8,n-8,true);};
fmt(0);
if(v>=7){let r=v;for(let i=0;i<12;i++)r=(r<<1)^((r>>>11)*0x1F25);const b=v<<12|r;for(let i=0;i<18;i++){const d=((b>>>i)&1)===1,a=n-11+i%3,c=Math.floor(i/3);set(a,c,d);set(c,a,d);}}
for(let i=0,r=n-1;r>=1;r-=2){if(r===6)r=5;for(let vt=0;vt<n;vt++)for(let j=0;j<2;j++){const x=r-j,up=((r+1)&2)===0,y=up?n-1-vt:vt;
if(!fn[y][x]&&i<cw.length*8){m[y][x]=((cw[i>>>3]>>>(7-(i&7)))&1)===1;i++;}}}
const flip=mk=>{const f=QR_MASK[mk];for(let y=0;y<n;y++)for(let x=0;x<n;x++)if(!fn[y][x]&&f(x,y))m[y][x]=!m[y][x];};
let mask=o.mask;
if(mask===undefined){let best=Infinity;for(let k=0;k<8;k++){flip(k);fmt(k);const p=qrPenalty(m);if(p<best){best=p;mask=k;}flip(k);}}
flip(mask);fmt(mask);return {size:n,m,v,mask};}
// The standard penalty (N1 runs, N2 blocks, N3 finder-like patterns, N4 balance): the mask with the least scans best.
function qrPenalty(m){const n=m.length;let p=0,dark=0;const at=(a,b,row)=>row?m[a][b]:m[b][a];
for(const row of [true,false])for(let a=0;a<n;a++){let run=1;
for(let b=1;b<=n;b++){if(b<n&&at(a,b,row)===at(a,b-1,row))run++;else{if(run>=5)p+=run-2;run=1;}}
for(let b=0;b+7<=n;b++){let hit=true;for(let k=0;k<7;k++)if(at(a,b+k,row)!==(k!==1&&k!==5)){hit=false;break;}if(!hit)continue;
let l=true,r=true;for(let k=1;k<=4;k++){if(b-k>=0&&at(a,b-k,row))l=false;if(b+6+k<n&&at(a,b+6+k,row))r=false;}if(l||r)p+=40;}}
for(let y=0;y<n;y++)for(let x=0;x<n;x++){const d=m[y][x];if(d)dark++;if(x<n-1&&y<n-1&&d===m[y][x+1]&&d===m[y+1][x]&&d===m[y+1][x+1])p+=3;}
return p+(Math.ceil(Math.abs(dark*20-n*n*10)/(n*n))-1)*10;}
// A code as SVG: one path of dark runs, with the four-module quiet zone scanners need. Always dark on white.
function qrSvg(q,label){const n=q.size,z=4;let d='';
for(let y=0;y<n;y++)for(let x=0;x<n;){if(!q.m[y][x]){x++;continue;}let w=1;while(x+w<n&&q.m[y][x+w])w++;d+=`M${x+z} ${y+z}h${w}v1h-${w}z`;x+=w;}
return `<svg class="qr" viewBox="0 0 ${n+2*z} ${n+2*z}" role="img" aria-label="${label}" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="#fff"/><path d="${d}" fill="#000"/></svg>`;}

View file

@ -0,0 +1,49 @@
/* ---------- moving a network to another device (#263) ----------
No server, no account: the network itself travels, gzipped, in the fragment of a link (#sot1.<id>.<i>.<n>.<data>),
which browsers never send to any server. One link carries all of it, to copy or share; QR codes carry it in parts a
phone's own camera app opens one after another. The receiving page collects the parts in its storage, in any order,
and imports the network like a save file once they are all there. */
const XFER_K='sot-xfer',XFER_RE=/sot1\.([a-z0-9]{3,8})\.(\d{1,3})\.(\d{1,3})\.([A-Za-z0-9_-]+)/,XFER_CHUNK=900,XFER_MAX=200,XFER_DAY=864e5;
// Taken out of the address bar before anything else can read it (the stats counter only loads after this script):
// a network in a link belongs to the player, and a reload must not import it again.
const XFER_HASH=(()=>{try{const h=location.hash||'';if(!h.startsWith('#sot1.'))return '';history.replaceState(null,'',location.pathname+location.search);return h.slice(1);}catch(e){return '';}})();
const b64u=u=>b64(u).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
const unb64u=t=>unb64(t.replace(/-/g,'+').replace(/_/g,'/')+'==='.slice((t.length+3)%4));
const xferBase=()=>/^https?:$/.test(location.protocol)?location.origin+location.pathname:'https://seriesoftub.es/';
// A network's save text: the one playing now (saved first), or any other straight from storage.
function xferText(id){if(id===UI.slot&&S&&!pzOn()){save(true);return Promise.resolve(JSON.stringify(packSave(S)));}
const raw=slotRaw(id);if(raw==null)return Promise.reject(new Error('no save'));return raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw);}
/* The link carries everything. The codes leave out the charts' history and the news log: more than half of a played
network, and only ever shown, never played with (the traffic odometer keeps its own count). A year-old network
takes 3 codes instead of 9; its charts start again on the other device, and the import says so. */
const xferGz=async(t,lean)=>b64u(await gzPipe(new TextEncoder().encode(`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},${lean?'"lean":1,':''}"S":${t}}`),new CompressionStream('gzip')));
async function xferPack(id){const e=slotIdx().find(x=>x.id===id),t=await xferText(id),o=JSON.parse(t);
const d=await xferGz(t),c=await xferGz(JSON.stringify({...o,hist:[],log:[]}),true);
const k=Math.floor(Math.random()*36**5).toString(36).padStart(5,'0'),n=Math.ceil(c.length/XFER_CHUNK),base=xferBase()+'#sot1.';
// Codes and link are two transfers: a code never completes a set with a piece of the link.
const parts=n>XFER_MAX?[]:Array.from({length:n},(_,i)=>`${base}${k}.${i}.${n}.${c.slice(i*XFER_CHUNK,(i+1)*XFER_CHUNK)}`);
return {name:e?e.name:o.name,link:`${base}${k}.0.1.${d}`,parts};}
// Parts that arrived so far (one transfer at a time; a day old, they are forgotten).
function xferStore(){let s=null;try{s=JSON.parse(localStorage.getItem(XFER_K)||'null');}catch(e){}
if(!s||typeof s!=='object'||typeof s.id!=='string'||!(s.n>1&&s.n<=999)||!s.p||typeof s.p!=='object'||!(Date.now()-s.at<XFER_DAY))return null;
for(const k in s.p)if(!(+k>=0&&+k<s.n)||typeof s.p[k]!=='string')return null;return s;}
function xferClear(){try{localStorage.removeItem(XFER_K);}catch(e){}}
// A link (or just its fragment, or text with one in it): one part, or a whole network.
function xferTake(h){const m=XFER_RE.exec(String(h||''));
if(!m){toast(tr('transfer.that_is_not_a_transfer_link'),'bad');sfx('err');return false;}
const id=m[1],i=+m[2],n=+m[3],d=m[4];if(!(n>=1&&i<n)){toast(tr('transfer.that_link_is_incomplete_or_damaged'),'bad');sfx('err');return false;}
if(n===1){xferOpen(d);return true;}
let s=xferStore();if(!s||s.id!==id||s.n!==n)s={id,n,p:{},at:Date.now()};s.p[i]=d;
if(Object.keys(s.p).length===n){xferClear();xferOpen(Array.from({length:n},(_,k)=>s.p[k]).join(''));return true;}
try{localStorage.setItem(XFER_K,JSON.stringify(s));}catch(e){}
openModal(xferWaitHtml(s));sfx('click');return true;}
function xferOpen(d){if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;}
let u=null;try{u=unb64u(d);}catch(e){}
const bad=()=>{toast(tr('transfer.that_link_is_incomplete_or_damaged'),'bad');sfx('err');};if(!u){bad();return;}
gzPipe(u,new DecompressionStream('gzip')).then(b=>{const r=parseSave(new TextDecoder().decode(b));
if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}importAsk(r);track('xfer_in');},bad);}
// Another window got a part (or finished): the one showing the progress follows.
addEventListener('storage',e=>{if(e.key!==XFER_K||!$('xferWait'))return;const s=xferStore();if(s)openModal(xferWaitHtml(s));else ACT.helpClose();});
addEventListener('hashchange',()=>{const h=location.hash||'';if(!h.startsWith('#sot1.'))return;try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}xferTake(h.slice(1));});
// After boot: a page opened from a transfer link takes its part.
function xferBoot(){if(XFER_HASH)xferTake(XFER_HASH);}

View file

@ -30,7 +30,7 @@ Object.assign(ACT,{
${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${saveFailing()?btn(tr('common.export_save'),'exportSave',{},'pink'):''}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''}
</div>
<div class="menu-tiles">${[['🗂️',tr('slots.your_networks'),'toTitle'],['🧩',tr('puzzles.puzzles'),'puzzleMenu'],['🏆',tr('common.scenarios'),'scenarios'],['🧑‍💻',tr('ops.standing_orders'),'opsOpen'],['📸',tr('common.share'),'share'],['⚙️',tr('common.settings'),'settings']].map(([i,l,a])=>`<button class="mtile" data-act="${a}"><i aria-hidden="true">${i}</i><span>${l}</span></button>`).join('')}</div>
<p class="menu-links">${[saveFailing()?null:[tr('common.export_save'),'exportSave'],[tr('common.import_a_save'),'importPick'],[tr('common.how_to_play'),'help'],RELEASE_NOTES.length?[tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow']:null,[tr('common.start_a_new_network'),'resetAsk']].filter(Boolean).map(([l,a])=>`<button class="lnk" data-act="${a}">${l}</button>`).join(' · ')}</p>
<p class="menu-links">${[saveFailing()?null:[tr('common.export_save'),'exportSave'],[tr('common.import_a_save'),'importPick'],[tr('transfer.send_to_another_device'),'xfer'],[tr('common.how_to_play'),'help'],RELEASE_NOTES.length?[tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow']:null,[tr('common.start_a_new_network'),'resetAsk']].filter(Boolean).map(([l,a])=>`<button class="lnk" data-act="${a}">${l}</button>`).join(' · ')}</p>
</div><div class="menu-plugs"><a class="mplug" href="${SIGNAL}" target="_blank" rel="noopener">💬 ${tr('modal_and_names.join_the_noc_chat')} →</a><a class="mplug" href="${ISSUES}" target="_blank" rel="noopener">🐛 ${tr('modal_and_names.found_a_bug_or_have_an')} →</a></div>`);},
settings:()=>{UI.setOpen=true;openModal(settingsHtml());},
settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();},

View file

@ -0,0 +1,14 @@
// Moving a network to another device (#263): codes and a link out, a pasted link in.
Object.assign(ACT,{
xfer:({id}={})=>{const sid=slotOkId(id)?id:UI.slot;if(!sid||!slotIdx().some(e=>e.id===sid))return;
if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;}
xferPack(sid).then(x=>{UI.xfer={...x,id:sid,i:0};openModal(xferHtml());track('xfer_open');},()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));},
xferPage:({i})=>{const x=UI.xfer;if(!x||!(i>=0&&i<x.parts.length))return;x.i=i;openModal(xferHtml());},
xferLink:()=>{const x=UI.xfer;if(!x)return;const t=x.link,no=()=>toast(tr('transfer.could_not_copy_the_link_here'),'bad');
if(navigator.share&&isPhone()){navigator.share({title:'Series of Tubes',url:t}).catch(()=>{});return;}
try{navigator.clipboard.writeText(t).then(()=>toast(tr('transfer.link_copied_open_it_on_your'),'good'),no);}catch(e){no();}},
xferFile:()=>{const x=UI.xfer;if(x)exportSlot(x.id);},
xferRecv:()=>openModal(xferRecvHtml()),
xferPaste:()=>{const el=$('xferIn');if(el)xferTake(el.value.trim());},
xferReset:()=>{xferClear();ACT.helpClose();},
});

View file

@ -81,11 +81,13 @@ function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_
if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links))return {err:tr('save.that_does_not_look_like_a')};
if(s.lost)return {err:tr('save.that_network_went_bankrupt_it_cannot')};
for(const c of Object.keys(s.pops))if(!isCity(c))return {err:tr('save.that_save_has_a_pop_in',{city:esc(String(c).slice(0,12))})};
return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};}
return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network')),lean:!!(j.lean&&j.S)};}
function importFile(file){if(!file)return;if(file.size>64e6){toast(tr('save.that_file_is_too_big_to'),'bad');return;}
const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}
UI.importing=r.s;openModal(`<div class="eyebrow">${tr('common.import_a_save')}</div><h2 style="font-size:26px">${tr('save.load_name',{name:esc(r.name)})}</h2><p class="tagline">${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}</p><p class="note">${tr('slots.it_joins_your_networks_on_this')}</p><div class="btns">${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}</div>`);};
importAsk(r);};
rd.readAsText(file);}
// A save from a file or a transfer link (#263), checked by parseSave(): what it is, and whether to load it.
function importAsk(r){UI.importing=r.s;openModal(`<div class="eyebrow">${tr('common.import_a_save')}</div><h2 style="font-size:26px">${tr('save.load_name',{name:esc(r.name)})}</h2><p class="tagline">${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}</p><p class="note">${tr('slots.it_joins_your_networks_on_this')}${r.lean?' '+tr('transfer.its_charts_and_news_start_fresh'):''}</p><div class="btns">${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}</div>`);}
// This window's network, read synchronously (a compressed one was unpacked before boot). UI.loadBad: there, but unreadable.
function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null;
try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){}

View file

@ -24,7 +24,7 @@ function showTitle(){
<label class="f" for="nmIn">${tr('title.name_your_network')}</label><div class="network-name"><div class="nmwrap"><input class="t" id="nmIn" maxlength="24" value="${esc(UI.nm)}" autocomplete="off"><button class="reroll" data-act="randomName" aria-label="${tr('common.another_one')}" title="${tr('common.another_one')}">↻</button></div><div class="asnwrap"><span aria-hidden="true">AS</span><input class="t" id="asnIn" inputmode="numeric" maxlength="10" value="${esc(UI.asnTxt==null?'':UI.asnTxt)}" placeholder="${UI.asnSug}" aria-label="${tr('title.as_number')}" autocomplete="off"></div></div>
${doorsHtml()}
<label class="f" id="homeLbl" for="homeSel">${tr('title.pick_your_home_city')}</label>${homePick()}<p class="note" id="homeWhat">${homeWhat()}</p>
<div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
<div class="btns cta tcta" style="margin-top:16px">${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}</div><p class="ver">v${APP_VERSION} · <a href="https://github.com/fjaeckel/seriesoftubes" target="_blank" rel="noopener">${tr('title.source_on_github')}</a> · <a href="${SIGNAL}" target="_blank" rel="noopener">${tr('title.chat_on_signal')}</a> · ${tr('title.cookieless_stats_no_tracking')}</p>`);
$('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;});
$('asnIn').addEventListener('input',e=>{UI.asnTxt=e.target.value.replace(/\D/g,'').slice(0,10);if(e.target.value!==UI.asnTxt)e.target.value=UI.asnTxt;e.target.classList.toggle('bad',!!UI.asnTxt&&!asnOk(+UI.asnTxt));});
}

View file

@ -19,7 +19,7 @@ function slotRefresh(){const el=$('slotList');if(!el||UI.started)return;const h=
function slotMenuHtml(id){const e=slotIdx().find(x=>x.id===id);if(!e)return '';const nm=esc(e.name||tr('common.unnamed_network'));
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">${slotIcon(e)} ${slotLine(e)}</div><h2 style="font-size:26px">${nm}</h2></div><button class="x" data-act="slotBack" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${e.at?tr('slots.last_played_ago',{ago:slotAgo(e.at)}):''}${e.size?' · '+tr('slots.size_on_this_device',{size:slotSize(e.size)}):''}</p>
<div class="menu-list">${e.broken?btn(tr('slots.try_again'),'slotRetry',{id},'pink big'):btn(tr('slots.continue_this_network'),'cont',{id},'pink big')}${btn(tr('game_and_settings.export_save_download_a_file'),'slotExport',{id},'')}${btn(tr('slots.delete_this_network'),'slotDel',{id},'red')}${btn(tr('common.back'),'slotBack',{},'ghost')}</div>`;}
<div class="menu-list">${e.broken?btn(tr('slots.try_again'),'slotRetry',{id},'pink big'):btn(tr('slots.continue_this_network'),'cont',{id},'pink big')}${btn(tr('game_and_settings.export_save_download_a_file'),'slotExport',{id},'')}${e.broken?'':btn(tr('transfer.send_to_another_device'),'xfer',{id},'')}${btn(tr('slots.delete_this_network'),'slotDel',{id},'red')}${btn(tr('common.back'),'slotBack',{},'ghost')}</div>`;}
const slotSize=n=>n>=1e6?(n/1e6).toFixed(1)+' MB':Math.max(1,Math.round(n/1e3))+' kB';
function slotBusyModal(id){const e=slotIdx().find(x=>x.id===id),nm=esc(e&&e.name||tr('common.unnamed_network'));
openModal(`<div class="eyebrow">🪟 ${tr('slots.two_windows_one_network')}</div><h2 style="font-size:26px">${tr('slots.name_is_open_in_another_window',{name:nm})}</h2>

View file

@ -0,0 +1,17 @@
/* Moving a network to another device (#263): the codes to scan and the link, and on the other side, where to paste it. */
function xferHtml(){const x=UI.xfer,n=x.parts.length,i=Math.min(x.i,n-1),nm=esc(x.name||tr('common.unnamed_network'));
const q=n?qrEncode(new TextEncoder().encode(x.parts[i])):null;
return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">📲 ${tr('transfer.send_to_another_device')}</div><h2 style="font-size:26px">${nm}</h2></div><button class="x" data-act="helpClose" aria-label="${tr('common.close')}">×</button></div>
${q?`<p class="tagline">${n>1?tr('transfer.on_your_other_device_open_the_many'):tr('transfer.on_your_other_device_open_the')}</p>${qrSvg(q,tr('transfer.qr_code_i_of_n',{i:i+1,n}))}
${n>1?`<div class="xfer-nav">${btn('‹','xferPage',{i:i-1},'ghost',i===0)}<b>${tr('transfer.code_i_of_n',{i:i+1,n})}</b>${btn(tr('transfer.next_code'),'xferPage',{i:i+1},'pink',i===n-1)}</div>`:''}`
:`<p class="tagline">${tr('transfer.this_network_is_too_big_for')}</p>`}
<div class="btns" style="margin-top:10px">${btn(navigator.share&&isPhone()?tr('transfer.send_the_link'):tr('transfer.copy_the_link'),'xferLink',{},n?'':'pink')}${btn(tr('common.export_save'),'xferFile',{},'ghost')}</div>
<p class="note">${n?tr('transfer.the_codes_leave_out_your_charts')+' ':''}${tr('transfer.nothing_is_uploaded_anywhere_the_codes')}</p>`;}
function xferRecvHtml(){return `<div style="display:flex;align-items:center"><div class="grow"><div class="eyebrow">📲 ${tr('transfer.from_another_device')}</div><h2 style="font-size:26px">${tr('transfer.moving_a_network_here')}</h2></div><button class="x" data-act="helpClose" aria-label="${tr('common.close')}">×</button></div>
<p class="tagline">${tr('transfer.on_the_other_device_open_the')}</p>
<label class="f" for="xferIn">${tr('transfer.paste_a_transfer_link')}</label><textarea class="t xfer-in" id="xferIn" rows="3" autocomplete="off" autocapitalize="off" spellcheck="false"></textarea>
<div class="btns" style="margin-top:10px">${btn(tr('common.open'),'xferPaste',{},'pink big')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}</div>`;}
function xferWaitHtml(s){const have=Object.keys(s.p).length;
return `<div id="xferWait" class="eyebrow">📲 ${tr('transfer.moving_a_network_here')}</div><h2 style="font-size:26px">${tr('transfer.have_of_n_codes_are_here',{have,n:s.n})}</h2>
<div class="xfer-dots" aria-hidden="true">${Array.from({length:s.n},(_,k)=>`<i${s.p[k]!==undefined?' class="on"':''}></i>`).join('')}</div>
<p class="tagline">${tr('transfer.scan_the_next_code_on_your')}</p><div class="btns">${btn(tr('common.close'),'helpClose',{},'pink big')}${btn(tr('transfer.start_over'),'xferReset',{},'ghost')}</div>`;}

View file

@ -18,7 +18,7 @@ function showHelp(){
<dt>${tr('common.waves')}</dt><dd>${tr('help.your_fiber_links_are_leased_waves')}</dd><dt>${tr('common.95th_percentile')}</dt><dd>${tr('help.transit_bills_sample_your_usage')}</dd><dt>${tr('common.routers')}</dt><dd>${tr('help.each_pop_s_router_model_caps')}</dd><dt>${tr('common.dark_fiber')}</dt><dd>${tr('help.lease_an_iru_or_build_your')}</dd><dt>${tr('common.subsea_cables')}</dt><dd>${tr('help.subsea_waves_can_only_follow_cable')}</dd><dt>${tr('common.latency')}</dt><dd>${tr('help.every_link_has_latency_high')}</dd><dt>${tr('common.noc_dashboard')}</dt><dd>${tr('help.the_chart_button_at_the_top')}</dd><dt>${tr('common.asia')}</dt><dd>${tr('help.a_weird_underserved_market_transit')}</dd><dt>${tr('common.russia')}</dt><dd>${tr('help.moscow_needs_a_mandatory_government')}</dd><dt>${tr('help.events_chains_and_wholesale')}</dt><dd>${tr('help.event_networks_a_final_a_festival')}</dd><dt>${tr('common.bank')}</dt><dd>${tr('help.tap_your_cash_to_open_the')}</dd><dt>${tr('common.lags')}</dt><dd>${tr('help.out_of_port_speed_bundle_up')}</dd><dt>${tr('common.traffic_engineering')}</dt><dd>${tr('help.tap_a_link_to_see_which')}</dd><dt>${tr('common.china')}</dt><dd>${tr('help.mainland_china_needs_a_license_and')}</dd><dt>${tr('common.weird_requirements')}</dt><dd>${tr('help.some_customers_come_with_conditions')}</dd><dt>${tr('common.customer_levels')}</dt><dd>${tr('help.as_your_peak_traffic_and_footprint')}</dd><dt>${tr('help.l2vpn_ddos_protection')}</dt><dd>${tr('help.businesses_may_want_a_private')}</dd><dt>${tr('common.ddos_attack')}</dt><dd>${tr('help.ddos_a_flood_comes_from')}</dd><dt>${tr('common.scrubbing_centers')}</dt><dd>${tr('help.scrubbing_a_center_pulls_floods')}</dd><dt>${tr('common.nni_fabrics')}</dt><dd>${tr('help.megapork_pocketfabric_and')}</dd>
<dt>${tr('common.conferences')}</dt><dd>${tr('help.nanog_ripe_denog_and_friends_come')}</dd><dt>${tr('common.modes')}</dt><dd>${tr('help.one_game_four_doors_and_the')}</dd><dt>${tr('common.traceroute')}</dt><dd>${tr('help.tap_traceroute_on_any_of_your')}</dd><dt>${tr('common.badges')}</dt><dd>${tr('help.below_your_goals_sits_a_wall')}</dd><dt>${tr('common.the_giants')}</dt><dd>${tr('help.at_customer_level_3_and_4')}</dd><dt>RouteScript</dt><dd>${tr('help.once_auto_te_is_installed_you')}</dd><dt>Auto-TE</dt><dd>${tr('help.traffic_follows_the_shortest_path_by')}</dd><dt>${tr('common.metro_diversity')}</dt><dd>${tr('help.a_pop_is_one_building_until')}</dd><dt>${tr('common.wave_markets')}</dt><dd>${tr('help.what_a_wave_costs_depends_on')}</dd><dt>${tr('common.regional_quirks')}</dt><dd>${tr('help.in_the_gulf_saudi_pops_need')}</dd><dt>${tr('common.boot_times')}</dt><dd>${tr('help.some_routers_take_forever_to_boot')}</dd><dt>${tr('common.failures')}</dt><dd>${tr('help.things_break_all_the_time_fiber')}</dd>
<dt>RouteScript</dt><dd>${tr('help.rules_for_your_auto_te_controller')}</dd>
</dl><h3 style="margin:16px 0 0">${tr('help.want_to_know_how_it_really')}</h3>${plugHtml(true)}${chatHtml()}${issueHtml()}</dl><div class="btns" style="margin-top:14px">${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}</div><div class="btns" style="margin-top:6px">${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}</div>`);
</dl><h3 style="margin:16px 0 0">${tr('help.want_to_know_how_it_really')}</h3>${plugHtml(true)}${chatHtml()}${issueHtml()}</dl><div class="btns" style="margin-top:14px">${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}</div><div class="btns" style="margin-top:6px">${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}</div>`);
}
function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`<div class="btns" style="margin-top:8px">${btn(tr('help.share_my_network'),'share',{},'pink')}</div><p class="meta" style="margin:12px 0 0">${tr('help.you_built_a_cartoon_internet_now')}</p>${plugHtml(true)}`);},0);openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">${tr('help.you_re_a_tier_1')}</h1><p class="tagline">${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:S.day,n:S.stats.incidents})}</p>${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');}
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">${tr('common.bankrupt')}</h1><p class="tagline">${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}</p>${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}}

View file

@ -11,5 +11,5 @@ let PD={t:0,b:null};
document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true);
function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true;
if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;}
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});
document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','xfer','xferPage','xferLink','xferFile','xferRecv','xferPaste','xferReset'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});

View file

@ -68,7 +68,7 @@ function boot(data){
// A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted.
else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot);
else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}}
renderHUD();renderLeft();
renderHUD();renderLeft();xferBoot();
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);}
}

View file

@ -4848,6 +4848,30 @@
"traceroute.this_one_is_set_to_mode":"; this one is set to {mode}",
"traceroute.transit_is_the_last_resort":"transit is the last resort",
"traceroute.your_traffic_follows_the_metrics_this":"Your internet traffic follows the metrics. This is the path a customer circuit on “{mode}” would take.",
"transfer.code_i_of_n":"Code {i} of {n}",
"transfer.copy_the_link":"Copy the link",
"transfer.could_not_copy_the_link_here":"Could not copy the link here. Export a save file instead.",
"transfer.from_another_device":"From another device",
"transfer.have_of_n_codes_are_here":"{have} of {n} codes are here",
"transfer.its_charts_and_news_start_fresh":"Its charts and news start fresh here.",
"transfer.link_copied_open_it_on_your":"Link copied. Open it on your other device.",
"transfer.moving_a_network_here":"Move a network here",
"transfer.next_code":"Next code",
"transfer.nothing_is_uploaded_anywhere_the_codes":"Nothing is uploaded anywhere: the codes and the link carry the network itself. Whoever opens them gets a copy, so keep them to yourself.",
"transfer.on_the_other_device_open_the":"On the device with your network, open the menu and pick <b>Send to another device</b>. Scan its code with this device's camera, or paste its link here.",
"transfer.on_your_other_device_open_the":"On your other device, point the camera at this code and open the link.",
"transfer.on_your_other_device_open_the_many":"On your other device, point the camera at this code and open the link, then come back here for the next one. They can arrive in any order.",
"transfer.paste_a_transfer_link":"Paste a transfer link",
"transfer.qr_code_i_of_n":"QR code {i} of {n}",
"transfer.scan_the_next_code_on_your":"Scan the next code on your other device and open its link. Your network loads as soon as the last one arrives.",
"transfer.send_the_link":"Send the link",
"transfer.send_to_another_device":"Send to another device",
"transfer.start_over":"Start over",
"transfer.that_is_not_a_transfer_link":"That is not a transfer link.",
"transfer.that_link_is_incomplete_or_damaged":"That link is incomplete or damaged. Copy it again, all of it.",
"transfer.the_codes_leave_out_your_charts":"To keep the codes few, they leave out your charts and news; the link carries everything.",
"transfer.this_browser_cannot_pack_networks_into":"This browser cannot pack networks into links. Use a save file instead.",
"transfer.this_network_is_too_big_for":"This network is too big for codes. Send the link instead, or export a save file.",
"tutorial.businesses_pop_up_as_bubbles_on":"Businesses pop up as $ bubbles on the map. Open Deals and sign your first customer.",
"tutorial.grow_drag_from_your_pink_router":"Grow: drag from your pink router onto a nearby city to lay fiber and open a second POP.",
"tutorial.start_the_clock_with_1_and":"Start the clock with 1× and watch traffic and money flow. You can pause any time.",

View file

@ -229,3 +229,8 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px}
.cmroute{align-items:flex-start}
.tag.cmhot{background:#FFE1D6;color:#B43A12}
.tag.cmcool{background:#DDF1FB;color:#1E6A8C}
/* Moving a network to another device (#263). A code stays dark on white in dark mode too: cameras need the contrast. */
svg.qr{display:block;width:100%;max-width:300px;height:auto;margin:10px auto 6px;border:3px solid var(--ink);border-radius:12px;background:#fff;box-sizing:border-box}
.xfer-nav{display:flex;align-items:center;justify-content:space-between;gap:8px;max-width:300px;margin:0 auto}.xfer-nav b{font:800 14px var(--display)}
textarea.xfer-in{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 10px;font:13px/1.35 ui-monospace,monospace;background:var(--soft);color:var(--ink);resize:vertical;word-break:break-all}
.xfer-dots{display:flex;flex-wrap:wrap;gap:5px;margin:10px 0}.xfer-dots i{width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);background:var(--soft)}.xfer-dots i.on{background:var(--ok)}