Send a network to another device through the share sheet instead of QR codes (#263)

QR codes do not scale: a played network takes several, a big one dozens. The
save file now goes through the device's own share sheet (AirDrop, Quick Share,
a chat with yourself, email), whatever its size, and opens on the other device
with Import a save. Chromium refuses to share .json files, so there the same
file goes as .txt, which Import a save now takes too. The whole-network link
stays for copy and paste. The file is prepared before the tap, because a share
sheet only opens straight from a user's gesture.
This commit is contained in:
Frederic Jung 2026-11-10 13:19:00 +01:00
parent 79426f7a00
commit 1ccdda171b
No known key found for this signature in database
17 changed files with 187 additions and 346 deletions

View file

@ -10,7 +10,7 @@ All notable changes to this project are documented here. The project follows
- Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48).
- Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61).
- RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136).
- You can now move a network to another device with QR codes or a link, without an account or a file: open the menu, pick Send to another device, and scan the codes with the other device's camera, or send yourself the link. Nothing is uploaded anywhere, as the codes and the link carry the network itself, and to keep the codes few they leave out your charts and news, which start fresh on the other device; on the other device, open the link or paste it under From another device on the title screen (#263).
- You can now send a network to another device straight from the game: open the menu, pick Send to another device, and send the save file with AirDrop, Quick Share, a chat with yourself or email, then open it there with Import a save. You can also copy a link that carries the whole network and paste it on the other device under From another device. Nothing is uploaded anywhere (#263).
- From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137).
- From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315).
- Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317).

View file

@ -4849,30 +4849,22 @@
"traceroute.this_one_is_set_to_mode":"; dieser steht auf {mode}",
"traceroute.transit_is_the_last_resort":"Transit ist der letzte Ausweg",
"traceroute.your_traffic_follows_the_metrics_this":"Dein Internetverkehr folgt den Metriken. Dies ist der Weg, den eine Kundenleitung auf „{mode}“ nehmen würde.",
"transfer.code_i_of_n":"Code {i} von {n}",
"transfer.copy_the_link":"Link kopieren",
"transfer.could_not_copy_the_link_here":"Der Link ließ sich hier nicht kopieren. Exportiere stattdessen deinen Spielstand.",
"transfer.download_the_save_file_and_send":"Lade die Spielstand-Datei herunter und schick sie an dein anderes Gerät, zum Beispiel per E-Mail oder in einem Chat mit dir selbst. Öffne sie dort mit <b>Spielstand importieren</b>.",
"transfer.from_another_device":"Von einem anderen Gerät",
"transfer.have_of_n_codes_are_here":"{have} von {n} Codes sind da",
"transfer.its_charts_and_news_start_fresh":"Seine Diagramme und Meldungen fangen hier neu an.",
"transfer.link_copied_open_it_on_your":"Link kopiert. Öffne ihn auf deinem anderen Gerät.",
"transfer.link_copied_paste_it_on_your":"Link kopiert. Füge ihn auf deinem anderen Gerät unter Von einem anderen Gerät ein.",
"transfer.moving_a_network_here":"Netzwerk hierher holen",
"transfer.next_code":"Nächster Code",
"transfer.nothing_is_uploaded_anywhere_the_codes":"Nichts wird irgendwo hochgeladen: Codes und Link tragen das Netzwerk selbst. Wer sie öffnet, bekommt eine Kopie, also behalte sie für dich.",
"transfer.on_the_other_device_open_the":"Öffne auf dem Gerät mit deinem Netzwerk das Menü und wähle <b>Auf ein anderes Gerät senden</b>. Scanne den Code mit der Kamera dieses Geräts oder füge den Link hier ein.",
"transfer.on_your_other_device_open_the":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link.",
"transfer.on_your_other_device_open_the_many":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link, dann komm für den nächsten zurück. Die Reihenfolge ist egal.",
"transfer.paste_a_transfer_link":"Transfer-Link einfügen",
"transfer.qr_code_i_of_n":"QR-Code {i} von {n}",
"transfer.scan_the_next_code_on_your":"Scanne den nächsten Code auf deinem anderen Gerät und öffne den Link. Dein Netzwerk lädt, sobald der letzte da ist.",
"transfer.send_the_link":"Link senden",
"transfer.nothing_is_uploaded_anywhere_the_file":"Nichts wird irgendwo hochgeladen: Datei und Link tragen das Netzwerk selbst. Wer sie öffnet, bekommt eine Kopie, also behalte sie für dich.",
"transfer.on_the_device_with_your_network":"Öffne auf dem Gerät mit deinem Netzwerk das Menü und wähle <b>Auf ein anderes Gerät senden</b>. Öffne die Datei dann hier mit <b>Spielstand importieren</b>.",
"transfer.or_copy_the_link_and_paste":"Oder kopiere den Link und füge ihn auf dem anderen Gerät unter <b>Von einem anderen Gerät</b> ein, praktisch mit einer geteilten Zwischenablage.",
"transfer.or_paste_a_transfer_link":"Oder füge einen Transfer-Link ein",
"transfer.send_the_save_file":"Spielstand senden",
"transfer.send_the_save_file_to_your":"Schick die Spielstand-Datei an dein anderes Gerät: AirDrop, Quick Share, ein Chat mit dir selbst oder E-Mail. Öffne sie dort mit <b>Spielstand importieren</b>.",
"transfer.send_to_another_device":"Auf ein anderes Gerät senden",
"transfer.start_over":"Neu anfangen",
"transfer.that_is_not_a_transfer_link":"Das ist kein Transfer-Link.",
"transfer.that_link_is_incomplete_or_damaged":"Der Link ist unvollständig oder beschädigt. Kopier ihn noch mal, komplett.",
"transfer.the_codes_leave_out_your_charts":"Damit es wenige Codes bleiben, fehlen darin deine Diagramme und Meldungen; der Link enthält alles.",
"transfer.this_browser_cannot_pack_networks_into":"Dieser Browser kann Netzwerke nicht in Links packen. Exportiere stattdessen deinen Spielstand.",
"transfer.this_network_is_too_big_for":"Dieses Netzwerk ist zu groß für Codes. Schick stattdessen den Link oder exportiere deinen Spielstand.",
"transfer.this_browser_cannot_open_transfer_links":"Dieser Browser kann keine Transfer-Links öffnen. Nimm stattdessen eine Spielstand-Datei.",
"tutorial.businesses_pop_up_as_bubbles_on":"Unternehmen tauchen als $-Blasen auf der Karte auf. Öffne Deals und gewinne deinen ersten Kunden.",
"tutorial.grow_drag_from_your_pink_router":"Wachse: Zieh von deiner Stadt zu einer Stadt in der Nähe, um Glasfaser zu verlegen und einen zweiten POP zu eröffnen.",
"tutorial.start_the_clock_with_1_and":"Starte die Uhr mit 1× und sieh zu, wie Traffic und Geld fließen. Du kannst jederzeit pausieren.",

