mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 19:25:56 +00:00
Merge master into feat/portable-characters
This commit is contained in:
commit
2b95553168
44 files changed
+2614
-108
No files matched your search
@@ -91,6 +91,8 @@ export {};
|
||||
if(cmd==="report_targets") return [{id:"manager",repo:"Corfirean/coa-server-manager",ours:true},{id:"companions",repo:"Corfirean/mod-coa-playerbots",ours:true},{id:"squid",repo:"Zyth45/mod-playerbots",ours:false}];
|
||||
if(cmd==="open_link"){(window as any).__lastLink=args.url;return null;}
|
||||
if(cmd==="export_diagnostics") return "C:\\Users\\you\\Desktop\\CoA-Diagnostics-20261001-140000.zip";
|
||||
if(cmd==="list_crashes") return [];
|
||||
if(cmd==="install_environment"){const docker=new URLSearchParams(location.search).get("flavor")==="docker";return docker?{flavor:"docker",default_dir:"/home/you/CoaServer",docker_problem:new URLSearchParams(location.search).has("nodocker")?"permission denied while trying to connect to the Docker daemon socket":null}:{flavor:"repack",default_dir:"C:\\Games\\CoA Server",docker_problem:null};}
|
||||
if(cmd==="install_preflight") return {ok:true,problems:[],free_bytes:210*2**30};
|
||||
if(cmd==="install_requirements") return {download_bytes:Math.round(5.9*2**30),unpacked_bytes:Math.round(11.4*2**30),version:"0.2.0"};
|
||||
if(cmd==="list_accounts"){const w=window as any;w.__acc=w.__acc??[{id:2,name:"ALICE",access:3,online:true,last_login:"2026-10-01 12:04:11",characters:4},{id:5,name:"BOB",access:0,online:false,last_login:null,characters:0},{id:6,name:"CAROL",access:2,online:false,last_login:"2026-09-30 21:40:02",characters:2}];return w.__acc;}
|
||||
|
||||
@@ -867,6 +867,21 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"fr.lan.unavailable": "Ausgewählte Adresse nicht verfügbar",
|
||||
"fr.lan.unavailableText": "Die ausgewählte Adresse ist derzeit keinem erkannten lokalen Netzwerkadapter zugewiesen. Wählen Sie eine andere Adresse oder Automatisch, oder behalten Sie diese Adresse bewusst bei.",
|
||||
"fr.lan.invalid": "Ungültige IPv4-Adresse",
|
||||
"unsaved.title": "Nicht gespeicherte Änderungen",
|
||||
"unsaved.message": "Sie haben nicht gespeicherte Änderungen. Möchten Sie diese vor dem Verlassen der Seite speichern?",
|
||||
"unsaved.saveFailed": "Änderungen konnten nicht gespeichert werden. Bitte Eingaben überprüfen.",
|
||||
"crash.autoRestart": "Automatischer Neustart bei Absturz",
|
||||
"crash.autoRestartDesc": "Startet den Server automatisch neu, falls er unerwartet abstürzt.",
|
||||
"crash.badge": "Abstürze: {n}",
|
||||
"crash.historyTitle": "Absturzverlauf des Servers",
|
||||
"crash.noCrashes": "Keine Absturzberichte gefunden.",
|
||||
"crash.restartNotice": "Der Server ist abgestürzt und wurde automatisch neu gestartet (Absturz #{n}).",
|
||||
"crash.loopPaused": "Automatischer Neustart pausiert: Der Server ist mehrfach kurz hintereinander abgestürzt.",
|
||||
"crash.details": "Absturzdetails",
|
||||
"crash.viewRaw": "Vollständigen Bericht anzeigen",
|
||||
"crash.hideRaw": "Vollständigen Bericht verbergen",
|
||||
"crash.copyReport": "Bericht kopieren",
|
||||
"crash.copied": "Kopiert!",
|
||||
};
|
||||
|
||||
export default de;
|
||||
@@ -192,6 +192,14 @@ const en = {
|
||||
"install.localPkg": "Install from a local package folder instead of downloading",
|
||||
"install.localPkgHint": "(leave empty to download)",
|
||||
"install.button": "Install",
|
||||
"install.docker.title": "Docker is needed",
|
||||
"install.docker.text": "On Linux the server runs in Docker. Install Docker and start it, or allow your user to use it, then check again.",
|
||||
"install.docker.retry": "Check again",
|
||||
"install.data.label": "Game data folder",
|
||||
"install.data.hint": "The folder with the game's dbc, maps, vmaps and mmaps. It is used where it is and never changed.",
|
||||
"install.data.dialogTitle": "Choose the game data folder",
|
||||
"install.linuxPkg.label": "Server package",
|
||||
"install.linuxPkg.hint": "A folder or an address of the Linux server package",
|
||||
"install.progressTitle": "Preparing your server",
|
||||
"install.progressText": "This can take a few minutes. You can leave this window open.",
|
||||
"install.step.checking": "Checking your computer",
|
||||
@@ -1158,6 +1166,21 @@ const en = {
|
||||
"access.linkUp": "Connected to the control service: players can get accounts and claim characters.",
|
||||
"access.linkDown": "Not connected to the control service yet.",
|
||||
"access.fileStore": "Secrets are kept in a protected file, not encrypted by the system, on this computer.",
|
||||
"unsaved.title": "Unsaved changes",
|
||||
"unsaved.message": "You have unsaved changes. Do you want to save them before leaving this page?",
|
||||
"unsaved.saveFailed": "Failed to save changes. Please check fields for errors.",
|
||||
"crash.autoRestart": "Auto-restart on crash",
|
||||
"crash.autoRestartDesc": "Automatically restart the world server if it crashes or stops unexpectedly.",
|
||||
"crash.badge": "Crashes: {n}",
|
||||
"crash.historyTitle": "Server Crash History",
|
||||
"crash.noCrashes": "No crash reports found.",
|
||||
"crash.restartNotice": "Server crashed and was automatically restarted (Crash #{n}).",
|
||||
"crash.loopPaused": "Auto-restart paused: the server crashed repeatedly in a short period.",
|
||||
"crash.details": "Crash Details",
|
||||
"crash.viewRaw": "View full crash report",
|
||||
"crash.hideRaw": "Hide full report",
|
||||
"crash.copyReport": "Copy crash report",
|
||||
"crash.copied": "Copied!",
|
||||
} as const;
|
||||
|
||||
export default en;
|
||||
@@ -867,6 +867,21 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"fr.lan.unavailable": "Dirección seleccionada no disponible",
|
||||
"fr.lan.unavailableText": "La dirección seleccionada no está asignada actualmente a ninguna interfaz local detectada. Elige otra dirección o Automática, o conserva esta dirección si así lo deseas.",
|
||||
"fr.lan.invalid": "Dirección IPv4 no válida",
|
||||
"unsaved.title": "Cambios sin guardar",
|
||||
"unsaved.message": "¿Tienes cambios sin guardar. ¿Quieres guardarlos antes de salir de esta página?",
|
||||
"unsaved.saveFailed": "Error al guardar los cambios. Revisa los campos.",
|
||||
"crash.autoRestart": "Reinicio automático tras caída",
|
||||
"crash.autoRestartDesc": "Reinicia automáticamente el servidor si se detiene de forma inesperada.",
|
||||
"crash.badge": "Caídas: {n}",
|
||||
"crash.historyTitle": "Historial de caídas del servidor",
|
||||
"crash.noCrashes": "No se encontraron informes de caídas.",
|
||||
"crash.restartNotice": "El servidor se cayó y se reinició automáticamente (Caída #{n}).",
|
||||
"crash.loopPaused": "Reinicio automático pausado: el servidor se ha caído varias veces en poco tiempo.",
|
||||
"crash.details": "Detalles de la caída",
|
||||
"crash.viewRaw": "Ver informe completo",
|
||||
"crash.hideRaw": "Ocultar informe completo",
|
||||
"crash.copyReport": "Copiar informe",
|
||||
"crash.copied": "¡Copiado!",
|
||||
};
|
||||
|
||||
export default es;
|
||||
@@ -867,6 +867,21 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"fr.lan.unavailable": "Adresse sélectionnée indisponible",
|
||||
"fr.lan.unavailableText": "Cette adresse n’est actuellement attribuée à aucune interface locale détectée. Choisissez une autre adresse ou le mode Automatique, ou conservez volontairement cette adresse.",
|
||||
"fr.lan.invalid": "Adresse IPv4 non valide",
|
||||
"unsaved.title": "Modifications non enregistrées",
|
||||
"unsaved.message": "Vous avez des modifications non enregistrées. Voulez-vous les enregistrer avant de quitter cette page ?",
|
||||
"unsaved.saveFailed": "Échec de l’enregistrement. Veuillez vérifier les champs.",
|
||||
"crash.autoRestart": "Redémarrage automatique en cas de plantage",
|
||||
"crash.autoRestartDesc": "Redémarre automatiquement le serveur s’il plante ou s’arrête de manière inattendue.",
|
||||
"crash.badge": "Plantages : {n}",
|
||||
"crash.historyTitle": "Historique des plantages du serveur",
|
||||
"crash.noCrashes": "Aucun rapport de plantage trouvé.",
|
||||
"crash.restartNotice": "Le serveur a planté et a été redémarré automatiquement (Plantage #{n}).",
|
||||
"crash.loopPaused": "Redémarrage automatique suspendu : le serveur a planté plusieurs fois successivement.",
|
||||
"crash.details": "Détails du plantage",
|
||||
"crash.viewRaw": "Afficher le rapport complet",
|
||||
"crash.hideRaw": "Masquer le rapport complet",
|
||||
"crash.copyReport": "Copier le rapport",
|
||||
"crash.copied": "Copié !",
|
||||
};
|
||||
|
||||
export default fr;
|
||||
@@ -1156,6 +1156,21 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"access.linkUp": "Подключено к службе управления: игроки могут получать аккаунты и переносить персонажей.",
|
||||
"access.linkDown": "К службе управления пока не подключено.",
|
||||
"access.fileStore": "Секреты хранятся в защищённом файле без шифрования системой на этом компьютере.",
|
||||
"unsaved.title": "Несохранённые изменения",
|
||||
"unsaved.message": "У вас есть несохранённые изменения. Сохранить их перед переходом на другую страницу?",
|
||||
"unsaved.saveFailed": "Не удалось сохранить настройки. Проверьте правильность значений.",
|
||||
"crash.autoRestart": "Автоподнятие при падении",
|
||||
"crash.autoRestartDesc": "Автоматически перезапускать сервер при внезапном падении или сбое.",
|
||||
"crash.badge": "Крашей: {n}",
|
||||
"crash.historyTitle": "История падений сервера",
|
||||
"crash.noCrashes": "Отчётов о падениях не найдено.",
|
||||
"crash.restartNotice": "Сервер упал и был автоматически перезапущен (Сбой #{n}).",
|
||||
"crash.loopPaused": "Автоподнятие приостановлено: сервер упал несколько раз подряд за короткое время.",
|
||||
"crash.details": "Подробности сбоя",
|
||||
"crash.viewRaw": "Показать полный отчёт",
|
||||
"crash.hideRaw": "Скрыть полный отчёт",
|
||||
"crash.copyReport": "Скопировать отчёт",
|
||||
"crash.copied": "Скопировано!",
|
||||
};
|
||||
|
||||
export default ru;
|
||||
@@ -869,6 +869,21 @@ const zh = {
|
||||
"fr.lan.unavailable": "所选地址不可用",
|
||||
"fr.lan.unavailableText": "所选地址目前未分配给检测到的本地网络接口。请选择其他地址、切换到自动,或有意保留此地址。",
|
||||
"fr.lan.invalid": "无效的 IPv4 地址",
|
||||
"unsaved.title": "未保存的修改",
|
||||
"unsaved.message": "您有未保存的修改。是否在离开前保存?",
|
||||
"unsaved.saveFailed": "保存失败,请检查填写内容。",
|
||||
"crash.autoRestart": "崩溃后自动重启",
|
||||
"crash.autoRestartDesc": "如果服务器意外崩溃或停止,自动重新拉起。",
|
||||
"crash.badge": "崩溃次数: {n}",
|
||||
"crash.historyTitle": "服务器崩溃记录",
|
||||
"crash.noCrashes": "未找到崩溃日志。",
|
||||
"crash.restartNotice": "服务器崩溃并已自动重新拉起(崩溃 #{n})。",
|
||||
"crash.loopPaused": "自动重启已暂停:服务器在短时间内连续崩溃。",
|
||||
"crash.details": "崩溃详情",
|
||||
"crash.viewRaw": "查看完整日志",
|
||||
"crash.hideRaw": "隐藏完整日志",
|
||||
"crash.copyReport": "复制崩溃报告",
|
||||
"crash.copied": "已复制!",
|
||||
} as const;
|
||||
|
||||
export default zh;
|
||||
+48
-2
@@ -265,6 +265,16 @@ export interface ReportTarget {
|
||||
ours: boolean;
|
||||
}
|
||||
|
||||
/** The kind of server this computer installs: a repack (Windows) or Docker containers (Linux). */
|
||||
export type Flavor = "repack" | "docker";
|
||||
|
||||
export interface InstallEnvironment {
|
||||
flavor: Flavor;
|
||||
default_dir: string;
|
||||
/** Why Docker cannot be used, in its own words; null when it works. */
|
||||
docker_problem: string | null;
|
||||
}
|
||||
|
||||
export interface InstallRequirements {
|
||||
download_bytes: number;
|
||||
unpacked_bytes: number;
|
||||
@@ -379,6 +389,22 @@ export interface ClientDownloadCheck {
|
||||
dest: string;
|
||||
}
|
||||
|
||||
export type ClientPatchState = "not-installed" | "enabled" | "disabled" | "partially-installed";
|
||||
|
||||
export interface CustomRacesClientStatus {
|
||||
state: ClientPatchState;
|
||||
installedMpqs: number;
|
||||
totalMpqs: number;
|
||||
hasRootFiles: boolean;
|
||||
clientPath: string | null;
|
||||
}
|
||||
|
||||
export interface CustomRacesProgress {
|
||||
id: string;
|
||||
step: string;
|
||||
percent: number;
|
||||
}
|
||||
|
||||
export type FriendsMode = "local" | "lan" | "direct" | "private";
|
||||
|
||||
export interface LanAddress {
|
||||
@@ -421,6 +447,21 @@ export interface ConsoleLine {
|
||||
level: "info" | "warn" | "error";
|
||||
}
|
||||
|
||||
export interface CrashItem {
|
||||
id: string;
|
||||
timestamp_ms: number;
|
||||
date_str: string;
|
||||
title: string;
|
||||
explanation: string;
|
||||
category: "assertion" | "access_violation" | "stack_overflow" | "out_of_memory" | "database" | "network" | "exception" | "generic";
|
||||
exception_code?: string | null;
|
||||
location?: string | null;
|
||||
function?: string | null;
|
||||
condition?: string | null;
|
||||
preview: string;
|
||||
full_log: string;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
remoteConnection: () => invoke<RemoteConnection>("remote_connection"),
|
||||
remoteConnect: (host: string) => invoke<RemoteConnection>("remote_connect", { host }),
|
||||
@@ -454,7 +495,8 @@ export const api = {
|
||||
deleteBackup: (id: string, backupId: string) => invoke<void>("delete_backup", { id, backupId }),
|
||||
restoreConfigs: (id: string, backupId: string) => invoke<RecoveryPoint>("restore_backup_configs", { id, backupId }),
|
||||
restoreDatabase: (id: string, backupId: string, database: string) => invoke<DbRestore>("restore_backup_database", { id, backupId, database }),
|
||||
installPreflight: (dest: string, needed?: number) => invoke<Preflight>("install_preflight", { dest, needed: needed ?? null }),
|
||||
installEnvironment: () => invoke<InstallEnvironment>("install_environment"),
|
||||
installPreflight: (dest: string, needed?: number, gameData?: string) => invoke<Preflight>("install_preflight", { dest, needed: needed ?? null, gameData: gameData ?? null }),
|
||||
installRequirements: (pkg?: string) => invoke<InstallRequirements>("install_requirements", { package: pkg ?? null }),
|
||||
realmlistProfiles: (id: string) => invoke<{ profiles: RealmProfile[]; active: string | null }>("realmlist_profiles", { id }),
|
||||
realmlistSave: (id: string, profileId: string | null, name: string, data: string) => invoke<RealmProfile>("realmlist_save", { id, profileId, name, data }),
|
||||
@@ -473,7 +515,7 @@ export const api = {
|
||||
accountSetAccess: (id: string, name: string, level: number) => invoke<void>("account_set_access", { id, name, level }),
|
||||
accountRename: (id: string, name: string, newName: string, password: string) => invoke<void>("account_rename", { id, name, newName, password }),
|
||||
accountDelete: (id: string, name: string) => invoke<void>("account_delete", { id, name }),
|
||||
installNew: (dest: string, pkg?: string) => invoke<ServerSummary>("install_new", { dest, package: pkg ?? null }),
|
||||
installNew: (dest: string, pkg?: string, gameData?: string) => invoke<ServerSummary>("install_new", { dest, package: pkg ?? null, gameData: gameData ?? null }),
|
||||
cancelInstall: () => invoke<void>("cancel_install"),
|
||||
createAccount: (id: string, username: string, password: string, administrator: boolean) =>
|
||||
invoke<void>("create_account", { id, username, password, administrator }),
|
||||
@@ -503,6 +545,9 @@ export const api = {
|
||||
clientSync: (id: string, keepModified: boolean) => invoke<void>("client_sync", { id, keepModified }),
|
||||
clientDownload: (id: string, parent: string) => invoke<ClientInfo>("client_download", { id, parent }),
|
||||
clientCancel: () => invoke<void>("client_cancel"),
|
||||
customRacesStatus: (id: string) => invoke<CustomRacesClientStatus | null>("custom_races_status", { id }),
|
||||
customRacesInstall: (id: string) => invoke<void>("custom_races_install", { id }),
|
||||
customRacesToggleClient: (id: string, enabled: boolean) => invoke<void>("custom_races_toggle_client", { id, enabled }),
|
||||
play: (id: string) => invoke<DriverOutcome>("play", { id }),
|
||||
friendsStatus: (id: string) => invoke<FriendsStatus>("friends_status", { id }),
|
||||
friendsCheckInternet: () => invoke<InternetCheck>("friends_check_internet"),
|
||||
@@ -512,6 +557,7 @@ export const api = {
|
||||
runDiagnostics: (id: string) => invoke<{ checks: DiagCheck[]; problems: number }>("run_diagnostics", { id }),
|
||||
verifyFiles: (id: string) => invoke<{ path: string; kind: "missing" | "changed" }[]>("verify_files", { id }),
|
||||
exportDiagnostics: (id: string) => invoke<string>("export_diagnostics", { id }),
|
||||
listCrashes: (id: string, limit?: number) => invoke<CrashItem[]>("list_crashes", { id, limit: limit ?? null }),
|
||||
consoleTail: (id: string, source: ConsoleSource, filter?: string, lines = 300) =>
|
||||
invoke<ConsoleLine[]>("console_tail", { id, source, filter: filter ?? null, lines }),
|
||||
consoleRisk: (command: string) => invoke<"normal" | "dangerous">("console_risk", { command }),
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useState } from "react";
|
||||
|
||||
const key = (id: string) => `coa-auto-restart-on-crash:${id}`;
|
||||
const fallback = () => false;
|
||||
|
||||
export function autoRestartOnCrash(id: string): boolean {
|
||||
try {
|
||||
const value = localStorage.getItem(key(id));
|
||||
return value === null ? fallback() : value === "1";
|
||||
} catch {
|
||||
return fallback();
|
||||
}
|
||||
}
|
||||
|
||||
export function setAutoRestartOnCrash(id: string, on: boolean) {
|
||||
try {
|
||||
localStorage.setItem(key(id), on ? "1" : "0");
|
||||
} catch {
|
||||
/* storage unavailable */
|
||||
}
|
||||
}
|
||||
|
||||
export function useAutoRestart(id: string): [boolean, (on: boolean) => void] {
|
||||
const [on, setOn] = useState(() => autoRestartOnCrash(id));
|
||||
return [
|
||||
on,
|
||||
(next) => {
|
||||
setAutoRestartOnCrash(id, next);
|
||||
setOn(next);
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -85,6 +85,11 @@ for (const [key, title, desc] of [
|
||||
] as [string, string[], string[]][]) add(`Enchanter.${key}`, "int", title, desc, { min: 0, advanced: true });
|
||||
for (let n = 1; n <= 3; n++) add(`EC.P${n}`, "string", [`NPC phrase ${n}`, `Реплика НПС ${n}`, `NPC-Satz ${n}`, `Phrase du PNJ ${n}`, `Frase del PNJ ${n}`, `NPC台词 ${n}`], ["Text spoken by the NPC. Keep the enclosing quotes.", "Текст реплики НПС. Сохраните кавычки вокруг текста.", "Gesprochener Text. Anführungszeichen beibehalten.", "Texte prononcé. Conservez les guillemets.", "Texto hablado. Conserva las comillas.", "NPC发言内容,请保留外层引号。"], { advanced: true });
|
||||
|
||||
add("CoACustomRaces.BotsEnable", "bool",
|
||||
["Bots can be custom races", "Боты кастомных рас", "Bots benutzerdefinierter Völker", "Bots de races personnalisées", "Bots de razas personalizadas", "允许机器人为自定义种族"],
|
||||
["Allow Playerbots to spawn as custom races.", "Разрешает ботам-игрокам появляться кастомными расами.", "Erlaubt Spieler-Bots, benutzerdefinierte Völker zu nutzen.", "Autorise les bots joueurs à s’incarner avec des races personnalisées.", "Permite a los bots jugadores crearse con razas personalizadas.", "允许玩家机器人扮演自定义种族。"]
|
||||
);
|
||||
|
||||
const ah = "AuctionHouseBot.";
|
||||
add(ah + "GUIDs", "string", ["Auction characters", "Персонажи аукциона", "Auktionscharaktere", "Personnages d’enchères", "Personajes de subasta", "拍卖角色"], ["Leave 0 and the server creates and uses its own auction character. To use your own, enter GUIDs separated by commas, without spaces; use dedicated offline characters, not companion bots.", "Оставьте 0, и сервер сам создаст и будет использовать своего персонажа аукциона. Чтобы использовать своих, укажите GUID через запятую без пробелов; нужны отдельные офлайн-персонажи, не боты-компаньоны.", "Bei 0 legt der Server selbst einen Auktionscharakter an und nutzt ihn. Eigene Charaktere: GUIDs durch Kommas, ohne Leerzeichen; separate Offline-Charaktere verwenden, keine Begleiter-Bots.", "Laissez 0 : le serveur crée et utilise son propre personnage d’enchères. Pour les vôtres, indiquez des GUID séparés par des virgules sans espaces ; personnages dédiés hors ligne, pas des bots compagnons.", "Deja 0 y el servidor crea y usa su propio personaje de subastas. Para usar los tuyos, indica GUID separados por comas sin espacios; personajes dedicados desconectados, no bots acompañantes.", "保持0时由服务器自动创建并使用拍卖角色。要使用自己的角色,请以逗号分隔填写GUID,不加空格;使用专用离线角色,勿用伙伴机器人。"], { advanced: true });
|
||||
add(ah + "EnableSeller", "bool", ["Post auctions", "Выставлять лоты", "Auktionen einstellen", "Publier des enchères", "Publicar subastas", "发布拍卖"], ["Let the auction characters sell items. The module switch is also required.", "Разрешает персонажам продавать предметы. Нужен включённый модуль.", "Erlaubt Verkäufe. Der Modulschalter muss ebenfalls aktiv sein.", "Autorise les ventes. Le module doit aussi être activé.", "Permite vender. También requiere el módulo activado.", "允许拍卖角色出售物品,还需启用模块。"]);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export interface UnsavedChangesGuard {
|
||||
isDirty: () => boolean;
|
||||
save: () => Promise<boolean>;
|
||||
discard: () => void;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useT } from "@/i18n";
|
||||
import { useAutoRestart } from "@/lib/autoRestartPrefs";
|
||||
|
||||
export function AutoRestartSettings({ serverId }: { serverId: string }) {
|
||||
const t = useT();
|
||||
const [autoRestart, setAutoRestart] = useAutoRestart(serverId);
|
||||
|
||||
return (
|
||||
<Card className="mt-6 p-6">
|
||||
<h2 className="font-semibold">{t("crash.autoRestart")}</h2>
|
||||
<label className="mt-3 flex cursor-pointer items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoRestart}
|
||||
onChange={(e) => setAutoRestart(e.target.checked)}
|
||||
className="h-4 w-4 accent-[#c9a24a]"
|
||||
/>
|
||||
<span className="text-sm font-medium">{t("crash.autoRestart")}</span>
|
||||
</label>
|
||||
<p className="mt-2 text-sm text-muted">{t("crash.autoRestartDesc")}</p>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { AlertTriangle, Check, ChevronDown, ChevronUp, Copy, Loader2, X } from "lucide-react";
|
||||
import { api, type CrashItem } from "@/lib/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useT } from "@/i18n";
|
||||
|
||||
export function CrashHistoryModal({
|
||||
serverId,
|
||||
onClose,
|
||||
}: {
|
||||
serverId: string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [crashes, setCrashes] = useState<CrashItem[]>([]);
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
void api
|
||||
.listCrashes(serverId, 30)
|
||||
.then((items) => {
|
||||
if (alive) {
|
||||
setCrashes(items);
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [serverId]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose]);
|
||||
|
||||
const copyReport = async (item: CrashItem) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(item.full_log);
|
||||
setCopiedId(item.id);
|
||||
setTimeout(() => setCopiedId(null), 2500);
|
||||
} catch {
|
||||
/* clipboard write failed */
|
||||
}
|
||||
};
|
||||
|
||||
const getCategoryColor = (category: CrashItem["category"]) => {
|
||||
switch (category) {
|
||||
case "assertion":
|
||||
return "bg-amber-500/15 text-amber-400 border-amber-500/30";
|
||||
case "access_violation":
|
||||
case "stack_overflow":
|
||||
case "out_of_memory":
|
||||
return "bg-bad/15 text-bad border-bad/30";
|
||||
case "network":
|
||||
case "database":
|
||||
return "bg-blue-500/15 text-blue-400 border-blue-500/30";
|
||||
default:
|
||||
return "bg-muted/15 text-muted border-line";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 md:p-6"
|
||||
role="presentation"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<Card
|
||||
className="flex max-h-[85vh] w-full max-w-2xl flex-col p-6 shadow-2xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("crash.historyTitle")}
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-line pb-4">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<AlertTriangle className="h-5 w-5 text-warn" aria-hidden />
|
||||
<h2 className="text-lg font-semibold">{t("crash.historyTitle")}</h2>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="cursor-pointer text-muted transition-colors hover:text-ink"
|
||||
aria-label={t("btn.close")}
|
||||
>
|
||||
<X className="h-5 w-5" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto py-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12 text-muted">
|
||||
<Loader2 className="h-6 w-6 animate-spin" aria-hidden />
|
||||
</div>
|
||||
) : crashes.length === 0 ? (
|
||||
<div className="py-12 text-center text-muted">
|
||||
<p>{t("crash.noCrashes")}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{crashes.map((item) => {
|
||||
const isExpanded = expandedId === item.id;
|
||||
const isCopied = copiedId === item.id;
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className="rounded-lg border border-line bg-card-2 p-4 text-sm transition-all"
|
||||
>
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<span
|
||||
className={`inline-block rounded border px-2 py-0.5 text-xs font-medium uppercase tracking-wide ${getCategoryColor(
|
||||
item.category,
|
||||
)}`}
|
||||
>
|
||||
{item.exception_code ? `${item.category} (${item.exception_code})` : item.category}
|
||||
</span>
|
||||
<h3 className="mt-1.5 font-semibold text-ink">{item.title}</h3>
|
||||
</div>
|
||||
<span className="text-xs text-muted tabular-nums">{item.date_str}</span>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-xs leading-relaxed text-muted">{item.explanation}</p>
|
||||
|
||||
<div className="mt-3 flex items-center justify-between border-t border-line/50 pt-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedId(isExpanded ? null : item.id)}
|
||||
className="inline-flex cursor-pointer items-center gap-1.5 text-xs font-medium text-gold transition-colors hover:underline"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronUp className="h-3.5 w-3.5" aria-hidden />
|
||||
{t("crash.hideRaw")}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronDown className="h-3.5 w-3.5" aria-hidden />
|
||||
{t("crash.viewRaw")}
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => void copyReport(item)}
|
||||
className="h-7 gap-1.5 px-2 text-xs text-muted hover:text-ink"
|
||||
>
|
||||
{isCopied ? (
|
||||
<>
|
||||
<Check className="h-3.5 w-3.5 text-ok" aria-hidden />
|
||||
<span className="text-ok">{t("crash.copied")}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-3.5 w-3.5" aria-hidden />
|
||||
<span>{t("crash.copyReport")}</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-3">
|
||||
<pre className="selectable max-h-56 overflow-x-auto overflow-y-auto rounded border border-line bg-black/40 p-3 font-mono text-[11px] leading-relaxed text-muted">
|
||||
{item.full_log}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end border-t border-line pt-4">
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
{t("btn.close")}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { Check, ChevronDown, ChevronRight, Loader2 } from "lucide-react";
|
||||
import { api, asUiError, type InstallRequirements, type InstallStep, type Preflight, type ServerSummary, type UiError } from "@/lib/api";
|
||||
import { api, asUiError, type InstallEnvironment, type InstallRequirements, type InstallStep, type Preflight, type ServerSummary, type UiError } from "@/lib/api";
|
||||
import { formatBytes } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@@ -33,6 +33,19 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
const [pkg, setPkg] = useState("");
|
||||
const [installed, setInstalled] = useState<ServerSummary | null>(null);
|
||||
const [showDetails, setShowDetails] = useState(false);
|
||||
// What this computer installs. A repack (Windows) needs nothing more than a folder; Docker (Linux) also needs the game data
|
||||
// folder and a package, and Docker itself.
|
||||
const [env, setEnv] = useState<InstallEnvironment | null>(null);
|
||||
const [gameData, setGameData] = useState("");
|
||||
const docker = env?.flavor === "docker";
|
||||
|
||||
function loadEnvironment(first: boolean) {
|
||||
void api.installEnvironment().then((e) => {
|
||||
setEnv(e);
|
||||
if (first && e.flavor === "docker") setDest(e.default_dir);
|
||||
}).catch(() => setEnv(null));
|
||||
}
|
||||
useEffect(() => loadEnvironment(true), []);
|
||||
|
||||
// how big the server is, from the package's signed list (re-read when another package source is entered)
|
||||
useEffect(() => {
|
||||
@@ -43,9 +56,9 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
// room for the unpacked server plus the download that is removed afterwards
|
||||
const needed = req ? req.unpacked_bytes + req.download_bytes : undefined;
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => void api.installPreflight(dest, needed).then(setPre).catch(() => setPre(null)), 250);
|
||||
const timer = setTimeout(() => void api.installPreflight(dest, needed, docker ? gameData.trim() : undefined).then(setPre).catch(() => setPre(null)), 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [dest, needed]);
|
||||
}, [dest, needed, docker, gameData]);
|
||||
|
||||
useEffect(() => {
|
||||
const un = listen<InstallStep>("install-progress", (e) => setStep(e.payload));
|
||||
@@ -56,7 +69,12 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
|
||||
async function browse() {
|
||||
const picked = await open({ directory: true, multiple: false, title: t("install.dialogTitle") });
|
||||
if (typeof picked === "string") setDest(picked.replace(/[\\/]+$/, "") + (picked.toLowerCase().includes("coa") ? "" : "\\CoA Server"));
|
||||
if (typeof picked === "string") setDest(picked.replace(/[\\/]+$/, "") + (picked.toLowerCase().includes("coa") ? "" : docker ? "/CoaServer" : "\\CoA Server"));
|
||||
}
|
||||
|
||||
async function browseGameData() {
|
||||
const picked = await open({ directory: true, multiple: false, title: t("install.data.dialogTitle") });
|
||||
if (typeof picked === "string") setGameData(picked);
|
||||
}
|
||||
|
||||
async function browsePackage() {
|
||||
@@ -69,7 +87,7 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
setPhase("installing");
|
||||
setStep({ step: "Preparing your server", percent: 0, detail: null });
|
||||
try {
|
||||
const s = await api.installNew(dest, pkg.trim() || undefined);
|
||||
const s = await api.installNew(dest, pkg.trim() || undefined, docker ? gameData.trim() : undefined);
|
||||
setInstalled(s);
|
||||
setPhase("done");
|
||||
} catch (e) {
|
||||
@@ -139,9 +157,34 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{pre && pre.problems.length > 0 && (
|
||||
{docker && (
|
||||
<div>
|
||||
<label htmlFor="gamedata" className="text-sm text-muted">{t("install.data.label")}</label>
|
||||
<div className="mt-1 flex gap-2">
|
||||
<input id="gamedata" value={gameData} onChange={(e) => setGameData(e.target.value)} className="selectable flex-1 rounded-md border border-line bg-card px-3 py-2.5 text-[15px] outline-none focus:border-gold" />
|
||||
<Button onClick={browseGameData}>{t("install.browse")}</Button>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted">{t("install.data.hint")}</p>
|
||||
<label htmlFor="linuxpkg" className="mt-4 block text-sm text-muted">{t("install.linuxPkg.label")}</label>
|
||||
<div className="mt-1 flex gap-2">
|
||||
<input id="linuxpkg" value={pkg} onChange={(e) => setPkg(e.target.value)} placeholder={t("install.linuxPkg.hint")} className="selectable flex-1 rounded-md border border-line bg-card px-3 py-2.5 text-[15px] outline-none focus:border-gold" />
|
||||
<Button onClick={browsePackage}>{t("install.browse")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{docker && env?.docker_problem && (
|
||||
<Card className="border-warn/40 p-4" role="alert">
|
||||
{pre.problems.map((p) => (
|
||||
<p className="font-medium text-warn">{t("install.docker.title")}</p>
|
||||
<p className="mt-1 text-sm text-muted">{t("install.docker.text")}</p>
|
||||
<pre className="mt-2 max-h-24 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-2 text-xs">{env.docker_problem}</pre>
|
||||
<Button className="mt-3" size="sm" onClick={() => loadEnvironment(false)}>{t("install.docker.retry")}</Button>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{pre && pre.problems.some((p) => !(docker && !gameData.trim() && p.code.startsWith("data"))) && (
|
||||
<Card className="border-warn/40 p-4" role="alert">
|
||||
{pre.problems.filter((p) => !(docker && !gameData.trim() && p.code.startsWith("data"))).map((p) => (
|
||||
<p key={p.code} className="text-sm text-warn">{p.message}</p>
|
||||
))}
|
||||
</Card>
|
||||
@@ -170,7 +213,7 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div>
|
||||
{!docker && <div>
|
||||
<button onClick={() => setShowAdvanced((v) => !v)} aria-expanded={showAdvanced} className="flex cursor-pointer items-center gap-1 text-sm text-muted hover:text-ink">
|
||||
{showAdvanced ? <ChevronDown className="h-4 w-4" aria-hidden /> : <ChevronRight className="h-4 w-4" aria-hidden />}
|
||||
{t("install.advanced")}
|
||||
@@ -184,10 +227,10 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="primary" size="md" disabled={!pre?.ok} onClick={() => void install()}>
|
||||
<Button variant="primary" size="md" disabled={!pre?.ok || (docker && (!!env?.docker_problem || !gameData.trim() || !pkg.trim()))} onClick={() => void install()}>
|
||||
{t("install.button")}
|
||||
</Button>
|
||||
{props.canCancel && (
|
||||
|
||||
+158
-11
@@ -1,12 +1,14 @@
|
||||
import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
|
||||
import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, type LucideProps } from "lucide-react";
|
||||
import { api, asUiError, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react";
|
||||
import { api, asUiError, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useHuman, useI18n, useSchemaText, type Key } from "@/i18n";
|
||||
import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField } from "@/lib/moduleSettings";
|
||||
import { AuctionTypes } from "@/screens/AuctionTypes";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
|
||||
/** The GitHub mark (lucide dropped its brand icons). */
|
||||
function GithubMark(props: { className?: string }) {
|
||||
@@ -27,6 +29,7 @@ const TILES: Record<string, { icon: ComponentType<LucideProps>; from: string; to
|
||||
gavel: { icon: Gavel, from: "from-yellow-500", to: "to-amber-700" },
|
||||
sparkles: { icon: Sparkles, from: "from-fuchsia-500", to: "to-purple-700" },
|
||||
swords: { icon: Swords, from: "from-rose-500", to: "to-red-800" },
|
||||
races: { icon: Users, from: "from-cyan-500", to: "to-blue-800" },
|
||||
};
|
||||
const DEFAULT_TILE = { icon: Puzzle, from: "from-slate-500", to: "to-slate-700" };
|
||||
|
||||
@@ -78,25 +81,68 @@ function Tile({ icon, off }: { icon: string; off: boolean }) {
|
||||
}
|
||||
|
||||
/** The server's optional modules: square cards with a switch, the module's status, a link to GitHub and its settings. */
|
||||
export function ModulesPage({ serverId, onChanged }: { serverId: string; onChanged?: () => void }) {
|
||||
export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId: string; onChanged?: () => void; onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void }) {
|
||||
const { t, locale } = useI18n();
|
||||
const human = useHuman();
|
||||
const [modules, setModules] = useState<ModuleView[] | null>(null);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
const [changed, setChanged] = useState(false);
|
||||
const [racesPatchStatus, setRacesPatchStatus] = useState<CustomRacesClientStatus | null>(null);
|
||||
const [racesInstalling, setRacesInstalling] = useState(false);
|
||||
const [racesProgress, setRacesProgress] = useState<CustomRacesProgress | null>(null);
|
||||
|
||||
const loadRacesStatus = useCallback(async () => {
|
||||
try {
|
||||
const st = await api.customRacesStatus(serverId);
|
||||
setRacesPatchStatus(st);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, [serverId]);
|
||||
const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
onRegisterGuard?.(guard);
|
||||
return () => onRegisterGuard?.(null);
|
||||
}, [guard, onRegisterGuard]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setModules((await api.modulesList(serverId)).filter((m) => !m.hidden));
|
||||
await loadRacesStatus();
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
}
|
||||
}, [serverId]);
|
||||
}, [serverId, loadRacesStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const un = listen<CustomRacesProgress>("custom-races-progress", (e) => {
|
||||
if (e.payload.id === serverId) {
|
||||
setRacesProgress(e.payload);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
void un.then((f) => f());
|
||||
};
|
||||
}, [load, serverId]);
|
||||
|
||||
async function installClientPatch() {
|
||||
setRacesInstalling(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.customRacesInstall(serverId);
|
||||
await loadRacesStatus();
|
||||
await load();
|
||||
onChanged?.();
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
} finally {
|
||||
setRacesInstalling(false);
|
||||
setRacesProgress(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggle(m: ModuleView) {
|
||||
setError(null);
|
||||
@@ -104,6 +150,9 @@ export function ModulesPage({ serverId, onChanged }: { serverId: string; onChang
|
||||
await api.moduleSetEnabled(serverId, m.id, !m.enabled);
|
||||
setChanged(true);
|
||||
await load();
|
||||
if (m.id === "custom-races") {
|
||||
await loadRacesStatus();
|
||||
}
|
||||
onChanged?.();
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
@@ -145,8 +194,9 @@ export function ModulesPage({ serverId, onChanged }: { serverId: string; onChang
|
||||
role="switch"
|
||||
aria-checked={m.enabled}
|
||||
aria-label={t("mod.switch", { name: m.name })}
|
||||
disabled={m.id === "custom-races" && racesInstalling}
|
||||
onClick={() => void toggle(m)}
|
||||
className={cn("relative mt-1 h-6 w-11 shrink-0 cursor-pointer rounded-full transition-colors", m.enabled ? "bg-gold" : "bg-white/15")}
|
||||
className={cn("relative mt-1 h-6 w-11 shrink-0 cursor-pointer rounded-full transition-colors", m.enabled ? "bg-gold" : "bg-white/15", (m.id === "custom-races" && racesInstalling) && "opacity-50 cursor-not-allowed")}
|
||||
>
|
||||
<span className={cn("absolute top-0.5 h-5 w-5 rounded-full bg-white transition-all", m.enabled ? "left-[22px]" : "left-0.5")} />
|
||||
</button>
|
||||
@@ -154,6 +204,70 @@ export function ModulesPage({ serverId, onChanged }: { serverId: string; onChang
|
||||
{m.installed && !m.switchable && m.status !== "soon" && m.compatibility !== "unsupported" && <span className="mt-1.5 shrink-0 text-xs text-muted">{t("mod.alwaysOn")}</span>}
|
||||
{!m.installed && m.status !== "soon" && <span className="mt-1.5 shrink-0 text-xs text-muted">{t("mod.notHere")}</span>}
|
||||
</div>
|
||||
{m.id === "custom-races" && (
|
||||
<div className="w-full">
|
||||
{racesInstalling && racesProgress ? (
|
||||
<div className="rounded-lg border border-gold/30 bg-gold/5 p-3">
|
||||
<div className="flex items-center justify-between gap-3 text-xs">
|
||||
<span className="flex min-w-0 items-center gap-2 font-medium text-ink">
|
||||
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-gold" />
|
||||
<span className="truncate">{racesProgress.step}</span>
|
||||
</span>
|
||||
<span className="shrink-0 font-mono text-xs font-semibold text-gold">
|
||||
{Math.round(racesProgress.percent * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2.5 h-2 w-full overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={Math.round(racesProgress.percent * 100)} aria-valuemin={0} aria-valuemax={100}>
|
||||
<div
|
||||
className="h-full rounded-full bg-gold transition-all duration-300"
|
||||
style={{ width: `${Math.round(racesProgress.percent * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-t border-line/40 pt-3 text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
{racesPatchStatus?.state === "enabled" && (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-ok/10 px-2.5 py-1 text-xs text-ok border border-ok/30">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-ok" />
|
||||
{locale === "ru" ? "Патч клиента: Включен" : "Client Patch: Active"}
|
||||
</span>
|
||||
)}
|
||||
{racesPatchStatus?.state === "disabled" && (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-white/5 px-2.5 py-1 text-xs text-muted border border-white/15" title="MPQ files disabled with .disabled suffix">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-muted" />
|
||||
{locale === "ru" ? "Патч клиента: Отключен (.disabled)" : "Client Patch: Disabled (.disabled)"}
|
||||
</span>
|
||||
)}
|
||||
{racesPatchStatus?.state === "not-installed" && (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-warn/10 px-2.5 py-1 text-xs text-warn border border-warn/30">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-warn" />
|
||||
{locale === "ru" ? "Патч клиента: Не установлен" : "Client Patch: Not Installed"}
|
||||
</span>
|
||||
)}
|
||||
{racesPatchStatus?.state === "partially-installed" && (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-warn/10 px-2.5 py-1 text-xs text-warn border border-warn/30">
|
||||
<span className="h-1.5 w-1.5 rounded-full bg-warn" />
|
||||
{locale === "ru" ? `Патч клиента: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ` : `Client Patch: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ`}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{(!racesPatchStatus || racesPatchStatus.state === "not-installed" || racesPatchStatus.state === "partially-installed") && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-7 px-3 text-xs border border-gold/40 hover:border-gold"
|
||||
disabled={racesInstalling || !racesPatchStatus?.clientPath}
|
||||
onClick={() => void installClientPatch()}
|
||||
>
|
||||
{racesInstalling && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||||
{locale === "ru" ? "Установить патч клиента" : "Install Client Patch 1.5"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-auto flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => void api.openLink(m.repo)}
|
||||
@@ -174,7 +288,7 @@ export function ModulesPage({ serverId, onChanged }: { serverId: string; onChang
|
||||
{selected?.has_settings && !selected.page && selectedAt >= 0 && Math.floor(selectedAt / 2) === Math.floor(i / 2) && (i % 2 === 1 || i === modules.length - 1) && (
|
||||
<SettingsPanel key={selected.id} className="sm:col-span-2">
|
||||
<h2 className="font-semibold">{t("mod.settingsOf", { name: selected.name })}</h2>
|
||||
<ModuleSettings serverId={serverId} module={selected} onSaved={() => setChanged(true)} />
|
||||
<ModuleSettings serverId={serverId} module={selected} onSaved={() => setChanged(true)} onRegisterGuard={setGuard} />
|
||||
</SettingsPanel>
|
||||
)}
|
||||
</Fragment>
|
||||
@@ -184,8 +298,8 @@ export function ModulesPage({ serverId, onChanged }: { serverId: string; onChang
|
||||
);
|
||||
}
|
||||
|
||||
function ModuleSettings({ serverId, module, onSaved }: { serverId: string; module: ModuleView; onSaved: () => void }) {
|
||||
const { t, locale } = useI18n();
|
||||
function ModuleSettings({ serverId, module, onSaved, onRegisterGuard }: { serverId: string; module: ModuleView; onSaved: () => void; onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void }) {
|
||||
const { t, tn, locale } = useI18n();
|
||||
const sx = useSchemaText();
|
||||
const human = useHuman();
|
||||
const [advanced, setAdvanced] = useState(false);
|
||||
@@ -208,7 +322,7 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul
|
||||
return () => { cancelled = true; };
|
||||
}, [serverId, module.id]);
|
||||
|
||||
async function save() {
|
||||
async function save(): Promise<boolean> {
|
||||
const errors: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(edits)) {
|
||||
const field = moduleField(key, locale, items?.find(item => item.key === key)?.field);
|
||||
@@ -222,7 +336,7 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul
|
||||
}
|
||||
}
|
||||
setFieldErrors(errors);
|
||||
if (Object.keys(errors).length) return;
|
||||
if (Object.keys(errors).length) return false;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNote(null);
|
||||
@@ -234,14 +348,33 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul
|
||||
onSaved();
|
||||
setNote(t("mod.saved", { n: done.length }));
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const dirty = Object.keys(edits).length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (dirty) {
|
||||
onRegisterGuard?.({
|
||||
isDirty: () => Object.keys(edits).length > 0,
|
||||
save: () => save(),
|
||||
discard: () => {
|
||||
setEdits({});
|
||||
setFieldErrors({});
|
||||
setNote(null);
|
||||
},
|
||||
});
|
||||
} else {
|
||||
onRegisterGuard?.(null);
|
||||
}
|
||||
return () => onRegisterGuard?.(null);
|
||||
}, [dirty, edits, onRegisterGuard]);
|
||||
const edit = (key: string, value: string) => setEdits(previous => {
|
||||
const next = { ...previous };
|
||||
if (value === items?.find(item => item.key === key)?.value) delete next[key];
|
||||
@@ -324,6 +457,20 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul
|
||||
{note && <span className="text-sm text-ok" role="status">{note}</span>}
|
||||
</div>}
|
||||
{error && <p className="mt-2 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||
{dirty && (
|
||||
<div className="fixed bottom-0 left-60 right-0 z-40 flex items-center justify-between border-t border-line bg-[#0b0c0e]/95 px-10 py-3 shadow-lg">
|
||||
<span className="text-sm text-muted">{tn("set.unsaved", Object.keys(edits).length)}</span>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="ghost" size="sm" disabled={busy} onClick={() => { setEdits({}); setFieldErrors({}); setNote(null); }}>
|
||||
{t("set.discard")}
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" disabled={busy} onClick={() => void save()}>
|
||||
{busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />}
|
||||
{t("acc.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+181
-33
@@ -1,6 +1,6 @@
|
||||
import { dismissClientJob, startClientUpdate, stopClientJob, syncClient, useClientJob } from "@/lib/clientJob";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Loader2, X } from "lucide-react";
|
||||
import { AlertTriangle, Loader2, X } from "lucide-react";
|
||||
import { api, asUiError, type ClientInfo, type Human, type Performance, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api";
|
||||
import { cn, formatBytes, formatUptime } from "@/lib/utils";
|
||||
import { useHuman, useT } from "@/i18n";
|
||||
@@ -9,6 +9,8 @@ import { checkClient, useClientStatus } from "@/lib/clientUpdate";
|
||||
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
|
||||
import { RealmlistMenu } from "@/screens/RealmlistMenu";
|
||||
import { RealmPicker } from "@/screens/RealmPicker";
|
||||
import { CrashHistoryModal } from "@/screens/CrashHistoryModal";
|
||||
import { useAutoRestart } from "@/lib/autoRestartPrefs";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
@@ -98,6 +100,35 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
const upd = useServerUpdate(server.id);
|
||||
const needsDecision = (upd.preview?.conflicts.length ?? 0) > 0;
|
||||
const [startBots, setStartBots] = useState<number | null | undefined>(undefined);
|
||||
const [autoRestart, setAutoRestart] = useAutoRestart(server.id);
|
||||
const autoRestartRef = useRef(autoRestart);
|
||||
autoRestartRef.current = autoRestart;
|
||||
|
||||
const [crashCount, setCrashCount] = useState(0);
|
||||
const crashCountRef = useRef(0);
|
||||
const [showCrashModal, setShowCrashModal] = useState(false);
|
||||
const [hasCrashHistory, setHasCrashHistory] = useState(false);
|
||||
const [crashLoopPaused, setCrashLoopPaused] = useState(false);
|
||||
const [crashRestartNotice, setCrashRestartNotice] = useState<string | null>(null);
|
||||
|
||||
const userStoppedRef = useRef(false);
|
||||
const wasWorldRunningRef = useRef(false);
|
||||
const actionRef = useRef<Action>(null);
|
||||
const crashTimestampsRef = useRef<number[]>([]);
|
||||
const pollRef = useRef<() => Promise<void>>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void api
|
||||
.listCrashes(server.id, 1)
|
||||
.then((items) => {
|
||||
if (active && items.length > 0) setHasCrashHistory(true);
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [server.id]);
|
||||
|
||||
useEffect(() => {
|
||||
void api
|
||||
@@ -115,18 +146,87 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
if (job.phase === "done" || job.phase === "current") void api.clientInfo(server.id).then(setClient).catch(() => undefined);
|
||||
}, [job.phase, server.id]);
|
||||
|
||||
const run = useCallback(
|
||||
async (kind: Exclude<Action, null>) => {
|
||||
if (kind === "stopping") {
|
||||
userStoppedRef.current = true;
|
||||
} else {
|
||||
userStoppedRef.current = false;
|
||||
setCrashLoopPaused(false);
|
||||
setCrashRestartNotice(null);
|
||||
}
|
||||
setFailure(null);
|
||||
setShowDetails(false);
|
||||
setAction(kind);
|
||||
actionRef.current = kind;
|
||||
try {
|
||||
if (kind !== "starting") {
|
||||
const out = await api.stop(server.id);
|
||||
if (!out.ok) throw { human: out.human, technical: out.output };
|
||||
}
|
||||
if (kind !== "stopping") {
|
||||
setAction("starting");
|
||||
actionRef.current = "starting";
|
||||
const out = await api.start(server.id);
|
||||
if (!out.ok) throw { human: out.human, technical: out.output };
|
||||
}
|
||||
} catch (e) {
|
||||
const ui = asUiError(e);
|
||||
setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical });
|
||||
} finally {
|
||||
setAction(null);
|
||||
actionRef.current = null;
|
||||
void pollRef.current?.();
|
||||
}
|
||||
},
|
||||
[server.id],
|
||||
);
|
||||
|
||||
const poll = useCallback(async () => {
|
||||
try {
|
||||
const s = await api.status(server.id);
|
||||
if (alive.current) setStatus(s);
|
||||
if (s.observed.world.state === "running") {
|
||||
const isWorldRunning = s.observed.world.state === "running";
|
||||
if (isWorldRunning) {
|
||||
wasWorldRunningRef.current = true;
|
||||
userStoppedRef.current = false;
|
||||
const p = await api.population(server.id).catch(() => null);
|
||||
if (alive.current) setPop(p);
|
||||
} else if (alive.current) setPop(null);
|
||||
} else {
|
||||
if (alive.current) setPop(null);
|
||||
if (
|
||||
wasWorldRunningRef.current &&
|
||||
!userStoppedRef.current &&
|
||||
actionRef.current === null
|
||||
) {
|
||||
wasWorldRunningRef.current = false;
|
||||
setHasCrashHistory(true);
|
||||
const now = Date.now();
|
||||
const recent = crashTimestampsRef.current.filter((ts) => now - ts < 180000);
|
||||
recent.push(now);
|
||||
crashTimestampsRef.current = recent;
|
||||
|
||||
crashCountRef.current += 1;
|
||||
const currentCrashCount = crashCountRef.current;
|
||||
setCrashCount(currentCrashCount);
|
||||
|
||||
if (recent.length >= 3) {
|
||||
setCrashLoopPaused(true);
|
||||
setCrashRestartNotice(null);
|
||||
} else if (autoRestartRef.current) {
|
||||
setCrashRestartNotice(t("crash.restartNotice", { n: currentCrashCount }));
|
||||
void run("starting");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* transient; next poll retries */
|
||||
}
|
||||
}, [server.id]);
|
||||
}, [server.id, t, run]);
|
||||
|
||||
useEffect(() => {
|
||||
pollRef.current = poll;
|
||||
}, [poll]);
|
||||
|
||||
// The tick rate comes from the server console (one short connection per reading), so it is read less often.
|
||||
const worldUp = status?.observed.world.state === "running";
|
||||
@@ -156,29 +256,6 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
};
|
||||
}, [poll]);
|
||||
|
||||
async function run(kind: Exclude<Action, null>) {
|
||||
setFailure(null);
|
||||
setShowDetails(false);
|
||||
setAction(kind);
|
||||
try {
|
||||
if (kind !== "starting") {
|
||||
const out = await api.stop(server.id);
|
||||
if (!out.ok) throw { human: out.human, technical: out.output };
|
||||
}
|
||||
if (kind !== "stopping") {
|
||||
setAction("starting");
|
||||
const out = await api.start(server.id);
|
||||
if (!out.ok) throw { human: out.human, technical: out.output };
|
||||
}
|
||||
} catch (e) {
|
||||
const ui = asUiError(e);
|
||||
setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical });
|
||||
} finally {
|
||||
setAction(null);
|
||||
void poll();
|
||||
}
|
||||
}
|
||||
|
||||
async function play() {
|
||||
setFailure(null);
|
||||
setShowDetails(false);
|
||||
@@ -234,13 +311,56 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
|
||||
<Card className="mt-6 p-7">
|
||||
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}</div>
|
||||
<div className={cn("flex items-center gap-3 text-3xl font-semibold", tone)} role="status" aria-live="polite">
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn("h-3 w-3 rounded-full", running && !transitioning ? "bg-ok" : transitioning || anyUp ? "bg-warn" : "bg-muted/50")}
|
||||
/>
|
||||
{headline}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className={cn("flex items-center gap-3 text-3xl font-semibold", tone)} role="status" aria-live="polite">
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn("h-3 w-3 rounded-full", running && !transitioning ? "bg-ok" : transitioning || anyUp ? "bg-warn" : "bg-muted/50")}
|
||||
/>
|
||||
{headline}
|
||||
</div>
|
||||
{(crashCount > 0 || hasCrashHistory) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCrashModal(true)}
|
||||
className={cn(
|
||||
"inline-flex cursor-pointer items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors",
|
||||
crashCount > 0
|
||||
? "border border-bad/40 bg-bad/15 text-bad hover:bg-bad/25"
|
||||
: "border border-line bg-card-2 text-muted hover:text-ink hover:border-gold/40",
|
||||
)}
|
||||
title={t("crash.historyTitle")}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5" aria-hidden />
|
||||
<span>{crashCount > 0 ? t("crash.badge", { n: crashCount }) : t("crash.historyTitle")}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{crashRestartNotice && !crashLoopPaused && (
|
||||
<div className="mt-3 flex items-center justify-between rounded-md border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-300">
|
||||
<span>{crashRestartNotice}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCrashRestartNotice(null)}
|
||||
className="cursor-pointer text-amber-300/70 hover:text-amber-300"
|
||||
aria-label={t("btn.close")}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{crashLoopPaused && (
|
||||
<div className="mt-3 flex items-center justify-between rounded-md border border-bad/40 bg-bad/15 p-3 text-xs text-bad">
|
||||
<span>{t("crash.loopPaused")}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCrashModal(true)}
|
||||
className="cursor-pointer font-medium underline"
|
||||
>
|
||||
{t("crash.historyTitle")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!transitioning && !running && anyUp && (
|
||||
<p className="mt-2 text-sm text-muted">
|
||||
{t("overview.reportHint")}{" "}
|
||||
@@ -363,6 +483,27 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-line/60 pt-4 text-xs text-muted">
|
||||
<label className="flex cursor-pointer items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoRestart}
|
||||
onChange={(e) => setAutoRestart(e.target.checked)}
|
||||
className="h-3.5 w-3.5 accent-[#c9a24a]"
|
||||
/>
|
||||
<span className="font-medium text-ink/80">{t("crash.autoRestart")}</span>
|
||||
<span className="hidden sm:inline text-muted">— {t("crash.autoRestartDesc")}</span>
|
||||
</label>
|
||||
{(crashCount > 0 || hasCrashHistory) && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCrashModal(true)}
|
||||
className="cursor-pointer text-gold hover:underline"
|
||||
>
|
||||
{t("crash.historyTitle")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{anyUp && !running && !transitioning && (
|
||||
<p className="mt-3 text-sm text-muted">{t("overview.partial")}</p>
|
||||
)}
|
||||
@@ -477,6 +618,13 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
onPlayAnyway={() => void play()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showCrashModal && (
|
||||
<CrashHistoryModal
|
||||
serverId={server.id}
|
||||
onClose={() => setShowCrashModal(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { LanguagePicker } from "@/components/LanguagePicker";
|
||||
import { RealmStartupSettings } from "@/screens/RealmStartupSettings";
|
||||
import { RepairCard } from "@/screens/RepairCard";
|
||||
import { PublishCard } from "@/screens/PublishCard";
|
||||
import { AutoRestartSettings } from "@/screens/AutoRestartSettings";
|
||||
|
||||
function mb(bytes: number) {
|
||||
return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
|
||||
@@ -172,6 +173,7 @@ export function SettingsHome({ serverId, serverName = "", path, onForget }: { se
|
||||
|
||||
<ClientCard serverId={serverId} />
|
||||
<RealmStartupSettings serverId={serverId} />
|
||||
<AutoRestartSettings serverId={serverId} />
|
||||
|
||||
<DiagnosticsCard serverId={serverId} />
|
||||
<RepairCard key={serverId} serverId={serverId} />
|
||||
|
||||
@@ -22,6 +22,7 @@ import { Card } from "@/components/ui/card";
|
||||
import { CollectionRows, RawRows, collectionsOf } from "@/screens/ExtraRows";
|
||||
import { CompanionsCard } from "@/screens/CompanionsCard";
|
||||
import { useHuman, useI18n, useSchemaText, useT, type Key } from "@/i18n";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
|
||||
type T = (k: Key, v?: Record<string, string | number>) => string;
|
||||
|
||||
@@ -154,7 +155,14 @@ function Row(props: { s: SettingView; value: JsonValue; error: string | null; on
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsPage(props: { serverId: string; scope: Scope; botModule?: "companions" | "playerbots"; title: string; question: string }) {
|
||||
export function SettingsPage(props: {
|
||||
serverId: string;
|
||||
scope: Scope;
|
||||
botModule?: "companions" | "playerbots";
|
||||
title: string;
|
||||
question: string;
|
||||
onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void;
|
||||
}) {
|
||||
const { serverId, scope } = props;
|
||||
const { t, tn, locale } = useI18n();
|
||||
const squid = scope === "bots" && props.botModule === "playerbots";
|
||||
@@ -317,10 +325,10 @@ export function SettingsPage(props: { serverId: string; scope: Scope; botModule?
|
||||
}
|
||||
|
||||
/** The save bar saves all three kinds of edits: the curated settings, the collection switches and the other documented ones. */
|
||||
async function saveEverything() {
|
||||
if (dirtyKeys.length && !(await save(Object.fromEntries(dirtyKeys.map((k) => [k, draft[k]]))))) return;
|
||||
async function saveEverything(): Promise<boolean> {
|
||||
if (dirtyKeys.length && !(await save(Object.fromEntries(dirtyKeys.map((k) => [k, draft[k]]))))) return false;
|
||||
const extra = [...Object.keys(rawEdits), ...Object.keys(colEdits)];
|
||||
if (!extra.length) return;
|
||||
if (!extra.length) return true;
|
||||
setBusy(true);
|
||||
setSaveErr(null);
|
||||
try {
|
||||
@@ -337,13 +345,33 @@ export function SettingsPage(props: { serverId: string; scope: Scope; botModule?
|
||||
const more = extra.map((key) => ({ key, title: key, restart: "world" as const, dangerous: false }));
|
||||
setSaved((prev) => ({ changed: [...(prev?.changed ?? []), ...more], restart: prev?.restart ?? "world", snapshot: prev?.snapshot ?? null }));
|
||||
void api.status(serverId).then((st) => setRunning(st.observed.world.state === "running"));
|
||||
return true;
|
||||
} catch (e) {
|
||||
setSaveErr(asUiError(e));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (pending > 0) {
|
||||
props.onRegisterGuard?.({
|
||||
isDirty: () => pending > 0,
|
||||
save: () => saveEverything(),
|
||||
discard: () => {
|
||||
setDraft({});
|
||||
setErrors({});
|
||||
setRawEdits({});
|
||||
setColEdits({});
|
||||
},
|
||||
});
|
||||
} else {
|
||||
props.onRegisterGuard?.(null);
|
||||
}
|
||||
return () => props.onRegisterGuard?.(null);
|
||||
}, [pending, props.onRegisterGuard]);
|
||||
|
||||
async function openPreset(id: string) {
|
||||
setSaved(null);
|
||||
if (squid) {
|
||||
|
||||
+72
-8
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Archive, BarChart3, Bot, Bug, Gauge, Globe, Puzzle, Server, Settings, Swords, Terminal, Users, type LucideIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Archive, BarChart3, Bot, Bug, Gauge, Globe, Loader2, Puzzle, Server, Settings, Swords, Terminal, Users, type LucideIcon } from "lucide-react";
|
||||
import { api, type ServerSummary } from "@/lib/api";
|
||||
import { useT, type Key } from "@/i18n";
|
||||
import logo from "@/assets/logo.png";
|
||||
@@ -17,8 +17,10 @@ import { ConsolePage } from "@/screens/ConsolePage";
|
||||
import { PortablePage } from "@/screens/PortablePage";
|
||||
import { DashboardPage } from "@/screens/DashboardPage";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { startServerUpdatePolling, useServerUpdate } from "@/lib/serverUpdate";
|
||||
import { startClientPolling } from "@/lib/clientUpdate";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
|
||||
type Page = "overview" | "bots" | "dashboard" | "server" | "modules" | "players" | "characters" | "friends" | "backups" | "console" | "report" | "settings";
|
||||
|
||||
@@ -53,6 +55,22 @@ export function Shell(props: {
|
||||
// A module that is switched off takes its page away (the companions' "Bots" page, for one).
|
||||
const [botModule, setBotModule] = useState<"companions" | "playerbots">("companions");
|
||||
const [hiddenPages, setHiddenPages] = useState<string[]>([]);
|
||||
const guardRef = useRef<UnsavedChangesGuard | null>(null);
|
||||
const registerGuard = useCallback((g: UnsavedChangesGuard | null) => {
|
||||
guardRef.current = g;
|
||||
}, []);
|
||||
const [pendingNav, setPendingNav] = useState<(() => void) | null>(null);
|
||||
const [modalSaving, setModalSaving] = useState(false);
|
||||
const [modalError, setModalError] = useState<string | null>(null);
|
||||
|
||||
const requestNavigation = (action: () => void) => {
|
||||
if (guardRef.current && guardRef.current.isDirty()) {
|
||||
setPendingNav(() => action);
|
||||
} else {
|
||||
action();
|
||||
}
|
||||
};
|
||||
|
||||
const reloadModules = useCallback(() => {
|
||||
void api
|
||||
.modulesList(props.activeId)
|
||||
@@ -91,7 +109,7 @@ export function Shell(props: {
|
||||
{NAV.filter((n) => !hiddenPages.includes(n.id) && (n.id !== "dashboard" || botModule === "playerbots")).map(({ id, label, icon: Icon }) => (
|
||||
<li key={id}>
|
||||
<button
|
||||
onClick={() => setPage(id)}
|
||||
onClick={() => requestNavigation(() => setPage(id))}
|
||||
aria-current={page === id ? "page" : undefined}
|
||||
className={cn(
|
||||
"flex h-10 w-full cursor-pointer items-center gap-3 rounded-md px-3 text-left text-[15px] transition-colors",
|
||||
@@ -113,7 +131,7 @@ export function Shell(props: {
|
||||
<select
|
||||
className="mb-2 w-full rounded-md border border-line bg-card px-2 py-2 text-sm"
|
||||
value={props.activeId}
|
||||
onChange={(e) => props.onSelect(e.target.value)}
|
||||
onChange={(e) => requestNavigation(() => props.onSelect(e.target.value))}
|
||||
aria-label={t("nav.serverPicker")}
|
||||
>
|
||||
{props.servers.map((s) => (
|
||||
@@ -123,7 +141,7 @@ export function Shell(props: {
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" className="w-full justify-start" onClick={props.onAddAnother}>
|
||||
<Button variant="ghost" size="sm" className="w-full justify-start" onClick={() => requestNavigation(props.onAddAnother)}>
|
||||
{t("nav.addAnother")}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -131,15 +149,15 @@ export function Shell(props: {
|
||||
|
||||
<main className="relative h-full flex-1 overflow-y-auto px-10 py-8">
|
||||
{page === "overview" ? (
|
||||
<Overview key={server.id} server={server} companions={botModule === "companions" && !hiddenPages.includes("bots")} onForget={() => props.onForget(server.id)} onOpenUpdates={() => setPage("settings")} onRealmChanged={reloadModules} onReport={() => setPage("report")} />
|
||||
<Overview key={server.id} server={server} companions={botModule === "companions" && !hiddenPages.includes("bots")} onForget={() => props.onForget(server.id)} onOpenUpdates={() => requestNavigation(() => setPage("settings"))} onRealmChanged={reloadModules} onReport={() => requestNavigation(() => setPage("report"))} />
|
||||
) : page === "bots" || page === "server" ? (
|
||||
<SettingsPage key={`${server.id}-${page}-${botModule}`} serverId={server.id} scope={page} botModule={botModule} title={t(current.label)} question={t(current.question)} />
|
||||
<SettingsPage key={`${server.id}-${page}-${botModule}`} serverId={server.id} scope={page} botModule={botModule} title={t(current.label)} question={t(current.question)} onRegisterGuard={registerGuard} />
|
||||
) : page === "dashboard" ? (
|
||||
<DashboardPage key={server.id} serverId={server.id} />
|
||||
) : page === "console" ? (
|
||||
<ConsolePage key={server.id} serverId={server.id} />
|
||||
) : page === "modules" ? (
|
||||
<ModulesPage key={server.id} serverId={server.id} onChanged={reloadModules} />
|
||||
<ModulesPage key={server.id} serverId={server.id} onChanged={reloadModules} onRegisterGuard={registerGuard} />
|
||||
) : page === "report" ? (
|
||||
<ReportPage key={server.id} serverId={server.id} />
|
||||
) : page === "friends" ? (
|
||||
@@ -156,6 +174,52 @@ export function Shell(props: {
|
||||
<Placeholder title={t(current.label)} question={t(current.question)} />
|
||||
)}
|
||||
</main>
|
||||
|
||||
{pendingNav && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-6" role="presentation">
|
||||
<Card className="w-full max-w-md p-6 shadow-2xl" role="dialog" aria-modal="true" aria-label={t("unsaved.title")}>
|
||||
<h2 className="text-lg font-semibold">{t("unsaved.title")}</h2>
|
||||
<p className="mt-2 text-sm text-muted">{t("unsaved.message")}</p>
|
||||
{modalError && <p className="mt-3 text-sm text-bad" role="alert">{modalError}</p>}
|
||||
<div className="mt-6 flex flex-wrap justify-end gap-2">
|
||||
<Button variant="ghost" disabled={modalSaving} onClick={() => { setPendingNav(null); setModalError(null); }}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="ghost" disabled={modalSaving} onClick={() => {
|
||||
guardRef.current?.discard();
|
||||
const act = pendingNav;
|
||||
setPendingNav(null);
|
||||
setModalError(null);
|
||||
act?.();
|
||||
}}>
|
||||
{t("set.discard")}
|
||||
</Button>
|
||||
<Button variant="primary" disabled={modalSaving} onClick={async () => {
|
||||
if (!guardRef.current) return;
|
||||
setModalSaving(true);
|
||||
setModalError(null);
|
||||
try {
|
||||
const ok = await guardRef.current.save();
|
||||
if (ok) {
|
||||
const act = pendingNav;
|
||||
setPendingNav(null);
|
||||
act?.();
|
||||
} else {
|
||||
setModalError(t("unsaved.saveFailed"));
|
||||
}
|
||||
} catch (e) {
|
||||
setModalError(String(e));
|
||||
} finally {
|
||||
setModalSaving(false);
|
||||
}
|
||||
}}>
|
||||
{modalSaving && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />}
|
||||
{t("acc.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user