mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +01:00
feat(player): retry held-back states and stop a loaded state syncing as a save
The browser held saves the server would not take; it now holds states the same way, and each capture is named after the moment it was taken so a retry updates that row rather than leaving a second copy of the same moment. An asset the server refuses for good is dropped rather than retried for the rest of time, and the player is told which game and why. Loading a state no longer mints a save. The tracker's baseline was read from the emulator's filesystem without dumping the core first, so it held the SRAM from before the restore and the next settled tick uploaded the state's SRAM as progress the player never made. Every state load re-baselines now, the picker and quick load included. Also in the player: - The screen and the sound stay held back until a loaded state has landed, instead of showing a second of the fresh boot. - Notices go through RomM's own toast host, so two landing together stack rather than overwrite each other, and EmulatorJS' own notices join them. - A capture is taken one at a time and gives up after 3s: EmulatorJS deletes the file the previous capture is still waiting on, and waits by polling forever, which wedged the save sync for the rest of the session. - The emulator is torn down once. The player and the shell around it both asked, and the second pass threw ErrnoError(28) and aborted the runtime. - A capture's id no longer needs `crypto.randomUUID`, which does not exist outside a secure context (RomM over plain http on a LAN address). And around it: - The connection notice moves to the player's corner while a game runs, says its piece and shrinks to its icon, with the full message and the retry button back once the game is over. - The player's save and state pickers use the launch screen's own asset lists rather than a card of their own, which leaves that card unused. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QTsTgdoBinvvxzXeLUjBmV
This commit is contained in:
@@ -129,7 +129,7 @@
|
||||
"search": "Търси",
|
||||
"select": "Избери",
|
||||
"select-platform": "Избери платформа",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Връзката със сървъра е прекъсната, повторен опит…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Статистики на сървъра",
|
||||
"settings": "Настройки",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Изход без запазване на скорошния напредък?",
|
||||
"keep-playing": "Продължи играта",
|
||||
"last-save-synced": "Последният запис за {game} е синхронизиран.",
|
||||
"last-state-synced": "Последният бърз запис за {game} е синхронизиран.",
|
||||
"latest-version": "Най-нова",
|
||||
"launch-extracting-archive": "Разопакуване на архива",
|
||||
"launch-extracting-pkg": "Инсталиране на файловете на играта",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Играйте и запишете в играта. Ще се синхронизира при края на сесията.",
|
||||
"save-data-note": "Възстановено на конзолата преди стартиране. Заредете го от менюто на самата игра.",
|
||||
"save-data-synced": "Синхронизирано",
|
||||
"save-not-synced": "Последният ви запис не достигна до сървъра. Той се съхранява в този браузър и ще се синхронизира следващия път, когато играете тази игра.",
|
||||
"save-not-synced": "Последният ви запис още не е достигнал до сървъра. Той се съхранява в този браузър и RomM продължава да опитва във фонов режим.",
|
||||
"save-progress-to": "Записвай напредъка в",
|
||||
"save-slot": "Слот за запазване",
|
||||
"save-state": "Запазване на състояние",
|
||||
"save-sync-refused": "Сървърът отхвърли съхранения запис за {game}: {reason}. Той вече не се съхранява в този браузър.",
|
||||
"select-background-color": "Избери цвят на фона",
|
||||
"select-save": "Избери запис",
|
||||
"select-state": "Избери бърз запис",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} версия | {count} версии",
|
||||
"start-fresh-hint": "Избери един по-долу, за да продължиш, или натисни Играй, за да започнеш отначало.",
|
||||
"state-incompatible-core": "Записан с {emulator}, което избраното ядро не може да зареди.",
|
||||
"state-not-synced": "Последният ви бърз запис още не е достигнал до сървъра. Той се съхранява в този браузър и RomM продължава да опитва във фонов режим.",
|
||||
"state-sync-refused": "Сървърът отхвърли съхранения бърз запис за {game}: {reason}. Той вече не се съхранява в този браузър.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Hledat",
|
||||
"select": "Vybrat",
|
||||
"select-platform": "Vyberte platformu",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Spojení se serverem bylo ztraceno, zkoušíme znovu…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Statistiky serveru",
|
||||
"settings": "Nastavení",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Ukončit bez uložení posledního postupu?",
|
||||
"keep-playing": "Pokračovat ve hře",
|
||||
"last-save-synced": "Poslední uložená pozice pro {game} byla synchronizována.",
|
||||
"last-state-synced": "Poslední stav pro {game} byl synchronizován.",
|
||||
"latest-version": "Nejnovější",
|
||||
"launch-extracting-archive": "Rozbalování archivu",
|
||||
"launch-extracting-pkg": "Instalace herních souborů",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Hrajte a uložte ve hře. Po skončení relace se data synchronizují.",
|
||||
"save-data-note": "Obnoveno do konzole před spuštěním. Načtěte je z nabídky samotné hry.",
|
||||
"save-data-synced": "Synchronizováno",
|
||||
"save-not-synced": "Vaše poslední uložená pozice se nedostala na server. Je uložena v tomto prohlížeči a synchronizuje se, až si tuto hru zahrajete příště.",
|
||||
"save-not-synced": "Vaše poslední uložená pozice se zatím nedostala na server. Je uložena v tomto prohlížeči a RomM to na pozadí zkouší dál.",
|
||||
"save-progress-to": "Ukládat postup do",
|
||||
"save-slot": "Pozice uložení",
|
||||
"save-state": "Uložit stav",
|
||||
"save-sync-refused": "Server odmítl uloženou pozici, kterou jsme měli pro {game}: {reason}. Už není uložena v tomto prohlížeči.",
|
||||
"select-background-color": "Vybrat barvu pozadí",
|
||||
"select-save": "Vybrat uloženou pozici",
|
||||
"select-state": "Vybrat stav",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} verzí | {count} verze | {count} verze | {count} verzí",
|
||||
"start-fresh-hint": "Vyberte níže pro pokračování, nebo stiskněte Hrát pro nový začátek.",
|
||||
"state-incompatible-core": "Uloženo pomocí {emulator}, což vybrané jádro nedokáže načíst.",
|
||||
"state-not-synced": "Váš poslední stav se zatím nedostal na server. Je uložen v tomto prohlížeči a RomM to na pozadí zkouší dál.",
|
||||
"state-sync-refused": "Server odmítl stav, který jsme měli pro {game}: {reason}. Už není uložen v tomto prohlížeči.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Suche",
|
||||
"select": "Auswählen",
|
||||
"select-platform": "Plattform auswählen",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Serververbindung verloren, neuer Versuch…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Serverstatistiken",
|
||||
"settings": "Einstellungen",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Beenden, ohne den letzten Fortschritt zu speichern?",
|
||||
"keep-playing": "Weiterspielen",
|
||||
"last-save-synced": "Letzter Spielstand für {game} synchronisiert.",
|
||||
"last-state-synced": "Letzter Zustand für {game} synchronisiert.",
|
||||
"latest-version": "Neueste",
|
||||
"launch-extracting-archive": "Archiv wird entpackt",
|
||||
"launch-extracting-pkg": "Spieldateien werden installiert",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Spiele und speichere im Spiel. Der Stand wird am Ende der Sitzung synchronisiert.",
|
||||
"save-data-note": "Vor dem Start auf die Konsole übertragen. Lade ihn im Menü des Spiels.",
|
||||
"save-data-synced": "Synchronisiert",
|
||||
"save-not-synced": "Dein letzter Spielstand hat den Server nicht erreicht. Er wird in diesem Browser aufbewahrt und beim nächsten Spielen dieses Spiels synchronisiert.",
|
||||
"save-not-synced": "Dein letzter Spielstand hat den Server noch nicht erreicht. Er wird in diesem Browser aufbewahrt und RomM versucht es im Hintergrund weiter.",
|
||||
"save-progress-to": "Fortschritt speichern in",
|
||||
"save-slot": "Speicherplatz",
|
||||
"save-state": "Spielstand speichern",
|
||||
"save-sync-refused": "Der Server hat den aufbewahrten Spielstand für {game} abgelehnt: {reason}. Er wird in diesem Browser nicht mehr aufbewahrt.",
|
||||
"select-background-color": "Hintergrundfarbe auswählen",
|
||||
"select-save": "Speicherstand auswählen",
|
||||
"select-state": "Speicherstand auswählen",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} Version | {count} Versionen",
|
||||
"start-fresh-hint": "Wähle unten einen, um fortzufahren, oder klicke auf Play, um neu zu starten.",
|
||||
"state-incompatible-core": "Mit {emulator} gespeichert, was der gewählte Core nicht laden kann.",
|
||||
"state-not-synced": "Dein letzter Zustand hat den Server noch nicht erreicht. Er wird in diesem Browser aufbewahrt und RomM versucht es im Hintergrund weiter.",
|
||||
"state-sync-refused": "Der Server hat den aufbewahrten Zustand für {game} abgelehnt: {reason}. Er wird in diesem Browser nicht mehr aufbewahrt.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Search",
|
||||
"select": "Select",
|
||||
"select-platform": "Select a platform",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Server connection lost, retrying…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Server stats",
|
||||
"settings": "Settings",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Quit without saving recent progress?",
|
||||
"keep-playing": "Keep playing",
|
||||
"last-save-synced": "Last save synced for {game}.",
|
||||
"last-state-synced": "Last state synced for {game}.",
|
||||
"latest-version": "Latest",
|
||||
"launch-extracting-archive": "Unpacking the archive",
|
||||
"launch-extracting-pkg": "Installing the game files",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Play, then save in-game. It syncs back when the session ends.",
|
||||
"save-data-note": "Restored to the console before launch. Load it from the game's own menu.",
|
||||
"save-data-synced": "Synced",
|
||||
"save-not-synced": "Your last save has not reached the server. It is kept in this browser and will sync the next time you play this game.",
|
||||
"save-not-synced": "Your last save has not reached the server yet. It is kept in this browser and RomM keeps retrying in the background.",
|
||||
"save-progress-to": "Save progress to",
|
||||
"save-slot": "Save slot",
|
||||
"save-state": "Save state",
|
||||
"save-sync-refused": "The server refused the save held for {game}: {reason}. It is no longer kept in this browser.",
|
||||
"select-background-color": "Select background colour",
|
||||
"select-save": "Select save",
|
||||
"select-state": "Select state",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} version | {count} versions",
|
||||
"start-fresh-hint": "Pick one below to resume, or hit Play to start fresh.",
|
||||
"state-incompatible-core": "Saved with {emulator}, which the selected core cannot load.",
|
||||
"state-not-synced": "Your last state has not reached the server yet. It is kept in this browser and RomM keeps retrying in the background.",
|
||||
"state-sync-refused": "The server refused the state held for {game}: {reason}. It is no longer kept in this browser.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Search",
|
||||
"select": "Select",
|
||||
"select-platform": "Select a platform",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Server connection lost, retrying…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Server stats",
|
||||
"settings": "Settings",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Quit without saving recent progress?",
|
||||
"keep-playing": "Keep playing",
|
||||
"last-save-synced": "Last save synced for {game}.",
|
||||
"last-state-synced": "Last state synced for {game}.",
|
||||
"latest-version": "Latest",
|
||||
"launch-extracting-archive": "Unpacking the archive",
|
||||
"launch-extracting-pkg": "Installing the game files",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Play, then save in-game. It syncs back when the session ends.",
|
||||
"save-data-note": "Restored to the console before launch. Load it from the game's own menu.",
|
||||
"save-data-synced": "Synced",
|
||||
"save-not-synced": "Your last save has not reached the server. It is kept in this browser and will sync the next time you play this game.",
|
||||
"save-not-synced": "Your last save has not reached the server yet. It is kept in this browser and RomM keeps retrying in the background.",
|
||||
"save-progress-to": "Save progress to",
|
||||
"save-slot": "Save slot",
|
||||
"save-state": "Save state",
|
||||
"save-sync-refused": "The server refused the save held for {game}: {reason}. It is no longer kept in this browser.",
|
||||
"select-background-color": "Select background color",
|
||||
"select-save": "Select save",
|
||||
"select-state": "Select state",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} version | {count} versions",
|
||||
"start-fresh-hint": "Pick one below to resume, or hit Play to start fresh.",
|
||||
"state-incompatible-core": "Saved with {emulator}, which the selected core cannot load.",
|
||||
"state-not-synced": "Your last state has not reached the server yet. It is kept in this browser and RomM keeps retrying in the background.",
|
||||
"state-sync-refused": "The server refused the state held for {game}: {reason}. It is no longer kept in this browser.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Buscar",
|
||||
"select": "Seleccionar",
|
||||
"select-platform": "Seleccionar plataforma",
|
||||
"server-offline-retrying": "Se perdió la conexión con el servidor · reintentando…",
|
||||
"server-offline-retrying": "Se perdió la conexión con el servidor, reintentando…",
|
||||
"server-reconnected": "Conexión con el servidor restablecida",
|
||||
"server-stats": "Estadísticas del servidor",
|
||||
"settings": "Ajustes",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "¿Salir sin guardar el progreso reciente?",
|
||||
"keep-playing": "Seguir jugando",
|
||||
"last-save-synced": "Se ha sincronizado la última partida guardada de {game}.",
|
||||
"last-state-synced": "Se ha sincronizado el último estado de {game}.",
|
||||
"latest-version": "Más reciente",
|
||||
"launch-extracting-archive": "Extrayendo el archivo",
|
||||
"launch-extracting-pkg": "Instalando los archivos del juego",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Juega y guarda dentro del juego. Se sincronizará al terminar la sesión.",
|
||||
"save-data-note": "Restaurado en la consola antes de iniciar. Cárgalo desde el menú del propio juego.",
|
||||
"save-data-synced": "Sincronizado",
|
||||
"save-not-synced": "Tu última partida guardada no ha llegado al servidor. Se conserva en este navegador y se sincronizará la próxima vez que juegues a este juego.",
|
||||
"save-not-synced": "Tu última partida guardada aún no ha llegado al servidor. Se conserva en este navegador y RomM sigue reintentándolo en segundo plano.",
|
||||
"save-progress-to": "Guardar progreso en",
|
||||
"save-slot": "Ranura de guardado",
|
||||
"save-state": "Guardar estado",
|
||||
"save-sync-refused": "El servidor ha rechazado la partida guardada que se conservaba de {game}: {reason}. Ya no se conserva en este navegador.",
|
||||
"select-background-color": "Seleccionar color de fondo",
|
||||
"select-save": "Seleccionar guardado",
|
||||
"select-state": "Seleccionar estado",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} versión | {count} versiones",
|
||||
"start-fresh-hint": "Empezar desde cero — sin partidas guardadas.",
|
||||
"state-incompatible-core": "Guardado con {emulator}, que el core seleccionado no puede cargar.",
|
||||
"state-not-synced": "Tu último estado aún no ha llegado al servidor. Se conserva en este navegador y RomM sigue reintentándolo en segundo plano.",
|
||||
"state-sync-refused": "El servidor ha rechazado el estado que se conservaba de {game}: {reason}. Ya no se conserva en este navegador.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Rechercher",
|
||||
"select": "Sélectionner",
|
||||
"select-platform": "Sélectionner une plateforme",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Connexion au serveur perdue, nouvelle tentative…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Statistiques du serveur",
|
||||
"settings": "Paramètres",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Quitter sans enregistrer la progression récente ?",
|
||||
"keep-playing": "Continuer à jouer",
|
||||
"last-save-synced": "Dernière sauvegarde de {game} synchronisée.",
|
||||
"last-state-synced": "Dernier état de {game} synchronisé.",
|
||||
"latest-version": "Dernière",
|
||||
"launch-extracting-archive": "Extraction de l'archive",
|
||||
"launch-extracting-pkg": "Installation des fichiers du jeu",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Jouez, puis sauvegardez dans le jeu. La synchronisation se fait à la fin de la session.",
|
||||
"save-data-note": "Restauré sur la console avant le lancement. Chargez-le depuis le menu du jeu.",
|
||||
"save-data-synced": "Synchronisé",
|
||||
"save-not-synced": "Votre dernière sauvegarde n'est pas parvenue au serveur. Elle est conservée dans ce navigateur et sera synchronisée la prochaine fois que vous jouerez à ce jeu.",
|
||||
"save-not-synced": "Votre dernière sauvegarde n'est pas encore parvenue au serveur. Elle est conservée dans ce navigateur et RomM continue d'essayer en arrière-plan.",
|
||||
"save-progress-to": "Enregistrer la progression dans",
|
||||
"save-slot": "Emplacement de sauvegarde",
|
||||
"save-state": "Sauvegarder l'état",
|
||||
"save-sync-refused": "Le serveur a refusé la sauvegarde conservée pour {game} : {reason}. Elle n'est plus conservée dans ce navigateur.",
|
||||
"select-background-color": "Sélectionner la couleur d'arrière-plan",
|
||||
"select-save": "Sélectionner la sauvegarde",
|
||||
"select-state": "Sélectionner l'état",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} version | {count} versions",
|
||||
"start-fresh-hint": "Choisissez-en un ci-dessous pour reprendre, ou appuyez sur Jouer pour démarrer une nouvelle partie.",
|
||||
"state-incompatible-core": "Sauvegardé avec {emulator}, que le cœur sélectionné ne peut pas charger.",
|
||||
"state-not-synced": "Votre dernier état n'est pas encore parvenu au serveur. Il est conservé dans ce navigateur et RomM continue d'essayer en arrière-plan.",
|
||||
"state-sync-refused": "Le serveur a refusé l'état conservé pour {game} : {reason}. Il n'est plus conservé dans ce navigateur.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Keresés",
|
||||
"select": "Kiválasztás",
|
||||
"select-platform": "Válassz platformot",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "A kiszolgálókapcsolat megszakadt, újrapróbálkozás…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Szerver statisztika",
|
||||
"settings": "Beállítások",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Kilépés a legutóbbi előrehaladás mentése nélkül?",
|
||||
"keep-playing": "Játék folytatása",
|
||||
"last-save-synced": "A(z) {game} legutóbbi mentése szinkronizálva.",
|
||||
"last-state-synced": "A(z) {game} legutóbbi állása szinkronizálva.",
|
||||
"latest-version": "Legújabb",
|
||||
"launch-extracting-archive": "Archívum kicsomagolása",
|
||||
"launch-extracting-pkg": "Játékfájlok telepítése",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Játssz, majd ments a játékon belül. A munkamenet végén szinkronizálódik.",
|
||||
"save-data-note": "Indítás előtt visszaállítva a konzolra. Töltsd be a játék saját menüjéből.",
|
||||
"save-data-synced": "Szinkronizálva",
|
||||
"save-not-synced": "A legutóbbi mentésed nem jutott el a kiszolgálóra. Ebben a böngészőben tárolódik, és a játék következő indításakor szinkronizálódik.",
|
||||
"save-not-synced": "A legutóbbi mentésed még nem jutott el a kiszolgálóra. Ebben a böngészőben tárolódik, és a RomM a háttérben tovább próbálkozik.",
|
||||
"save-progress-to": "Haladás mentése ide",
|
||||
"save-slot": "Mentési hely",
|
||||
"save-state": "Állapot mentése",
|
||||
"save-sync-refused": "A kiszolgáló elutasította a(z) {game} megőrzött mentését: {reason}. Már nem tárolódik ebben a böngészőben.",
|
||||
"select-background-color": "Háttérszín kiválasztása",
|
||||
"select-save": "Mentés kiválasztása",
|
||||
"select-state": "Állás kiválasztása",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} verzió | {count} verzió",
|
||||
"start-fresh-hint": "Válassz egyet az alábbiak közül a folytatáshoz, vagy nyomd meg az Indítást egy új játékhoz.",
|
||||
"state-incompatible-core": "{emulator} emulátorral mentve, amit a kiválasztott mag nem tud betölteni.",
|
||||
"state-not-synced": "A legutóbbi állásod még nem jutott el a kiszolgálóra. Ebben a böngészőben tárolódik, és a RomM a háttérben tovább próbálkozik.",
|
||||
"state-sync-refused": "A kiszolgáló elutasította a(z) {game} megőrzött állását: {reason}. Már nem tárolódik ebben a böngészőben.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Cerca",
|
||||
"select": "Seleziona",
|
||||
"select-platform": "Seleziona una piattaforma",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Connessione al server persa, nuovo tentativo…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Statistiche del server",
|
||||
"settings": "Impostazioni",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Uscire senza salvare i progressi recenti?",
|
||||
"keep-playing": "Continua a giocare",
|
||||
"last-save-synced": "Ultimo salvataggio di {game} sincronizzato.",
|
||||
"last-state-synced": "Ultimo stato di {game} sincronizzato.",
|
||||
"latest-version": "Più recente",
|
||||
"launch-extracting-archive": "Estrazione dell'archivio",
|
||||
"launch-extracting-pkg": "Installazione dei file di gioco",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Gioca e salva dentro il gioco. Verrà sincronizzato al termine della sessione.",
|
||||
"save-data-note": "Ripristinato sulla console prima dell'avvio. Caricalo dal menu del gioco.",
|
||||
"save-data-synced": "Sincronizzato",
|
||||
"save-not-synced": "Il tuo ultimo salvataggio non è arrivato al server. Viene conservato in questo browser e verrà sincronizzato la prossima volta che giocherai a questo gioco.",
|
||||
"save-not-synced": "Il tuo ultimo salvataggio non è ancora arrivato al server. Viene conservato in questo browser e RomM continua a riprovare in background.",
|
||||
"save-progress-to": "Salva i progressi in",
|
||||
"save-slot": "Slot di salvataggio",
|
||||
"save-state": "Salva stato",
|
||||
"save-sync-refused": "Il server ha rifiutato il salvataggio conservato per {game}: {reason}. Non è più conservato in questo browser.",
|
||||
"select-background-color": "Seleziona colore di sfondo",
|
||||
"select-save": "Seleziona Salvataggio",
|
||||
"select-state": "Seleziona Stato",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} versione | {count} versioni",
|
||||
"start-fresh-hint": "Scegline uno qui sotto per riprendere, oppure premi Gioca per iniziare da capo.",
|
||||
"state-incompatible-core": "Salvato con {emulator}, che il core selezionato non può caricare.",
|
||||
"state-not-synced": "Il tuo ultimo stato non è ancora arrivato al server. Viene conservato in questo browser e RomM continua a riprovare in background.",
|
||||
"state-sync-refused": "Il server ha rifiutato lo stato conservato per {game}: {reason}. Non è più conservato in questo browser.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "検索",
|
||||
"select": "選択",
|
||||
"select-platform": "プラットフォームを選択",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "サーバーとの接続が切れました、再試行中…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "サーバーステータス",
|
||||
"settings": "設定",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "最近の進行状況を保存せずに終了しますか?",
|
||||
"keep-playing": "プレイを続ける",
|
||||
"last-save-synced": "{game} の最後のセーブデータを同期しました。",
|
||||
"last-state-synced": "{game} の最後のステートを同期しました。",
|
||||
"latest-version": "最新",
|
||||
"launch-extracting-archive": "アーカイブを展開しています",
|
||||
"launch-extracting-pkg": "ゲームファイルをインストールしています",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "プレイしてゲーム内でセーブしてください。セッション終了時に同期されます。",
|
||||
"save-data-note": "起動前に本体へ復元されます。ゲーム内のメニューから読み込んでください。",
|
||||
"save-data-synced": "同期済み",
|
||||
"save-not-synced": "最後のセーブデータはサーバーに届きませんでした。このブラウザーに保存されており、次にこのゲームをプレイしたときに同期されます。",
|
||||
"save-not-synced": "最後のセーブデータはまだサーバーに届いていません。このブラウザーに保存されており、RomM がバックグラウンドで再試行を続けます。",
|
||||
"save-progress-to": "進行状況の保存先",
|
||||
"save-slot": "セーブスロット",
|
||||
"save-state": "ステートをセーブ",
|
||||
"save-sync-refused": "サーバーが {game} の保存していたセーブデータを拒否しました: {reason}。このブラウザーには残りません。",
|
||||
"select-background-color": "背景色を選択",
|
||||
"select-save": "セーブデータを選択",
|
||||
"select-state": "ステートを選択",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count}件のバージョン | {count}件のバージョン",
|
||||
"start-fresh-hint": "下から選んで再開するか、Playを押して最初から始めてください。",
|
||||
"state-incompatible-core": "{emulator} で保存されたため、選択中のコアでは読み込めません。",
|
||||
"state-not-synced": "最後のステートはまだサーバーに届いていません。このブラウザーに保存されており、RomM がバックグラウンドで再試行を続けます。",
|
||||
"state-sync-refused": "サーバーが {game} の保存していたステートを拒否しました: {reason}。このブラウザーには残りません。",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "검색",
|
||||
"select": "선택",
|
||||
"select-platform": "플랫폼 선택",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "서버 연결이 끊어졌습니다, 다시 시도하는 중…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "서버 통계",
|
||||
"settings": "설정",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "최근 진행 상황을 저장하지 않고 종료하시겠습니까?",
|
||||
"keep-playing": "계속 플레이",
|
||||
"last-save-synced": "{game}의 마지막 저장 데이터를 동기화했습니다.",
|
||||
"last-state-synced": "{game}의 마지막 상태를 동기화했습니다.",
|
||||
"latest-version": "최신",
|
||||
"launch-extracting-archive": "아카이브 압축을 푸는 중",
|
||||
"launch-extracting-pkg": "게임 파일을 설치하는 중",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "플레이한 뒤 게임에서 저장하세요. 세션이 끝나면 동기화됩니다.",
|
||||
"save-data-note": "실행 전에 콘솔로 복원됩니다. 게임 자체 메뉴에서 불러오세요.",
|
||||
"save-data-synced": "동기화됨",
|
||||
"save-not-synced": "마지막 저장 데이터가 서버에 전달되지 않았습니다. 이 브라우저에 보관되며 다음에 이 게임을 플레이할 때 동기화됩니다.",
|
||||
"save-not-synced": "마지막 저장 데이터가 아직 서버에 전달되지 않았습니다. 이 브라우저에 보관되며 RomM이 백그라운드에서 계속 재시도합니다.",
|
||||
"save-progress-to": "진행 상황 저장 위치",
|
||||
"save-slot": "저장 슬롯",
|
||||
"save-state": "상태 저장",
|
||||
"save-sync-refused": "서버가 {game}의 보관 중이던 저장 데이터를 거부했습니다: {reason}. 이제 이 브라우저에 보관되지 않습니다.",
|
||||
"select-background-color": "배경색 선택",
|
||||
"select-save": "세이브 선택",
|
||||
"select-state": "상태 선택",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "버전 {count}개 | 버전 {count}개",
|
||||
"start-fresh-hint": "아래에서 하나를 선택하여 이어 하거나, 실행을 눌러 새로 시작하세요.",
|
||||
"state-incompatible-core": "{emulator}(으)로 저장되어 선택한 코어에서 불러올 수 없습니다.",
|
||||
"state-not-synced": "마지막 상태가 아직 서버에 전달되지 않았습니다. 이 브라우저에 보관되며 RomM이 백그라운드에서 계속 재시도합니다.",
|
||||
"state-sync-refused": "서버가 {game}의 보관 중이던 상태를 거부했습니다: {reason}. 이제 이 브라우저에 보관되지 않습니다.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Szukaj",
|
||||
"select": "Wybierz",
|
||||
"select-platform": "Wybierz platformę",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Utracono połączenie z serwerem, ponawianie…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Statystyki serwera",
|
||||
"settings": "Ustawienia",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Wyjść bez zapisywania ostatnich postępów?",
|
||||
"keep-playing": "Graj dalej",
|
||||
"last-save-synced": "Zsynchronizowano ostatni zapis gry {game}.",
|
||||
"last-state-synced": "Zsynchronizowano ostatni stan gry {game}.",
|
||||
"latest-version": "Najnowsza",
|
||||
"launch-extracting-archive": "Rozpakowywanie archiwum",
|
||||
"launch-extracting-pkg": "Instalowanie plików gry",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Zagraj i zapisz w grze. Synchronizacja nastąpi po zakończeniu sesji.",
|
||||
"save-data-note": "Przywrócone na konsolę przed uruchomieniem. Wczytaj je z menu samej gry.",
|
||||
"save-data-synced": "Zsynchronizowano",
|
||||
"save-not-synced": "Twój ostatni zapis nie dotarł na serwer. Jest przechowywany w tej przeglądarce i zostanie zsynchronizowany przy następnym uruchomieniu tej gry.",
|
||||
"save-not-synced": "Twój ostatni zapis jeszcze nie dotarł na serwer. Jest przechowywany w tej przeglądarce, a RomM ponawia próby w tle.",
|
||||
"save-progress-to": "Zapisuj postęp do",
|
||||
"save-slot": "Miejsce zapisu",
|
||||
"save-state": "Zapisz stan",
|
||||
"save-sync-refused": "Serwer odrzucił przechowywany zapis gry {game}: {reason}. Nie jest już przechowywany w tej przeglądarce.",
|
||||
"select-background-color": "Wybierz kolor tła",
|
||||
"select-save": "Wybierz zapis",
|
||||
"select-state": "Wybierz stan",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} wersja | {count} wersje | {count} wersji",
|
||||
"start-fresh-hint": "Wybierz jeden poniżej, aby wznowić, lub naciśnij Graj, aby zacząć od nowa.",
|
||||
"state-incompatible-core": "Zapisano w {emulator}, czego wybrany rdzeń nie może wczytać.",
|
||||
"state-not-synced": "Twój ostatni stan jeszcze nie dotarł na serwer. Jest przechowywany w tej przeglądarce, a RomM ponawia próby w tle.",
|
||||
"state-sync-refused": "Serwer odrzucił przechowywany stan gry {game}: {reason}. Nie jest już przechowywany w tej przeglądarce.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Buscar",
|
||||
"select": "Selecionar",
|
||||
"select-platform": "Selecione uma plataforma",
|
||||
"server-offline-retrying": "Conexão com o servidor perdida · tentando novamente…",
|
||||
"server-offline-retrying": "Conexão com o servidor perdida, tentando novamente…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Estatísticas do servidor",
|
||||
"settings": "Configurações",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Sair sem salvar o progresso recente?",
|
||||
"keep-playing": "Continuar jogando",
|
||||
"last-save-synced": "Último save de {game} sincronizado.",
|
||||
"last-state-synced": "Último state de {game} sincronizado.",
|
||||
"latest-version": "Mais recente",
|
||||
"launch-extracting-archive": "Extraindo o arquivo",
|
||||
"launch-extracting-pkg": "Instalando os arquivos do jogo",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Jogue e salve dentro do jogo. A sincronização acontece ao encerrar a sessão.",
|
||||
"save-data-note": "Restaurado no console antes de iniciar. Carregue pelo menu do próprio jogo.",
|
||||
"save-data-synced": "Sincronizado",
|
||||
"save-not-synced": "Seu último save não chegou ao servidor. Ele fica armazenado neste navegador e será sincronizado na próxima vez que você jogar este jogo.",
|
||||
"save-not-synced": "Seu último save ainda não chegou ao servidor. Ele fica guardado neste navegador e o RomM continua tentando em segundo plano.",
|
||||
"save-progress-to": "Salvar progresso em",
|
||||
"save-slot": "Slot de salvamento",
|
||||
"save-state": "Salvar estado",
|
||||
"save-sync-refused": "O servidor recusou o save que estava guardado de {game}: {reason}. Ele não fica mais neste navegador.",
|
||||
"select-background-color": "Selecionar cor de fundo",
|
||||
"select-save": "Selecionar save",
|
||||
"select-state": "Selecionar estado",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} versão | {count} versões",
|
||||
"start-fresh-hint": "Escolha um abaixo para retomar, ou clique em Jogar para começar do zero.",
|
||||
"state-incompatible-core": "Salvo com {emulator}, que o core selecionado não consegue carregar.",
|
||||
"state-not-synced": "Seu último state ainda não chegou ao servidor. Ele fica guardado neste navegador e o RomM continua tentando em segundo plano.",
|
||||
"state-sync-refused": "O servidor recusou o state que estava guardado de {game}: {reason}. Ele não fica mais neste navegador.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Căutare",
|
||||
"select": "Selectează",
|
||||
"select-platform": "Selectează o platformă",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Conexiunea la server s-a pierdut, se reîncearcă…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Statistici server",
|
||||
"settings": "Setări",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Ieși fără a salva progresul recent?",
|
||||
"keep-playing": "Continuă să joci",
|
||||
"last-save-synced": "Ultima salvare pentru {game} a fost sincronizată.",
|
||||
"last-state-synced": "Ultima stare pentru {game} a fost sincronizată.",
|
||||
"latest-version": "Cea mai recentă",
|
||||
"launch-extracting-archive": "Se dezarhivează arhiva",
|
||||
"launch-extracting-pkg": "Se instalează fișierele jocului",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Joacă, apoi salvează în joc. Se sincronizează la încheierea sesiunii.",
|
||||
"save-data-note": "Restaurat pe consolă înainte de lansare. Încarcă-l din meniul jocului.",
|
||||
"save-data-synced": "Sincronizat",
|
||||
"save-not-synced": "Ultima ta salvare nu a ajuns pe server. Este păstrată în acest browser și se va sincroniza data viitoare când joci acest joc.",
|
||||
"save-not-synced": "Ultima ta salvare încă nu a ajuns pe server. Este păstrată în acest browser, iar RomM încearcă în continuare în fundal.",
|
||||
"save-progress-to": "Salvează progresul în",
|
||||
"save-slot": "Slot de salvare",
|
||||
"save-state": "Salvează starea",
|
||||
"save-sync-refused": "Serverul a refuzat salvarea păstrată pentru {game}: {reason}. Nu mai este păstrată în acest browser.",
|
||||
"select-background-color": "Selectează culoarea de fundal",
|
||||
"select-save": "Selectează salvare",
|
||||
"select-state": "Selectează stare",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} versiune | {count} versiuni",
|
||||
"start-fresh-hint": "Alege una mai jos pentru a relua sau apasă Joacă pentru a începe de la zero.",
|
||||
"state-incompatible-core": "Salvat cu {emulator}, pe care nucleul selectat nu îl poate încărca.",
|
||||
"state-not-synced": "Ultima ta stare încă nu a ajuns pe server. Este păstrată în acest browser, iar RomM încearcă în continuare în fundal.",
|
||||
"state-sync-refused": "Serverul a refuzat starea păstrată pentru {game}: {reason}. Nu mai este păstrată în acest browser.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Поиск",
|
||||
"select": "Выбрать",
|
||||
"select-platform": "Выберите платформу",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "Соединение с сервером потеряно, повторная попытка…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "Статистика сервера",
|
||||
"settings": "Настройки",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Выйти, не сохраняя недавний прогресс?",
|
||||
"keep-playing": "Продолжить игру",
|
||||
"last-save-synced": "Последнее сохранение для {game} синхронизировано.",
|
||||
"last-state-synced": "Последнее состояние для {game} синхронизировано.",
|
||||
"latest-version": "Последняя",
|
||||
"launch-extracting-archive": "Распаковка архива",
|
||||
"launch-extracting-pkg": "Установка файлов игры",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Играйте и сохранитесь в игре. Синхронизация произойдёт в конце сеанса.",
|
||||
"save-data-note": "Восстановлено на консоль перед запуском. Загрузите его из меню самой игры.",
|
||||
"save-data-synced": "Синхронизировано",
|
||||
"save-not-synced": "Ваше последнее сохранение не дошло до сервера. Оно хранится в этом браузере и синхронизируется при следующем запуске этой игры.",
|
||||
"save-not-synced": "Ваше последнее сохранение ещё не дошло до сервера. Оно хранится в этом браузере, и RomM продолжает попытки в фоне.",
|
||||
"save-progress-to": "Сохранять прогресс в",
|
||||
"save-slot": "Слот сохранения",
|
||||
"save-state": "Сохранить состояние",
|
||||
"save-sync-refused": "Сервер отклонил сохранение, которое хранилось для {game}: {reason}. Оно больше не хранится в этом браузере.",
|
||||
"select-background-color": "Выбрать цвет фона",
|
||||
"select-save": "Выбрать сохранение",
|
||||
"select-state": "Выбрать состояние",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} версия | {count} версий",
|
||||
"start-fresh-hint": "Выберите одно из ниже, чтобы продолжить, или нажмите «Играть», чтобы начать заново.",
|
||||
"state-incompatible-core": "Сохранено в {emulator}, выбранное ядро не может его загрузить.",
|
||||
"state-not-synced": "Ваше последнее состояние ещё не дошло до сервера. Оно хранится в этом браузере, и RomM продолжает попытки в фоне.",
|
||||
"state-sync-refused": "Сервер отклонил состояние, которое хранилось для {game}: {reason}. Оно больше не хранится в этом браузере.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "Ara",
|
||||
"select": "Seç",
|
||||
"select-platform": "Platform seçin",
|
||||
"server-offline-retrying": "Sunucu bağlantısı kesildi · yeniden bağlanılıyor…",
|
||||
"server-offline-retrying": "Sunucu bağlantısı kesildi, yeniden bağlanılıyor…",
|
||||
"server-reconnected": "Sunucuya yeniden bağlanıldı",
|
||||
"server-stats": "Sunucu istatistikleri",
|
||||
"settings": "Ayarlar",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "Son ilerlemeyi kaydetmeden çıkılsın mı?",
|
||||
"keep-playing": "Oynamaya devam et",
|
||||
"last-save-synced": "{game} için son kayıt eşitlendi.",
|
||||
"last-state-synced": "{game} için son durum kaydı eşitlendi.",
|
||||
"latest-version": "En yeni",
|
||||
"launch-extracting-archive": "Arşiv çıkarılıyor",
|
||||
"launch-extracting-pkg": "Oyun dosyaları yükleniyor",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "Oyna, sonra oyun içinde kaydet. Oturum bitince eşitlenir.",
|
||||
"save-data-note": "Başlatmadan önce konsola geri yüklendi. Oyunun kendi menüsünden yükle.",
|
||||
"save-data-synced": "Eşitlendi",
|
||||
"save-not-synced": "Son kaydınız sunucuya ulaşmadı. Bu tarayıcıda saklanıyor ve bu oyunu bir sonraki oynayışınızda eşitlenecek.",
|
||||
"save-not-synced": "Son kaydınız sunucuya henüz ulaşmadı. Bu tarayıcıda saklanıyor ve RomM arka planda denemeye devam ediyor.",
|
||||
"save-progress-to": "İlerlemeyi şuraya kaydet",
|
||||
"save-slot": "Kayıt yuvası",
|
||||
"save-state": "Durumu kaydet",
|
||||
"save-sync-refused": "Sunucu {game} için saklanan kaydı reddetti: {reason}. Artık bu tarayıcıda saklanmıyor.",
|
||||
"select-background-color": "Arka plan rengi seç",
|
||||
"select-save": "Kayıt seç",
|
||||
"select-state": "Durum kaydı seç",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} sürüm | {count} sürüm",
|
||||
"start-fresh-hint": "Devam etmek için aşağıdan birini seçin veya baştan başlamak için Oyna'ya basın.",
|
||||
"state-incompatible-core": "{emulator} ile kaydedildi; seçili çekirdek bunu yükleyemez.",
|
||||
"state-not-synced": "Son durum kaydınız sunucuya henüz ulaşmadı. Bu tarayıcıda saklanıyor ve RomM arka planda denemeye devam ediyor.",
|
||||
"state-sync-refused": "Sunucu {game} için saklanan durum kaydını reddetti: {reason}. Artık bu tarayıcıda saklanmıyor.",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "搜索",
|
||||
"select": "选择",
|
||||
"select-platform": "选择平台",
|
||||
"server-offline-retrying": "与服务器的连接已断开 · 正在重试…",
|
||||
"server-offline-retrying": "与服务器的连接已断开,正在重试…",
|
||||
"server-reconnected": "已重新连接到服务器",
|
||||
"server-stats": "服务器状态",
|
||||
"settings": "设置",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "不保存最近的进度并退出吗?",
|
||||
"keep-playing": "继续游戏",
|
||||
"last-save-synced": "{game} 的最近存档已同步。",
|
||||
"last-state-synced": "{game} 的最近即时存档已同步。",
|
||||
"latest-version": "最新",
|
||||
"launch-extracting-archive": "正在解压压缩包",
|
||||
"launch-extracting-pkg": "正在安装游戏文件",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "先游玩,然后在游戏内存档。会话结束时会同步回来。",
|
||||
"save-data-note": "启动前已还原到主机。请从游戏自身的菜单中读取。",
|
||||
"save-data-synced": "已同步",
|
||||
"save-not-synced": "你最近的存档尚未上传到服务器。它保存在此浏览器中,下次游玩该游戏时会自动同步。",
|
||||
"save-not-synced": "你最近的存档还没有上传到服务器。它保存在此浏览器中,RomM 会在后台继续重试。",
|
||||
"save-progress-to": "进度保存到",
|
||||
"save-slot": "存档位",
|
||||
"save-state": "保存即时存档",
|
||||
"save-sync-refused": "服务器拒绝了 {game} 暂存的存档:{reason}。它已从此浏览器中移除。",
|
||||
"select-background-color": "选择背景颜色",
|
||||
"select-save": "选择存档",
|
||||
"select-state": "选择状态",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} 个版本 | {count} 个版本",
|
||||
"start-fresh-hint": "选择下方任一项继续,或点击开始从头开始。",
|
||||
"state-incompatible-core": "由 {emulator} 保存,所选核心无法加载。",
|
||||
"state-not-synced": "你最近的即时存档还没有上传到服务器。它保存在此浏览器中,RomM 会在后台继续重试。",
|
||||
"state-sync-refused": "服务器拒绝了 {game} 暂存的即时存档:{reason}。它已从此浏览器中移除。",
|
||||
"states-view": "状态视图",
|
||||
"states-view-grid": "网格",
|
||||
"states-view-list": "列表",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
"search": "搜尋",
|
||||
"select": "選擇",
|
||||
"select-platform": "選擇平台",
|
||||
"server-offline-retrying": "Server connection lost · retrying…",
|
||||
"server-offline-retrying": "與伺服器的連線已中斷,正在重試…",
|
||||
"server-reconnected": "Reconnected to the server",
|
||||
"server-stats": "伺服器狀態",
|
||||
"settings": "設定",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"jsdos-quit-without-saving": "不儲存最近的進度並退出嗎?",
|
||||
"keep-playing": "繼續遊戲",
|
||||
"last-save-synced": "{game} 的最近存檔已同步。",
|
||||
"last-state-synced": "{game} 的最近即時存檔已同步。",
|
||||
"latest-version": "最新",
|
||||
"launch-extracting-archive": "正在解壓縮封存檔",
|
||||
"launch-extracting-pkg": "正在安裝遊戲檔案",
|
||||
@@ -140,10 +141,11 @@
|
||||
"save-data-none-note": "先遊玩,然後在遊戲內存檔。工作階段結束時會同步回來。",
|
||||
"save-data-note": "啟動前已還原到主機。請從遊戲本身的選單中讀取。",
|
||||
"save-data-synced": "已同步",
|
||||
"save-not-synced": "你最近的存檔尚未上傳到伺服器。它保存在此瀏覽器中,下次遊玩該遊戲時會自動同步。",
|
||||
"save-not-synced": "你最近的存檔還沒有上傳到伺服器。它保存在此瀏覽器中,RomM 會在背景繼續重試。",
|
||||
"save-progress-to": "進度儲存至",
|
||||
"save-slot": "存檔格",
|
||||
"save-state": "儲存即時存檔",
|
||||
"save-sync-refused": "伺服器拒絕了 {game} 暫存的存檔:{reason}。它已從此瀏覽器中移除。",
|
||||
"select-background-color": "選擇背景顏色",
|
||||
"select-save": "選擇存檔",
|
||||
"select-state": "選擇即時存檔",
|
||||
@@ -160,6 +162,8 @@
|
||||
"slot-versions": "{count} 個版本 | {count} 個版本",
|
||||
"start-fresh-hint": "從下方選擇一項繼續遊玩,或按下 Play 重新開始。",
|
||||
"state-incompatible-core": "由 {emulator} 儲存,所選核心無法載入。",
|
||||
"state-not-synced": "你最近的即時存檔還沒有上傳到伺服器。它保存在此瀏覽器中,RomM 會在背景繼續重試。",
|
||||
"state-sync-refused": "伺服器拒絕了 {game} 暫存的即時存檔:{reason}。它已從此瀏覽器中移除。",
|
||||
"states-view": "State view",
|
||||
"states-view-grid": "Grid",
|
||||
"states-view-list": "List",
|
||||
|
||||
@@ -9,6 +9,19 @@ import { buildFormInput } from "@/utils/formData";
|
||||
|
||||
export const stateApi = api;
|
||||
|
||||
/** States are named after the ROM and the moment the core was serialized. */
|
||||
export function sessionStateName(
|
||||
rom: { fs_name_no_ext: string },
|
||||
capturedAt: Date,
|
||||
): string {
|
||||
const timestamp = capturedAt
|
||||
.toISOString()
|
||||
.replace(/[:.]/g, "-")
|
||||
.replace("T", " ")
|
||||
.replace("Z", "");
|
||||
return `${rom.fs_name_no_ext.trim()} [${timestamp}]`;
|
||||
}
|
||||
|
||||
type StateUploadInput = Omit<AddStateInput, "stateFile" | "screenshotFile"> & {
|
||||
stateFile: File;
|
||||
screenshotFile?: File;
|
||||
|
||||
321
frontend/src/services/pending-asset.test.ts
Normal file
321
frontend/src/services/pending-asset.test.ts
Normal file
@@ -0,0 +1,321 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import pendingAssetStore, {
|
||||
hasPendingAssets,
|
||||
pendingAssetId,
|
||||
pendingAssetKinds,
|
||||
syncPendingAssets,
|
||||
type PendingAsset,
|
||||
} from "@/services/pending-asset";
|
||||
|
||||
const romApiMocks = vi.hoisted(() => ({ getRom: vi.fn() }));
|
||||
const saveApiMocks = vi.hoisted(() => ({ uploadSaves: vi.fn() }));
|
||||
const stateApiMocks = vi.hoisted(() => ({ uploadStates: vi.fn() }));
|
||||
|
||||
vi.mock("@/services/api/rom", () => ({ default: romApiMocks }));
|
||||
vi.mock("@/services/api/save", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/services/api/save")>()),
|
||||
default: saveApiMocks,
|
||||
}));
|
||||
vi.mock("@/services/api/state", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/services/api/state")>()),
|
||||
default: stateApiMocks,
|
||||
}));
|
||||
|
||||
// happy-dom ships no IndexedDB, which is also what a locked-down origin or a
|
||||
// private window looks like. Losing the frame must never cost the player a save.
|
||||
describe("pendingAssetStore without IndexedDB", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("lists nothing rather than throwing", async () => {
|
||||
await expect(pendingAssetStore.list()).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("swallows a write", async () => {
|
||||
await expect(
|
||||
pendingAssetStore.write({
|
||||
id: "1:a",
|
||||
kind: "save",
|
||||
romId: 1,
|
||||
romName: "Game",
|
||||
bytes: new Uint8Array([1, 2, 3]).buffer,
|
||||
capturedAt: 0,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("swallows a clear", async () => {
|
||||
await expect(pendingAssetStore.clear("1:a")).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("reports nothing as held", async () => {
|
||||
await expect(pendingAssetKinds(1)).resolves.toEqual(new Set());
|
||||
});
|
||||
|
||||
it("has nothing to hand over", async () => {
|
||||
await expect(syncPendingAssets()).resolves.toEqual({
|
||||
synced: [],
|
||||
dropped: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("pendingAssetId", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("keys a capture to its rom", () => {
|
||||
expect(pendingAssetId(7)).toMatch(/^7:.+/);
|
||||
});
|
||||
|
||||
// RomM served over plain http on a LAN address is not a secure context, and
|
||||
// there `crypto.randomUUID` does not exist at all (#4610).
|
||||
it("still hands out distinct ids without randomUUID", () => {
|
||||
vi.stubGlobal("crypto", {});
|
||||
|
||||
const first = pendingAssetId(7);
|
||||
const second = pendingAssetId(7);
|
||||
|
||||
expect(first).toMatch(/^7:.+/);
|
||||
expect(second).not.toBe(first);
|
||||
});
|
||||
});
|
||||
|
||||
// The sliver of IndexedDB the store uses, in memory, so the retry itself can
|
||||
// be exercised rather than only its unavailable-storage fallback.
|
||||
function installFakeIndexedDB(rows: Map<string, PendingAsset>) {
|
||||
function request(result?: unknown) {
|
||||
const req: Record<string, unknown> = { result };
|
||||
queueMicrotask(() => (req.onsuccess as (() => void) | undefined)?.());
|
||||
return req;
|
||||
}
|
||||
const objectStore = {
|
||||
getAll: () => request([...rows.values()]),
|
||||
put: (entry: PendingAsset) => {
|
||||
rows.set(entry.id, entry);
|
||||
return request();
|
||||
},
|
||||
delete: (id: string) => {
|
||||
rows.delete(id);
|
||||
return request();
|
||||
},
|
||||
};
|
||||
const db = {
|
||||
objectStoreNames: [] as string[],
|
||||
createObjectStore: () => objectStore,
|
||||
deleteObjectStore: () => undefined,
|
||||
close: () => undefined,
|
||||
transaction: () => {
|
||||
const transaction: Record<string, unknown> = {
|
||||
objectStore: () => objectStore,
|
||||
error: null,
|
||||
};
|
||||
queueMicrotask(() =>
|
||||
(transaction.oncomplete as (() => void) | undefined)?.(),
|
||||
);
|
||||
return transaction;
|
||||
},
|
||||
};
|
||||
vi.stubGlobal("indexedDB", {
|
||||
open: () => {
|
||||
const req: Record<string, unknown> = { result: db };
|
||||
queueMicrotask(() => {
|
||||
(req.onupgradeneeded as (() => void) | undefined)?.();
|
||||
(req.onsuccess as (() => void) | undefined)?.();
|
||||
});
|
||||
return req;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// What axios hands back: a status only when the server answered at all.
|
||||
function refusal(status?: number, detail?: string) {
|
||||
return Object.assign(new Error(`Request failed with status code ${status}`), {
|
||||
isAxiosError: true,
|
||||
response:
|
||||
status === undefined
|
||||
? undefined
|
||||
: { status, statusText: `HTTP ${status}`, data: { detail } },
|
||||
});
|
||||
}
|
||||
|
||||
describe("syncPendingAssets", () => {
|
||||
let rows: Map<string, PendingAsset>;
|
||||
const bytes = new Uint8Array([1, 2, 3]).buffer;
|
||||
const shot = new Uint8Array([9, 9]).buffer;
|
||||
|
||||
// The ids are unique per test: a row the server has taken is remembered for
|
||||
// the lifetime of the module, which is what stops it syncing twice.
|
||||
function queue(entry: Partial<PendingAsset> & { id: string }) {
|
||||
const row: PendingAsset = {
|
||||
kind: "save",
|
||||
romId: 1,
|
||||
romName: "Held Game",
|
||||
bytes,
|
||||
capturedAt: Date.parse("2024-05-06T07:08:09.010Z"),
|
||||
...entry,
|
||||
};
|
||||
rows.set(row.id, row);
|
||||
return row;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
rows = new Map();
|
||||
installFakeIndexedDB(rows);
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
romApiMocks.getRom.mockResolvedValue({
|
||||
data: {
|
||||
id: 1,
|
||||
name: "Game",
|
||||
fs_name_no_ext: "game",
|
||||
path_cover_small: "cover.png",
|
||||
},
|
||||
});
|
||||
saveApiMocks.uploadSaves.mockResolvedValue([{ status: "fulfilled" }]);
|
||||
stateApiMocks.uploadStates.mockResolvedValue([{ status: "fulfilled" }]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
romApiMocks.getRom.mockReset();
|
||||
saveApiMocks.uploadSaves.mockReset();
|
||||
stateApiMocks.uploadStates.mockReset();
|
||||
});
|
||||
|
||||
it("hands a held save to the slot it was written for", async () => {
|
||||
queue({ id: "save:taken", slot: "main_quest", screenshotBytes: shot });
|
||||
|
||||
await expect(syncPendingAssets()).resolves.toEqual({
|
||||
synced: [{ kind: "save", romId: 1, name: "Game", cover: "cover.png" }],
|
||||
dropped: [],
|
||||
});
|
||||
|
||||
const request = saveApiMocks.uploadSaves.mock.calls[0][0];
|
||||
expect(request).toMatchObject({
|
||||
slot: "main_quest",
|
||||
autocleanup: false,
|
||||
overwrite: false,
|
||||
});
|
||||
expect(request.savesToUpload[0].screenshotFile.name).toBe("game.png");
|
||||
expect(rows.size).toBe(0);
|
||||
});
|
||||
|
||||
it("hands a held state over under the name of its capture", async () => {
|
||||
queue({ id: "state:taken", kind: "state", screenshotBytes: shot });
|
||||
|
||||
await expect(syncPendingAssets()).resolves.toEqual({
|
||||
synced: [{ kind: "state", romId: 1, name: "Game", cover: "cover.png" }],
|
||||
dropped: [],
|
||||
});
|
||||
|
||||
const { statesToUpload } = stateApiMocks.uploadStates.mock.calls[0][0];
|
||||
expect(statesToUpload[0].stateFile.name).toBe(
|
||||
"game [2024-05-06 07-08-09-010].state",
|
||||
);
|
||||
expect(statesToUpload[0].screenshotFile.name).toBe(
|
||||
"game [2024-05-06 07-08-09-010].png",
|
||||
);
|
||||
expect(rows.size).toBe(0);
|
||||
});
|
||||
|
||||
// A server that is down or failing has not judged the asset, so it keeps it.
|
||||
it.each([
|
||||
["no response at all", refusal(undefined)],
|
||||
["a server that is failing", refusal(500)],
|
||||
["a session that has expired", refusal(401)],
|
||||
])("holds on through %s", async (_label, reason) => {
|
||||
stateApiMocks.uploadStates.mockResolvedValue([
|
||||
{ status: "rejected", reason },
|
||||
]);
|
||||
queue({ id: `state:kept:${Math.random()}`, kind: "state" });
|
||||
|
||||
await expect(syncPendingAssets()).resolves.toMatchObject({
|
||||
synced: [],
|
||||
dropped: [],
|
||||
});
|
||||
|
||||
expect(rows.size).toBe(1);
|
||||
await expect(hasPendingAssets()).resolves.toBe(true);
|
||||
});
|
||||
|
||||
// Retrying a refusal for the rest of time would only nag the player about
|
||||
// progress that is never going through.
|
||||
it("drops what the server refused for good and says why", async () => {
|
||||
stateApiMocks.uploadStates.mockResolvedValue([
|
||||
{ status: "rejected", reason: refusal(409, "Slot has a newer save") },
|
||||
]);
|
||||
queue({ id: "state:refused", kind: "state" });
|
||||
|
||||
await expect(syncPendingAssets()).resolves.toEqual({
|
||||
synced: [],
|
||||
dropped: [
|
||||
{
|
||||
kind: "state",
|
||||
romId: 1,
|
||||
name: "Game",
|
||||
cover: "cover.png",
|
||||
reason: "Slot has a newer save",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(rows.size).toBe(0);
|
||||
await expect(hasPendingAssets()).resolves.toBe(false);
|
||||
});
|
||||
|
||||
// The rom is gone, so the name stored with the row is all there is to go on.
|
||||
it("names a game the server no longer knows from the row itself", async () => {
|
||||
romApiMocks.getRom.mockRejectedValue(refusal(404, "Rom not found"));
|
||||
queue({ id: "save:orphan" });
|
||||
|
||||
await expect(syncPendingAssets()).resolves.toMatchObject({
|
||||
dropped: [{ name: "Held Game", reason: "Rom not found" }],
|
||||
});
|
||||
|
||||
expect(rows.size).toBe(0);
|
||||
});
|
||||
|
||||
it("drops a row that holds no bytes rather than uploading nothing", async () => {
|
||||
queue({ id: "save:empty", bytes: new ArrayBuffer(0) });
|
||||
|
||||
await expect(syncPendingAssets()).resolves.toEqual({
|
||||
synced: [],
|
||||
dropped: [],
|
||||
});
|
||||
|
||||
expect(saveApiMocks.uploadSaves).not.toHaveBeenCalled();
|
||||
expect(rows.size).toBe(0);
|
||||
});
|
||||
|
||||
// A running session owns its own save, so the caller can ask for the rest.
|
||||
it("hands over only the kinds it was asked for", async () => {
|
||||
queue({ id: "save:not-asked" });
|
||||
queue({ id: "state:asked", kind: "state" });
|
||||
|
||||
await expect(syncPendingAssets(["state"])).resolves.toMatchObject({
|
||||
synced: [{ kind: "state" }],
|
||||
});
|
||||
|
||||
expect(saveApiMocks.uploadSaves).not.toHaveBeenCalled();
|
||||
expect([...rows.keys()]).toEqual(["save:not-asked"]);
|
||||
});
|
||||
|
||||
it("reports both kinds a rom is still owed", async () => {
|
||||
queue({ id: "save:held" });
|
||||
queue({ id: "state:held", kind: "state" });
|
||||
queue({ id: "other-rom:held", romId: 2 });
|
||||
|
||||
await expect(pendingAssetKinds(1)).resolves.toEqual(
|
||||
new Set(["save", "state"]),
|
||||
);
|
||||
await expect(pendingAssetKinds(2)).resolves.toEqual(new Set(["save"]));
|
||||
await expect(pendingAssetKinds(3)).resolves.toEqual(new Set());
|
||||
});
|
||||
});
|
||||
317
frontend/src/services/pending-asset.ts
Normal file
317
frontend/src/services/pending-asset.ts
Normal file
@@ -0,0 +1,317 @@
|
||||
// Saves and states the server has not accepted yet, held in the browser with
|
||||
// the frame captured at the moment the game wrote them. A sync that fails
|
||||
// offline would otherwise lose that frame and picture a later moment on the
|
||||
// retry, and a closed tab would lose the progress outright.
|
||||
import axios from "axios";
|
||||
import type { DetailedRomSchema } from "@/__generated__";
|
||||
import romApi from "@/services/api/rom";
|
||||
import saveApi, { AUTOSAVE_SLOT, sessionSaveFile } from "@/services/api/save";
|
||||
import stateApi, { sessionStateName } from "@/services/api/state";
|
||||
|
||||
const DB_NAME = "romm-player";
|
||||
// A row cannot be rekeyed or reshaped in place, so every upgrade rebuilds the
|
||||
// store rather than migrating it.
|
||||
const DB_VERSION = 3;
|
||||
const STORE_NAME = "pending-assets";
|
||||
|
||||
export type PendingAssetKind = "save" | "state";
|
||||
|
||||
export interface PendingAsset {
|
||||
/** One row per capture, so two offline sessions cannot overwrite each other. */
|
||||
id: string;
|
||||
kind: PendingAssetKind;
|
||||
romId: number;
|
||||
/** Named at capture time, so a rom the server no longer has can still be announced. */
|
||||
romName: string;
|
||||
bytes: ArrayBuffer;
|
||||
screenshotBytes?: ArrayBuffer;
|
||||
/** Saves only: the slot the session was writing to. */
|
||||
slot?: string;
|
||||
emulator?: string;
|
||||
/** Saves only: the device the session was playing on. */
|
||||
deviceId?: string;
|
||||
capturedAt: number;
|
||||
}
|
||||
|
||||
// `crypto.randomUUID` needs a secure context and RomM is often served over
|
||||
// plain http on a LAN address. The id only has to be unique within a browser.
|
||||
function randomToken(): string {
|
||||
const webCrypto = globalThis.crypto;
|
||||
if (typeof webCrypto?.randomUUID === "function")
|
||||
return webCrypto.randomUUID();
|
||||
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
/** A key of its own for one capture, so no other can write over it. */
|
||||
export function pendingAssetId(romId: number): string {
|
||||
return `${romId}:${randomToken()}`;
|
||||
}
|
||||
|
||||
export interface PendingAssetStore {
|
||||
list(): Promise<PendingAsset[]>;
|
||||
write(entry: PendingAsset): Promise<void>;
|
||||
clear(id: string): Promise<void>;
|
||||
}
|
||||
|
||||
function openDatabase(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
for (const name of Array.from(db.objectStoreNames)) {
|
||||
db.deleteObjectStore(name);
|
||||
}
|
||||
db.createObjectStore(STORE_NAME, { keyPath: "id" });
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
// Storage is a best effort: a private window, a blocked origin or a failed
|
||||
// upgrade must cost the player nothing, so every path resolves to null.
|
||||
async function withStore<T>(
|
||||
mode: IDBTransactionMode,
|
||||
run: (store: IDBObjectStore) => IDBRequest,
|
||||
): Promise<T | null> {
|
||||
if (typeof indexedDB === "undefined") return null;
|
||||
|
||||
let db: IDBDatabase;
|
||||
try {
|
||||
db = await openDatabase();
|
||||
} catch (error) {
|
||||
console.error("Pending asset storage unavailable", error);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await new Promise<T>((resolve, reject) => {
|
||||
const transaction = db.transaction(STORE_NAME, mode);
|
||||
const request = run(transaction.objectStore(STORE_NAME));
|
||||
// A delete that resolves on the request alone can still be rolled back,
|
||||
// which is how a row survives its own removal and syncs forever.
|
||||
transaction.oncomplete = () => resolve(request.result as T);
|
||||
transaction.onabort = () => reject(transaction.error);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Pending asset storage failed", error);
|
||||
return null;
|
||||
} finally {
|
||||
// The connection closes once the transaction above commits.
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
const pendingAssetStore: PendingAssetStore = {
|
||||
async list() {
|
||||
return (
|
||||
(await withStore<PendingAsset[]>("readonly", (store) =>
|
||||
store.getAll(),
|
||||
)) ?? []
|
||||
);
|
||||
},
|
||||
async write(entry) {
|
||||
await withStore("readwrite", (store) => store.put(entry));
|
||||
},
|
||||
async clear(id) {
|
||||
await withStore("readwrite", (store) => store.delete(id));
|
||||
},
|
||||
};
|
||||
|
||||
export default pendingAssetStore;
|
||||
|
||||
/** What the browser is still holding for a rom, save and state apart. */
|
||||
export async function pendingAssetKinds(
|
||||
romId: number,
|
||||
): Promise<Set<PendingAssetKind>> {
|
||||
const entries = await pendingAssetStore.list();
|
||||
return new Set(
|
||||
entries
|
||||
.filter((entry) => entry.romId === romId && !accepted.has(entry.id))
|
||||
.map((entry) => entry.kind),
|
||||
);
|
||||
}
|
||||
|
||||
// Rows the server has taken. A delete that does not stick would otherwise have
|
||||
// this upload the same progress again on the next pass, and again after that.
|
||||
const accepted = new Set<string>();
|
||||
|
||||
async function uploadSave(
|
||||
entry: PendingAsset,
|
||||
rom: DetailedRomSchema,
|
||||
): Promise<PromiseSettledResult<unknown> | undefined> {
|
||||
const slot = entry.slot ?? AUTOSAVE_SLOT;
|
||||
const uploaded = await saveApi.uploadSaves({
|
||||
rom,
|
||||
emulator: entry.emulator,
|
||||
deviceId: entry.deviceId,
|
||||
slot,
|
||||
autocleanup: slot === AUTOSAVE_SLOT,
|
||||
// The dedupe is the point: a retry of bytes the server already has must
|
||||
// return that version, not mint another one.
|
||||
overwrite: false,
|
||||
savesToUpload: [
|
||||
{
|
||||
saveFile: sessionSaveFile(rom, null, entry.bytes),
|
||||
screenshotFile: entry.screenshotBytes
|
||||
? new File(
|
||||
[entry.screenshotBytes],
|
||||
`${rom.fs_name_no_ext.trim()}.png`,
|
||||
{ type: "application/octet-stream" },
|
||||
)
|
||||
: undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
return uploaded[0];
|
||||
}
|
||||
|
||||
async function uploadState(
|
||||
entry: PendingAsset,
|
||||
rom: DetailedRomSchema,
|
||||
): Promise<PromiseSettledResult<unknown> | undefined> {
|
||||
// The backend files a state under the row already at that name, so pinning
|
||||
// the name to the capture has a retry update it rather than duplicate it.
|
||||
const name = sessionStateName(rom, new Date(entry.capturedAt));
|
||||
const uploaded = await stateApi.uploadStates({
|
||||
rom,
|
||||
emulator: entry.emulator,
|
||||
statesToUpload: [
|
||||
{
|
||||
stateFile: new File([entry.bytes], `${name}.state`, {
|
||||
type: "application/octet-stream",
|
||||
}),
|
||||
screenshotFile: entry.screenshotBytes
|
||||
? new File([entry.screenshotBytes], `${name}.png`, {
|
||||
type: "application/octet-stream",
|
||||
})
|
||||
: undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
return uploaded[0];
|
||||
}
|
||||
|
||||
// A server that is failing, a network that is down and an expired session all
|
||||
// deserve another pass; anything else the server answers with is its verdict.
|
||||
const RETRYABLE_STATUSES = new Set([401, 408, 425, 429]);
|
||||
|
||||
/**
|
||||
* Why the server refused this asset for good, if it did.
|
||||
*
|
||||
* Returns:
|
||||
* The reason to show the player, or null when the attempt is worth repeating.
|
||||
*/
|
||||
function permanentRefusal(error: unknown): string | null {
|
||||
if (!axios.isAxiosError(error) || !error.response) return null;
|
||||
const { status, statusText, data } = error.response;
|
||||
if (status >= 500 || RETRYABLE_STATUSES.has(status)) return null;
|
||||
const detail = data?.detail;
|
||||
return (typeof detail === "string" && detail) || statusText || error.message;
|
||||
}
|
||||
|
||||
interface AssetOutcome {
|
||||
asset: SyncedAsset;
|
||||
/** Set when the server refused it for good and the row was dropped. */
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
// A row the server has answered for is no longer owed, refused as much as
|
||||
// taken: holding a refusal back would only retry it for the rest of time.
|
||||
async function settle(
|
||||
entry: PendingAsset,
|
||||
rom: DetailedRomSchema | null,
|
||||
reason?: string,
|
||||
): Promise<AssetOutcome> {
|
||||
accepted.add(entry.id);
|
||||
await pendingAssetStore.clear(entry.id);
|
||||
return {
|
||||
asset: {
|
||||
kind: entry.kind,
|
||||
romId: entry.romId,
|
||||
name: rom?.name ?? rom?.fs_name_no_ext ?? entry.romName,
|
||||
cover: rom?.path_cover_small,
|
||||
},
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
async function uploadPendingAsset(
|
||||
entry: PendingAsset,
|
||||
): Promise<AssetOutcome | null> {
|
||||
if (accepted.has(entry.id)) return null;
|
||||
if (!entry.bytes?.byteLength) {
|
||||
await pendingAssetStore.clear(entry.id);
|
||||
return null;
|
||||
}
|
||||
|
||||
let rom: DetailedRomSchema | null = null;
|
||||
try {
|
||||
rom = (await romApi.getRom({ romId: entry.romId })).data;
|
||||
const upload =
|
||||
entry.kind === "state"
|
||||
? await uploadState(entry, rom)
|
||||
: await uploadSave(entry, rom);
|
||||
if (upload?.status === "fulfilled") return settle(entry, rom);
|
||||
|
||||
const refusal = permanentRefusal(
|
||||
upload?.status === "rejected" ? upload.reason : null,
|
||||
);
|
||||
return refusal ? settle(entry, rom, refusal) : null;
|
||||
} catch (error) {
|
||||
const refusal = permanentRefusal(error);
|
||||
if (refusal) return settle(entry, rom, refusal);
|
||||
console.error("Pending asset sync failed", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** An asset the server has just taken, named so the toast can say which game. */
|
||||
export interface SyncedAsset {
|
||||
kind: PendingAssetKind;
|
||||
romId: number;
|
||||
name: string;
|
||||
cover?: string | null;
|
||||
}
|
||||
|
||||
/** One the server refused for good, dropped rather than retried forever. */
|
||||
export interface DroppedAsset extends SyncedAsset {
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface PendingSyncResult {
|
||||
synced: SyncedAsset[];
|
||||
dropped: DroppedAsset[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the server what the browser is still holding.
|
||||
*
|
||||
* Args:
|
||||
* kinds: What to hand over, for a caller that owns one of them itself.
|
||||
*
|
||||
* Returns:
|
||||
* What the server took, so their views can refresh and say so, and what it
|
||||
* refused for good, so the player is told why it is gone.
|
||||
*/
|
||||
export async function syncPendingAssets(
|
||||
kinds: readonly PendingAssetKind[] = ["save", "state"],
|
||||
): Promise<PendingSyncResult> {
|
||||
const synced: SyncedAsset[] = [];
|
||||
const dropped: DroppedAsset[] = [];
|
||||
for (const entry of await pendingAssetStore.list()) {
|
||||
if (!kinds.includes(entry.kind)) continue;
|
||||
const outcome = await uploadPendingAsset(entry);
|
||||
if (!outcome) continue;
|
||||
if (outcome.reason === undefined) synced.push(outcome.asset);
|
||||
else dropped.push({ ...outcome.asset, reason: outcome.reason });
|
||||
}
|
||||
return { synced, dropped };
|
||||
}
|
||||
|
||||
/** Whether anything is still owed, ignoring rows a delete failed to remove. */
|
||||
export async function hasPendingAssets(): Promise<boolean> {
|
||||
const entries = await pendingAssetStore.list();
|
||||
return entries.some((entry) => !accepted.has(entry.id));
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import pendingSaveStore, {
|
||||
pendingSaveRomIds,
|
||||
syncPendingSaves,
|
||||
} from "@/services/pending-save";
|
||||
|
||||
// happy-dom ships no IndexedDB, which is also what a locked-down origin or a
|
||||
// private window looks like. Losing the frame must never cost the player a save.
|
||||
describe("pendingSaveStore without IndexedDB", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("lists nothing rather than throwing", async () => {
|
||||
await expect(pendingSaveStore.list()).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
it("swallows a write", async () => {
|
||||
await expect(
|
||||
pendingSaveStore.write({
|
||||
id: "1:a",
|
||||
romId: 1,
|
||||
saveBytes: new Uint8Array([1, 2, 3]).buffer,
|
||||
capturedAt: 0,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("swallows a clear", async () => {
|
||||
await expect(pendingSaveStore.clear("1:a")).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("reports no rom as held when nothing is stored", async () => {
|
||||
await expect(pendingSaveRomIds()).resolves.toEqual(new Set());
|
||||
});
|
||||
|
||||
it("has nothing to hand over", async () => {
|
||||
await expect(syncPendingSaves()).resolves.toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,187 +0,0 @@
|
||||
// Saves the server has not accepted yet, held in the browser with the frame
|
||||
// captured at the moment the game wrote them. A sync that fails offline would
|
||||
// otherwise lose that frame and picture a later moment on the retry, and a
|
||||
// closed tab would lose the progress outright.
|
||||
import romApi from "@/services/api/rom";
|
||||
import saveApi, { AUTOSAVE_SLOT, sessionSaveFile } from "@/services/api/save";
|
||||
|
||||
const DB_NAME = "romm-player";
|
||||
// v2 rekeyed the store from the rom to the playing session. An upgrade cannot
|
||||
// rewrite keys in place, and a row carrying the old key can never be deleted by
|
||||
// the new one, so the store is rebuilt rather than migrated.
|
||||
const DB_VERSION = 2;
|
||||
const STORE_NAME = "pending-saves";
|
||||
|
||||
export interface PendingSave {
|
||||
/** One row per playing session, so two offline sessions cannot overwrite each other. */
|
||||
id: string;
|
||||
romId: number;
|
||||
saveBytes: ArrayBuffer;
|
||||
screenshotBytes?: ArrayBuffer;
|
||||
slot?: string;
|
||||
emulator?: string;
|
||||
deviceId?: string;
|
||||
capturedAt: number;
|
||||
}
|
||||
|
||||
export interface PendingSaveStore {
|
||||
list(): Promise<PendingSave[]>;
|
||||
write(entry: PendingSave): Promise<void>;
|
||||
clear(id: string): Promise<void>;
|
||||
}
|
||||
|
||||
function openDatabase(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
request.onupgradeneeded = () => {
|
||||
const db = request.result;
|
||||
if (db.objectStoreNames.contains(STORE_NAME)) {
|
||||
db.deleteObjectStore(STORE_NAME);
|
||||
}
|
||||
db.createObjectStore(STORE_NAME, { keyPath: "id" });
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
// Storage is a best effort: a private window, a blocked origin or a failed
|
||||
// upgrade must cost the player nothing, so every path resolves to null.
|
||||
async function withStore<T>(
|
||||
mode: IDBTransactionMode,
|
||||
run: (store: IDBObjectStore) => IDBRequest,
|
||||
): Promise<T | null> {
|
||||
if (typeof indexedDB === "undefined") return null;
|
||||
|
||||
let db: IDBDatabase;
|
||||
try {
|
||||
db = await openDatabase();
|
||||
} catch (error) {
|
||||
console.error("Pending save storage unavailable", error);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await new Promise<T>((resolve, reject) => {
|
||||
const transaction = db.transaction(STORE_NAME, mode);
|
||||
const request = run(transaction.objectStore(STORE_NAME));
|
||||
// A delete that resolves on the request alone can still be rolled back,
|
||||
// which is how a row survives its own removal and syncs forever.
|
||||
transaction.oncomplete = () => resolve(request.result as T);
|
||||
transaction.onabort = () => reject(transaction.error);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Pending save storage failed", error);
|
||||
return null;
|
||||
} finally {
|
||||
// The connection closes once the transaction above commits.
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
const pendingSaveStore: PendingSaveStore = {
|
||||
async list() {
|
||||
return (
|
||||
(await withStore<PendingSave[]>("readonly", (store) => store.getAll())) ??
|
||||
[]
|
||||
);
|
||||
},
|
||||
async write(entry) {
|
||||
await withStore("readwrite", (store) => store.put(entry));
|
||||
},
|
||||
async clear(id) {
|
||||
await withStore("readwrite", (store) => store.delete(id));
|
||||
},
|
||||
};
|
||||
|
||||
export default pendingSaveStore;
|
||||
|
||||
/** The rom ids the browser is still holding progress for. */
|
||||
export async function pendingSaveRomIds(): Promise<Set<number>> {
|
||||
const entries = await pendingSaveStore.list();
|
||||
return new Set(
|
||||
entries.filter((e) => !accepted.has(e.id)).map((entry) => entry.romId),
|
||||
);
|
||||
}
|
||||
|
||||
// Rows the server has taken. A delete that does not stick would otherwise have
|
||||
// this upload the same progress again on the next pass, and again after that.
|
||||
const accepted = new Set<string>();
|
||||
|
||||
async function uploadPendingSave(
|
||||
entry: PendingSave,
|
||||
): Promise<SyncedSave | null> {
|
||||
if (accepted.has(entry.id)) return null;
|
||||
if (!entry.saveBytes?.byteLength) {
|
||||
await pendingSaveStore.clear(entry.id);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const { data: rom } = await romApi.getRom({ romId: entry.romId });
|
||||
const slot = entry.slot ?? AUTOSAVE_SLOT;
|
||||
const uploaded = await saveApi.uploadSaves({
|
||||
rom,
|
||||
emulator: entry.emulator,
|
||||
deviceId: entry.deviceId,
|
||||
slot,
|
||||
autocleanup: slot === AUTOSAVE_SLOT,
|
||||
// The dedupe is the point: a retry of bytes the server already has must
|
||||
// return that version, not mint another one.
|
||||
overwrite: false,
|
||||
savesToUpload: [
|
||||
{
|
||||
saveFile: sessionSaveFile(rom, null, entry.saveBytes),
|
||||
screenshotFile: entry.screenshotBytes
|
||||
? new File(
|
||||
[entry.screenshotBytes],
|
||||
`${rom.fs_name_no_ext.trim()}.png`,
|
||||
{ type: "application/octet-stream" },
|
||||
)
|
||||
: undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (uploaded[0]?.status !== "fulfilled") return null;
|
||||
accepted.add(entry.id);
|
||||
await pendingSaveStore.clear(entry.id);
|
||||
return {
|
||||
romId: entry.romId,
|
||||
name: rom.name ?? rom.fs_name_no_ext,
|
||||
cover: rom.path_cover_small,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Pending save sync failed", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A save the server has just taken, named so the toast can say which game. */
|
||||
export interface SyncedSave {
|
||||
romId: number;
|
||||
name: string;
|
||||
cover?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the server everything the browser is still holding.
|
||||
*
|
||||
* Returns:
|
||||
* The saves the server took, so their views can refresh and say so.
|
||||
*/
|
||||
export async function syncPendingSaves(): Promise<SyncedSave[]> {
|
||||
const synced: SyncedSave[] = [];
|
||||
for (const entry of await pendingSaveStore.list()) {
|
||||
const result = await uploadPendingSave(entry);
|
||||
if (result) synced.push(result);
|
||||
}
|
||||
return synced;
|
||||
}
|
||||
|
||||
/** Whether anything is still owed, ignoring rows a delete failed to remove. */
|
||||
export async function hasPendingSaves(): Promise<boolean> {
|
||||
const entries = await pendingSaveStore.list();
|
||||
return entries.some((entry) => !accepted.has(entry.id));
|
||||
}
|
||||
104
frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts
Normal file
104
frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ref } from "vue";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import BackendStatusBanner from "./BackendStatusBanner.vue";
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
const isOffline = ref(false);
|
||||
vi.mock("@/v2/composables/useServerConnection", () => ({
|
||||
useServerConnection: () => ({ isOffline, retryNow: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@v2/lib", () => ({
|
||||
RBtn: { name: "RBtn", template: "<button><slot /></button>" },
|
||||
RIcon: { name: "RIcon", template: "<i />" },
|
||||
RTooltip: {
|
||||
name: "RTooltip",
|
||||
props: ["text", "activator", "location"],
|
||||
template: "<span class='r-tooltip-stub' />",
|
||||
},
|
||||
}));
|
||||
|
||||
let wrapper: ReturnType<typeof mount> | null = null;
|
||||
|
||||
async function render() {
|
||||
wrapper = mount(BackendStatusBanner);
|
||||
await wrapper.vm.$nextTick();
|
||||
}
|
||||
|
||||
const banner = () => wrapper!.find(".r-backend-banner");
|
||||
const body = () => wrapper!.find(".r-backend-banner__body");
|
||||
|
||||
describe("BackendStatusBanner", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
vi.useFakeTimers();
|
||||
isOffline.value = false;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
wrapper?.unmount();
|
||||
wrapper = null;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("stays out of sight while the server answers", async () => {
|
||||
await render();
|
||||
|
||||
expect(banner().exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("offers the retry button outside a game", async () => {
|
||||
isOffline.value = true;
|
||||
|
||||
await render();
|
||||
|
||||
expect(banner().classes()).not.toContain("r-backend-banner--in-game");
|
||||
expect(wrapper!.find(".r-backend-banner__retry").exists()).toBe(true);
|
||||
// The message is right there to read, so nothing hovers over it.
|
||||
expect(banner().attributes("title")).toBeUndefined();
|
||||
expect(wrapper!.find(".r-tooltip-stub").exists()).toBe(false);
|
||||
});
|
||||
|
||||
// A notice the player cannot dismiss has no business sitting over the game.
|
||||
it("shrinks to its icon once a game has been running a while", async () => {
|
||||
isOffline.value = true;
|
||||
storePlaying().setPlaying(true);
|
||||
|
||||
await render();
|
||||
expect(banner().classes()).toContain("r-backend-banner--in-game");
|
||||
expect(body().exists()).toBe(true);
|
||||
expect(wrapper!.find(".r-backend-banner__retry").exists()).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(6000);
|
||||
await wrapper!.vm.$nextTick();
|
||||
|
||||
expect(body().exists()).toBe(false);
|
||||
expect(banner().classes()).toContain("r-backend-banner--collapsed");
|
||||
// Only the icon is left, so the message moves into a tooltip of our own.
|
||||
expect(banner().attributes("title")).toBeUndefined();
|
||||
expect(wrapper!.find(".r-tooltip-stub").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("says its piece again in full once the game is over", async () => {
|
||||
isOffline.value = true;
|
||||
const playing = storePlaying();
|
||||
playing.setPlaying(true);
|
||||
|
||||
await render();
|
||||
await vi.advanceTimersByTimeAsync(6000);
|
||||
await wrapper!.vm.$nextTick();
|
||||
expect(body().exists()).toBe(false);
|
||||
|
||||
playing.setPlaying(false);
|
||||
await wrapper!.vm.$nextTick();
|
||||
|
||||
expect(body().exists()).toBe(true);
|
||||
expect(wrapper!.find(".r-backend-banner__retry").exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -11,36 +11,89 @@
|
||||
// poll / passive DOM-event listeners / recovery watcher (idempotent). This
|
||||
// component is mounted once, under `v-if="isV2"` in RomM.vue, so it covers both
|
||||
// the auth and main shells.
|
||||
import { RBtn, RIcon } from "@v2/lib";
|
||||
import { RBtn, RIcon, RTooltip } from "@v2/lib";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import { useServerConnection } from "@/v2/composables/useServerConnection";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
// Long enough to read before the notice gets out of the way of the game.
|
||||
const COLLAPSE_MS = 6000;
|
||||
|
||||
const { t } = useI18n();
|
||||
const { isOffline, retryNow } = useServerConnection();
|
||||
const { playing } = storeToRefs(storePlaying());
|
||||
|
||||
// A notice that cannot be dismissed has no business sitting over a running
|
||||
// game, so it says its piece and then shrinks to its icon.
|
||||
const collapsed = ref(false);
|
||||
let collapseTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function stopCollapsing() {
|
||||
if (collapseTimer === null) return;
|
||||
clearTimeout(collapseTimer);
|
||||
collapseTimer = null;
|
||||
}
|
||||
|
||||
watch(
|
||||
[isOffline, playing],
|
||||
([offline, inGame]) => {
|
||||
stopCollapsing();
|
||||
collapsed.value = false;
|
||||
if (!offline || !inGame) return;
|
||||
collapseTimer = setTimeout(() => (collapsed.value = true), COLLAPSE_MS);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(stopCollapsing);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Transition name="r-backend-banner">
|
||||
<div v-if="isOffline" class="r-backend-banner" role="alert">
|
||||
<div
|
||||
v-if="isOffline"
|
||||
class="r-backend-banner"
|
||||
:class="{
|
||||
'r-backend-banner--in-game': playing,
|
||||
'r-backend-banner--collapsed': collapsed,
|
||||
}"
|
||||
role="alert"
|
||||
:aria-label="collapsed ? t('common.server-offline-retrying') : undefined"
|
||||
>
|
||||
<!-- Shrunk to its icon, so the message still has to be readable. -->
|
||||
<RTooltip
|
||||
v-if="collapsed"
|
||||
activator="parent"
|
||||
location="bottom start"
|
||||
open-on-tap
|
||||
:text="t('common.server-offline-retrying')"
|
||||
/>
|
||||
<RIcon
|
||||
icon="mdi-lan-disconnect"
|
||||
size="18"
|
||||
class="r-backend-banner__icon"
|
||||
/>
|
||||
<span class="r-backend-banner__msg">
|
||||
{{ t("common.server-offline-retrying") }}
|
||||
</span>
|
||||
<RBtn
|
||||
size="small"
|
||||
variant="text"
|
||||
prepend-icon="mdi-refresh"
|
||||
class="r-backend-banner__retry"
|
||||
@click="retryNow"
|
||||
>
|
||||
{{ t("common.try-again") }}
|
||||
</RBtn>
|
||||
<Transition name="r-backend-banner-body">
|
||||
<div v-if="!collapsed" class="r-backend-banner__body">
|
||||
<span class="r-backend-banner__msg">
|
||||
{{ t("common.server-offline-retrying") }}
|
||||
</span>
|
||||
<RBtn
|
||||
v-if="!playing"
|
||||
size="small"
|
||||
variant="text"
|
||||
prepend-icon="mdi-refresh"
|
||||
class="r-backend-banner__retry"
|
||||
@click="retryNow"
|
||||
>
|
||||
{{ t("common.try-again") }}
|
||||
</RBtn>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</Transition>
|
||||
</template>
|
||||
@@ -79,11 +132,40 @@ const { isOffline, retryNow } = useServerConnection();
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* A running game owns the screen, so the notice takes the corner the player
|
||||
already puts its own messages in and leaves the middle of the screen alone. */
|
||||
.r-backend-banner--in-game {
|
||||
top: 16px;
|
||||
left: 16px;
|
||||
right: auto;
|
||||
transform: none;
|
||||
max-width: min(420px, calc(100vw - 32px));
|
||||
/* The retry button is what pads the right edge out; without it the text
|
||||
needs the same room the icon gets. */
|
||||
padding: 8px 14px;
|
||||
}
|
||||
|
||||
.r-backend-banner--in-game .r-backend-banner__body {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.r-backend-banner--collapsed {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.r-backend-banner__icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--r-color-danger-fg);
|
||||
}
|
||||
|
||||
.r-backend-banner__body {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.r-backend-banner__msg {
|
||||
min-width: 0;
|
||||
}
|
||||
@@ -105,6 +187,24 @@ const { isOffline, retryNow } = useServerConnection();
|
||||
opacity: 0;
|
||||
transform: translate(-50%, -12px);
|
||||
}
|
||||
.r-backend-banner--in-game.r-backend-banner-enter-from,
|
||||
.r-backend-banner--in-game.r-backend-banner-leave-to {
|
||||
transform: translateY(-12px);
|
||||
}
|
||||
|
||||
/* Collapsing to the icon: the text slides shut rather than blinking out. */
|
||||
.r-backend-banner-body-enter-active,
|
||||
.r-backend-banner-body-leave-active {
|
||||
transition:
|
||||
opacity var(--r-motion-med) var(--r-motion-ease-out),
|
||||
max-width var(--r-motion-med) var(--r-motion-ease-out);
|
||||
max-width: 420px;
|
||||
}
|
||||
.r-backend-banner-body-enter-from,
|
||||
.r-backend-banner-body-leave-to {
|
||||
opacity: 0;
|
||||
max-width: 0;
|
||||
}
|
||||
|
||||
/* On phones keep it centred but allow the safe full width. */
|
||||
html[data-bp~="xs"] .r-backend-banner {
|
||||
@@ -118,4 +218,10 @@ html[data-bp~="xs"] .r-backend-banner-enter-from,
|
||||
html[data-bp~="xs"] .r-backend-banner-leave-to {
|
||||
transform: translateY(-12px);
|
||||
}
|
||||
html[data-bp~="xs"] .r-backend-banner--in-game {
|
||||
left: 12px;
|
||||
right: auto;
|
||||
max-width: calc(100vw - 24px);
|
||||
justify-content: flex-start;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -23,6 +23,8 @@ type Toast = {
|
||||
msg: string;
|
||||
icon?: string;
|
||||
image?: string | null;
|
||||
/** Artwork the browser could not load, so the tone's icon stands in. */
|
||||
imageBroken?: boolean;
|
||||
tone: ToastTone;
|
||||
timer?: number;
|
||||
};
|
||||
@@ -83,46 +85,59 @@ function dismiss(id: number) {
|
||||
|
||||
const openHandler = (snackbar: SnackbarStatus) => push(snackbar);
|
||||
emitter?.on("snackbarShow", openHandler);
|
||||
|
||||
// A fullscreen element is the only thing the browser paints, so the host moves
|
||||
// inside it: a player that took the screen still gets to show its notices.
|
||||
const fullscreenHost = ref<HTMLElement | null>(null);
|
||||
function trackFullscreen() {
|
||||
fullscreenHost.value = document.fullscreenElement as HTMLElement | null;
|
||||
}
|
||||
document.addEventListener("fullscreenchange", trackFullscreen);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
emitter?.off("snackbarShow", openHandler);
|
||||
document.removeEventListener("fullscreenchange", trackFullscreen);
|
||||
toasts.value.forEach((t) => t.timer && window.clearTimeout(t.timer));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="r-v2-toasts" role="status" aria-live="polite">
|
||||
<transition-group name="r-v2-toast">
|
||||
<div
|
||||
v-for="toast in toasts"
|
||||
:key="toast.id"
|
||||
class="r-v2-toast"
|
||||
:class="[`r-v2-toast--${toast.tone}`]"
|
||||
role="alert"
|
||||
>
|
||||
<img
|
||||
v-if="toast.image"
|
||||
:src="toast.image"
|
||||
alt=""
|
||||
class="r-v2-toast__art"
|
||||
/>
|
||||
<RIcon
|
||||
v-else-if="toast.icon"
|
||||
:icon="toast.icon"
|
||||
size="18"
|
||||
class="r-v2-toast__icon"
|
||||
/>
|
||||
<span class="r-v2-toast__msg">{{ toast.msg }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="r-v2-toast__close"
|
||||
:aria-label="t('common.dismiss')"
|
||||
@click="dismiss(toast.id)"
|
||||
<Teleport :to="fullscreenHost ?? 'body'" :disabled="!fullscreenHost">
|
||||
<div class="r-v2-toasts" role="status" aria-live="polite">
|
||||
<transition-group name="r-v2-toast">
|
||||
<div
|
||||
v-for="toast in toasts"
|
||||
:key="toast.id"
|
||||
class="r-v2-toast"
|
||||
:class="[`r-v2-toast--${toast.tone}`]"
|
||||
role="alert"
|
||||
>
|
||||
<RIcon icon="mdi-close" size="14" />
|
||||
</button>
|
||||
</div>
|
||||
</transition-group>
|
||||
</div>
|
||||
<img
|
||||
v-if="toast.image && !toast.imageBroken"
|
||||
:src="toast.image"
|
||||
alt=""
|
||||
class="r-v2-toast__art"
|
||||
@error="toast.imageBroken = true"
|
||||
/>
|
||||
<RIcon
|
||||
v-else-if="toast.icon"
|
||||
:icon="toast.icon"
|
||||
size="18"
|
||||
class="r-v2-toast__icon"
|
||||
/>
|
||||
<span class="r-v2-toast__msg">{{ toast.msg }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="r-v2-toast__close"
|
||||
:aria-label="t('common.dismiss')"
|
||||
@click="dismiss(toast.id)"
|
||||
>
|
||||
<RIcon icon="mdi-close" size="14" />
|
||||
</button>
|
||||
</div>
|
||||
</transition-group>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
import type { Meta, StoryObj } from "@storybook/vue3-vite";
|
||||
import type { SaveSchema, StateSchema } from "@/__generated__";
|
||||
import AssetCard from "./AssetCard.vue";
|
||||
|
||||
// Helper builders — avoid spamming the same shape into every story.
|
||||
function makeSave(overrides: Partial<SaveSchema> = {}): SaveSchema {
|
||||
return {
|
||||
id: 1,
|
||||
rom_id: 1,
|
||||
user_id: 1,
|
||||
file_name: "super_mario_world_slot1.srm",
|
||||
file_name_no_tags: "super_mario_world_slot1.srm",
|
||||
file_name_no_ext: "super_mario_world_slot1",
|
||||
file_extension: "srm",
|
||||
file_path: "/saves/snes",
|
||||
file_size_bytes: 8192,
|
||||
full_path: "/saves/snes/super_mario_world_slot1.srm",
|
||||
download_path: "/api/saves/1/content",
|
||||
missing_from_fs: false,
|
||||
created_at: "2026-03-14T10:12:00Z",
|
||||
updated_at: "2026-05-10T18:45:00Z",
|
||||
emulator: "snes9x",
|
||||
slot: "slot1",
|
||||
screenshot: null,
|
||||
...overrides,
|
||||
} as SaveSchema;
|
||||
}
|
||||
|
||||
function makeState(overrides: Partial<StateSchema> = {}): StateSchema {
|
||||
return {
|
||||
id: 1,
|
||||
rom_id: 1,
|
||||
user_id: 1,
|
||||
file_name: "chrono_trigger_quicksave.state",
|
||||
file_name_no_tags: "chrono_trigger_quicksave.state",
|
||||
file_name_no_ext: "chrono_trigger_quicksave",
|
||||
file_extension: "state",
|
||||
file_path: "/states/snes",
|
||||
file_size_bytes: 524288,
|
||||
full_path: "/states/snes/chrono_trigger_quicksave.state",
|
||||
download_path: "/api/states/1/content",
|
||||
missing_from_fs: false,
|
||||
created_at: "2026-04-02T09:00:00Z",
|
||||
updated_at: "2026-05-13T22:08:00Z",
|
||||
emulator: "snes9x",
|
||||
screenshot: {
|
||||
id: 1,
|
||||
rom_id: 1,
|
||||
user_id: 1,
|
||||
file_name: "chrono_trigger_quicksave.png",
|
||||
file_name_no_tags: "chrono_trigger_quicksave.png",
|
||||
file_name_no_ext: "chrono_trigger_quicksave",
|
||||
file_extension: "png",
|
||||
file_path: "/screenshots/snes",
|
||||
// Use a placeholder cover so the story renders something
|
||||
// recognisable in the 16:9 slot.
|
||||
download_path:
|
||||
"https://placehold.co/640x360/2d2147/ffffff?text=Quicksave",
|
||||
} as StateSchema["screenshot"],
|
||||
...overrides,
|
||||
} as StateSchema;
|
||||
}
|
||||
|
||||
const meta: Meta<typeof AssetCard> = {
|
||||
title: "Media/AssetCard",
|
||||
component: AssetCard,
|
||||
argTypes: {
|
||||
type: { control: "inline-radio", options: ["save", "state"] },
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof AssetCard>;
|
||||
|
||||
// ── Save (no screenshot) ────────────────────────────────────────
|
||||
|
||||
export const Save: Story = {
|
||||
render: () => ({
|
||||
components: { AssetCard },
|
||||
setup: () => ({ asset: makeSave() }),
|
||||
template: `
|
||||
<div style="width:200px">
|
||||
<AssetCard :asset="asset" type="save" />
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
|
||||
// ── Save without emulator chip ─────────────────────────────────
|
||||
|
||||
export const SaveNoEmulator: Story = {
|
||||
name: "Save (no emulator)",
|
||||
render: () => ({
|
||||
components: { AssetCard },
|
||||
setup: () => ({ asset: makeSave({ emulator: null }) }),
|
||||
template: `
|
||||
<div style="width:200px">
|
||||
<AssetCard :asset="asset" type="save" />
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
|
||||
// ── State (with screenshot) ─────────────────────────────────────
|
||||
|
||||
export const State: Story = {
|
||||
render: () => ({
|
||||
components: { AssetCard },
|
||||
setup: () => ({ asset: makeState() }),
|
||||
template: `
|
||||
<div style="width:240px">
|
||||
<AssetCard :asset="asset" type="state" />
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
|
||||
// ── State without a screenshot (placeholder pattern) ────────────
|
||||
|
||||
export const StateNoScreenshot: Story = {
|
||||
name: "State (placeholder screenshot)",
|
||||
render: () => ({
|
||||
components: { AssetCard },
|
||||
setup: () => ({
|
||||
asset: makeState({
|
||||
file_name: "earthbound_save_4.state",
|
||||
screenshot: null,
|
||||
}),
|
||||
}),
|
||||
template: `
|
||||
<div style="width:240px">
|
||||
<AssetCard :asset="asset" type="state" />
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
|
||||
// ── Long filename — ellipsis path ──────────────────────────────
|
||||
|
||||
export const LongFilename: Story = {
|
||||
name: "Long filename",
|
||||
render: () => ({
|
||||
components: { AssetCard },
|
||||
setup: () => ({
|
||||
asset: makeSave({
|
||||
file_name:
|
||||
"the_legend_of_zelda_a_link_to_the_past_speedrun_attempt_27.srm",
|
||||
file_size_bytes: 64 * 1024,
|
||||
}),
|
||||
}),
|
||||
template: `
|
||||
<div style="width:200px">
|
||||
<AssetCard :asset="asset" type="save" />
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
|
||||
// ── Grid layout (real picker context) ──────────────────────────
|
||||
|
||||
export const Grid: Story = {
|
||||
name: "Grid (picker layout)",
|
||||
render: () => ({
|
||||
components: { AssetCard },
|
||||
setup: () => {
|
||||
const states: StateSchema[] = [
|
||||
makeState({ id: 1, file_name: "chrono_trigger_1.state" }),
|
||||
makeState({
|
||||
id: 2,
|
||||
file_name: "chrono_trigger_2.state",
|
||||
screenshot: {
|
||||
...(makeState().screenshot as NonNullable<
|
||||
StateSchema["screenshot"]
|
||||
>),
|
||||
download_path:
|
||||
"https://placehold.co/640x360/1a3d2e/ffffff?text=Forest+Save",
|
||||
},
|
||||
}),
|
||||
makeState({
|
||||
id: 3,
|
||||
file_name: "chrono_trigger_3.state",
|
||||
emulator: null,
|
||||
screenshot: null,
|
||||
}),
|
||||
makeState({
|
||||
id: 4,
|
||||
file_name: "chrono_trigger_boss.state",
|
||||
file_size_bytes: 1 * 1024 * 1024,
|
||||
screenshot: {
|
||||
...(makeState().screenshot as NonNullable<
|
||||
StateSchema["screenshot"]
|
||||
>),
|
||||
download_path:
|
||||
"https://placehold.co/640x360/4a1a1a/ffffff?text=Boss+Fight",
|
||||
},
|
||||
}),
|
||||
];
|
||||
return { states };
|
||||
},
|
||||
template: `
|
||||
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;width:600px;padding:8px">
|
||||
<AssetCard v-for="s in states" :key="s.id" :asset="s" type="state" />
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
};
|
||||
@@ -1,160 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
// AssetCard (v2) — feature composite for the save/state pickers shown
|
||||
// before launching EmulatorJS. Renders a 16:9 screenshot (states),
|
||||
// filename, emulator + size chips, and a relative "updated" line.
|
||||
//
|
||||
// Lives in `components/Player/` because it knows about SaveSchema /
|
||||
// StateSchema — domain coupling means it can't be a /lib primitive.
|
||||
// Built from R primitives + shared utils; no Vuetify.
|
||||
import { RImg, RTag } from "@v2/lib";
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { SaveSchema, StateSchema } from "@/__generated__";
|
||||
import { formatBytes, formatRelativeDate, formatTimestamp } from "@/utils";
|
||||
import { getEmptyCoverImage } from "@/v2/utils/covers";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
export type AssetType = "save" | "state";
|
||||
|
||||
const props = defineProps<{
|
||||
asset: SaveSchema | StateSchema;
|
||||
type: AssetType;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
(e: "click", event: MouseEvent): void;
|
||||
}>();
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
|
||||
// Fall back to a placeholder keyed by the file name so identical
|
||||
// filenames render the same colour
|
||||
// — visual cue across the grid that two assets share a base name.
|
||||
const screenshotSrc = computed(() => {
|
||||
if (!("screenshot" in props.asset)) return null;
|
||||
return (
|
||||
props.asset.screenshot?.download_path ??
|
||||
getEmptyCoverImage(props.asset.file_name, 16 / 9)
|
||||
);
|
||||
});
|
||||
|
||||
const updatedText = computed(() =>
|
||||
formatTimestamp(props.asset.updated_at, locale.value),
|
||||
);
|
||||
|
||||
const relativeText = computed(() => formatRelativeDate(props.asset.updated_at));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article
|
||||
class="r-v2-asset-card"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:data-asset-type="type"
|
||||
@click="(e) => $emit('click', e)"
|
||||
@keydown.enter.prevent="(e) => $emit('click', e as unknown as MouseEvent)"
|
||||
@keydown.space.prevent="(e) => $emit('click', e as unknown as MouseEvent)"
|
||||
>
|
||||
<RImg
|
||||
v-if="screenshotSrc"
|
||||
:src="screenshotSrc"
|
||||
:alt="asset.file_name"
|
||||
aspect-ratio="16 / 9"
|
||||
cover
|
||||
class="r-v2-asset-card__screenshot"
|
||||
/>
|
||||
|
||||
<div class="r-v2-asset-card__body">
|
||||
<div class="r-v2-asset-card__name" :title="asset.file_name">
|
||||
{{ asset.file_name }}
|
||||
</div>
|
||||
|
||||
<div class="r-v2-asset-card__chips">
|
||||
<RTag
|
||||
v-if="'slot' in asset && asset.slot"
|
||||
tone="brand"
|
||||
size="x-small"
|
||||
prepend-icon="mdi-content-save-all-outline"
|
||||
:text="asset.slot"
|
||||
/>
|
||||
<RTag
|
||||
v-if="asset.emulator"
|
||||
tone="warning"
|
||||
size="x-small"
|
||||
:text="asset.emulator"
|
||||
/>
|
||||
<RTag size="x-small" :text="formatBytes(asset.file_size_bytes)" />
|
||||
</div>
|
||||
|
||||
<div class="r-v2-asset-card__meta">
|
||||
<span>{{ t("rom.updated") }}: {{ updatedText }}</span>
|
||||
<span class="r-v2-asset-card__relative">({{ relativeText }})</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-asset-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
background: var(--r-color-bg-elevated);
|
||||
border: 1px solid var(--r-color-border);
|
||||
border-radius: var(--r-radius-md);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color var(--r-motion-fast) var(--r-motion-ease-out),
|
||||
transform var(--r-motion-fast) var(--r-motion-ease-out),
|
||||
background var(--r-motion-fast) var(--r-motion-ease-out);
|
||||
user-select: none;
|
||||
}
|
||||
.r-v2-asset-card:hover {
|
||||
border-color: var(--r-color-border-strong);
|
||||
background: var(--r-color-surface);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.r-v2-asset-card:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.r-v2-asset-card__screenshot {
|
||||
border-radius: var(--r-radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.r-v2-asset-card__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 2px 2px 0;
|
||||
}
|
||||
|
||||
.r-v2-asset-card__name {
|
||||
font-size: 12px;
|
||||
font-weight: var(--r-font-weight-semibold);
|
||||
color: var(--r-color-brand-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.r-v2-asset-card__chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.r-v2-asset-card__meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
font-size: 11px;
|
||||
color: var(--r-color-fg-secondary);
|
||||
}
|
||||
.r-v2-asset-card__relative {
|
||||
color: var(--r-color-fg-muted);
|
||||
}
|
||||
</style>
|
||||
@@ -1,16 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
// v2 SelectSaveDialog — listens for `selectSaveDialog`, shows a grid of
|
||||
// the ROM's saves and emits `saveSelected` on click (consumed by the
|
||||
// EmulatorJS view).
|
||||
import { RBtn, RDialog, REmptyState } from "@v2/lib";
|
||||
// v2 SelectSaveDialog — listens for `selectSaveDialog`, lists the ROM's saves
|
||||
// and emits `saveSelected` on pick (consumed by the player). The list is the
|
||||
// launch screen's, so a save reads the same before the game boots and inside it.
|
||||
import { RBtn, RDialog } from "@v2/lib";
|
||||
import type { Emitter } from "mitt";
|
||||
import { inject, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { SaveSchema } from "@/__generated__";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import AssetCard from "@/v2/components/Player/AssetCard.vue";
|
||||
import AssetList from "@/v2/components/shared/AssetList.vue";
|
||||
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
|
||||
import type { Asset } from "@/v2/utils/assets";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
@@ -27,9 +28,8 @@ const openHandler = (selectedRom: DetailedRom) => {
|
||||
emitter?.on("selectSaveDialog", openHandler);
|
||||
onBeforeUnmount(() => emitter?.off("selectSaveDialog", openHandler));
|
||||
|
||||
function onCardClick(save: SaveSchema) {
|
||||
if (!save) return;
|
||||
emitter?.emit("saveSelected", save);
|
||||
function onSelect(asset: Asset) {
|
||||
emitter?.emit("saveSelected", asset as SaveSchema);
|
||||
closeDialog();
|
||||
}
|
||||
|
||||
@@ -53,20 +53,11 @@ function closeDialog() {
|
||||
<span>{{ t("play.select-save") }}</span>
|
||||
</template>
|
||||
<template #content>
|
||||
<div v-if="rom && rom.user_saves.length > 0" class="r-v2-save-picker">
|
||||
<AssetCard
|
||||
v-for="save in rom.user_saves"
|
||||
:key="save.id"
|
||||
:asset="save"
|
||||
type="save"
|
||||
class="r-v2-save-picker__item"
|
||||
@click="onCardClick(save)"
|
||||
/>
|
||||
</div>
|
||||
<REmptyState
|
||||
v-else
|
||||
icon="mdi-help-rhombus-outline"
|
||||
:title="t('rom.no-saves-found')"
|
||||
<AssetList
|
||||
:assets="rom?.user_saves ?? []"
|
||||
type="save"
|
||||
:scrollable="false"
|
||||
@select="onSelect"
|
||||
/>
|
||||
</template>
|
||||
<template #footer>
|
||||
@@ -77,16 +68,3 @@ function closeDialog() {
|
||||
</template>
|
||||
</RDialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-save-picker {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 12px;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.r-v2-save-picker__item {
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
// v2 SelectStateDialog — same pattern as SelectSaveDialog, but listens for
|
||||
// `selectStateDialog` and emits `stateSelected`.
|
||||
import { RBtn, RDialog, REmptyState } from "@v2/lib";
|
||||
// `selectStateDialog` and emits `stateSelected`. The list is the launch
|
||||
// screen's, so a state reads the same whether it is picked before the game
|
||||
// boots or from inside it.
|
||||
import { RBtn, RDialog } from "@v2/lib";
|
||||
import type { Emitter } from "mitt";
|
||||
import { inject, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { StateSchema } from "@/__generated__";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import AssetCard from "@/v2/components/Player/AssetCard.vue";
|
||||
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
|
||||
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
|
||||
import type { Asset } from "@/v2/utils/assets";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
@@ -26,9 +29,15 @@ const openHandler = (selectedRom: DetailedRom) => {
|
||||
emitter?.on("selectStateDialog", openHandler);
|
||||
onBeforeUnmount(() => emitter?.off("selectStateDialog", openHandler));
|
||||
|
||||
function onCardClick(state: StateSchema) {
|
||||
if (!state) return;
|
||||
emitter?.emit("stateSelected", state);
|
||||
// A state another core wrote stays listed, disabled, so the count adds up.
|
||||
function stateDisabledReason(asset: Asset) {
|
||||
const emulator = "emulator" in asset ? asset.emulator : null;
|
||||
if (!emulator || emulator === window.EJS_core) return null;
|
||||
return t("play.state-incompatible-core", { emulator });
|
||||
}
|
||||
|
||||
function onSelect(asset: Asset) {
|
||||
emitter?.emit("stateSelected", asset as StateSchema);
|
||||
closeDialog();
|
||||
}
|
||||
|
||||
@@ -52,20 +61,13 @@ function closeDialog() {
|
||||
<span>{{ t("play.select-state") }}</span>
|
||||
</template>
|
||||
<template #content>
|
||||
<div v-if="rom && rom.user_states.length > 0" class="r-v2-state-picker">
|
||||
<AssetCard
|
||||
v-for="state in rom.user_states"
|
||||
:key="state.id"
|
||||
:asset="state"
|
||||
type="state"
|
||||
class="r-v2-state-picker__item"
|
||||
@click="onCardClick(state)"
|
||||
/>
|
||||
</div>
|
||||
<REmptyState
|
||||
v-else
|
||||
icon="mdi-help-rhombus-outline"
|
||||
:title="t('rom.no-states-found')"
|
||||
<AssetStrip
|
||||
:assets="rom?.user_states ?? []"
|
||||
type="state"
|
||||
layout="flow"
|
||||
group-by="emulator"
|
||||
:disabled-reason="stateDisabledReason"
|
||||
@select="onSelect"
|
||||
/>
|
||||
</template>
|
||||
<template #footer>
|
||||
@@ -76,16 +78,3 @@ function closeDialog() {
|
||||
</template>
|
||||
</RDialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-state-picker {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 12px;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.r-v2-state-picker__item {
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
|
||||
248
frontend/src/v2/composables/usePendingAssetSync/index.test.ts
Normal file
248
frontend/src/v2/composables/usePendingAssetSync/index.test.ts
Normal file
@@ -0,0 +1,248 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent, nextTick, ref } from "vue";
|
||||
import type {
|
||||
PendingAssetKind,
|
||||
PendingSyncResult,
|
||||
} from "@/services/pending-asset";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import { installPendingAssetSync } from "./index";
|
||||
|
||||
type Entry = { id: string; romId: number; kind: PendingAssetKind };
|
||||
const queue = { entries: [] as Entry[] };
|
||||
// The server takes everything unless a test says otherwise.
|
||||
async function acceptAll(
|
||||
kinds: readonly PendingAssetKind[] = ["save", "state"],
|
||||
): Promise<PendingSyncResult> {
|
||||
const taken = queue.entries.filter((entry) => kinds.includes(entry.kind));
|
||||
queue.entries = queue.entries.filter((entry) => !kinds.includes(entry.kind));
|
||||
return {
|
||||
synced: taken.map((entry) => ({
|
||||
kind: entry.kind,
|
||||
romId: entry.romId,
|
||||
name: "Game",
|
||||
cover: null,
|
||||
})),
|
||||
dropped: [],
|
||||
};
|
||||
}
|
||||
const syncPendingAssets = vi.fn(acceptAll);
|
||||
|
||||
vi.mock("@/services/pending-asset", () => ({
|
||||
default: { list: async () => queue.entries },
|
||||
syncPendingAssets: (kinds?: PendingAssetKind[]) => syncPendingAssets(kinds),
|
||||
hasPendingAssets: async () => queue.entries.length > 0,
|
||||
}));
|
||||
|
||||
const success = vi.fn();
|
||||
const error = vi.fn();
|
||||
vi.mock("@/v2/composables/useSnackbar", () => ({
|
||||
useSnackbar: () => ({
|
||||
success,
|
||||
error,
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api/rom", () => ({
|
||||
default: { getRom: vi.fn(async () => ({ data: { id: 1 } })) },
|
||||
}));
|
||||
|
||||
const isOffline = ref(false);
|
||||
vi.mock("@/v2/composables/useServerConnection", () => ({
|
||||
useServerConnection: () => ({ isOffline, retryNow: vi.fn() }),
|
||||
}));
|
||||
|
||||
// The composable only runs inside a component scope, like AppLayout's. The
|
||||
// wrapper is kept so each test's watcher dies with it, rather than answering
|
||||
// the next test's reconnect.
|
||||
let wrapper: ReturnType<typeof mount> | null = null;
|
||||
function install() {
|
||||
wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
installPendingAssetSync();
|
||||
return () => null;
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Lets the watch, the drain and the queue re-read settle.
|
||||
async function settle() {
|
||||
for (let i = 0; i < 6; i++) await nextTick();
|
||||
}
|
||||
|
||||
describe("installPendingAssetSync", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
vi.useFakeTimers();
|
||||
queue.entries = [];
|
||||
isOffline.value = false;
|
||||
syncPendingAssets.mockReset();
|
||||
syncPendingAssets.mockImplementation(acceptAll);
|
||||
success.mockClear();
|
||||
error.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
wrapper?.unmount();
|
||||
wrapper = null;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("hands over what the browser is holding as soon as it installs", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(syncPendingAssets).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stops asking once the queue is empty", async () => {
|
||||
install();
|
||||
await settle();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await settle();
|
||||
|
||||
expect(syncPendingAssets).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps retrying while a save is still owed", async () => {
|
||||
// Refused by the server, so the entry outlives the attempt.
|
||||
syncPendingAssets.mockImplementation(async () => ({
|
||||
synced: [],
|
||||
dropped: [],
|
||||
}));
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
expect(syncPendingAssets).toHaveBeenCalledTimes(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
await settle();
|
||||
|
||||
expect(syncPendingAssets).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// The running session owns its save; nothing but this hands over a state.
|
||||
it("leaves a running game its own save but takes its states", async () => {
|
||||
queue.entries = [
|
||||
{ id: "1:a", romId: 1, kind: "save" as const },
|
||||
{ id: "1:b", romId: 1, kind: "state" as const },
|
||||
];
|
||||
storePlaying().setPlaying(true);
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(syncPendingAssets).toHaveBeenCalledWith(["state"]);
|
||||
expect(queue.entries.map((entry) => entry.kind)).toEqual(["save"]);
|
||||
});
|
||||
|
||||
it("hands the save over once the game is over", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
const playing = storePlaying();
|
||||
playing.setPlaying(true);
|
||||
|
||||
install();
|
||||
await settle();
|
||||
expect(queue.entries).toHaveLength(1);
|
||||
|
||||
playing.setPlaying(false);
|
||||
await settle();
|
||||
|
||||
expect(syncPendingAssets).toHaveBeenLastCalledWith(["save", "state"]);
|
||||
expect(queue.entries).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("says which game just reached the server", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(success).toHaveBeenCalledWith(
|
||||
"play.last-save-synced",
|
||||
expect.objectContaining({ image: null }),
|
||||
);
|
||||
});
|
||||
|
||||
it("tells a state apart from a save", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "state" as const }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(success).toHaveBeenCalledWith(
|
||||
"play.last-state-synced",
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
// The progress is gone from the browser, so the reason is all the player has.
|
||||
it("says why the server refused what it dropped", async () => {
|
||||
syncPendingAssets.mockImplementation(async () => {
|
||||
queue.entries = [];
|
||||
return {
|
||||
synced: [],
|
||||
dropped: [
|
||||
{
|
||||
kind: "save" as const,
|
||||
romId: 1,
|
||||
name: "Game",
|
||||
cover: null,
|
||||
reason: "Slot has a newer save",
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(error).toHaveBeenCalledWith(
|
||||
"play.save-sync-refused",
|
||||
expect.anything(),
|
||||
);
|
||||
expect(success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("owes a game one line however many states it was holding", async () => {
|
||||
queue.entries = [
|
||||
{ id: "1:a", romId: 1, kind: "state" as const },
|
||||
{ id: "1:b", romId: 1, kind: "state" as const },
|
||||
{ id: "1:c", romId: 1, kind: "save" as const },
|
||||
];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(success).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("waits for the server to come back", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
isOffline.value = true;
|
||||
|
||||
install();
|
||||
await settle();
|
||||
expect(syncPendingAssets).not.toHaveBeenCalled();
|
||||
|
||||
isOffline.value = false;
|
||||
await settle();
|
||||
|
||||
expect(syncPendingAssets).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
134
frontend/src/v2/composables/usePendingAssetSync/index.ts
Normal file
134
frontend/src/v2/composables/usePendingAssetSync/index.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
// Hands the server saves and states the browser is still holding, from
|
||||
// wherever the user is in the app. Doing it at launch instead would be too
|
||||
// late: by then the player has already drawn its picker, so the asset would
|
||||
// land behind the choice the user just made.
|
||||
import { onScopeDispose, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import {
|
||||
hasPendingAssets,
|
||||
syncPendingAssets,
|
||||
type DroppedAsset,
|
||||
type PendingAssetKind,
|
||||
type SyncedAsset,
|
||||
} from "@/services/pending-asset";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import storeRoms from "@/stores/roms";
|
||||
import { useServerConnection } from "@/v2/composables/useServerConnection";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
|
||||
// Long enough that a server that is up but refusing the upload is not hammered.
|
||||
const RETRY_MS = 30_000;
|
||||
|
||||
const SYNCED_MESSAGE: Record<PendingAssetKind, string> = {
|
||||
save: "play.last-save-synced",
|
||||
state: "play.last-state-synced",
|
||||
};
|
||||
|
||||
const REFUSED_MESSAGE: Record<PendingAssetKind, string> = {
|
||||
save: "play.save-sync-refused",
|
||||
state: "play.state-sync-refused",
|
||||
};
|
||||
|
||||
// A session that queued several captures owes the player one line per game,
|
||||
// not one per capture.
|
||||
function firstPerGame<T extends SyncedAsset>(assets: T[]): T[] {
|
||||
const seen = new Set<string>();
|
||||
const first: T[] = [];
|
||||
for (const asset of assets) {
|
||||
const key = `${asset.kind}:${asset.romId}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
first.push(asset);
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
// Two shells must not both be draining the same rows into the same server.
|
||||
let draining = false;
|
||||
|
||||
export function installPendingAssetSync() {
|
||||
const playingStore = storePlaying();
|
||||
const romsStore = storeRoms();
|
||||
const snackbar = useSnackbar();
|
||||
const { t } = useI18n();
|
||||
const { isOffline } = useServerConnection();
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function stopRetrying() {
|
||||
if (timer === null) return;
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
|
||||
function announce(synced: SyncedAsset[]) {
|
||||
for (const asset of firstPerGame(synced)) {
|
||||
snackbar.success(t(SYNCED_MESSAGE[asset.kind], { game: asset.name }), {
|
||||
image: asset.cover,
|
||||
timeout: 5000,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// The progress is gone from the browser, so the player is told why rather
|
||||
// than left waiting for a sync that will never come.
|
||||
function reportRefused(dropped: DroppedAsset[]) {
|
||||
for (const asset of firstPerGame(dropped)) {
|
||||
snackbar.error(
|
||||
t(REFUSED_MESSAGE[asset.kind], {
|
||||
game: asset.name,
|
||||
reason: asset.reason,
|
||||
}),
|
||||
{ image: asset.cover, timeout: 10000 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// An asset that just landed is one the open details view is showing stale.
|
||||
async function refresh(synced: SyncedAsset[]) {
|
||||
const current = romsStore.currentRom?.id;
|
||||
if (!current || !synced.some((asset) => asset.romId === current)) return;
|
||||
try {
|
||||
const { data } = await romApi.getRom({ romId: current });
|
||||
romsStore.setCurrentRom(data);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Failed to refresh a rom after a pending asset synced",
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function drain() {
|
||||
if (draining) return;
|
||||
draining = true;
|
||||
try {
|
||||
// A running session retries its own save every second, and a version
|
||||
// opened from under it is one it would not know about. A state is a
|
||||
// finished capture, and nothing else is going to hand it over.
|
||||
const kinds: PendingAssetKind[] = playingStore.playing
|
||||
? ["state"]
|
||||
: ["save", "state"];
|
||||
if (!isOffline.value) {
|
||||
const { synced, dropped } = await syncPendingAssets(kinds);
|
||||
announce(synced);
|
||||
reportRefused(dropped);
|
||||
await refresh(synced);
|
||||
}
|
||||
stopRetrying();
|
||||
if (await hasPendingAssets()) {
|
||||
timer = setTimeout(() => void drain(), RETRY_MS);
|
||||
}
|
||||
} finally {
|
||||
draining = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Quitting a game is what queues an asset, and reconnecting is what lets it
|
||||
// through, so both are worth another attempt.
|
||||
watch([() => playingStore.playing, isOffline], () => void drain(), {
|
||||
immediate: true,
|
||||
});
|
||||
onScopeDispose(stopRetrying);
|
||||
}
|
||||
@@ -1,171 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defineComponent, nextTick, ref } from "vue";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import { installPendingSaveSync } from "./index";
|
||||
|
||||
const queue = { entries: [] as { id: string; romId: number }[] };
|
||||
// The server takes everything unless a test says otherwise.
|
||||
async function acceptAll() {
|
||||
const taken = queue.entries.map((entry) => ({
|
||||
romId: entry.romId,
|
||||
name: "Game",
|
||||
cover: null,
|
||||
}));
|
||||
queue.entries = [];
|
||||
return taken;
|
||||
}
|
||||
const syncPendingSaves = vi.fn(acceptAll);
|
||||
|
||||
vi.mock("@/services/pending-save", () => ({
|
||||
default: { list: async () => queue.entries },
|
||||
syncPendingSaves: () => syncPendingSaves(),
|
||||
hasPendingSaves: async () => queue.entries.length > 0,
|
||||
}));
|
||||
|
||||
const success = vi.fn();
|
||||
vi.mock("@/v2/composables/useSnackbar", () => ({
|
||||
useSnackbar: () => ({
|
||||
success,
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api/rom", () => ({
|
||||
default: { getRom: vi.fn(async () => ({ data: { id: 1 } })) },
|
||||
}));
|
||||
|
||||
const isOffline = ref(false);
|
||||
vi.mock("@/v2/composables/useServerConnection", () => ({
|
||||
useServerConnection: () => ({ isOffline, retryNow: vi.fn() }),
|
||||
}));
|
||||
|
||||
// The composable only runs inside a component scope, like AppLayout's. The
|
||||
// wrapper is kept so each test's watcher dies with it, rather than answering
|
||||
// the next test's reconnect.
|
||||
let wrapper: ReturnType<typeof mount> | null = null;
|
||||
function install() {
|
||||
wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
installPendingSaveSync();
|
||||
return () => null;
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Lets the watch, the drain and the queue re-read settle.
|
||||
async function settle() {
|
||||
for (let i = 0; i < 6; i++) await nextTick();
|
||||
}
|
||||
|
||||
describe("installPendingSaveSync", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
vi.useFakeTimers();
|
||||
queue.entries = [];
|
||||
isOffline.value = false;
|
||||
syncPendingSaves.mockReset();
|
||||
syncPendingSaves.mockImplementation(acceptAll);
|
||||
success.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
wrapper?.unmount();
|
||||
wrapper = null;
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("hands over what the browser is holding as soon as it installs", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1 }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(syncPendingSaves).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stops asking once the queue is empty", async () => {
|
||||
install();
|
||||
await settle();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await settle();
|
||||
|
||||
expect(syncPendingSaves).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps retrying while a save is still owed", async () => {
|
||||
// Refused by the server, so the entry outlives the attempt.
|
||||
syncPendingSaves.mockImplementation(async () => []);
|
||||
queue.entries = [{ id: "1:a", romId: 1 }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
expect(syncPendingSaves).toHaveBeenCalledTimes(1);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
await settle();
|
||||
|
||||
expect(syncPendingSaves).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("leaves a running game to sync its own session", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1 }];
|
||||
storePlaying().setPlaying(true);
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(syncPendingSaves).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tries again once the game is over", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1 }];
|
||||
const playing = storePlaying();
|
||||
playing.setPlaying(true);
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
playing.setPlaying(false);
|
||||
await settle();
|
||||
|
||||
expect(syncPendingSaves).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("says which game just reached the server", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1 }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(success).toHaveBeenCalledWith(
|
||||
"play.last-save-synced",
|
||||
expect.objectContaining({ image: null }),
|
||||
);
|
||||
});
|
||||
|
||||
it("waits for the server to come back", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1 }];
|
||||
isOffline.value = true;
|
||||
|
||||
install();
|
||||
await settle();
|
||||
expect(syncPendingSaves).not.toHaveBeenCalled();
|
||||
|
||||
isOffline.value = false;
|
||||
await settle();
|
||||
|
||||
expect(syncPendingSaves).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
// Hands the server saves the browser is still holding, from wherever the user
|
||||
// is in the app. Doing it at launch instead would be too late: by then the
|
||||
// player has already drawn its save picker, so the save would land behind the
|
||||
// choice the user just made.
|
||||
import { onScopeDispose, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import {
|
||||
hasPendingSaves,
|
||||
syncPendingSaves,
|
||||
type SyncedSave,
|
||||
} from "@/services/pending-save";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import storeRoms from "@/stores/roms";
|
||||
import { useServerConnection } from "@/v2/composables/useServerConnection";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
|
||||
// Long enough that a server that is up but refusing the save is not hammered.
|
||||
const RETRY_MS = 30_000;
|
||||
|
||||
// Two shells must not both be draining the same rows into the same server.
|
||||
let draining = false;
|
||||
|
||||
export function installPendingSaveSync() {
|
||||
const playingStore = storePlaying();
|
||||
const romsStore = storeRoms();
|
||||
const snackbar = useSnackbar();
|
||||
const { t } = useI18n();
|
||||
const { isOffline } = useServerConnection();
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function stopRetrying() {
|
||||
if (timer === null) return;
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
}
|
||||
|
||||
function announce(synced: SyncedSave[]) {
|
||||
for (const save of synced) {
|
||||
snackbar.success(t("play.last-save-synced", { game: save.name }), {
|
||||
image: save.cover,
|
||||
timeout: 5000,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// A save that just landed is one the open details view is showing stale.
|
||||
async function refresh(synced: SyncedSave[]) {
|
||||
const current = romsStore.currentRom?.id;
|
||||
if (!current || !synced.some((save) => save.romId === current)) return;
|
||||
try {
|
||||
const { data } = await romApi.getRom({ romId: current });
|
||||
romsStore.setCurrentRom(data);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Failed to refresh a rom after a pending save synced",
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function drain() {
|
||||
if (draining) return;
|
||||
draining = true;
|
||||
try {
|
||||
// The player retries its own session every second while a game runs, and
|
||||
// a version opened from under it is one that session would not know about.
|
||||
if (!playingStore.playing && !isOffline.value) {
|
||||
const synced = await syncPendingSaves();
|
||||
announce(synced);
|
||||
await refresh(synced);
|
||||
}
|
||||
stopRetrying();
|
||||
if (await hasPendingSaves()) {
|
||||
timer = setTimeout(() => void drain(), RETRY_MS);
|
||||
}
|
||||
} finally {
|
||||
draining = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Quitting a game is what queues a save, and reconnecting is what lets it
|
||||
// through, so both are worth another attempt.
|
||||
watch([() => playingStore.playing, isOffline], () => void drain(), {
|
||||
immediate: true,
|
||||
});
|
||||
onScopeDispose(stopRetrying);
|
||||
}
|
||||
@@ -37,7 +37,7 @@ import { useGamepad } from "@/v2/composables/useGamepad";
|
||||
import { useGlobalHotkeys } from "@/v2/composables/useGlobalHotkeys";
|
||||
import { useInputModality } from "@/v2/composables/useInputModality";
|
||||
import { installOverlayRouteDismiss } from "@/v2/composables/useOverlayRouteDismiss";
|
||||
import { installPendingSaveSync } from "@/v2/composables/usePendingSaveSync";
|
||||
import { installPendingAssetSync } from "@/v2/composables/usePendingAssetSync";
|
||||
import { prefetchPlatformIcons } from "@/v2/composables/usePlatformIconCache";
|
||||
import { useReducedMotion } from "@/v2/composables/useReducedMotion";
|
||||
import { installScanLifecycle } from "@/v2/composables/useScanLifecycle";
|
||||
@@ -50,9 +50,9 @@ installPermissionsHydration();
|
||||
// route the user is on (navbar indicator + /scan view consume the same
|
||||
// store state).
|
||||
installScanLifecycle();
|
||||
// Saves a player could not hand over reach the server from any route, so the
|
||||
// next launch screen can offer them.
|
||||
installPendingSaveSync();
|
||||
// Saves and states a player could not hand over reach the server from any
|
||||
// route, so the next launch screen can offer them.
|
||||
installPendingAssetSync();
|
||||
// Mirror useBreakpoint() refs onto <html data-bp="…"> so scoped styles
|
||||
// can branch on viewport via `html[data-bp~="xs"] .foo { … }` instead of
|
||||
// hardcoding `@media (max-width: …)` values across every SFC.
|
||||
|
||||
@@ -14,7 +14,7 @@ import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
|
||||
import type { IGDBRelatedGame, SimilarRomSchema } from "@/__generated__";
|
||||
import { useUISettings } from "@/composables/useUISettings";
|
||||
import romApi from "@/services/api/rom";
|
||||
import { pendingSaveRomIds } from "@/services/pending-save";
|
||||
import { pendingAssetKinds } from "@/services/pending-asset";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storeRoms from "@/stores/roms";
|
||||
import { useStreamingStore } from "@/stores/streaming";
|
||||
@@ -71,7 +71,7 @@ useRightStickScroll(panelEl);
|
||||
useRomScanRefresh();
|
||||
|
||||
// The player replaces the document on its way out, which takes any toast it
|
||||
// raised with it, so a save the browser is still holding is announced here
|
||||
// raised with it, so progress the browser is still holding is announced here
|
||||
// instead. The app shell keeps retrying it in the background.
|
||||
const snackbar = useSnackbar();
|
||||
const isAlive = useIsAlive();
|
||||
@@ -79,10 +79,10 @@ watch(
|
||||
() => currentRom.value?.id ?? null,
|
||||
async (romId) => {
|
||||
if (!romId) return;
|
||||
const held = await pendingSaveRomIds();
|
||||
if (held.has(romId) && isAlive.value) {
|
||||
snackbar.warning(t("play.save-not-synced"));
|
||||
}
|
||||
const held = await pendingAssetKinds(romId);
|
||||
if (!isAlive.value) return;
|
||||
if (held.has("save")) snackbar.warning(t("play.save-not-synced"));
|
||||
if (held.has("state")) snackbar.warning(t("play.state-not-synced"));
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
@@ -103,6 +103,7 @@ import {
|
||||
type SlotChoice,
|
||||
} from "@/v2/utils/saveSlots";
|
||||
import { isJsResource, loadScript } from "@/v2/utils/scriptLoader";
|
||||
import { exitEmulatorOnce } from "@/views/Player/EmulatorJS/utils";
|
||||
import { rememberCore, resolveRememberedCore } from "./coreStorage";
|
||||
import {
|
||||
isLaunchIntent,
|
||||
@@ -516,7 +517,7 @@ onBeforeUnmount(() => {
|
||||
// Hand the keyboard and gamepad back to the UI; the flag otherwise
|
||||
// stays true and pad/hotkey navigation is dead until a reload.
|
||||
playing.value = false;
|
||||
window.EJS_emulator?.callEvent("exit");
|
||||
exitEmulatorOnce();
|
||||
emitter?.off("saveSelected", selectSave);
|
||||
emitter?.off("stateSelected", selectState);
|
||||
window.removeEventListener("gamepad:buttondown", onGamepadButton);
|
||||
|
||||
@@ -12,7 +12,10 @@ import type {
|
||||
} from "@/__generated__";
|
||||
import { ROUTES } from "@/plugins/router";
|
||||
import { saveApi as api } from "@/services/api/save";
|
||||
import pendingSaveStore, { type PendingSave } from "@/services/pending-save";
|
||||
import pendingAssetStore, {
|
||||
pendingAssetId,
|
||||
type PendingAsset,
|
||||
} from "@/services/pending-asset";
|
||||
import storeAuth from "@/stores/auth";
|
||||
import storeConfig from "@/stores/config";
|
||||
import storeLanguage from "@/stores/language";
|
||||
@@ -28,6 +31,8 @@ import {
|
||||
import {
|
||||
saveSave,
|
||||
captureScreenshot,
|
||||
dumpSaveFile,
|
||||
exitEmulatorOnce,
|
||||
resolveScreenshot,
|
||||
storedScreenshotFor,
|
||||
saveState,
|
||||
@@ -73,10 +78,7 @@ const deviceIDRef = ref(authStore.user?.current_device_id ?? undefined);
|
||||
// Bytes the server already holds, so forced writes can skip an unchanged SRAM.
|
||||
const saveTracker = createSaveSyncTracker();
|
||||
function baselineSaveTrackerFromEmulator() {
|
||||
// Passing false reads the SRAM without dumping it, so this fires no tick.
|
||||
saveTracker.baseline(
|
||||
window.EJS_emulator?.gameManager?.getSaveFile(false) ?? null,
|
||||
);
|
||||
saveTracker.baseline(dumpSaveFile());
|
||||
}
|
||||
// Writes run one at a time so concurrent writers cannot both open a version;
|
||||
// loading a save bumps the generation, which voids writes queued before it,
|
||||
@@ -89,29 +91,43 @@ let inFlightSave: Uint8Array | null = null;
|
||||
// Progress the server has not taken yet, kept in the browser with the frame
|
||||
// from the moment the game wrote it. Stored before every upload attempt, so a
|
||||
// sync that fails offline retries later with that frame rather than a newer one.
|
||||
let pendingSave: PendingSave | null = null;
|
||||
let pendingSave: PendingAsset | null = null;
|
||||
// One row per session: a save an earlier session never got through still owes
|
||||
// the server its own version, so this must not write over it.
|
||||
const pendingSaveId = `${romRef.value.id}:${crypto.randomUUID()}`;
|
||||
const pendingSaveId = pendingAssetId(romRef.value.id);
|
||||
async function rememberPendingSave(
|
||||
saveBytes: ArrayBuffer,
|
||||
screenshotBytes?: ArrayBuffer,
|
||||
) {
|
||||
pendingSave = {
|
||||
id: pendingSaveId,
|
||||
kind: "save",
|
||||
romId: romRef.value.id,
|
||||
saveBytes,
|
||||
romName: romRef.value.name ?? romRef.value.fs_name_no_ext,
|
||||
bytes: saveBytes,
|
||||
screenshotBytes,
|
||||
slot: loadedSave?.slot || props.saveSlot || undefined,
|
||||
emulator: window.EJS_core,
|
||||
deviceId: deviceIDRef.value,
|
||||
capturedAt: Date.now(),
|
||||
};
|
||||
await pendingSaveStore.write(pendingSave);
|
||||
await pendingAssetStore.write(pendingSave);
|
||||
}
|
||||
async function forgetPendingSave() {
|
||||
pendingSave = null;
|
||||
await pendingSaveStore.clear(pendingSaveId);
|
||||
await pendingAssetStore.clear(pendingSaveId);
|
||||
}
|
||||
// The tick re-offers a save whose upload failed on every pass, so what was
|
||||
// said for these bytes is remembered: every save the game writes is announced,
|
||||
// every retry of the same one is not.
|
||||
let heldBackSave: Uint8Array | null = null;
|
||||
function announceSaveHeldBack(saveFile: Uint8Array) {
|
||||
heldBackSave = saveFile;
|
||||
displayMessage("Save kept in this browser, it will sync later", {
|
||||
duration: 4000,
|
||||
tone: "warning",
|
||||
icon: "mdi-cloud-clock-outline",
|
||||
});
|
||||
}
|
||||
function writeSave(
|
||||
file: { saveFile: ArrayBuffer; screenshotFile?: ArrayBuffer },
|
||||
@@ -160,6 +176,29 @@ async function writeSaveIfChanged(file: {
|
||||
}
|
||||
return (await writeSave(file, generation)) !== null;
|
||||
}
|
||||
// A state restores the machine mid-scene, so every frame the core renders and
|
||||
// every note it plays on the way there belong to a moment the player did not
|
||||
// pick. Both are held back until the state has landed.
|
||||
const applyingState = ref(false);
|
||||
let restoreVolume: (() => void) | null = null;
|
||||
function silenceUntilStateApplied() {
|
||||
applyingState.value = true;
|
||||
const emulator = window.EJS_emulator;
|
||||
if (restoreVolume || typeof emulator?.setVolume !== "function") return;
|
||||
const { volume, muted } = emulator;
|
||||
emulator.setVolume(0);
|
||||
restoreVolume = () => {
|
||||
// setVolume persists the settings before applying them, so the flag goes
|
||||
// back first or the next launch starts muted.
|
||||
emulator.muted = muted;
|
||||
emulator.setVolume(muted ? 0 : volume);
|
||||
};
|
||||
}
|
||||
function stateApplied() {
|
||||
applyingState.value = false;
|
||||
restoreVolume?.();
|
||||
restoreVolume = null;
|
||||
}
|
||||
const theme = useTheme();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
const { playing, fullScreen } = storeToRefs(playingStore);
|
||||
@@ -345,33 +384,33 @@ onBeforeUnmount(async () => {
|
||||
uninstallAutoSaveSync();
|
||||
emitter?.off("saveSelected", loadSave);
|
||||
emitter?.off("stateSelected", loadState);
|
||||
window.EJS_emulator?.callEvent("exit");
|
||||
exitEmulatorOnce();
|
||||
fullScreen.value = false;
|
||||
playing.value = false;
|
||||
});
|
||||
|
||||
type MessageTone = "success" | "error" | "warning" | "info";
|
||||
|
||||
// The app's own toast host: it stacks, so two notices raised together read as
|
||||
// two, and it draws its icons as components rather than through a font class.
|
||||
function displayMessage(
|
||||
message: string,
|
||||
{
|
||||
duration,
|
||||
className,
|
||||
tone = "info",
|
||||
icon,
|
||||
}: {
|
||||
duration: number;
|
||||
className?: "msg-error" | "msg-success";
|
||||
tone?: MessageTone;
|
||||
icon?: string;
|
||||
},
|
||||
) {
|
||||
window.EJS_emulator?.displayMessage(message, duration);
|
||||
const element = document.querySelector("#game .ejs_message");
|
||||
if (element) {
|
||||
const classes = [className, icon].filter((c): c is string => !!c);
|
||||
if (classes.length === 0) return;
|
||||
element.classList.add(...classes);
|
||||
setTimeout(() => {
|
||||
element.classList.remove(...classes);
|
||||
}, duration);
|
||||
}
|
||||
emitter?.emit("snackbarShow", {
|
||||
msg: message,
|
||||
color: tone,
|
||||
icon,
|
||||
timeout: duration,
|
||||
});
|
||||
}
|
||||
|
||||
// Poll until EmulatorJS' gameManager is ready to accept save/state
|
||||
@@ -388,8 +427,8 @@ async function waitForGameManager(timeoutMs = 5000): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Settle window after boot before applying a state. Some cores need a few
|
||||
// frames rendered before loadState takes cleanly.
|
||||
// Settle window around applying a state: cores need a few frames rendered
|
||||
// before loadState takes cleanly, and RetroArch applies it off its task queue.
|
||||
const STATE_APPLY_SETTLE_MS = 500;
|
||||
|
||||
// Periodic save upload on the "saveSaveFiles" tick that pollSaveFiles fires
|
||||
@@ -422,12 +461,16 @@ function installAutoSaveSync() {
|
||||
const save = await writeSave({ saveFile: saveBytes, screenshotFile });
|
||||
if (save) {
|
||||
await forgetPendingSave();
|
||||
heldBackSave = null;
|
||||
romsStore.update(romRef.value);
|
||||
displayMessage("Save synced with server", {
|
||||
duration: 3000,
|
||||
className: "msg-success",
|
||||
tone: "success",
|
||||
icon: "mdi-cloud-sync",
|
||||
});
|
||||
// A write voided by a save being loaded is not the server refusing it.
|
||||
} else if (!saveLoading && !bytesEqual(saveFile, heldBackSave)) {
|
||||
announceSaveHeldBack(saveFile);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Periodic save sync failed", error);
|
||||
@@ -551,36 +594,49 @@ window.EJS_onSaveSave = async function ({
|
||||
romsStore.update(romRef.value);
|
||||
|
||||
if (synced) {
|
||||
heldBackSave = null;
|
||||
displayMessage("Save synced with server", {
|
||||
duration: 4000,
|
||||
className: "msg-success",
|
||||
tone: "success",
|
||||
icon: "mdi-cloud-sync",
|
||||
});
|
||||
} else {
|
||||
displayMessage("Error syncing save with server", {
|
||||
duration: 4000,
|
||||
className: "msg-error",
|
||||
icon: "mdi-sync-alert",
|
||||
});
|
||||
// Asked for by hand, so it answers every time, and the tick behind it
|
||||
// knows these bytes have been spoken for.
|
||||
announceSaveHeldBack(new Uint8Array(saveFile));
|
||||
}
|
||||
};
|
||||
|
||||
// States management
|
||||
async function loadState(state: StateSchema) {
|
||||
const { data } = await api.get(state.download_path.replace("/api", ""), {
|
||||
responseType: "arraybuffer",
|
||||
});
|
||||
if (data) {
|
||||
loadEmulatorJSState(new Uint8Array(data));
|
||||
displayMessage("State loaded from server", {
|
||||
duration: 3000,
|
||||
icon: "mdi-cloud-download-outline",
|
||||
});
|
||||
return;
|
||||
}
|
||||
// A state restores the SRAM along with the rest of the machine, so the bytes
|
||||
// the tick reads next belong to the state, not to progress the player made.
|
||||
async function rebaselineAfterState() {
|
||||
await new Promise((resolve) => setTimeout(resolve, STATE_APPLY_SETTLE_MS));
|
||||
baselineSaveTrackerFromEmulator();
|
||||
}
|
||||
|
||||
const file = await window.EJS_emulator.selectFile();
|
||||
loadEmulatorJSState(new Uint8Array(await file.arrayBuffer()));
|
||||
async function loadState(state: StateSchema) {
|
||||
silenceUntilStateApplied();
|
||||
try {
|
||||
const { data } = await api.get(state.download_path.replace("/api", ""), {
|
||||
responseType: "arraybuffer",
|
||||
});
|
||||
if (data) {
|
||||
loadEmulatorJSState(new Uint8Array(data));
|
||||
displayMessage("State loaded from server", {
|
||||
duration: 3000,
|
||||
icon: "mdi-cloud-download-outline",
|
||||
});
|
||||
await rebaselineAfterState();
|
||||
return;
|
||||
}
|
||||
|
||||
const file = await window.EJS_emulator.selectFile();
|
||||
loadEmulatorJSState(new Uint8Array(await file.arrayBuffer()));
|
||||
await rebaselineAfterState();
|
||||
} finally {
|
||||
stateApplied();
|
||||
}
|
||||
}
|
||||
|
||||
window.EJS_onLoadState = async function () {
|
||||
@@ -609,19 +665,29 @@ window.EJS_onSaveState = async function ({
|
||||
if (state) {
|
||||
displayMessage("State synced with server", {
|
||||
duration: 4000,
|
||||
className: "msg-success",
|
||||
tone: "success",
|
||||
icon: "mdi-cloud-sync",
|
||||
});
|
||||
} else {
|
||||
displayMessage("Error syncing state with server", {
|
||||
displayMessage("State kept in this browser, it will sync later", {
|
||||
duration: 4000,
|
||||
className: "msg-error",
|
||||
icon: "mdi-sync-alert",
|
||||
tone: "warning",
|
||||
icon: "mdi-cloud-clock-outline",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
window.EJS_onGameStart = async () => {
|
||||
// EmulatorJS' own notices (its browser save-state slots) go through the
|
||||
// same host, so nothing of ours is overwritten by one of theirs.
|
||||
const emulator = window.EJS_emulator;
|
||||
if (emulator && !emulator.__rommMessageStack) {
|
||||
emulator.__rommMessageStack = true;
|
||||
emulator.displayMessage = (text: string, duration?: number) =>
|
||||
displayMessage(text, { duration: duration ?? 3000 });
|
||||
}
|
||||
|
||||
if (props.state) silenceUntilStateApplied();
|
||||
// The emulator now owns the keyboard: every key, "/" included, belongs to
|
||||
// the game (a DOS prompt typing "mount A / -t floppy" must not reach the
|
||||
// global hotkeys). Callers flag this at launch too, but taking it from the
|
||||
@@ -667,6 +733,7 @@ window.EJS_onGameStart = async () => {
|
||||
const ready = await waitForGameManager();
|
||||
if (!ready) {
|
||||
console.warn("Game manager not ready for save/state injection");
|
||||
stateApplied();
|
||||
} else {
|
||||
// A state restores the whole machine, SRAM included, so a save applied
|
||||
// alongside it would be discarded: the state wins when both are set.
|
||||
@@ -675,7 +742,6 @@ window.EJS_onGameStart = async () => {
|
||||
setTimeout(resolve, STATE_APPLY_SETTLE_MS),
|
||||
);
|
||||
await loadState(props.state);
|
||||
baselineSaveTrackerFromEmulator();
|
||||
} else if (props.save) {
|
||||
await loadSave(props.save);
|
||||
} else {
|
||||
@@ -706,12 +772,13 @@ window.EJS_onGameStart = async () => {
|
||||
) {
|
||||
window.EJS_emulator.storage.states
|
||||
.get(window.EJS_emulator.getBaseFileName() + ".state")
|
||||
.then((e: Uint8Array) => {
|
||||
window.EJS_emulator.gameManager.loadState(e);
|
||||
.then(async (e: Uint8Array) => {
|
||||
loadEmulatorJSState(e);
|
||||
displayMessage("Quick load from server", {
|
||||
duration: 3000,
|
||||
icon: "mdi-flash",
|
||||
});
|
||||
await rebaselineAfterState();
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -771,6 +838,7 @@ onUnmounted(() => {
|
||||
|
||||
<template>
|
||||
<div id="game" />
|
||||
<div v-if="applyingState" class="ejs-state-cover" aria-hidden="true" />
|
||||
<div
|
||||
v-if="rom.ss_metadata?.bezel_path"
|
||||
class="pointer-events-none fixed inset-0 flex items-center justify-center z-20 overflow-hidden"
|
||||
@@ -787,6 +855,16 @@ onUnmounted(() => {
|
||||
</template>
|
||||
|
||||
<style>
|
||||
/* Up until a state has been applied: the core has to render frames for the
|
||||
load to take, and they picture a scene the player did not ask for. */
|
||||
.ejs-state-cover {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 30;
|
||||
pointer-events: none;
|
||||
background: black;
|
||||
}
|
||||
|
||||
#game .ejs_cheat_code {
|
||||
background-color: white;
|
||||
}
|
||||
@@ -803,60 +881,4 @@ onUnmounted(() => {
|
||||
#game .ejs_menu_bar .ejs_menu_button:nth-child(-1) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* EmulatorJS raises its own messages through this element and adds none of
|
||||
RomM's classes, so the unclassed state has to be legible. It wears the v2
|
||||
toast's glass panel; the fallbacks keep it readable under the v1 theme. */
|
||||
#game .ejs_message {
|
||||
top: 16px;
|
||||
left: 16px;
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
max-width: min(420px, calc(100% - 32px));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border: 1px solid
|
||||
var(--r-color-border-strong, rgba(var(--v-theme-on-surface), 0.15));
|
||||
border-radius: var(--r-radius-md, 8px);
|
||||
background: var(--r-color-toast-bg, rgba(var(--v-theme-surface), 0.92));
|
||||
backdrop-filter: blur(18px);
|
||||
box-shadow:
|
||||
0 10px 28px color-mix(in srgb, black 45%, transparent),
|
||||
0 2px 6px color-mix(in srgb, black 30%, transparent);
|
||||
color: var(--r-color-fg, rgb(var(--v-theme-on-surface)));
|
||||
font: 13px / 1.45 var(--r-font-family-sans, inherit);
|
||||
text-shadow: none;
|
||||
transition:
|
||||
opacity var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out),
|
||||
transform var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out);
|
||||
}
|
||||
|
||||
/* A message expires by having its text cleared, not the element removed, so
|
||||
the empty state is where it fades out. */
|
||||
#game .ejs_message:empty {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
visibility: hidden;
|
||||
transition:
|
||||
opacity var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out),
|
||||
transform var(--r-motion-fast, 160ms) var(--r-motion-ease-out, ease-out),
|
||||
visibility 0s var(--r-motion-fast, 160ms);
|
||||
}
|
||||
|
||||
/* The icon class lands on the message itself, so the glyph is its ::before,
|
||||
tinted by tone like the v2 toast icon. */
|
||||
#game .ejs_message::before {
|
||||
flex-shrink: 0;
|
||||
font: normal normal normal 18px / 1 "Material Design Icons";
|
||||
color: var(--r-color-brand-primary, rgb(var(--v-theme-romm-blue)));
|
||||
}
|
||||
|
||||
#game .ejs_message.msg-success::before {
|
||||
color: var(--r-color-success, rgb(var(--v-theme-romm-green)));
|
||||
}
|
||||
|
||||
#game .ejs_message.msg-error::before {
|
||||
color: var(--r-color-danger-fg, rgb(var(--v-theme-romm-red)));
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SaveSchema } from "@/__generated__";
|
||||
import type { StateSchema } from "@/__generated__";
|
||||
import { sessionStateName } from "@/services/api/state";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import {
|
||||
buildStateFormData,
|
||||
captureScreenshot,
|
||||
dumpSaveFile,
|
||||
storedScreenshotFor,
|
||||
createSaveSyncTracker,
|
||||
installEJSDefaultOptionsTrap,
|
||||
@@ -23,12 +25,24 @@ const saveApiMocks = vi.hoisted(() => ({
|
||||
const stateApiMocks = vi.hoisted(() => ({
|
||||
uploadStates: vi.fn(),
|
||||
}));
|
||||
const pendingAssetMocks = vi.hoisted(() => ({
|
||||
write: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
list: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api/save", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/services/api/save")>()),
|
||||
default: saveApiMocks,
|
||||
}));
|
||||
vi.mock("@/services/api/state", () => ({ default: stateApiMocks }));
|
||||
vi.mock("@/services/api/state", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/services/api/state")>()),
|
||||
default: stateApiMocks,
|
||||
}));
|
||||
vi.mock("@/services/pending-asset", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/services/pending-asset")>()),
|
||||
default: pendingAssetMocks,
|
||||
}));
|
||||
|
||||
const STORAGE_KEY = "ejs-7-n64-Test Game-settings";
|
||||
|
||||
@@ -341,6 +355,79 @@ describe("captureScreenshot", () => {
|
||||
|
||||
await expect(captureScreenshot()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
// EmulatorJS waits for its screenshot by polling the filesystem forever, and
|
||||
// a capture deletes the file the one before it is still waiting on.
|
||||
it("takes one capture at a time", async () => {
|
||||
const order: string[] = [];
|
||||
let release: (() => void) | undefined;
|
||||
const first = new Promise<ArrayBuffer>((resolve) => {
|
||||
release = () => resolve(new ArrayBuffer(8));
|
||||
});
|
||||
const screenshot = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
order.push("first");
|
||||
return first;
|
||||
})
|
||||
.mockImplementationOnce(async () => {
|
||||
order.push("second");
|
||||
return new ArrayBuffer(4);
|
||||
});
|
||||
(window as any).EJS_emulator = { gameManager: { screenshot } };
|
||||
|
||||
const pending = [captureScreenshot(), captureScreenshot()];
|
||||
await vi.waitFor(() => expect(order).toEqual(["first"]));
|
||||
|
||||
release?.();
|
||||
await Promise.all(pending);
|
||||
|
||||
expect(order).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
// That poll runs for the rest of the session unless the file turns up.
|
||||
it("releases a capture that never arrived", async () => {
|
||||
vi.useFakeTimers();
|
||||
const writeFile = vi.fn();
|
||||
(window as any).EJS_emulator = {
|
||||
gameManager: {
|
||||
FS: { writeFile },
|
||||
screenshot: () => new Promise(() => {}),
|
||||
},
|
||||
};
|
||||
|
||||
const capture = captureScreenshot();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
|
||||
await expect(capture).resolves.toBeUndefined();
|
||||
expect(writeFile).toHaveBeenCalledWith(
|
||||
"/screenshot.png",
|
||||
new Uint8Array(0),
|
||||
);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
describe("dumpSaveFile", () => {
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
afterEach(() => {
|
||||
(window as any).EJS_emulator = undefined;
|
||||
});
|
||||
|
||||
// A state restores the SRAM into the core's memory, not into the file, so a
|
||||
// read that skips the dump hands back bytes from before the restore.
|
||||
it("has the core write its SRAM out before reading it", () => {
|
||||
const getSaveFile = vi.fn(() => new Uint8Array([1, 2, 3]));
|
||||
(window as any).EJS_emulator = { gameManager: { getSaveFile } };
|
||||
|
||||
expect(dumpSaveFile()).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(getSaveFile).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("has nothing to offer before the emulator is up", () => {
|
||||
expect(dumpSaveFile()).toBeNull();
|
||||
});
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
});
|
||||
|
||||
describe("resolveScreenshot", () => {
|
||||
@@ -370,10 +457,12 @@ describe("resolveScreenshot", () => {
|
||||
|
||||
describe("storedScreenshotFor", () => {
|
||||
const shot = new Uint8Array([9, 9]).buffer;
|
||||
const pendingFor = (saveBytes: ArrayBuffer) => ({
|
||||
const pendingFor = (bytes: ArrayBuffer) => ({
|
||||
id: "1:a",
|
||||
kind: "save" as const,
|
||||
romId: 1,
|
||||
saveBytes,
|
||||
romName: "Game",
|
||||
bytes,
|
||||
screenshotBytes: shot,
|
||||
capturedAt: 0,
|
||||
});
|
||||
@@ -408,8 +497,15 @@ describe("storedScreenshotFor", () => {
|
||||
});
|
||||
|
||||
it("keeps bytes that were stored without a frame frameless", () => {
|
||||
const saveBytes = new Uint8Array([1, 2, 3]).buffer;
|
||||
const pending = { id: "1:a", romId: 1, saveBytes, capturedAt: 0 };
|
||||
const bytes = new Uint8Array([1, 2, 3]).buffer;
|
||||
const pending = {
|
||||
id: "1:a",
|
||||
kind: "save" as const,
|
||||
romId: 1,
|
||||
romName: "Game",
|
||||
bytes,
|
||||
capturedAt: 0,
|
||||
};
|
||||
|
||||
expect(
|
||||
storedScreenshotFor(pending, new Uint8Array([1, 2, 3]).buffer),
|
||||
@@ -431,6 +527,8 @@ describe("saveState", () => {
|
||||
stateApiMocks.uploadStates.mockResolvedValue([
|
||||
{ status: "fulfilled", value: { id: 7 } as StateSchema },
|
||||
]);
|
||||
pendingAssetMocks.write.mockReset().mockResolvedValue(undefined);
|
||||
pendingAssetMocks.clear.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("uploads the screenshot named after the state", async () => {
|
||||
@@ -447,6 +545,46 @@ describe("saveState", () => {
|
||||
const { statesToUpload } = stateApiMocks.uploadStates.mock.calls[0][0];
|
||||
expect(statesToUpload[0].screenshotFile).toBeUndefined();
|
||||
});
|
||||
|
||||
it("holds the state in the browser until the server takes it", async () => {
|
||||
await saveState({ rom, stateFile: bytes, screenshotFile: bytes });
|
||||
|
||||
const held = pendingAssetMocks.write.mock.calls[0][0];
|
||||
expect(held).toMatchObject({
|
||||
kind: "state",
|
||||
romId: 1,
|
||||
romName: "game",
|
||||
bytes,
|
||||
screenshotBytes: bytes,
|
||||
});
|
||||
expect(pendingAssetMocks.clear).toHaveBeenCalledWith(held.id);
|
||||
});
|
||||
|
||||
it("keeps a state the server refused", async () => {
|
||||
stateApiMocks.uploadStates.mockResolvedValue([
|
||||
{ status: "rejected", reason: new Error("offline") },
|
||||
]);
|
||||
|
||||
await expect(saveState({ rom, stateFile: bytes })).resolves.toBeNull();
|
||||
|
||||
expect(pendingAssetMocks.write).toHaveBeenCalledTimes(1);
|
||||
expect(pendingAssetMocks.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// The name pins the moment of the capture, so a retry updates the row the
|
||||
// first attempt opened instead of leaving a second copy behind.
|
||||
it("names the state after the moment it was captured", async () => {
|
||||
await saveState({ rom, stateFile: bytes });
|
||||
|
||||
const { capturedAt } = pendingAssetMocks.write.mock.calls[0][0];
|
||||
const { statesToUpload } = stateApiMocks.uploadStates.mock.calls[0][0];
|
||||
expect(statesToUpload[0].stateFile.name).toMatch(
|
||||
/^game \[\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}-\d{3}\]\.state$/,
|
||||
);
|
||||
expect(statesToUpload[0].stateFile.name).toBe(
|
||||
`${sessionStateName(rom, new Date(capturedAt))}.state`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveSaveOnUnload", () => {
|
||||
|
||||
@@ -5,28 +5,87 @@ import {
|
||||
type StateSchema,
|
||||
} from "@/__generated__";
|
||||
import saveApi, { AUTOSAVE_SLOT, sessionSaveFile } from "@/services/api/save";
|
||||
import stateApi from "@/services/api/state";
|
||||
import { type PendingSave } from "@/services/pending-save";
|
||||
import stateApi, { sessionStateName } from "@/services/api/state";
|
||||
import pendingAssetStore, {
|
||||
pendingAssetId,
|
||||
type PendingAsset,
|
||||
} from "@/services/pending-asset";
|
||||
import { type DetailedRom } from "@/stores/roms";
|
||||
import { buildFormInput } from "@/utils/formData";
|
||||
|
||||
function buildStateName(rom: DetailedRom): string {
|
||||
const romName = rom.fs_name_no_ext.trim();
|
||||
return `${romName} [${new Date().toISOString().replace(/[:.]/g, "-").replace("T", " ").replace("Z", "")}]`;
|
||||
/**
|
||||
* Tears the emulator down, once however many owners ask.
|
||||
*
|
||||
* The player component and the shell around it both unmount on the way out,
|
||||
* and EmulatorJS' exit unmounts its filesystem: a second pass throws
|
||||
* `ErrnoError(28)` and then aborts the runtime.
|
||||
*/
|
||||
export function exitEmulatorOnce() {
|
||||
const emulator = window.EJS_emulator;
|
||||
if (!emulator || emulator.__rommExited) return;
|
||||
emulator.__rommExited = true;
|
||||
emulator.callEvent("exit");
|
||||
}
|
||||
|
||||
// Long enough for any core to hand over a frame.
|
||||
const SCREENSHOT_TIMEOUT_MS = 3000;
|
||||
|
||||
// EmulatorJS 4.2.3 hands `EJS_onSaveState` nothing under `screenshot` and its
|
||||
// own capture renders only a slice of the frame, so every picture RomM stores
|
||||
// is read off the live canvas, which means capturing before any pause.
|
||||
export async function captureScreenshot(): Promise<ArrayBuffer | undefined> {
|
||||
//
|
||||
// Its capture deletes the file the previous one is still waiting on, and the
|
||||
// wait is a poll that never gives up, so captures are taken one at a time.
|
||||
let capturing: Promise<ArrayBuffer | undefined> = Promise.resolve(undefined);
|
||||
|
||||
export function captureScreenshot(): Promise<ArrayBuffer | undefined> {
|
||||
capturing = capturing.catch(() => undefined).then(takeScreenshot);
|
||||
return capturing;
|
||||
}
|
||||
|
||||
async function takeScreenshot(): Promise<ArrayBuffer | undefined> {
|
||||
const gameManager = window.EJS_emulator?.gameManager;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const screenshot = await window.EJS_emulator?.gameManager?.screenshot();
|
||||
const screenshot = await Promise.race([
|
||||
gameManager?.screenshot(),
|
||||
new Promise<undefined>((resolve) => {
|
||||
timer = setTimeout(() => resolve(undefined), SCREENSHOT_TIMEOUT_MS);
|
||||
}),
|
||||
]);
|
||||
// An empty buffer is a failed readback, not a picture.
|
||||
return screenshot?.byteLength ? screenshot : undefined;
|
||||
if (screenshot?.byteLength) return screenshot;
|
||||
} catch (error) {
|
||||
console.error("Failed to capture a screenshot", error);
|
||||
return undefined;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
releaseScreenshotWait(gameManager);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// The poll behind a capture that never arrived runs for the rest of the
|
||||
// session; the file it is waiting for is what stops it.
|
||||
function releaseScreenshotWait(gameManager?: {
|
||||
FS?: { writeFile(path: string, data: Uint8Array): void };
|
||||
}) {
|
||||
try {
|
||||
gameManager?.FS?.writeFile("/screenshot.png", new Uint8Array(0));
|
||||
} catch (error) {
|
||||
console.error("Failed to release a stuck screenshot capture", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SRAM as the core holds it right now.
|
||||
*
|
||||
* Returns:
|
||||
* The bytes, or null when the core has written no save file.
|
||||
*/
|
||||
export function dumpSaveFile(): Uint8Array | null {
|
||||
// Passing true flushes the core's memory into the file this reads: the copy
|
||||
// already on the emulator's filesystem predates a state it just restored.
|
||||
return window.EJS_emulator?.gameManager?.getSaveFile(true) ?? null;
|
||||
}
|
||||
|
||||
/** The picture for a save or a state: the live canvas, else EmulatorJS'. */
|
||||
@@ -43,12 +102,12 @@ export async function resolveScreenshot(
|
||||
* The stored picture, or undefined when the bytes have moved on since.
|
||||
*/
|
||||
export function storedScreenshotFor(
|
||||
pending: PendingSave | null,
|
||||
pending: PendingAsset | null,
|
||||
saveBytes: ArrayBuffer,
|
||||
): ArrayBuffer | undefined {
|
||||
if (!pending) return undefined;
|
||||
const sameBytes = bytesEqual(
|
||||
new Uint8Array(pending.saveBytes),
|
||||
new Uint8Array(pending.bytes),
|
||||
new Uint8Array(saveBytes),
|
||||
);
|
||||
return sameBytes ? pending.screenshotBytes : undefined;
|
||||
@@ -88,7 +147,22 @@ export async function saveState({
|
||||
return null;
|
||||
}
|
||||
|
||||
const filename = buildStateName(rom);
|
||||
const capturedAt = new Date();
|
||||
const filename = sessionStateName(rom, capturedAt);
|
||||
// Held in the browser until the server takes it, so a state captured with
|
||||
// no connection reaches the server on a later pass instead of being lost.
|
||||
const pendingId = pendingAssetId(rom.id);
|
||||
await pendingAssetStore.write({
|
||||
id: pendingId,
|
||||
kind: "state",
|
||||
romId: rom.id,
|
||||
romName: rom.name ?? rom.fs_name_no_ext,
|
||||
bytes: stateFile,
|
||||
screenshotBytes: screenshotFile,
|
||||
emulator: window.EJS_core,
|
||||
capturedAt: capturedAt.getTime(),
|
||||
});
|
||||
|
||||
try {
|
||||
const uploadedStates = await stateApi.uploadStates({
|
||||
rom: rom,
|
||||
@@ -109,6 +183,7 @@ export async function saveState({
|
||||
|
||||
const uploadedState = uploadedStates[0];
|
||||
if (uploadedState.status == "fulfilled") {
|
||||
await pendingAssetStore.clear(pendingId);
|
||||
if (rom) rom.user_states.unshift(uploadedState.value);
|
||||
return uploadedState.value;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user