View file

@ -4847,30 +4847,22 @@
"traceroute.this_one_is_set_to_mode":"; esta está en {mode}",
"traceroute.transit_is_the_last_resort":"el tránsito es el último recurso",
"traceroute.your_traffic_follows_the_metrics_this":"Tu tráfico de internet sigue las métricas. Este es el camino que tomaría un circuito de cliente en «{mode}».",
"transfer.code_i_of_n":"Código {i} de {n}",
"transfer.copy_the_link":"Copiar el enlace",
"transfer.could_not_copy_the_link_here":"No se pudo copiar el enlace aquí. Exporta un archivo de partida.",
"transfer.download_the_save_file_and_send":"Descarga el archivo de partida y envíalo a tu otro dispositivo, por ejemplo por correo o en un chat contigo mismo. Ábrelo allí con <b>Importar una partida</b>.",
"transfer.from_another_device":"Desde otro dispositivo",
"transfer.have_of_n_codes_are_here":"Han llegado {have} de {n} códigos",
"transfer.its_charts_and_news_start_fresh":"Sus gráficos y noticias empiezan de cero aquí.",
"transfer.link_copied_open_it_on_your":"Enlace copiado. Ábrelo en tu otro dispositivo.",
"transfer.link_copied_paste_it_on_your":"Enlace copiado. Pégalo en tu otro dispositivo en Desde otro dispositivo.",
"transfer.moving_a_network_here":"Traer una red aquí",
"transfer.next_code":"Siguiente código",
"transfer.nothing_is_uploaded_anywhere_the_codes":"No se sube nada a ningún sitio: los códigos y el enlace llevan la red misma. Quien los abra obtiene una copia, así que guárdalos para ti.",
"transfer.on_the_other_device_open_the":"En el dispositivo con tu red, abre el menú y elige <b>Enviar a otro dispositivo</b>. Escanea su código con la cámara de este dispositivo o pega aquí su enlace.",
"transfer.on_your_other_device_open_the":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace.",
"transfer.on_your_other_device_open_the_many":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace; luego vuelve aquí por el siguiente. Pueden llegar en cualquier orden.",
"transfer.paste_a_transfer_link":"Pega un enlace de traspaso",
"transfer.qr_code_i_of_n":"Código QR {i} de {n}",
"transfer.scan_the_next_code_on_your":"Escanea el siguiente código en tu otro dispositivo y abre su enlace. Tu red se carga en cuanto llegue el último.",
"transfer.send_the_link":"Enviar el enlace",
"transfer.nothing_is_uploaded_anywhere_the_file":"No se sube nada a ningún sitio: el archivo y el enlace llevan la red misma. Quien los abra obtiene una copia, así que guárdalos para ti.",
"transfer.on_the_device_with_your_network":"En el dispositivo con tu red, abre el menú y elige <b>Enviar a otro dispositivo</b>. Luego abre aquí el archivo que envía con <b>Importar una partida</b>.",
"transfer.or_copy_the_link_and_paste":"O copia el enlace y pégalo en el otro dispositivo en <b>Desde otro dispositivo</b>, práctico si tus dispositivos comparten portapapeles.",
"transfer.or_paste_a_transfer_link":"O pega un enlace de traspaso",
"transfer.send_the_save_file":"Enviar la partida",
"transfer.send_the_save_file_to_your":"Envía el archivo de partida a tu otro dispositivo: AirDrop, Quick Share, un chat contigo mismo o correo. Ábrelo allí con <b>Importar una partida</b>.",
"transfer.send_to_another_device":"Enviar a otro dispositivo",
"transfer.start_over":"Empezar de nuevo",
"transfer.that_is_not_a_transfer_link":"Eso no es un enlace de traspaso.",
"transfer.that_link_is_incomplete_or_damaged":"Ese enlace está incompleto o dañado. Cópialo otra vez, entero.",
"transfer.the_codes_leave_out_your_charts":"Para que sean pocos códigos, dejan fuera tus gráficos y noticias; el enlace lo lleva todo.",
"transfer.this_browser_cannot_pack_networks_into":"Este navegador no puede meter redes en enlaces. Usa un archivo de partida.",
"transfer.this_network_is_too_big_for":"Esta red es demasiado grande para códigos. Envía el enlace o exporta un archivo de partida.",
"transfer.this_browser_cannot_open_transfer_links":"Este navegador no puede abrir enlaces de traspaso. Usa un archivo de partida.",
"tutorial.businesses_pop_up_as_bubbles_on":"Las empresas aparecen como burbujas de $ en el mapa. Abre Tratos y firma a tu primer cliente.",
"tutorial.grow_drag_from_your_pink_router":"Crece: arrastra desde tu router rosa hasta una ciudad cercana para tender fibra y abrir un segundo POP.",
"tutorial.start_the_clock_with_1_and":"Pon el reloj en marcha con 1× y mira cómo fluyen el tráfico y el dinero. Puedes pausar cuando quieras.",

View file

