UI: translate Players, Companions, Client cards

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ДмитрийandClaude Sonnet 5.5 committed 2026-09-30 11:52:50 +05:00
1 parent 9dee0ce8b1
commit 488a1a45c6
8 files changed
+307 -43

No files matched your search

+51
View File
@@ -147,6 +147,57 @@ const de: Partial<Record<keyof typeof en, string>> = {
"install.doneTitle": "Dein Server ist bereit", "install.doneTitle": "Dein Server ist bereit",
"install.doneText": "Alles ist installiert. Starte ihn auf dem nächsten Bildschirm.", "install.doneText": "Alles ist installiert. Starte ihn auf dem nächsten Bildschirm.",
"install.open": "MEINEN SERVER ÖFFNEN", "install.open": "MEINEN SERVER ÖFFNEN",
// Players
"players.title": "Spieler",
"players.createTitle": "Erstelle dein Konto",
"players.createText": "Das sind der Name und das Passwort, mit denen du dich im Spiel anmeldest.",
"players.startFirst": "Starte zuerst den Server – Konten werden erstellt, solange er läuft.",
"players.username": "Benutzername",
"players.password": "Passwort",
"players.admin": "Dieses Konto zum Administrator machen",
"players.adminHint": "Administratoren können im Spiel Gamemaster-Befehle nutzen. Tu dies nur für Konten, denen du vertraust.",
"players.create": "Konto erstellen",
"players.created": "Konto „{name}“ erstellt. Du kannst dich jetzt damit im Spiel anmelden.",
// Companions
"comp.title": "KI-Begleiter",
"comp.population": "{online} jetzt online · insgesamt {total} erstellt",
"comp.reading": "Aktuelle Anzahl wird gelesen …",
"comp.startToSee": "Starte den Server, um zu sehen, wie viele Begleiter online sind.",
"comp.wantMore": "Möchtest du mehr Begleiter?",
"comp.custom": "Benutzerdefiniert",
"comp.numberLabel": "Anzahl der Begleiter",
"comp.largeWarning": "Große Mengen können mehr CPU und Speicher benötigen. Erhöhe schrittweise.",
"comp.hardware": "Dieser Computer: {cores} Kerne, {ram} GB Arbeitsspeicher.",
"comp.add": "{n} Begleiter hinzufügen",
"comp.addPlain": "Begleiter hinzufügen",
"comp.stoppedHint": "Der Server ist gestoppt: Sie werden beim nächsten Start erstellt.",
"comp.spawned": "{n} Begleiter werden erstellt. Sie erscheinen nach und nach in den nächsten Minuten.",
"comp.saved": "Gespeichert. {n} Begleiter melden sich beim Serverstart an.",
// Client
"client.title": "Spielclient",
"client.looking": "Suche …",
"client.intro": "Sag dem Manager, wo dein Spiel installiert ist, um einen SPIELEN-Button zu erhalten. Deine Spieldateien werden nie geändert, außer der Serveradresse und dem Begleiter-Addon.",
"client.chooseFolder": "Spielordner wählen …",
"client.dialogTitle": "Wähle den Ordner deines Spielclients",
"client.connectsTo": "Verbindet mit",
"client.thisComputer": "✓ dieser Computer",
"client.notThisServer": "nicht dieser Server",
"client.addon": "Begleiter-Addon",
"client.installedVersion": "Installiert (Version {v})",
"client.installed": "Installiert",
"client.addonNotInstalled": "Nicht installiert",
"client.updateAvailable": "ein Update ist verfügbar",
"client.otherAddons": "Andere Addons",
"client.leftAsIs": "{n} – bleiben unverändert",
"client.pointLocal": "Spiel auf diesen Server ausrichten",
"client.pointedNote": "Das Spiel verbindet sich jetzt mit diesem Computer. Die vorherige Adresse wurde gespeichert.",
"client.installAddon": "Begleiter-Addon installieren",
"client.updateAddon": "Begleiter-Addon aktualisieren",
"client.addonNote": "Begleiter-Addon installiert. Andere Addons wurden nicht angetastet.",
"client.changeFolder": "Ordner ändern …",
}; };
export default de; export default de;
+51
View File
@@ -147,6 +147,57 @@ const en = {
"install.doneTitle": "Your server is ready", "install.doneTitle": "Your server is ready",
"install.doneText": "Everything is installed. Start it from the next screen.", "install.doneText": "Everything is installed. Start it from the next screen.",
"install.open": "OPEN MY SERVER", "install.open": "OPEN MY SERVER",
// Players
"players.title": "Players",
"players.createTitle": "Create your account",
"players.createText": "This is the name and password you use to log in to the game.",
"players.startFirst": "Start the server first — accounts are created while it is running.",
"players.username": "Username",
"players.password": "Password",
"players.admin": "Make this account an administrator",
"players.adminHint": "Administrators can use game-master commands in the game. Only do this for accounts you trust.",
"players.create": "Create account",
"players.created": "Account “{name}” created. You can log in to the game with it now.",
// Companions
"comp.title": "AI companions",
"comp.population": "{online} online now · {total} created in total",
"comp.reading": "Reading the current population…",
"comp.startToSee": "Start the server to see how many companions are online.",
"comp.wantMore": "Would you like more companions?",
"comp.custom": "Custom",
"comp.numberLabel": "Number of companions",
"comp.largeWarning": "Large populations may need more CPU and memory. Increase gradually.",
"comp.hardware": "This computer: {cores} cores, {ram} GB memory.",
"comp.add": "Add {n} companions",
"comp.addPlain": "Add companions",
"comp.stoppedHint": "The server is stopped: they will be created the next time it runs.",
"comp.spawned": "Creating {n} companions. They appear gradually over the next minutes.",
"comp.saved": "Saved. {n} companions will log in when the server starts.",
// Client
"client.title": "Game client",
"client.looking": "Looking…",
"client.intro": "Tell Manager where your game is installed to get a PLAY button. Your game files are never changed except the server address and the companion addon.",
"client.chooseFolder": "Choose game folder…",
"client.dialogTitle": "Choose your game client folder",
"client.connectsTo": "Connects to",
"client.thisComputer": "✓ this computer",
"client.notThisServer": "not this server",
"client.addon": "Companion addon",
"client.installedVersion": "Installed (version {v})",
"client.installed": "Installed",
"client.addonNotInstalled": "Not installed",
"client.updateAvailable": "an update is available",
"client.otherAddons": "Other addons",
"client.leftAsIs": "{n} — left exactly as they are",
"client.pointLocal": "Point the game at this server",
"client.pointedNote": "The game now connects to this computer. The previous address was saved.",
"client.installAddon": "Install companion addon",
"client.updateAddon": "Update companion addon",
"client.addonNote": "Companion addon installed. Other addons were not touched.",
"client.changeFolder": "Change folder…",
} as const; } as const;
export default en; export default en;
+51
View File
@@ -147,6 +147,57 @@ const es: Partial<Record<keyof typeof en, string>> = {
"install.doneTitle": "Tu servidor está listo", "install.doneTitle": "Tu servidor está listo",
"install.doneText": "Todo está instalado. Inícialo desde la siguiente pantalla.", "install.doneText": "Todo está instalado. Inícialo desde la siguiente pantalla.",
"install.open": "ABRIR MI SERVIDOR", "install.open": "ABRIR MI SERVIDOR",
// Players
"players.title": "Jugadores",
"players.createTitle": "Crea tu cuenta",
"players.createText": "Este es el nombre y la contraseña con los que inicias sesión en el juego.",
"players.startFirst": "Inicia primero el servidor: las cuentas se crean mientras está en marcha.",
"players.username": "Nombre de usuario",
"players.password": "Contraseña",
"players.admin": "Convertir esta cuenta en administrador",
"players.adminHint": "Los administradores pueden usar comandos de game master en el juego. Hazlo solo con cuentas de confianza.",
"players.create": "Crear cuenta",
"players.created": "Cuenta «{name}» creada. Ya puedes iniciar sesión en el juego con ella.",
// Companions
"comp.title": "Compañeros de IA",
"comp.population": "{online} en línea ahora · {total} creados en total",
"comp.reading": "Leyendo la población actual…",
"comp.startToSee": "Inicia el servidor para ver cuántos compañeros hay en línea.",
"comp.wantMore": "¿Quieres más compañeros?",
"comp.custom": "Personalizado",
"comp.numberLabel": "Número de compañeros",
"comp.largeWarning": "Las poblaciones grandes pueden requerir más CPU y memoria. Aumenta poco a poco.",
"comp.hardware": "Este equipo: {cores} núcleos, {ram} GB de memoria.",
"comp.add": "Añadir {n} compañeros",
"comp.addPlain": "Añadir compañeros",
"comp.stoppedHint": "El servidor está detenido: se crearán la próxima vez que se inicie.",
"comp.spawned": "Creando {n} compañeros. Aparecerán gradualmente durante los próximos minutos.",
"comp.saved": "Guardado. {n} compañeros iniciarán sesión cuando se inicie el servidor.",
// Client
"client.title": "Cliente del juego",
"client.looking": "Buscando…",
"client.intro": "Indica al Manager dónde está instalado el juego para obtener un botón JUGAR. Tus archivos del juego nunca se modifican, salvo la dirección del servidor y el addon de compañeros.",
"client.chooseFolder": "Elegir carpeta del juego…",
"client.dialogTitle": "Elige la carpeta de tu cliente del juego",
"client.connectsTo": "Se conecta a",
"client.thisComputer": "✓ este equipo",
"client.notThisServer": "no este servidor",
"client.addon": "Addon de compañeros",
"client.installedVersion": "Instalado (versión {v})",
"client.installed": "Instalado",
"client.addonNotInstalled": "No instalado",
"client.updateAvailable": "hay una actualización disponible",
"client.otherAddons": "Otros addons",
"client.leftAsIs": "{n}: se dejan exactamente como están",
"client.pointLocal": "Apuntar el juego a este servidor",
"client.pointedNote": "El juego ahora se conecta a este equipo. La dirección anterior se guardó.",
"client.installAddon": "Instalar addon de compañeros",
"client.updateAddon": "Actualizar addon de compañeros",
"client.addonNote": "Addon de compañeros instalado. Los demás addons no se tocaron.",
"client.changeFolder": "Cambiar carpeta…",
}; };
export default es; export default es;
+51
View File
@@ -147,6 +147,57 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"install.doneTitle": "Votre serveur est prêt", "install.doneTitle": "Votre serveur est prêt",
"install.doneText": "Tout est installé. Démarrez-le depuis l’écran suivant.", "install.doneText": "Tout est installé. Démarrez-le depuis l’écran suivant.",
"install.open": "OUVRIR MON SERVEUR", "install.open": "OUVRIR MON SERVEUR",
// Players
"players.title": "Joueurs",
"players.createTitle": "Créez votre compte",
"players.createText": "C’est le nom et le mot de passe que vous utilisez pour vous connecter au jeu.",
"players.startFirst": "Démarrez d’abord le serveur : les comptes sont créés pendant qu’il fonctionne.",
"players.username": "Nom d’utilisateur",
"players.password": "Mot de passe",
"players.admin": "Faire de ce compte un administrateur",
"players.adminHint": "Les administrateurs peuvent utiliser les commandes de maître de jeu. Ne le faites que pour des comptes de confiance.",
"players.create": "Créer le compte",
"players.created": "Compte « {name} » créé. Vous pouvez maintenant vous connecter au jeu avec.",
// Companions
"comp.title": "Compagnons IA",
"comp.population": "{online} en ligne maintenant · {total} créés au total",
"comp.reading": "Lecture de la population actuelle…",
"comp.startToSee": "Démarrez le serveur pour voir combien de compagnons sont en ligne.",
"comp.wantMore": "Souhaitez-vous plus de compagnons ?",
"comp.custom": "Personnalisé",
"comp.numberLabel": "Nombre de compagnons",
"comp.largeWarning": "De grandes populations peuvent nécessiter plus de processeur et de mémoire. Augmentez progressivement.",
"comp.hardware": "Cet ordinateur : {cores} cœurs, {ram} Go de mémoire.",
"comp.add": "Ajouter {n} compagnons",
"comp.addPlain": "Ajouter des compagnons",
"comp.stoppedHint": "Le serveur est arrêté : ils seront créés au prochain démarrage.",
"comp.spawned": "Création de {n} compagnons. Ils apparaissent progressivement dans les prochaines minutes.",
"comp.saved": "Enregistré. {n} compagnons se connecteront au démarrage du serveur.",
// Client
"client.title": "Client du jeu",
"client.looking": "Recherche…",
"client.intro": "Indiquez au Manager où le jeu est installé pour obtenir un bouton JOUER. Vos fichiers de jeu ne sont jamais modifiés, sauf l’adresse du serveur et l’addon des compagnons.",
"client.chooseFolder": "Choisir le dossier du jeu…",
"client.dialogTitle": "Choisissez le dossier de votre client de jeu",
"client.connectsTo": "Se connecte à",
"client.thisComputer": "✓ cet ordinateur",
"client.notThisServer": "pas ce serveur",
"client.addon": "Addon des compagnons",
"client.installedVersion": "Installé (version {v})",
"client.installed": "Installé",
"client.addonNotInstalled": "Non installé",
"client.updateAvailable": "une mise à jour est disponible",
"client.otherAddons": "Autres addons",
"client.leftAsIs": "{n} — laissés tels quels",
"client.pointLocal": "Diriger le jeu vers ce serveur",
"client.pointedNote": "Le jeu se connecte maintenant à cet ordinateur. L’ancienne adresse a été enregistrée.",
"client.installAddon": "Installer l’addon des compagnons",
"client.updateAddon": "Mettre à jour l’addon des compagnons",
"client.addonNote": "Addon des compagnons installé. Les autres addons n’ont pas été touchés.",
"client.changeFolder": "Changer de dossier…",
}; };
export default fr; export default fr;
+51
View File
@@ -147,6 +147,57 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"install.doneTitle": "Ваш сервер готов", "install.doneTitle": "Ваш сервер готов",
"install.doneText": "Всё установлено. Запустите сервер на следующем экране.", "install.doneText": "Всё установлено. Запустите сервер на следующем экране.",
"install.open": "ОТКРЫТЬ МОЙ СЕРВЕР", "install.open": "ОТКРЫТЬ МОЙ СЕРВЕР",
// Players
"players.title": "Игроки",
"players.createTitle": "Создайте свою учётную запись",
"players.createText": "Это имя и пароль, с которыми вы входите в игру.",
"players.startFirst": "Сначала запустите сервер — учётные записи создаются, пока он работает.",
"players.username": "Имя пользователя",
"players.password": "Пароль",
"players.admin": "Сделать эту учётную запись администратором",
"players.adminHint": "Администраторы могут использовать команды гейм-мастера в игре. Делайте это только для тех, кому доверяете.",
"players.create": "Создать учётную запись",
"players.created": "Учётная запись «{name}» создана. Теперь с ней можно войти в игру.",
// Companions
"comp.title": "ИИ-компаньоны",
"comp.population": "Сейчас в сети: {online} · всего создано: {total}",
"comp.reading": "Считываю текущее количество…",
"comp.startToSee": "Запустите сервер, чтобы увидеть, сколько компаньонов в сети.",
"comp.wantMore": "Хотите больше компаньонов?",
"comp.custom": "Своё число",
"comp.numberLabel": "Количество компаньонов",
"comp.largeWarning": "Большое количество может потребовать больше процессора и памяти. Увеличивайте постепенно.",
"comp.hardware": "Этот компьютер: ядер — {cores}, памяти — {ram} ГБ.",
"comp.add": "Добавить компаньонов: {n}",
"comp.addPlain": "Добавить компаньонов",
"comp.stoppedHint": "Сервер остановлен: компаньоны будут созданы при следующем запуске.",
"comp.spawned": "Создаю компаньонов: {n}. Они появятся постепенно в течение нескольких минут.",
"comp.saved": "Сохранено. Компаньоны ({n}) войдут в игру при запуске сервера.",
// Client
"client.title": "Клиент игры",
"client.looking": "Ищу…",
"client.intro": "Укажите, где установлена игра, чтобы появилась кнопка «Играть». Файлы игры не изменяются, кроме адреса сервера и аддона компаньонов.",
"client.chooseFolder": "Выбрать папку игры…",
"client.dialogTitle": "Выберите папку клиента игры",
"client.connectsTo": "Подключается к",
"client.thisComputer": "✓ этот компьютер",
"client.notThisServer": "не этот сервер",
"client.addon": "Аддон компаньонов",
"client.installedVersion": "Установлен (версия {v})",
"client.installed": "Установлен",
"client.addonNotInstalled": "Не установлен",
"client.updateAvailable": "доступно обновление",
"client.otherAddons": "Другие аддоны",
"client.leftAsIs": "{n} — остаются без изменений",
"client.pointLocal": "Направить игру на этот сервер",
"client.pointedNote": "Теперь игра подключается к этому компьютеру. Прежний адрес сохранён.",
"client.installAddon": "Установить аддон компаньонов",
"client.updateAddon": "Обновить аддон компаньонов",
"client.addonNote": "Аддон компаньонов установлен. Другие аддоны не затронуты.",
"client.changeFolder": "Сменить папку…",
}; };
export default ru; export default ru;
+21 -18
View File
@@ -3,8 +3,11 @@ import { open } from "@tauri-apps/plugin-dialog";
import { api, asUiError, type ClientInfo, type UiError } from "@/lib/api"; import { api, asUiError, type ClientInfo, type UiError } from "@/lib/api";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { useHuman, useT } from "@/i18n";
export function ClientCard({ serverId }: { serverId: string }) { export function ClientCard({ serverId }: { serverId: string }) {
const t = useT();
const human = useHuman();
const [info, setInfo] = useState<ClientInfo | null | undefined>(undefined); const [info, setInfo] = useState<ClientInfo | null | undefined>(undefined);
const [error, setError] = useState<UiError | null>(null); const [error, setError] = useState<UiError | null>(null);
const [note, setNote] = useState<string | null>(null); const [note, setNote] = useState<string | null>(null);
@@ -31,7 +34,7 @@ export function ClientCard({ serverId }: { serverId: string }) {
} }
async function choose() { async function choose() {
const picked = await open({ directory: true, multiple: false, title: "Choose your game client folder" }); const picked = await open({ directory: true, multiple: false, title: t("client.dialogTitle") });
if (typeof picked === "string") await run(async () => void (await api.setClient(serverId, picked))); if (typeof picked === "string") await run(async () => void (await api.setClient(serverId, picked)));
} }
@@ -40,48 +43,48 @@ export function ClientCard({ serverId }: { serverId: string }) {
return ( return (
<Card className="mt-6 p-6"> <Card className="mt-6 p-6">
<h2 className="font-semibold">Game client</h2> <h2 className="font-semibold">{t("client.title")}</h2>
{info === undefined && <p className="mt-2 text-sm text-muted">Looking…</p>} {info === undefined && <p className="mt-2 text-sm text-muted">{t("client.looking")}</p>}
{info === null && ( {info === null && (
<> <>
<p className="mt-1 text-sm text-muted">Tell Manager where your game is installed to get a PLAY button. Your game files are never changed except the server address and the companion addon.</p> <p className="mt-1 text-sm text-muted">{t("client.intro")}</p>
<Button className="mt-4" onClick={() => void choose()} disabled={busy}>Choose game folder…</Button> <Button className="mt-4" onClick={() => void choose()} disabled={busy}>{t("client.chooseFolder")}</Button>
</> </>
)} )}
{info && ( {info && (
<> <>
<p className="selectable mt-1 break-all text-sm text-muted">{info.path}</p> <p className="selectable mt-1 break-all text-sm text-muted">{info.path}</p>
<dl className="mt-4 grid grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm"> <dl className="mt-4 grid grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm">
<dt className="text-muted">Connects to</dt> <dt className="text-muted">{t("client.connectsTo")}</dt>
<dd> <dd>
{hosts.length ? hosts.filter(Boolean).join(", ") : "—"} {hosts.length ? hosts.filter(Boolean).join(", ") : "—"}
{pointsLocal ? <span className="ml-2 text-ok">✓ this computer</span> : <span className="ml-2 text-warn">not this server</span>} {pointsLocal ? <span className="ml-2 text-ok">{t("client.thisComputer")}</span> : <span className="ml-2 text-warn">{t("client.notThisServer")}</span>}
</dd> </dd>
<dt className="text-muted">Companion addon</dt> <dt className="text-muted">{t("client.addon")}</dt>
<dd> <dd>
{info.addon.installed ? `Installed${info.addon.version ? ` (version ${info.addon.version})` : ""}` : "Not installed"} {info.addon.installed ? (info.addon.version ? t("client.installedVersion", { v: info.addon.version }) : t("client.installed")) : t("client.addonNotInstalled")}
{info.addon.up_to_date === false && <span className="ml-2 text-warn">an update is available</span>} {info.addon.up_to_date === false && <span className="ml-2 text-warn">{t("client.updateAvailable")}</span>}
</dd> </dd>
<dt className="text-muted">Other addons</dt> <dt className="text-muted">{t("client.otherAddons")}</dt>
<dd>{info.other_addons} — left exactly as they are</dd> <dd>{t("client.leftAsIs", { n: info.other_addons })}</dd>
</dl> </dl>
<div className="mt-4 flex flex-wrap gap-2"> <div className="mt-4 flex flex-wrap gap-2">
{!pointsLocal && ( {!pointsLocal && (
<Button size="sm" disabled={busy} onClick={() => void run(async () => { await api.setRealmlist(serverId, "127.0.0.1"); return "The game now connects to this computer. The previous address was saved."; })}> <Button size="sm" disabled={busy} onClick={() => void run(async () => { await api.setRealmlist(serverId, "127.0.0.1"); return t("client.pointedNote"); })}>
Point the game at this server {t("client.pointLocal")}
</Button> </Button>
)} )}
{(!info.addon.installed || info.addon.up_to_date === false) && ( {(!info.addon.installed || info.addon.up_to_date === false) && (
<Button size="sm" disabled={busy} onClick={() => void run(async () => { await api.installAddon(serverId); return "Companion addon installed. Other addons were not touched."; })}> <Button size="sm" disabled={busy} onClick={() => void run(async () => { await api.installAddon(serverId); return t("client.addonNote"); })}>
{info.addon.installed ? "Update companion addon" : "Install companion addon"} {info.addon.installed ? t("client.updateAddon") : t("client.installAddon")}
</Button> </Button>
)} )}
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void choose()}>Change folder…</Button> <Button size="sm" variant="ghost" disabled={busy} onClick={() => void choose()}>{t("client.changeFolder")}</Button>
</div> </div>
</> </>
)} )}
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>} {note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : error.human.message}</p>} {error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
</Card> </Card>
); );
} }
+16 -13
View File
@@ -3,8 +3,11 @@ import { Loader2 } from "lucide-react";
import { api, asUiError, type CompanionSizes, type Population, type UiError } from "@/lib/api"; import { api, asUiError, type CompanionSizes, type Population, type UiError } from "@/lib/api";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { useHuman, useT } from "@/i18n";
export function CompanionsCard({ serverId }: { serverId: string }) { export function CompanionsCard({ serverId }: { serverId: string }) {
const t = useT();
const human = useHuman();
const [sizes, setSizes] = useState<CompanionSizes | null>(null); const [sizes, setSizes] = useState<CompanionSizes | null>(null);
const [pop, setPop] = useState<Population | null>(null); const [pop, setPop] = useState<Population | null>(null);
const [running, setRunning] = useState(false); const [running, setRunning] = useState(false);
@@ -33,7 +36,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
}, [serverId]); }, [serverId]);
const count = choice === "custom" ? Number(custom) : (sizes?.sizes.find((s) => s.id === choice)?.bots ?? 0); const count = choice === "custom" ? Number(custom) : (sizes?.sizes.find((s) => s.id === choice)?.bots ?? 0);
const warning = choice === "custom" ? (count > 500 ? "Large populations may need more CPU and memory. Increase gradually." : null) : (sizes?.sizes.find((s) => s.id === choice)?.warning ?? null); const warning = choice === "custom" ? (count > 500 ? t("comp.largeWarning") : null) : (sizes?.sizes.find((s) => s.id === choice)?.warning ?? null);
const valid = Number.isInteger(count) && count >= 1 && count <= 2000; const valid = Number.isInteger(count) && count >= 1 && count <= 2000;
async function add() { async function add() {
@@ -42,7 +45,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
setNote(null); setNote(null);
try { try {
const r = await api.addCompanions(serverId, count); const r = await api.addCompanions(serverId, count);
setNote(r.spawned ? `Creating ${count} companions. They appear gradually over the next minutes.` : `Saved. ${count} companions will log in when the server starts.`); setNote(r.spawned ? t("comp.spawned", { n: count }) : t("comp.saved", { n: count }));
} catch (e) { } catch (e) {
setError(asUiError(e)); setError(asUiError(e));
} finally { } finally {
@@ -52,17 +55,17 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
return ( return (
<Card className="mt-6 p-6"> <Card className="mt-6 p-6">
<h2 className="font-semibold">AI companions</h2> <h2 className="font-semibold">{t("comp.title")}</h2>
<p className="mt-1 text-sm text-muted"> <p className="mt-1 text-sm text-muted">
{pop {pop
? `${pop.bots_online} online now · ${pop.bots_total} created in total` ? t("comp.population", { online: pop.bots_online, total: pop.bots_total })
: running : running
? "Reading the current population…" ? t("comp.reading")
: "Start the server to see how many companions are online."} : t("comp.startToSee")}
</p> </p>
<fieldset className="mt-4"> <fieldset className="mt-4">
<legend className="text-sm text-muted">Would you like more companions?</legend> <legend className="text-sm text-muted">{t("comp.wantMore")}</legend>
<div className="mt-2 flex flex-wrap gap-2"> <div className="mt-2 flex flex-wrap gap-2">
{sizes?.sizes.map((s) => ( {sizes?.sizes.map((s) => (
<label key={s.id} className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === s.id ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}> <label key={s.id} className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === s.id ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}>
@@ -72,26 +75,26 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
))} ))}
<label className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === "custom" ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}> <label className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === "custom" ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}>
<input type="radio" name="size" className="sr-only" checked={choice === "custom"} onChange={() => setChoice("custom")} /> <input type="radio" name="size" className="sr-only" checked={choice === "custom"} onChange={() => setChoice("custom")} />
Custom {t("comp.custom")}
</label> </label>
{choice === "custom" && ( {choice === "custom" && (
<input aria-label="Number of companions" value={custom} onChange={(e) => setCustom(e.target.value)} inputMode="numeric" className="w-24 rounded-md border border-line bg-bg px-3 py-2 text-right text-sm outline-none focus:border-gold" /> <input aria-label={t("comp.numberLabel")} value={custom} onChange={(e) => setCustom(e.target.value)} inputMode="numeric" className="w-24 rounded-md border border-line bg-bg px-3 py-2 text-right text-sm outline-none focus:border-gold" />
)} )}
</div> </div>
</fieldset> </fieldset>
{warning && <p className="mt-3 text-sm text-warn" role="status">{warning}</p>} {warning && <p className="mt-3 text-sm text-warn" role="status">{warning}</p>}
{sizes && <p className="mt-2 text-xs text-muted">This computer: {sizes.hardware.cores} cores, {sizes.hardware.ram_gb.toFixed(0)} GB memory.</p>} {sizes && <p className="mt-2 text-xs text-muted">{t("comp.hardware", { cores: sizes.hardware.cores, ram: sizes.hardware.ram_gb.toFixed(0) })}</p>}
<div className="mt-4 flex items-center gap-3"> <div className="mt-4 flex items-center gap-3">
<Button variant="primary" disabled={busy || !valid} onClick={() => void add()}> <Button variant="primary" disabled={busy || !valid} onClick={() => void add()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />} {busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
Add {valid ? count : ""} companions {valid ? t("comp.add", { n: count }) : t("comp.addPlain")}
</Button> </Button>
{!running && <span className="text-xs text-muted">The server is stopped: they will be created the next time it runs.</span>} {!running && <span className="text-xs text-muted">{t("comp.stoppedHint")}</span>}
</div> </div>
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>} {note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : error.human.message}</p>} {error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
</Card> </Card>
); );
} }
+15 -12
View File
@@ -2,8 +2,11 @@ import { useEffect, useState } from "react";
import { api, asUiError, type UiError } from "@/lib/api"; import { api, asUiError, type UiError } from "@/lib/api";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { useHuman, useT } from "@/i18n";
export function PlayersPage({ serverId }: { serverId: string }) { export function PlayersPage({ serverId }: { serverId: string }) {
const t = useT();
const human = useHuman();
const [online, setOnline] = useState<boolean | null>(null); const [online, setOnline] = useState<boolean | null>(null);
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
@@ -42,37 +45,37 @@ export function PlayersPage({ serverId }: { serverId: string }) {
const input = "w-72 rounded-md border border-line bg-bg px-3 py-2.5 text-[15px] outline-none focus:border-gold"; const input = "w-72 rounded-md border border-line bg-bg px-3 py-2.5 text-[15px] outline-none focus:border-gold";
return ( return (
<div className="max-w-xl"> <div className="max-w-xl">
<h1 className="text-2xl font-semibold">Players</h1> <h1 className="text-2xl font-semibold">{t("players.title")}</h1>
<p className="mt-1 text-muted">Who is playing right now?</p> <p className="mt-1 text-muted">{t("q.players")}</p>
<Card className="mt-6 p-6"> <Card className="mt-6 p-6">
<h2 className="font-semibold">Create your account</h2> <h2 className="font-semibold">{t("players.createTitle")}</h2>
<p className="mt-1 text-sm text-muted">This is the name and password you use to log in to the game.</p> <p className="mt-1 text-sm text-muted">{t("players.createText")}</p>
{online === false && <p className="mt-3 text-sm text-warn">Start the server first — accounts are created while it is running.</p>} {online === false && <p className="mt-3 text-sm text-warn">{t("players.startFirst")}</p>}
<div className="mt-4 flex flex-col gap-3"> <div className="mt-4 flex flex-col gap-3">
<div> <div>
<label htmlFor="acc-user" className="text-sm text-muted">Username</label> <label htmlFor="acc-user" className="text-sm text-muted">{t("players.username")}</label>
<input id="acc-user" className={input + " mt-1 block"} value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="off" /> <input id="acc-user" className={input + " mt-1 block"} value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="off" />
</div> </div>
<div> <div>
<label htmlFor="acc-pass" className="text-sm text-muted">Password</label> <label htmlFor="acc-pass" className="text-sm text-muted">{t("players.password")}</label>
<input id="acc-pass" type="password" className={input + " mt-1 block"} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" /> <input id="acc-pass" type="password" className={input + " mt-1 block"} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" />
</div> </div>
<label className="flex cursor-pointer items-start gap-2 text-sm"> <label className="flex cursor-pointer items-start gap-2 text-sm">
<input type="checkbox" checked={admin} onChange={(e) => setAdmin(e.target.checked)} className="mt-1" /> <input type="checkbox" checked={admin} onChange={(e) => setAdmin(e.target.checked)} className="mt-1" />
<span> <span>
Make this account an administrator {t("players.admin")}
<span className="block text-xs text-muted">Administrators can use game-master commands in the game. Only do this for accounts you trust.</span> <span className="block text-xs text-muted">{t("players.adminHint")}</span>
</span> </span>
</label> </label>
</div> </div>
<Button className="mt-5" variant="primary" disabled={busy || !online || !username || !password} onClick={() => void create()}> <Button className="mt-5" variant="primary" disabled={busy || !online || !username || !password} onClick={() => void create()}>
Create account {t("players.create")}
</Button> </Button>
{done && <p className="mt-3 text-sm text-ok" role="status">Account “{done}” created. You can log in to the game with it now.</p>} {done && <p className="mt-3 text-sm text-ok" role="status">{t("players.created", { name: done })}</p>}
{error && ( {error && (
<p className="mt-3 text-sm text-bad" role="alert"> <p className="mt-3 text-sm text-bad" role="alert">
{error.human.code === "unknown" ? error.technical : error.human.message} {error.human.code === "unknown" ? error.technical : human(error.human).message}
</p> </p>
)} )}
</Card> </Card>