@ -4847,30 +4847,22 @@
"traceroute.this_one_is_set_to_mode":" ; celle-ci est réglée sur {mode}",
"traceroute.transit_is_the_last_resort":"le transit est le dernier recours",
"traceroute.your_traffic_follows_the_metrics_this":"Ton trafic internet suit les métriques. Voici le chemin que prendrait un circuit client en « {mode} ».",
"transfer.code_i_of_n":"Code {i} sur {n}",
"transfer.copy_the_link":"Copier le lien",
"transfer.could_not_copy_the_link_here":"Impossible de copier le lien ici. Exporte plutôt un fichier de sauvegarde.",
"transfer.download_the_save_file_and_send":"Télécharge le fichier de sauvegarde et envoie-le à ton autre appareil, par exemple par e-mail ou dans une discussion avec toi-même. Ouvre-le là-bas avec <b>Importer une sauvegarde</b>.",
"transfer.from_another_device":"Depuis un autre appareil",
"transfer.have_of_n_codes_are_here":"{have} codes sur {n} sont arrivés",
"transfer.its_charts_and_news_start_fresh":"Ses graphiques et son fil d'infos repartent de zéro ici.",
"transfer.link_copied_open_it_on_your":"Lien copié. Ouvre-le sur ton autre appareil.",
"transfer.link_copied_paste_it_on_your":"Lien copié. Colle-le sur ton autre appareil sous Depuis un autre appareil.",
"transfer.moving_a_network_here":"Amener un réseau ici",
"transfer.next_code":"Code suivant",
"transfer.nothing_is_uploaded_anywhere_the_codes":"Rien n'est envoyé nulle part : les codes et le lien contiennent le réseau lui-même. Qui les ouvre en obtient une copie, alors garde-les pour toi.",
"transfer.on_the_other_device_open_the":"Sur l'appareil qui a ton réseau, ouvre le menu et choisis <b>Envoyer vers un autre appareil</b>. Scanne son code avec l'appareil photo de cet appareil, ou colle son lien ici.",
"transfer.on_your_other_device_open_the":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien.",
"transfer.on_your_other_device_open_the_many":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien, puis reviens ici pour le suivant. L'ordre n'a pas d'importance.",
"transfer.paste_a_transfer_link":"Colle un lien de transfert",
"transfer.qr_code_i_of_n":"QR code {i} sur {n}",
"transfer.scan_the_next_code_on_your":"Scanne le code suivant sur ton autre appareil et ouvre son lien. Ton réseau se charge dès que le dernier arrive.",
"transfer.send_the_link":"Envoyer le lien",
"transfer.nothing_is_uploaded_anywhere_the_file":"Rien n'est envoyé nulle part : le fichier et le lien contiennent le réseau lui-même. Qui les ouvre en obtient une copie, alors garde-les pour toi.",
"transfer.on_the_device_with_your_network":"Sur l'appareil qui a ton réseau, ouvre le menu et choisis <b>Envoyer vers un autre appareil</b>. Ouvre ensuite ici le fichier envoyé avec <b>Importer une sauvegarde</b>.",
"transfer.or_copy_the_link_and_paste":"Ou copie le lien et colle-le sur l'autre appareil sous <b>Depuis un autre appareil</b>, pratique si tes appareils partagent le presse-papiers.",
"transfer.or_paste_a_transfer_link":"Ou colle un lien de transfert",
"transfer.send_the_save_file":"Envoyer la sauvegarde",
"transfer.send_the_save_file_to_your":"Envoie le fichier de sauvegarde à ton autre appareil : AirDrop, Quick Share, une discussion avec toi-même ou un e-mail. Ouvre-le là-bas avec <b>Importer une sauvegarde</b>.",
"transfer.send_to_another_device":"Envoyer vers un autre appareil",
"transfer.start_over":"Recommencer",
"transfer.that_is_not_a_transfer_link":"Ce n'est pas un lien de transfert.",
"transfer.that_link_is_incomplete_or_damaged":"Ce lien est incomplet ou abîmé. Copie-le à nouveau, en entier.",
"transfer.the_codes_leave_out_your_charts":"Pour garder peu de codes, ils laissent de côté tes graphiques et ton fil d'infos ; le lien contient tout.",
"transfer.this_browser_cannot_pack_networks_into":"Ce navigateur ne sait pas mettre un réseau dans un lien. Utilise plutôt un fichier de sauvegarde.",
"transfer.this_network_is_too_big_for":"Ce réseau est trop gros pour des codes. Envoie plutôt le lien, ou exporte un fichier de sauvegarde.",
"transfer.this_browser_cannot_open_transfer_links":"Ce navigateur ne sait pas ouvrir les liens de transfert. Utilise plutôt un fichier de sauvegarde.",
"tutorial.businesses_pop_up_as_bubbles_on":"Les entreprises apparaissent sous forme de bulles $ sur la carte. Ouvre Offres et signe ton premier client.",
"tutorial.grow_drag_from_your_pink_router":"Grandis : fais glisser depuis ton routeur rose vers une ville proche pour poser de la fibre et ouvrir un deuxième POP.",
"tutorial.start_the_clock_with_1_and":"Lance le temps en 1× et regarde le trafic et l’argent couler. Tu peux mettre en pause à tout moment.",

View file

@ -4847,30 +4847,22 @@
"traceroute.this_one_is_set_to_mode":"; questa è impostata su {mode}",
"traceroute.transit_is_the_last_resort":"il transit è l’ultima spiaggia",
"traceroute.your_traffic_follows_the_metrics_this":"Il tuo traffico internet segue le metriche. Questo è il percorso che prenderebbe un circuito cliente su «{mode}».",
"transfer.code_i_of_n":"Codice {i} di {n}",
"transfer.copy_the_link":"Copia il link",
"transfer.could_not_copy_the_link_here":"Non riesco a copiare il link qui. Esporta un file di salvataggio.",
"transfer.download_the_save_file_and_send":"Scarica il file di salvataggio e invialo all'altro dispositivo, per esempio via email o in una chat con te stesso. Aprilo lì con <b>Importa un salvataggio</b>.",
"transfer.from_another_device":"Da un altro dispositivo",
"transfer.have_of_n_codes_are_here":"Sono arrivati {have} codici su {n}",
"transfer.its_charts_and_news_start_fresh":"I suoi grafici e le notizie ripartono da zero qui.",
"transfer.link_copied_open_it_on_your":"Link copiato. Aprilo sull'altro dispositivo.",
"transfer.link_copied_paste_it_on_your":"Link copiato. Incollalo sull'altro dispositivo in Da un altro dispositivo.",
"transfer.moving_a_network_here":"Porta qui una rete",
"transfer.next_code":"Codice successivo",
"transfer.nothing_is_uploaded_anywhere_the_codes":"Non viene caricato nulla da nessuna parte: i codici e il link contengono la rete stessa. Chi li apre ne riceve una copia, quindi tienili per te.",
"transfer.on_the_other_device_open_the":"Sul dispositivo con la tua rete, apri il menu e scegli <b>Invia a un altro dispositivo</b>. Scansiona il codice con la fotocamera di questo dispositivo, oppure incolla qui il link.",
"transfer.on_your_other_device_open_the":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link.",
"transfer.on_your_other_device_open_the_many":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link, poi torna qui per il prossimo. L'ordine non conta.",
"transfer.paste_a_transfer_link":"Incolla un link di trasferimento",
"transfer.qr_code_i_of_n":"Codice QR {i} di {n}",
"transfer.scan_the_next_code_on_your":"Scansiona il prossimo codice sull'altro dispositivo e apri il link. La tua rete si carica appena arriva l'ultimo.",
"transfer.send_the_link":"Invia il link",
"transfer.nothing_is_uploaded_anywhere_the_file":"Non viene caricato nulla da nessuna parte: il file e il link contengono la rete stessa. Chi li apre ne riceve una copia, quindi tienili per te.",
"transfer.on_the_device_with_your_network":"Sul dispositivo con la tua rete, apri il menu e scegli <b>Invia a un altro dispositivo</b>. Poi apri qui il file che invia con <b>Importa un salvataggio</b>.",
"transfer.or_copy_the_link_and_paste":"Oppure copia il link e incollalo sull'altro dispositivo in <b>Da un altro dispositivo</b>, comodo se i tuoi dispositivi condividono gli appunti.",
"transfer.or_paste_a_transfer_link":"Oppure incolla un link di trasferimento",
"transfer.send_the_save_file":"Invia il salvataggio",
"transfer.send_the_save_file_to_your":"Invia il file di salvataggio all'altro dispositivo: AirDrop, Quick Share, una chat con te stesso o email. Aprilo lì con <b>Importa un salvataggio</b>.",
"transfer.send_to_another_device":"Invia a un altro dispositivo",
"transfer.start_over":"Ricomincia",
"transfer.that_is_not_a_transfer_link":"Questo non è un link di trasferimento.",
"transfer.that_link_is_incomplete_or_damaged":"Il link è incompleto o danneggiato. Copialo di nuovo, tutto intero.",
"transfer.the_codes_leave_out_your_charts":"Per restare pochi, i codici lasciano fuori i grafici e le notizie; il link contiene tutto.",
"transfer.this_browser_cannot_pack_networks_into":"Questo browser non riesce a mettere una rete in un link. Usa un file di salvataggio.",
"transfer.this_network_is_too_big_for":"Questa rete è troppo grande per i codici. Invia il link, oppure esporta un file di salvataggio.",
"transfer.this_browser_cannot_open_transfer_links":"Questo browser non riesce ad aprire i link di trasferimento. Usa un file di salvataggio.",
"tutorial.businesses_pop_up_as_bubbles_on":"Le aziende spuntano come bolle $ sulla mappa. Apri Offerte e firma il tuo primo cliente.",
"tutorial.grow_drag_from_your_pink_router":"Cresci: trascina dal tuo router rosa su una città vicina per posare fibra e aprire un secondo POP.",
"tutorial.start_the_clock_with_1_and":"Fai partire il tempo con 1× e guarda scorrere traffico e soldi. Puoi mettere in pausa quando vuoi.",

View file

@ -4847,30 +4847,22 @@
"traceroute.this_one_is_set_to_mode":"; esta está configurada como {mode}",
"traceroute.transit_is_the_last_resort":"transit é o último recurso",
"traceroute.your_traffic_follows_the_metrics_this":"O teu tráfego de internet segue as métricas. Este é o caminho que um circuito de cliente em «{mode}» tomaria.",
"transfer.code_i_of_n":"Código {i} de {n}",
"transfer.copy_the_link":"Copiar o link",
"transfer.could_not_copy_the_link_here":"Não deu para copiar o link aqui. Exporte um arquivo de save.",
"transfer.download_the_save_file_and_send":"Baixe o arquivo de save e envie para o outro dispositivo, por exemplo por e-mail ou num chat com você mesmo. Abra lá com <b>Importar um save</b>.",
"transfer.from_another_device":"De outro dispositivo",
"transfer.have_of_n_codes_are_here":"Chegaram {have} de {n} códigos",
"transfer.its_charts_and_news_start_fresh":"Os gráficos e notícias dela recomeçam do zero aqui.",
"transfer.link_copied_open_it_on_your":"Link copiado. Abra-o no outro dispositivo.",
"transfer.link_copied_paste_it_on_your":"Link copiado. Cole-o no outro dispositivo em De outro dispositivo.",
"transfer.moving_a_network_here":"Trazer uma rede para cá",
"transfer.next_code":"Próximo código",
"transfer.nothing_is_uploaded_anywhere_the_codes":"Nada é enviado para lugar nenhum: os códigos e o link carregam a própria rede. Quem os abrir recebe uma cópia, então guarde-os para você.",
"transfer.on_the_other_device_open_the":"No dispositivo com a sua rede, abra o menu e escolha <b>Enviar para outro dispositivo</b>. Escaneie o código com a câmera deste dispositivo ou cole o link aqui.",
"transfer.on_your_other_device_open_the":"No outro dispositivo, aponte a câmera para este código e abra o link.",
"transfer.on_your_other_device_open_the_many":"No outro dispositivo, aponte a câmera para este código e abra o link, depois volte aqui para o próximo. A ordem não importa.",
"transfer.paste_a_transfer_link":"Cole um link de transferência",
"transfer.qr_code_i_of_n":"Código QR {i} de {n}",
"transfer.scan_the_next_code_on_your":"Escaneie o próximo código no outro dispositivo e abra o link. Sua rede carrega assim que o último chegar.",
"transfer.send_the_link":"Enviar o link",
"transfer.nothing_is_uploaded_anywhere_the_file":"Nada é enviado para lugar nenhum: o arquivo e o link carregam a própria rede. Quem os abrir recebe uma cópia, então guarde-os para você.",
"transfer.on_the_device_with_your_network":"No dispositivo com a sua rede, abra o menu e escolha <b>Enviar para outro dispositivo</b>. Depois abra aqui o arquivo enviado com <b>Importar um save</b>.",
"transfer.or_copy_the_link_and_paste":"Ou copie o link e cole no outro dispositivo em <b>De outro dispositivo</b>, prático se seus dispositivos compartilham a área de transferência.",
"transfer.or_paste_a_transfer_link":"Ou cole um link de transferência",
"transfer.send_the_save_file":"Enviar o save",
"transfer.send_the_save_file_to_your":"Envie o arquivo de save para o outro dispositivo: AirDrop, Quick Share, um chat com você mesmo ou e-mail. Abra lá com <b>Importar um save</b>.",
"transfer.send_to_another_device":"Enviar para outro dispositivo",
"transfer.start_over":"Recomeçar",
"transfer.that_is_not_a_transfer_link":"Isso não é um link de transferência.",
"transfer.that_link_is_incomplete_or_damaged":"Esse link está incompleto ou danificado. Copie de novo, inteiro.",
"transfer.the_codes_leave_out_your_charts":"Para serem poucos códigos, eles deixam de fora seus gráficos e notícias; o link leva tudo.",
"transfer.this_browser_cannot_pack_networks_into":"Este navegador não consegue colocar redes em links. Use um arquivo de save.",
"transfer.this_network_is_too_big_for":"Esta rede é grande demais para códigos. Envie o link ou exporte um arquivo de save.",
"transfer.this_browser_cannot_open_transfer_links":"Este navegador não consegue abrir links de transferência. Use um arquivo de save.",
"tutorial.businesses_pop_up_as_bubbles_on":"Empresas aparecem como bolhas de $ no mapa. Abra Negócios e feche seu primeiro cliente.",
"tutorial.grow_drag_from_your_pink_router":"Cresça: arraste do seu router rosa até uma cidade próxima para lançar fibra e abrir um segundo POP.",
"tutorial.start_the_clock_with_1_and":"Comece o relógio em 1× e veja o tráfego e o dinheiro fluírem. Dá pra pausar a qualquer momento.",

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',xfer:'files',xferFile:'files',xferPage:'files',xferPaste:'files',xferRecv:'files',xferReset:'files',
exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPaste:'files',xferRecv:'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',xferLink:'browser',
install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser',xferShare:'browser',
};

View file

@ -1,59 +0,0 @@
/* ---------- 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

@ -1,9 +1,9 @@
/* ---------- 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;
No server, no account. The save file goes through the device's own share sheet (AirDrop, Quick Share, a chat with
yourself, email), whatever its size, and opens on the other device with "Import a save". For copy and paste
(a synced clipboard, a note to self) the network also fits in a link: gzipped, in the fragment (#sot1.<id>.0.1.<data>),
which browsers never send to any server. Opening the link, or pasting it, imports the network like a save file. */
const XFER_RE=/sot1\.([a-z0-9]{3,8})\.0\.1\.([A-Za-z0-9_-]+)/;
// 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 '';}})();
@ -13,37 +13,25 @@ const xferBase=()=>/^https?:$/.test(location.protocol)?location.origin+location.
// 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.
/* Everything is ready before the sheet opens: browsers only open a share sheet straight from a tap, not after waiting
for compression. Chromium shares only some file types, and not .json (Safari does): there the same file is a .txt,
which "Import a save" takes too. */
async function xferPack(id){const e=slotIdx().find(x=>x.id===id),t=await xferText(id),name=e&&e.name||S&&S.name;
const w=`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},"exported":"${new Date().toISOString()}","S":${t}}`;
let file=null;try{const fn=saveFileName(name),ok=f=>!!navigator.canShare&&navigator.canShare({files:[f]});
file=new File([w],fn,{type:'application/json'});if(!ok(file)){file=new File([w],fn.replace(/\.json$/,'.txt'),{type:'text/plain'});if(!ok(file))file=null;}}catch(err){file=null;}
let link=null;if(gzOk()){const k=Math.floor(Math.random()*36**5).toString(36).padStart(5,'0');
link=`${xferBase()}#sot1.${k}.0.1.${b64u(await gzPipe(new TextEncoder().encode(w),new CompressionStream('gzip')))}`;}
return {id,name,file,link};}
// A link (or just its fragment, or text with one in it).
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;}
xferOpen(m[2]);return true;}
function xferOpen(d){if(!gzOk()){toast(tr('transfer.this_browser_cannot_open_transfer_links'),'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.
// After boot: a page opened from a transfer link imports it.
function xferBoot(){if(XFER_HASH)xferTake(XFER_HASH);}

View file

@ -20,7 +20,7 @@ Object.assign(ACT,{
newgame:()=>{if(pzOn())pzLeave();const id=UI.slot;if(id){slotDrop(id);slotFree(id);}gameClear();showTitle();},
keepPlaying:()=>{closeModal();},
exportSave:()=>exportSave(),
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,.txt,application/json,text/plain';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();},
importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S;
// An import is a new network next to the others: the one playing here is saved and kept.
try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');},

View file

@ -1,14 +1,13 @@
// Moving a network to another device (#263): codes and a link out, a pasted link in.
// Moving a network to another device (#263): the save file through the share sheet, or a link to paste.
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();}},
xferPack(sid).then(x=>{UI.xfer=x;openModal(xferHtml());track('xfer_open');},()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));},
// Straight from the tap: a share sheet only opens on a user's gesture.
xferShare:()=>{const x=UI.xfer;if(!x||!x.file)return;
try{navigator.share({files:[x.file],title:'Series of Tubes'}).then(()=>track('xfer_share'),e=>{if(e&&e.name!=='AbortError')exportSlot(x.id);});}catch(e){exportSlot(x.id);}},
xferLink:()=>{const x=UI.xfer;if(!x||!x.link)return;const no=()=>toast(tr('transfer.could_not_copy_the_link_here'),'bad');
try{navigator.clipboard.writeText(x.link).then(()=>toast(tr('transfer.link_copied_paste_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,13 +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')),lean:!!(j.lean&&j.S)};}
return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};}
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;}
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>`);}
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')}</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

@ -1,17 +1,12 @@
/* 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;
/* Moving a network to another device (#263): the save file through the share sheet, or the link; on the other side,
where to open it. */
function xferHtml(){const x=UI.xfer,nm=esc(x.name||tr('common.unnamed_network'));
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>`;}
<p class="tagline">${x.file?tr('transfer.send_the_save_file_to_your'):tr('transfer.download_the_save_file_and_send')}</p>
<div class="btns" style="margin-top:10px">${x.file?btn(tr('transfer.send_the_save_file'),'xferShare',{},'pink big'):btn(tr('common.export_save'),'xferFile',{},'pink big')}${x.link?btn(tr('transfer.copy_the_link'),'xferLink',{},''):''}</div>
${x.link?`<p class="note">${tr('transfer.or_copy_the_link_and_paste')}</p>`:''}<p class="note">${tr('transfer.nothing_is_uploaded_anywhere_the_file')}</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>`;}
<p class="tagline">${tr('transfer.on_the_device_with_your_network')}</p>
<div class="btns" style="margin-top:10px">${btn(tr('common.import_a_save'),'importPick',{},'pink big')}</div>
<label class="f" for="xferIn">${tr('transfer.or_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',{},'')}</div>`;}

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','xfer','xferPage','xferLink','xferFile','xferRecv','xferPaste','xferReset'].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','xferShare','xferLink','xferFile','xferRecv','xferPaste'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);});

View file

@ -4848,30 +4848,22 @@
"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.download_the_save_file_and_send":"Download the save file and send it to your other device, for example by email or a chat with yourself. Open it there with <b>Import a save</b>.",
"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.link_copied_paste_it_on_your":"Link copied. Paste it on your other device under From another 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.nothing_is_uploaded_anywhere_the_file":"Nothing is uploaded anywhere: the file and the link carry the network itself. Whoever opens them gets a copy, so keep them to yourself.",
"transfer.on_the_device_with_your_network":"On the device with your network, open the menu and pick <b>Send to another device</b>. Then open the file it sends with <b>Import a save</b>.",
"transfer.or_copy_the_link_and_paste":"Or copy the link and paste it on the other device under <b>From another device</b>, handy with a clipboard your devices share.",
"transfer.or_paste_a_transfer_link":"Or paste a transfer link",
"transfer.send_the_save_file":"Send the save file",
"transfer.send_the_save_file_to_your":"Send the save file to your other device: AirDrop, Quick Share, a chat with yourself or email. Open it there with <b>Import a save</b>.",
"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.",
"transfer.this_browser_cannot_open_transfer_links":"This browser cannot open transfer links. Use a save file instead.",
"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,8 +229,5 @@ 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)}
/* Moving a network to another device (#263): a pasted link is long, so it wraps anywhere. */
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)}

View file

@ -1,164 +1,133 @@
// Moving a network to another device with QR codes or a link (#263): no server, the network travels in the link.
// Moving a network to another device (#263): the save file through the share sheet, or a link to paste. No server.
const test = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const { load } = require('./harness');
const { until } = require('./net');
const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond);
const hash = (rows) => crypto.createHash('sha256').update(rows).digest('hex').slice(0, 16);
const SNAP = "JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name,hist:S.hist.length})";
/* A share sheet like Chromium's: no .json files, .txt yes. Calls are recorded; share() is called at once (a sheet only
opens straight from the tap). window.__shareResult: 'ok', 'abort' or 'fail'. */
const CHROMIUM_SHARE = `navigator.canShare=d=>!!d&&Array.isArray(d.files)&&d.files.every(f=>/\\.txt$/.test(f.name));
window.__shared=[];window.__shareResult='ok';
navigator.share=d=>{__shared.push(d);return __shareResult==='ok'?Promise.resolve():Promise.reject(new DOMException('x',__shareResult==='abort'?'AbortError':'NotAllowedError'));};`;
// Module matrices from Project Nayuki's reference encoder (qrcodegen), byte mode, one per mask.
const REF = [
['https://seriesoftub.es/#sot1.ab12c.0.3.HELLO-world_42', 'L', 3, ['30728883c56ec1b1', '18174c37d6786fa7', 'a981f41d89cceb7e', 'e28c29324d50ad09', 'd05a240976233180', 'd7ad281bfed61f9e', '083a4137b252f78f', 'a82468785d358d89']],
['x'.repeat(200), 'M', 10, ['750d745db4aee09b', '9ff2474eb4806262', 'c8294f9a437b1546', '1bf4d13e40b47c5f', 'fdce0323024df963', '87c3d49925e75834', 'b719f9e8d1b0dd89', '342f8ed986243039']],
['Series of Tubes '.repeat(40), 'L', 17, ['6d81d73a8426ecea', 'c36740777a080ce2', '79556df75d596a27', 'c4999ca1f4c7cdff', '23185df5abef3f74', '5b2fc9fa8d26aac0', '88b5814b383833f3', '298a1c7f2a08b6ae']],
['AS64512 '.repeat(120), 'L', 22, ['f8229058824f8960', '0c473ae025a4c779', '58c3ab340313be0a', 'd4fa9891688a1ccc', 'eaac167548e8e5f3', '3f14beb40d1dc4cf', 'a29dee8e6e34fd04', 'b0c682d9933fe28a']],
['peering '.repeat(360), 'L', 40, ['6efd1b3513f437d0', 'c18c188947dc52bc', 'cd93f7d4626a657f', 'a596a01654473a8d', '33fa5bbfe6b4915a', 'c547ade997387b9e', 'ed333919d660b05a', '44f32c8d979821a8']],
];
test('the QR encoder draws exactly the reference codes, for every mask, from version 3 to 40', () => {
const { ev, errors } = load();
for (const [s, ecc, v, masks] of REF) {
masks.forEach((h, mask) => {
const q = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}',mask:${mask}});return JSON.stringify({v:q.v,size:q.size,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join('')});})()`));
assert.equal(q.v, v, `${s.slice(0, 12)}… version`);
assert.equal(q.size, v * 4 + 17);
assert.equal(hash(q.m), h, `${s.slice(0, 12)}… ${ecc} mask ${mask}`);
});
// Left to choose, it picks one of the eight valid masks.
const auto = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}'});return JSON.stringify({v:q.v,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join(''),mask:q.mask});})()`));
assert.equal(auto.v, v);
assert.equal(hash(auto.m), masks[auto.mask]);
}
assert.equal(ev("qrEncode(new Uint8Array(2954))"), null, 'more than version 40 holds');
assert.match(ev("qrSvg(qrEncode(new TextEncoder().encode('hi')),'x')"), /^<svg class="qr" viewBox="0 0 29 29"/);
assert.deepEqual(errors, []);
});
// A network that has played a while, sent from page A.
async function sender() {
const a = load({ gzip: true });
async function sender(opts = {}) {
const a = load({ gzip: true, ...opts });
if (opts.share) a.ev(CHROMIUM_SHARE);
a.ev("$('nmIn').value='Tube Mover';ACT.start({});S.cash=4321987;for(let i=0;i<40;i++)dayTick();save(true)");
a.ev('ACT.xfer({})');
await settle(a.ev, "!!document.querySelector('#modalCard svg.qr')", 'the codes are on screen');
await settle(a.ev, '!!UI.xfer', 'the send screen opens');
return a;
}
test('the save file goes to the share sheet straight from the tap, as a .txt where .json cannot be shared, and loads on the other device', async () => {
const a = await sender({ share: true });
assert.match(a.ev("$('modalCard').textContent"), /Send the save file/);
assert.equal(a.ev('UI.xfer.file.name'), 'series-of-tubes-tube-mover-' + a.ev('new Date().toISOString().slice(0,10)') + '.txt');
a.ev(`document.querySelector('#modalCard [data-act="xferShare"]').click()`);
assert.equal(a.ev('__shared.length'), 1, 'the sheet opens in the same tap, not after waiting for anything');
assert.equal(a.ev('__shared[0].files[0]===UI.xfer.file'), true);
// The file arrives on the other device and opens with Import a save.
const txt = await a.dom.window.eval('__shared[0].files[0].text()'), want = a.ev(SNAP);
const b = load({ gzip: true });
b.dom.window.__txt = txt;
b.ev("importFile(new File([__txt],'series-of-tubes-tube-mover.txt',{type:'text/plain'}))");
await settle(b.ev, '!!UI.importing', 'it asks before loading');
b.ev('ACT.importGo()');
assert.equal(b.ev(SNAP), want, 'the same network, charts and all');
// The picker takes the .txt that Chromium shares as well as .json.
b.ev("HTMLInputElement.prototype.click=function(){window.__accept=this.accept;};ACT.importPick()");
assert.match(b.ev('__accept'), /\.txt/);
assert.match(b.ev('__accept'), /\.json/);
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);
});
test('a browser that shares .json gets the .json; one that cannot share files gets a download button', async () => {
const a = load({ gzip: true });
a.ev("navigator.canShare=()=>true;navigator.share=()=>Promise.resolve();ACT.start({});save(true);ACT.xfer({})");
await settle(a.ev, '!!UI.xfer');
assert.match(a.ev('UI.xfer.file.name'), /\.json$/);
assert.equal(a.ev('UI.xfer.file.type'), 'application/json');
const c = await sender();
assert.equal(c.ev('UI.xfer.file'), null);
assert.ok(c.ev(`!!document.querySelector('#modalCard [data-act="xferFile"]')`), 'Export save instead');
assert.ok(!c.ev(`document.querySelector('#modalCard [data-act="xferShare"]')`));
assert.match(c.ev("$('modalCard').textContent"), /Download the save file/);
assert.deepEqual(a.errors, []);
assert.deepEqual(c.errors, []);
});
test('a share that fails falls back to the download; closing the sheet does nothing', async () => {
const a = await sender({ share: true });
a.ev("window.__dl=0;exportSlot=()=>{__dl++;}");
a.ev("__shareResult='abort';ACT.xferShare()");
await new Promise((r) => setTimeout(r, 50));
assert.equal(a.ev('__dl'), 0, 'the player closed the sheet: nothing else happens');
a.ev("__shareResult='fail';ACT.xferShare()");
await settle(a.ev, '__dl===1', 'a refused share downloads the file instead');
assert.deepEqual(a.errors, []);
});
test('one link carries the whole network: opened on another device it loads the same game, and leaves the address bar', async () => {
const a = await sender();
const link = a.ev('UI.xfer.link'), want = a.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})");
const link = a.ev('UI.xfer.link'), want = a.ev(SNAP);
assert.ok(link.startsWith('https://tests.invalid/#sot1.'), link.slice(0, 40));
assert.ok(a.ev('UI.xfer.parts.length') > 1, 'a played network takes several codes');
assert.ok(a.ev('UI.xfer.parts.every(p=>p.length<=qrCap(22))'), 'every code is small enough to scan from a phone screen');
const b = load({ gzip: true, url: link });
assert.equal(b.ev('location.hash'), '', 'the network is taken out of the address bar at once');
await settle(b.ev, '!!UI.importing', 'it asks before loading');
assert.match(b.ev("$('modalCard').textContent"), /Tube Mover/);
assert.doesNotMatch(b.ev("$('modalCard').textContent"), /start fresh/, 'the link carries everything');
const hist = a.ev('JSON.stringify(S.hist)'), log = a.ev('S.log.length');
b.ev('ACT.importGo()');
assert.equal(b.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})"), want);
assert.equal(b.ev('JSON.stringify(S.hist)'), hist, 'the charts came along');
assert.equal(b.ev('S.log.length'), log + 1, 'the news came along (plus the welcome)');
assert.equal(b.ev(SNAP), want);
assert.equal(b.ev('slotIdx().length'), 1, 'it joins the networks on that device');
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);
// Pasted on the title screen, with whatever whitespace a clipboard adds.
const c = load({ gzip: true });
c.ev('ACT.xferRecv()');
assert.ok(c.ev(`!!document.querySelector('#modalCard [data-act="importPick"]')`), 'Import a save is right there for the file');
c.ev(`$('xferIn').value=${JSON.stringify(' ' + link + '\n')};ACT.xferPaste()`);
await settle(c.ev, '!!UI.importing');
for (const x of [a, b, c]) assert.deepEqual(x.errors, []);
});
test('the codes arrive one by one, in any order; the network loads when the last one is in', async () => {
test('bad or cut links say so and load nothing', async () => {
const a = await sender();
const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), n = parts.length;
// Paging through the codes on the sending device.
a.ev('ACT.xferPage({i:1})');
assert.match(a.ev("$('modalCard').textContent"), new RegExp(`Code 2 of ${n}`));
const link = a.ev('UI.xfer.link');
const b = load({ gzip: true });
const order = parts.map((p, i) => i).reverse();
for (const [k, i] of order.entries()) {
b.ev(`xferTake(${JSON.stringify(parts[i])})`);
if (k < n - 1) {
assert.match(b.ev("$('modalCard').textContent"), new RegExp(`${k + 1} of ${n} codes are here`));
assert.equal(b.ev('document.querySelectorAll(".xfer-dots i.on").length'), k + 1);
// The same code twice changes nothing.
b.ev(`xferTake(${JSON.stringify(parts[i])})`);
assert.equal(b.ev('Object.keys(xferStore().p).length'), k + 1);
}
}
await settle(b.ev, '!!UI.importing', 'the last code opens the network');
assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null, 'the parts are cleaned up');
assert.match(b.ev("$('modalCard').textContent"), /charts and news start fresh/, 'it says what the codes left out');
const vol = a.ev('S.vol');
b.ev('ACT.importGo()');
assert.equal(b.ev('S.name'), 'Tube Mover');
assert.equal(b.ev('S.cash'), a.ev('S.cash'));
assert.equal(b.ev('S.day'), a.ev('S.day'));
assert.equal(b.ev('S.vol'), vol, 'the traffic odometer keeps its count');
assert.equal(b.ev('S.hist.length'), 0, 'only charts and news were left out');
assert.equal(b.ev('S.log.length'), 1, 'the news starts with the welcome');
b.ev('for(let i=0;i<3;i++)dayTick()');
assert.equal(b.ev('S.hist.length'), 3, 'the charts start again');
assert.deepEqual(b.errors, []);
});
test('a code from another transfer starts over, and bad or cut links say so and load nothing', async () => {
const a = await sender();
const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), link = a.ev('UI.xfer.link');
const b = load({ gzip: true });
b.ev(`xferTake(${JSON.stringify(parts[0])})`);
b.ev(`xferTake(${JSON.stringify(parts[1].replace(/#sot1\.[a-z0-9]+\./, '#sot1.zzzzz.'))})`);
assert.equal(b.ev("xferStore().id"), 'zzzzz');
assert.equal(b.ev('Object.keys(xferStore().p).length'), 1);
b.ev('ACT.xferReset()');
assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null);
b.ev("xferTake('https://example.com/nothing-here')");
assert.match(b.ev("$('toasts')?$('toasts').textContent:document.body.textContent"), /not a transfer link/);
assert.match(b.ev('document.body.textContent'), /not a transfer link/);
b.ev(`xferTake(${JSON.stringify(link.slice(0, -40))})`);
await settle(b.ev, "/incomplete or damaged/.test(document.body.textContent)", 'a cut link is reported');
await settle(b.ev, '/incomplete or damaged/.test(document.body.textContent)', 'a cut link is reported');
assert.equal(b.ev('!!UI.importing'), false);
assert.equal(b.ev('S'), null, 'nothing was loaded');
// Pasted into the box on the title screen, the whole link works too.
b.ev('ACT.xferRecv()');
b.ev(`$('xferIn').value=${JSON.stringify(' ' + link + '\n')};ACT.xferPaste()`);
await settle(b.ev, '!!UI.importing');
assert.deepEqual(b.errors, []);
});
test('any network on the title screen can be sent, and the codes fit a 360 px phone', async () => {
const a = await sender();
a.ev("ACT.toTitle()");
test('any network on the title screen can be sent without loading it, and the screen fits a 360 px phone', async () => {
const a = await sender({ share: true });
a.ev('ACT.toTitle()');
const id = a.ev('slotIdx()[0].id');
a.ev(`ACT.slotMenu({id:'${id}'})`);
assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xfer"]')`), 'the network menu offers it');
a.ev('window.innerWidth=360;UI.xfer=null');
a.ev(`document.querySelector('#modalCard [data-act="xfer"]').click()`);
await settle(a.ev, '!!UI.xfer&&!!document.querySelector("#modalCard svg.qr")', 'sent from storage, without loading it');
await settle(a.ev, '!!UI.xfer', 'sent from storage');
assert.equal(a.ev('S'), null, 'not loaded');
assert.equal(a.ev('UI.xfer.name'), 'Tube Mover');
assert.ok(a.ev("!!document.querySelector('#modalCard .xfer-nav')"));
const css = a.ev("[...document.styleSheets].flatMap(s=>[...s.cssRules]).map(r=>r.cssText).join('\\n')");
assert.match(css, /svg\.qr\s*\{[^}]*max-width:\s*300px/, 'the code never gets wider than a small phone');
assert.match(await a.dom.window.eval('UI.xfer.file.text()'), /"name":"Tube Mover"/);
assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferShare"]')`));
assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferLink"]')`));
assert.deepEqual(a.errors, []);
});
test('a year-old network takes a handful of codes, because the codes leave out charts and news', async () => {
const a = load({ gzip: true });
a.ev("ACT.start({});for(let i=0;i<365;i++)dayTick();save(true);ACT.xfer({})");
test('without compression the file still goes, only the link is missing', async () => {
const a = load();
a.ev(CHROMIUM_SHARE + "ACT.start({});save(true);ACT.xfer({})");
await settle(a.ev, '!!UI.xfer');
const n = a.ev('UI.xfer.parts.length'), full = Math.ceil(a.ev("UI.xfer.link.split('.').pop().length") / 900);
assert.ok(n <= 4, `${n} codes`);
assert.ok(full >= 2 * n, `the whole network would take ${full}`);
assert.match(a.ev("$('modalCard').textContent"), /leave out your charts and news/);
assert.equal(a.ev('UI.xfer.link'), null);
assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferShare"]')`));
assert.ok(!a.ev(`document.querySelector('#modalCard [data-act="xferLink"]')`));
assert.deepEqual(a.errors, []);
});
test('without compression in the browser it says so instead of failing', () => {
const { ev, errors } = load();
ev("ACT.start({});save(true);ACT.xfer({})");
assert.equal(ev('UI.xfer'), undefined);
assert.match(ev('document.body.textContent'), /cannot pack networks into links/);
assert.deepEqual(errors, []);
});