merge: bring preview/modules-v2 up to date with master (base 0.9.7)

This commit is contained in:
Дмитрий committed 2026-11-03 12:01:47 +05:00
commit 7d062faa1a
327 files changed
+15358 -1098

No files matched your search

+11 -33
View File
@@ -1,12 +1,12 @@
import { useEffect, useState } from "react";
import { getVersion } from "@tauri-apps/api/app";
import { Loader2 } from "lucide-react";
import { Loader2, RefreshCw, Monitor } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useT } from "@/i18n";
import { autoUpdateEnabled, installNow, lookForUpdate, setAutoUpdate, useSelfUpdate } from "@/lib/selfUpdate";
export function AboutCard() {
export function AboutCard({ onHistory }: { onHistory?: () => void }) {
const t = useT();
const s = useSelfUpdate();
const [version, setVersion] = useState("");
@@ -21,37 +21,12 @@ export function AboutCard() {
return (
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("app.name")}</h2>
<p className="mt-1 text-sm text-muted">{t("about.version", { v: version || "…" })}</p>
<label className="mt-3 flex cursor-pointer items-start gap-2 text-sm">
<input
type="checkbox"
className="mt-1"
checked={auto}
onChange={(e) => {
setAuto(e.target.checked);
setAutoUpdate(e.target.checked);
}}
/>
<span>
{t("about.auto")}
<span className="block text-xs text-muted">{t("about.autoHint")}</span>
</span>
</label>
<div className="flex items-start justify-between gap-3">
<div><h2 className="flex items-center gap-2 font-semibold"><Monitor className="h-4 w-4 text-gold" aria-hidden />{t("history.manager")}</h2><p className="mt-2 text-sm text-muted">{t("settings.version", { v: version || "…" })}</p></div>
<Button size="sm" disabled={busy} aria-label={t("about.check")} title={t("about.check")} onClick={() => { setAsked(true); void lookForUpdate({ download: false }); }}><RefreshCw className={`h-4 w-4 ${s.phase === "checking" ? "animate-spin" : ""}`} aria-hidden /></Button>
</div>
<p className="mt-3 text-xs text-muted">{t("about.autoHint")}</p>
<div className="mt-4 flex flex-wrap items-center gap-3">
<Button
size="sm"
disabled={busy}
onClick={() => {
setAsked(true);
void lookForUpdate({ download: false });
}}
>
{s.phase === "checking" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("about.check")}
</Button>
{s.version && s.phase !== "current" && (
<Button size="sm" variant="primary" disabled={busy} onClick={() => void installNow()}>
{(s.phase === "downloading" || s.phase === "installing") && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
@@ -64,7 +39,7 @@ export function AboutCard() {
</span>
)}
</div>
{s.version && s.notes && s.phase !== "current" && <p className="mt-3 whitespace-pre-line text-sm text-muted">{s.notes}</p>}
{onHistory ? <button className="mt-3 cursor-pointer text-sm text-gold hover:underline" onClick={onHistory}>{t(s.version && s.phase !== "current" ? "history.open" : "history.title")}</button> : s.version && s.notes && s.phase !== "current" && <p className="mt-3 whitespace-pre-line text-sm text-muted">{s.notes}</p>}
{s.phase === "ready" && <p className="mt-3 text-sm text-ok" role="status">{t("selfupd.onClose")}</p>}
{asked && s.phase === "current" && <p className="mt-3 text-sm text-ok" role="status">{t("about.upToDate")}</p>}
{s.phase === "error" && (
@@ -73,6 +48,9 @@ export function AboutCard() {
{s.error && <p className="selectable mt-1 break-all text-xs text-muted">{s.error}</p>}
</div>
)}
<label className="mt-5 flex cursor-pointer items-center justify-between gap-3 border-t border-line pt-4 text-sm" title={t("about.auto")}>
<span>{t("settings.autoManager")}</span><input type="checkbox" role="switch" aria-description={t("about.auto")} checked={auto} onChange={e => { setAuto(e.target.checked); setAutoUpdate(e.target.checked); }} className="h-4 w-4 accent-[#c9a24a]" />
</label>
</Card>
);
}
+15 -3
View File
@@ -193,6 +193,17 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
}
export function BrowsePage() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void browse.enabled().then(setEnabled).catch(e => setError(asUiError(e).technical)); }, []);
if (error) return <p role="alert" className="text-bad">{error}</p>;
if (enabled === null) return <Loader2 className="h-5 w-5 animate-spin" aria-label={t("portable.make.loading")} />;
if (!enabled) return <div><h1 className="text-2xl font-semibold">{t("browse.title")}</h1><p className="mt-2 text-muted">{t("browse.disabled")}</p></div>;
return <EnabledBrowsePage />;
}
function EnabledBrowsePage() {
const { t } = useI18n();
const { status } = useRegistryStatus(5000);
const [q, setQ] = useState("");
@@ -213,6 +224,7 @@ export function BrowsePage() {
const [preferredSaved, setPreferredSaved] = useState("");
const [preferredNote, setPreferredNote] = useState<string | null>(null);
const ticket = useRef(0);
const [requested, setRequested] = useState(false);
useEffect(() => { void control.status().then((c) => { setPreferred(c.preferred_username); setPreferredSaved(c.preferred_username); }).catch(() => {}); }, []);
useEffect(() => { void browse.modules().then((m) => setCatalog(Object.fromEntries(m.map((x) => [x.id, x])))).catch(() => {}); }, []);
@@ -244,10 +256,10 @@ export function BrowsePage() {
}, [params]);
useEffect(() => {
if (!status?.url) return;
if (!requested || !status?.url) return;
const timer = setTimeout(() => void load(), q ? 300 : 0);
return () => clearTimeout(timer);
}, [load, status?.url]); // eslint-disable-line react-hooks/exhaustive-deps
}, [load, status?.url, requested]); // eslint-disable-line react-hooks/exhaustive-deps
function onSort(k: SortKey) {
if (k === sort) setOrder((o) => (o === "asc" ? "desc" : "asc"));
@@ -263,7 +275,7 @@ export function BrowsePage() {
<h1 className="text-2xl font-semibold">{t("browse.title")}</h1>
<p className="mt-1 text-sm text-muted">{t("browse.text")}</p>
</div>
<Button size="sm" onClick={() => void load()} disabled={loading || noUrl}>{loading ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <RefreshCw className="h-4 w-4" aria-hidden />}{t("browse.refresh")}</Button>
<Button size="sm" onClick={() => { if (requested) void load(); else setRequested(true); }} disabled={loading || noUrl}>{loading ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <RefreshCw className="h-4 w-4" aria-hidden />}{t("browse.refresh")}</Button>
</div>
{noUrl && <p className="mt-2 text-sm text-warn">{t("browse.noUrl")}</p>}
+2
View File
@@ -3,6 +3,7 @@ import { listen } from "@tauri-apps/api/event";
import { open } from "@tauri-apps/plugin-dialog";
import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api";
import { checkClient } from "@/lib/clientUpdate";
import { ClientGraphics } from "./ClientGraphics";
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -95,6 +96,7 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
<dt className="text-muted">{t("client.otherAddons")}</dt>
<dd>{t("client.leftAsIs", { n: info.other_addons })}</dd>
</dl>
<ClientGraphics key={info.path} serverId={serverId} />
{!remote && (
<label className="mt-4 flex cursor-pointer items-center gap-2 text-sm">
<input type="checkbox" checked={playAfter} onChange={(e) => setPlayAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
import { api, asUiError } from "@/lib/api";
import { checkClient } from "@/lib/clientUpdate";
import { useI18n } from "@/i18n";
export function ClientGraphics({ serverId }: { serverId: string }) {
const { t } = useI18n();
const [state, setState] = useState<{ dxvk_disabled: boolean; enhancements_disabled: boolean } | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void api.clientGraphics(serverId).then(setState).catch(e => setError(asUiError(e).technical)); }, [serverId]);
async function change(name: string, disabled: boolean) {
setBusy(true); setError(null);
try { setState(await api.clientSetGraphics(serverId, name, disabled)); await checkClient(serverId); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
return <div className="mt-5 space-y-3 border-t border-line pt-4">
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={state?.dxvk_disabled ?? false} disabled={!state || busy} onChange={e => void change("d3d9.dll", e.target.checked)} />{t("client.graphics.dxvk")}</label>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={state?.enhancements_disabled ?? false} disabled={!state || busy} onChange={e => void change("dxgi.dll", e.target.checked)} />{t("client.graphics.enhancements")}</label>
<p className="text-xs text-muted">{t("client.graphics.hint")}</p>
{error && <p className="text-sm text-bad" role="alert">{error}</p>}
</div>;
}
+28
View File
@@ -0,0 +1,28 @@
import { useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { useI18n } from "@/i18n";
export function ForceStopDialog({ onCancel, onConfirm }: { onCancel: () => void; onConfirm: () => void }) {
const { t } = useI18n();
const panel = useRef<HTMLDivElement>(null);
useEffect(() => {
const previous = document.activeElement;
panel.current?.querySelector<HTMLButtonElement>("button")?.focus();
return () => { if (previous instanceof HTMLElement) previous.focus(); };
}, []);
return <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-5">
<div ref={panel} role="alertdialog" aria-modal="true" aria-labelledby="force-stop-title" aria-describedby="force-stop-warning" className="w-full max-w-lg rounded-lg border border-bad/40 bg-card p-6" onKeyDown={e => {
if (e.key === "Escape") { e.preventDefault(); onCancel(); }
if (e.key === "Tab") {
const buttons = panel.current?.querySelectorAll<HTMLButtonElement>("button");
if (!buttons?.length) return;
if (e.shiftKey && document.activeElement === buttons[0]) { e.preventDefault(); buttons[buttons.length - 1].focus(); }
else if (!e.shiftKey && document.activeElement === buttons[buttons.length - 1]) { e.preventDefault(); buttons[0].focus(); }
}
}}>
<h2 id="force-stop-title" className="text-lg font-semibold">{t("stop.forceTitle")}</h2>
<p id="force-stop-warning" className="mt-3 text-sm text-muted">{t("stop.forceWarning")}</p>
<div className="mt-5 flex justify-end gap-3"><Button onClick={onCancel}>{t("stop.cancel")}</Button><Button variant="secondary" onClick={onConfirm}>{t("stop.force")}</Button></div>
</div>
</div>;
}
+4 -2
View File
@@ -5,6 +5,7 @@ import {
Ban,
Bot,
CheckCircle2,
Clock,
Database,
Download,
ExternalLink,
@@ -54,7 +55,7 @@ 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 { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField, retiredModuleKeys } from "@/lib/moduleSettings";
import { AuctionTypes } from "@/screens/AuctionTypes";
import { RaceAvailabilitySettings } from "@/screens/RaceAvailabilitySettings";
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
@@ -70,6 +71,7 @@ function GithubMark(props: { className?: string }) {
/** Icon and colors of a module's square tile */
const TILES: Record<string, { icon: ComponentType<LucideProps>; from: string; to: string }> = {
clock: { icon: Clock, from: "from-indigo-400", to: "to-violet-800" },
bot: { icon: Bot, from: "from-emerald-500", to: "to-teal-700" },
scaling: { icon: Scaling, from: "from-violet-500", to: "to-indigo-700" },
plug: { icon: Plug, from: "from-amber-500", to: "to-orange-700" },
@@ -2676,7 +2678,7 @@ function ModuleSettings({
return next;
});
const available = items?.filter((s) => s.key !== moduleEnableKey(module.id)) ?? [];
const available = items?.filter((s) => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256"].includes(s.key) && !retiredModuleKeys.has(s.key)) ?? [];
const advancedCount = available.filter(
(s) =>
!auctionWeightKey(s.key) &&
+57 -44
View File
@@ -1,3 +1,6 @@
import { ForceStopDialog } from "./ForceStopDialog";
import { serverLifecycle } from "@/lib/serverLifecycle";
import { serverUpdateBlocksRestart } from "@/lib/serverUpdate";
import { dismissClientJob, startClientUpdate, stopClientJob, syncClient, useClientJob } from "@/lib/clientJob";
import { useCallback, useEffect, useRef, useState } from "react";
import { AlertTriangle, Loader2, X } from "lucide-react";
@@ -10,7 +13,12 @@ import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { RealmlistMenu } from "@/screens/RealmlistMenu";
import { RealmPicker } from "@/screens/RealmPicker";
import { CrashHistoryModal } from "@/screens/CrashHistoryModal";
import { ListingChip } from "@/screens/PublishCard";
import { PublishRealmDialog } from "@/screens/PublishDialog";
import { useRegistryStatus } from "@/lib/registry";
import { usePublishRealms, type PublishRealm } from "@/lib/publishRealms";
import { useAutoRestart } from "@/lib/autoRestartPrefs";
import { SplitButton } from "@/components/ui/split-button";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -86,6 +94,8 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
}, [bothWorlds, server.id]);
const [action, setAction] = useState<Action>(null);
const [realmBusy, setRealmBusy] = useState(false);
const [stopFailed, setStopFailed] = useState(false);
const [confirmForce, setConfirmForce] = useState(false);
const [failure, setFailure] = useState<Failure | null>(null);
const [showDetails, setShowDetails] = useState(false);
const [pop, setPop] = useState<Population | null>(null);
@@ -114,12 +124,19 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const [crashCount, setCrashCount] = useState(0);
const crashCountRef = useRef(0);
const [showCrashModal, setShowCrashModal] = useState(false);
const publishRealms = usePublishRealms(server.id, server.name);
const { status: registry } = useRegistryStatus(5000);
const [publishing, setPublishing] = useState<PublishRealm | null>(null);
// The realm a card shows: the first card is the main realm, then the realm that starts next to it, then Warcraft Reborn.
const chipOf = (realm: PublishRealm | undefined) => realm && <ListingChip status={registry?.realms.find((r) => r.local_id === realm.localId)} hasUrl={!!registry?.url} onOpen={() => setPublishing(realm)} />;
const mainRealm = publishRealms?.[0];
const secondRealm = publishRealms?.find((r) => r !== mainRealm && r.mode !== "reborn");
const rebornRealm = publishRealms?.find((r) => r !== mainRealm && r.mode === "reborn");
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 lifecycle = serverLifecycle(server.id);
const actionRef = useRef<Action>(null);
const crashTimestampsRef = useRef<number[]>([]);
const pollRef = useRef<() => Promise<void>>(undefined);
@@ -155,10 +172,9 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const run = useCallback(
async (kind: Exclude<Action, null>) => {
if (kind === "stopping") {
userStoppedRef.current = true;
} else {
userStoppedRef.current = false;
setStopFailed(false);
lifecycle.request(kind);
if (kind !== "stopping") {
setCrashLoopPaused(false);
setCrashRestartNotice(null);
}
@@ -168,8 +184,8 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
actionRef.current = kind;
try {
if (kind !== "starting") {
const out = await api.stop(server.id);
if (!out.ok) throw { human: out.human, technical: out.output };
const out = await api.stop(server.id).catch(e => { setStopFailed(true); throw e; });
if (!out.ok) { setStopFailed(true); throw { human: out.human, technical: out.output }; }
}
if (kind !== "stopping") {
setAction("starting");
@@ -181,6 +197,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const ui = asUiError(e);
setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical });
} finally {
lifecycle.complete(kind);
setAction(null);
actionRef.current = null;
void pollRef.current?.();
@@ -189,24 +206,30 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
[server.id],
);
async function forceStop() {
setConfirmForce(false); setFailure(null); setShowDetails(false); setStopFailed(false);
lifecycle.request("stopping"); setAction("stopping"); actionRef.current = "stopping";
try {
const out = await api.forceStop(server.id);
if (!out.ok) throw { human: out.human, technical: out.output };
} catch (e) { setStopFailed(true); setFailure(asUiError(e)); }
finally { lifecycle.complete("stopping"); setAction(null); actionRef.current = null; void pollRef.current?.(); }
}
const poll = useCallback(async () => {
try {
const s = await api.status(server.id);
if (alive.current) setStatus(s);
const isWorldRunning = s.observed.world.state === "running";
if (isWorldRunning) {
wasWorldRunningRef.current = true;
userStoppedRef.current = false;
lifecycle.observe(true, actionRef.current !== null, serverUpdateBlocksRestart(server.id));
const p = await api.population(server.id).catch(() => null);
if (alive.current) setPop(p);
} else {
if (alive.current) setPop(null);
if (
wasWorldRunningRef.current &&
!userStoppedRef.current &&
actionRef.current === null
lifecycle.observe(false, actionRef.current !== null, serverUpdateBlocksRestart(server.id))
) {
wasWorldRunningRef.current = false;
setHasCrashHistory(true);
const now = Date.now();
const recent = crashTimestampsRef.current.filter((ts) => now - ts < 180000);
@@ -317,7 +340,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<RealmPicker serverId={server.id} running={anyUp} disabled={transitioning || upd.applying} onBusy={setRealmBusy} onChanged={() => { onRealmChanged(); void poll(); }} />
<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="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}</span>{chipOf(mainRealm)}</div>
<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
@@ -388,7 +411,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
</div>
<div>
<dt className="text-muted">{t("overview.players")}</dt>
<dd className="mt-0.5 text-lg">{pop ? `${pop.players_online}` : "—"}{companions && pop && pop.bots_online > 0 ? <span className="ml-2 text-sm text-muted">{t("overview.companions", { n: pop.bots_online })}</span> : null}</dd>
<dd className="mt-0.5 text-lg">{pop ? `${pop.players_online}` : "—"}{pop && pop.bots_online > 0 ? <span className="ml-2 text-sm text-muted">{t("overview.bots", { n: pop.bots_online })}</span> : null}</dd>
</div>
</dl>
{companions && startBots !== undefined && (
@@ -398,32 +421,21 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<div className="mt-7 flex flex-wrap items-center gap-x-4 gap-y-3">
{running ? (
<Button variant="secondary" size="xl" disabled={transitioning} onClick={() => run("stopping")} className="min-w-56">
<Button variant="secondary" size="xl" disabled={transitioning} onClick={() => run("stopping")} className="min-w-40">
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{t("btn.stop")}
</Button>
) : upd.available ? (
<Button
variant="primary"
size="xl"
disabled={transitioning || upd.applying}
onClick={() => (needsDecision ? onOpenUpdates() : void runServerUpdate())}
className="min-w-56"
>
{upd.applying && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")}
</Button>
<SplitButton label={t("overview.server")}
primary={{ disabled: transitioning || upd.applying, onClick: () => (needsDecision ? onOpenUpdates() : void runServerUpdate()), children: <>{upd.applying && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")}</> }}
secondary={{ disabled: transitioning || upd.applying, onClick: () => run("starting"), children: t("btn.startWithoutUpdate") }}
/>
) : (
<Button variant="primary" size="xl" disabled={transitioning} onClick={() => run("starting")} className="min-w-56">
<Button variant="primary" size="xl" disabled={transitioning} onClick={() => run("starting")} className="min-w-40">
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{transitioning ? (action === "stopping" ? t("btn.stoppingCaps") : t("btn.startingCaps")) : t("btn.start")}
</Button>
)}
{!running && upd.available && (
<Button variant="secondary" size="sm" disabled={transitioning || upd.applying} onClick={() => run("starting")}>
{t("btn.startWithoutUpdate")}
</Button>
)}
{running && (
<Button variant="ghost" size="sm" disabled={transitioning || upd.applying} onClick={() => run("restarting")}>
{t("btn.restart")}
@@ -444,7 +456,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{client && <RealmlistMenu serverId={server.id} />}
{client && jobBusy ? (
<div
className="relative flex h-16 min-w-64 items-center overflow-hidden rounded-md border border-gold/50 bg-card-2"
className="relative flex h-12 min-w-64 items-center overflow-hidden rounded-md border border-gold/50 bg-card-2"
role="progressbar"
aria-valuenow={jobPct}
aria-valuemin={0}
@@ -470,9 +482,10 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
</button>
</div>
) : client && (clientStatus?.update_available || job.phase === "choose") ? (
<Button variant="primary" size="xl" disabled={playing || job.phase === "choose"} onClick={() => void startClientUpdate(server.id)} className="min-w-40">
{t("btn.updateClient")}
</Button>
<SplitButton label={t("btn.play")}
primary={{ disabled: playing || job.phase === "choose", onClick: () => void startClientUpdate(server.id), children: t("btn.updateClient") }}
secondary={{ disabled: realmBusy || playing || upd.applying, onClick: () => void play(), children: <>{playing && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("btn.playWithoutUpdate")}</> }}
/>
) : client ? (
<Button variant="primary" size="xl" disabled={realmBusy || playing} onClick={() => void play()} className="min-w-40">
{playing && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
@@ -483,11 +496,6 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{t("btn.setupClient")}
</Button>
) : null}
{client && !jobBusy && (clientStatus?.update_available || job.phase === "choose") && (
<Button variant="secondary" size="sm" disabled={realmBusy || playing || upd.applying} onClick={() => void play()}>
{t("btn.playWithoutUpdate")}
</Button>
)}
</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">
@@ -542,10 +550,12 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<Button size="sm" variant="ghost" onClick={() => void startClientUpdate(server.id)}>{t("client.dl.retry")}</Button>
</p>
)}
{upd.result && "committed" in upd.result && !!upd.result.preexistingCharacters && <p className="mt-3 text-sm text-warn" role="status">{t("upd.preexistingCharacters", { n: upd.result.preexistingCharacters })}</p>}
{upd.available && upd.preview && (
<div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm">
<p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p>
{upd.preview.latest_version && <p>{t("upd.intermediate", { to: upd.preview.to_version, latest: upd.preview.latest_version })}</p>}
<button className="mt-2 cursor-pointer text-gold hover:underline" onClick={onOpenUpdates}>{t("history.open")}</button>
{needsDecision && <p className="mt-1 text-muted">{t("overview.updateConflicts")}</p>}
{upd.applying && (
<div className="mt-2">
@@ -565,7 +575,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{secondary_world && (
<Card className="mt-4 p-7">
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}</div>
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}</span>{chipOf(secondRealm)}</div>
<div
className={cn("flex items-center gap-3 text-3xl font-semibold", secondary_world.state === "running" ? "text-ok" : secondary_world.state === "starting" || transitioning ? "text-warn" : "text-muted")}
role="status"
@@ -587,7 +597,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{reborn_world && (
<Card className="mt-4 p-7">
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.reborn} · ${t("overview.server")}` : t("realm.rebornWorld")}</div>
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.reborn} · ${t("overview.server")}` : t("realm.rebornWorld")}</span>{chipOf(rebornRealm)}</div>
<div
className={cn("flex items-center gap-3 text-3xl font-semibold", reborn_world.state === "running" ? "text-ok" : reborn_world.state === "starting" || transitioning ? "text-warn" : "text-muted")}
role="status"
@@ -620,6 +630,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<Card className="mt-4 border-bad/40 p-5" role="alert">
<p className="font-medium text-bad">{human(visibleFailure.human).title}</p>
<p className="mt-1 text-sm text-muted">{human(visibleFailure.human).message}</p>
{anyUp && (stopFailed || /still stopping|could not be stopped|Stop the server before updating/i.test(visibleFailure.technical)) && <Button className="mt-3" size="sm" variant="secondary" disabled={transitioning || upd.applying} onClick={() => setConfirmForce(true)}>{t("stop.force")}</Button>}
<div className="mt-3 flex gap-2">
<Button size="sm" onClick={() => setShowDetails((v) => !v)}>
{showDetails ? t("common.hideDetails") : t("common.viewDetails")}
@@ -649,6 +660,8 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
/>
)}
{publishing && <PublishRealmDialog realm={publishing} onClose={() => setPublishing(null)} />}
{confirmForce && <ForceStopDialog onCancel={() => setConfirmForce(false)} onConfirm={() => void forceStop()} />}
{showCrashModal && (
<CrashHistoryModal
serverId={server.id}
+3 -2
View File
@@ -2,10 +2,11 @@ import { useState } from "react";
import { Globe, Network } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { PublishCard } from "./PublishCard";
import { BrowsePage } from "@/screens/BrowsePage";
import { FriendsPage } from "@/screens/FriendsPage";
export function PlayWithFriends({ serverId }: { serverId: string; path?: string }) {
export function PlayWithFriends({ serverId, serverName = "" }: { serverId: string; serverName?: string; path?: string }) {
const t = useT();
const [tab, setTab] = useState<"servers" | "lan">("servers");
@@ -38,7 +39,7 @@ export function PlayWithFriends({ serverId }: { serverId: string; path?: string
</button>
</div>
{tab === "servers" && <BrowsePage />}
{tab === "servers" && <><PublishCard serverId={serverId} serverName={serverName} /><BrowsePage /></>}
{tab === "lan" && <FriendsPage serverId={serverId} />}
</div>
);
+1 -1
View File
@@ -36,12 +36,12 @@ export function PlayersPage({ serverId }: { serverId: string }) {
try {
await api.createAccount(serverId, username, password, admin);
setDone(username);
setCreated((n) => n + 1);
setUsername("");
setPassword("");
} catch (e) {
setError(asUiError(e));
} finally {
setCreated((n) => n + 1);
setBusy(false);
}
}
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { useI18n } from "@/i18n";
import { browse } from "@/lib/browse";
import { asUiError } from "@/lib/api";
export function PublicServerSettings() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void browse.enabled().then(setEnabled).catch(e => setError(asUiError(e).technical)); }, []);
async function change(next: boolean) {
setBusy(true); setError(null);
try { await browse.setEnabled(next); setEnabled(next); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
return <Card className="mt-6 p-6">
<label className="flex items-center gap-3 font-semibold"><input type="checkbox" checked={enabled === true} disabled={enabled === null || busy} onChange={e => void change(e.target.checked)} aria-describedby="public-server-hint" />{t("settings.publicServers")}</label>
<p id="public-server-hint" className="mt-2 text-sm text-muted">{t("settings.publicServersHint")}</p>
{error && <p role="alert" className="mt-2 text-sm text-bad">{error}</p>}
</Card>;
}
+49 -126
View File
@@ -1,141 +1,64 @@
import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { useT, type Key } from "@/i18n";
import { asUiError, api } from "@/lib/api";
import { realmRegistry, useRegistryStatus } from "@/lib/registry";
import { asControlError, control, type ControlStatus } from "@/lib/control";
import { useRegistryStatus } from "@/lib/registry";
import { isListed, stateTone, usePublishRealms, type PublishRealm } from "@/lib/publishRealms";
import type { RealmPublishStatus } from "@/lib/registry";
import { PublishAllDialog, PublishRealmDialog } from "@/screens/PublishDialog";
const LANGUAGES = ["en", "ru", "de", "fr", "es", "zh", "pt", "pl", "uk"];
/** A small button on a realm card: the listing state of that realm; it opens the window to publish or configure it. */
export function ListingChip({ status, hasUrl, onOpen }: { status: RealmPublishStatus | undefined; hasUrl: boolean; onOpen: () => void }) {
const t = useT();
const listed = isListed(status);
if (!listed && !hasUrl) return null;
return (
<button
type="button"
onClick={onOpen}
className={cn("inline-flex cursor-pointer items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium normal-case tracking-normal transition-colors", listed ? "border-line bg-card-2 hover:border-gold/40" : "border-gold/40 text-gold hover:bg-gold/10")}
title={t("registry.title")}
>
{listed ? <span className={stateTone(status?.state)}>{t(`registry.short.${status!.state}` as Key)}</span> : t("registry.publishShort")}
</button>
);
}
/** Publishing this server's realm to the central Registry: a name, a description, a language. Nothing else leaves this machine. */
/** The public listing of this server's realms: one line per realm; the form opens in a window. */
export function PublishCard({ serverId, serverName }: { serverId: string; serverName: string }) {
const t = useT();
const localId = `srv-${serverId}`;
const { status, refresh } = useRegistryStatus();
const mine = status?.realms.find((r) => r.local_id === localId);
const published = !!mine?.enabled;
const [name, setName] = useState(serverName);
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [existingOnly, setExistingOnly] = useState(false);
const [portableEnabled, setPortableEnabled] = useState(true);
const [route, setRoute] = useState("");
const [accessSaved, setAccessSaved] = useState(false);
const [ctl, setCtl] = useState<ControlStatus | null>(null);
const link = ctl?.hosting.find((h) => h.local_id === localId)?.link;
useEffect(() => {
let active = true;
void api.allSettings(serverId).then((items) => {
if (!active) return;
const item = items.find((i) => i.key === "PortableSession.Enable");
if (item) {
setPortableEnabled(item.value === "1" || item.value.toLowerCase() === "true");
}
}).catch(() => {});
return () => { active = false; };
}, [serverId]);
useEffect(() => {
const load = () => void control.status().then(setCtl).catch(() => {});
load();
const timer = setInterval(load, 3000);
return () => clearInterval(timer);
}, []);
useEffect(() => { if (mine) { setExistingOnly(mine.existing_only); setRoute(mine.route ?? ""); } }, [mine?.existing_only, mine?.route]);
async function saveAccess() {
setBusy(true); setError(null); setAccessSaved(false);
try {
await Promise.all([
control.setAccess(localId, existingOnly, route.trim() === "" ? null : route.trim()),
api.allSettingsSave(serverId, {
"PortableSession.Enable": portableEnabled ? "1" : "0",
...(portableEnabled ? { "CharacterDatabase.WorkerThreads": "1" } : {}),
}),
]);
await refresh();
setAccessSaved(true);
} catch (e) {
setError(asControlError(e).message);
} finally {
setBusy(false);
}
}
useEffect(() => {
if (mine && mine.display_name) { setName(mine.display_name); setDescription(mine.description); setLanguage(mine.language || "en"); setRegion(mine.region ?? ""); }
}, [mine?.display_name, mine?.description, mine?.language]);
async function run(action: () => Promise<void>) {
setBusy(true);
setError(null);
try { await action(); await refresh(); } catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
const tone = mine?.state === "online" ? "text-ok" : mine?.state === "rejected" ? "text-bad" : mine?.state === "retrying" || mine?.state === "realm_stopped" || mine?.state === "waiting_for_realm" ? "text-warn" : "text-muted";
const realms = usePublishRealms(serverId, serverName);
const { status } = useRegistryStatus();
const [open, setOpen] = useState<PublishRealm | "all" | null>(null);
if (!realms) return null;
const listed = (r: PublishRealm) => isListed(status?.realms.find((s) => s.local_id === r.localId));
const someUnlisted = realms.some((r) => !listed(r));
return (
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("registry.title")}</h2>
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="font-semibold">{t("registry.title")}</h2>
{realms.length > 1 && someUnlisted && <Button size="sm" onClick={() => setOpen("all")}>{t("registry.publishAll")}</Button>}
</div>
<p className="mt-1 text-sm text-muted">{t("registry.text")}</p>
{!published && <>
<label htmlFor="registry-name" className="mt-4 block text-sm font-medium">{t("registry.name")}</label>
<input id="registry-name" value={name} maxLength={80} onChange={(e) => setName(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<label htmlFor="registry-description" className="mt-3 block text-sm font-medium">{t("registry.description")}</label>
<textarea id="registry-description" value={description} rows={3} onChange={(e) => setDescription(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<p className="mt-1 text-xs text-muted">{t("registry.descriptionHint")}</p>
<label htmlFor="registry-language" className="mt-3 block text-sm font-medium">{t("registry.language")}</label>
<select id="registry-language" value={language} onChange={(e) => setLanguage(e.target.value)} className="mt-1 rounded-md border border-line bg-card px-3 py-2">
{LANGUAGES.map((l) => <option key={l} value={l}>{l}</option>)}
</select>
<label htmlFor="registry-region" className="mt-3 block text-sm font-medium">{t("registry.region")}</label>
<input id="registry-region" value={region} maxLength={16} placeholder="EU" onChange={(e) => setRegion(e.target.value)} className="mt-1 w-32 rounded-md border border-line bg-card px-3 py-2" />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url || name.trim() === ""} onClick={() => void run(() => realmRegistry.publish(localId, name, description, language, region.trim() === "" ? null : region.trim()))}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publish")}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</>}
{mine && (published || mine.state === "unpublishing") && <div className="mt-4 rounded-md border border-line p-3 text-sm" role="status">
<p className={cn("font-medium", tone)} data-state={mine.state}>{t(`registry.state.${mine.state}` as Key)}</p>
<p className="mt-1 text-xs text-muted">{mine.display_name}{mine.metadata_revision ? ` · ${t("registry.revision", { n: mine.metadata_revision })}` : ""}</p>
{mine.state === "realm_stopped" && <p className="mt-2 text-xs text-warn">{t("registry.realmStoppedHint")}</p>}
{mine.last_error && <p className="mt-1 text-xs text-warn">{mine.last_error}</p>}
{mine.state === "retrying" && mine.retry_in_secs !== null && <p className="mt-1 text-xs text-muted">{t("registry.retryIn", { s: mine.retry_in_secs })}</p>}
<div className="mt-3 flex gap-2">
{mine.state === "rejected" && <Button size="sm" onClick={() => void run(async () => { await realmRegistry.retry(localId); })}>{t("registry.retry")}</Button>}
<Button size="sm" disabled={busy} onClick={() => void run(() => realmRegistry.unpublish(localId))}>{t("registry.stop")}</Button>
</div>
</div>}
{mine && (published || mine.state === "unpublishing") && <div className="mt-4 rounded-md border border-line p-3 text-sm" data-testid="access-options">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={portableEnabled} onChange={(e) => setPortableEnabled(e.target.checked)} className="mt-1" data-testid="portable-enabled" /><span>{t("access.portableEnabled")}<span className="block text-xs text-muted">{t("access.portableEnabledHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" data-testid="existing-only" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label htmlFor="access-route" className="mt-3 block font-medium">{t("access.route")}</label>
<input id="access-route" value={route} placeholder="play.example.org:3724" onChange={(e) => setRoute(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" data-testid="access-route" />
<p className="mt-1 text-xs text-muted">{t("access.routeHint")}</p>
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy} onClick={() => void saveAccess()}>{t("access.save")}</Button>
{accessSaved && <span className="text-xs text-ok" role="status">{t("access.saved")}</span>}
</div>
<p className={cn("mt-3 text-xs", link?.connected ? "text-ok" : "text-muted")} data-testid="control-link" data-connected={link?.connected ? "yes" : "no"}>
{link?.connected ? t("access.linkUp") : t("access.linkDown")}{link?.last_error && !link.connected ? ` — ${link.last_error}` : ""}
</p>
{ctl && ctl.secret_store === "file" && <p className="mt-1 text-xs text-warn">{t("access.fileStore")}</p>}
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
<ul className="mt-4 divide-y divide-line border-y border-line">
{realms.map((r) => {
const mine = status?.realms.find((s) => s.local_id === r.localId);
return (
<li key={r.localId} className="flex flex-wrap items-center justify-between gap-3 py-3">
<div>
<p className="font-medium">{r.label}</p>
<p className={cn("text-xs", stateTone(isListed(mine) ? mine?.state : undefined))} data-state={mine?.state}>{t(`registry.short.${isListed(mine) ? mine!.state : "disabled"}` as Key)}</p>
</div>
<Button size="sm" onClick={() => setOpen(r)}>{isListed(mine) ? t("registry.configure") : t("registry.publishShort")}</Button>
</li>
);
})}
</ul>
{!status?.url && <p className="mt-3 text-xs text-muted">{t("registry.noUrl")}</p>}
{open === "all" && <PublishAllDialog realms={realms} onClose={() => setOpen(null)} />}
{open && open !== "all" && <PublishRealmDialog realm={open} onClose={() => setOpen(null)} />}
</Card>
);
}
+253
View File
@@ -0,0 +1,253 @@
import { useEffect, useState, type ReactNode } from "react";
import { Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { useT, type Key } from "@/i18n";
import { asUiError, api } from "@/lib/api";
import { realmRegistry, useRegistryStatus } from "@/lib/registry";
import { asControlError, control, type ControlStatus } from "@/lib/control";
import { isListed, stateTone, type PublishRealm } from "@/lib/publishRealms";
const LANGUAGES = ["en", "ru", "de", "fr", "es", "zh", "pt", "pl", "uk"];
function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
const t = useT();
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
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-[88vh] w-full max-w-xl flex-col p-6 shadow-2xl" role="dialog" aria-modal="true" aria-label={title}>
<div className="flex items-center justify-between border-b border-line pb-4">
<h2 className="text-lg font-semibold">{title}</h2>
<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 pt-4">{children}</div>
</Card>
</div>
);
}
/** The name, description, language and region of a listing; the fields are the same for one realm and for all of them. */
function ListingFields({ idPrefix, name, setName, description, setDescription, language, setLanguage, region, setRegion, hideName }: {
idPrefix: string; name: string; setName: (v: string) => void; description: string; setDescription: (v: string) => void;
language: string; setLanguage: (v: string) => void; region: string; setRegion: (v: string) => void; hideName?: boolean;
}) {
const t = useT();
return <>
{!hideName && <>
<label htmlFor={`${idPrefix}-name`} className="block text-sm font-medium">{t("registry.name")}</label>
<input id={`${idPrefix}-name`} value={name} maxLength={80} onChange={(e) => setName(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
</>}
<label htmlFor={`${idPrefix}-description`} className="mt-3 block text-sm font-medium">{t("registry.description")}</label>
<textarea id={`${idPrefix}-description`} value={description} rows={3} onChange={(e) => setDescription(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<p className="mt-1 text-xs text-muted">{t("registry.descriptionHint")}</p>
<div className="mt-3 flex flex-wrap gap-4">
<div>
<label htmlFor={`${idPrefix}-language`} className="block text-sm font-medium">{t("registry.language")}</label>
<select id={`${idPrefix}-language`} value={language} onChange={(e) => setLanguage(e.target.value)} className="mt-1 rounded-md border border-line bg-card px-3 py-2">
{LANGUAGES.map((l) => <option key={l} value={l}>{l}</option>)}
</select>
</div>
<div>
<label htmlFor={`${idPrefix}-region`} className="block text-sm font-medium">{t("registry.region")}</label>
<input id={`${idPrefix}-region`} value={region} maxLength={16} placeholder="EU" onChange={(e) => setRegion(e.target.value)} className="mt-1 w-32 rounded-md border border-line bg-card px-3 py-2" />
</div>
</div>
</>;
}
/** Who may join and how: shown before publishing, so the choice is made once, not found later. */
function JoinChoices({ existingOnly, setExistingOnly, allowPortable, setAllowPortable }: { existingOnly: boolean; setExistingOnly: (v: boolean) => void; allowPortable: boolean; setAllowPortable: (v: boolean) => void }) {
const t = useT();
return (
<div className="mt-4 rounded-md border border-line p-3 text-sm">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
</div>
);
}
/** Publishing, stopping and the access options of one realm. */
export function PublishRealmDialog({ realm, onClose }: { realm: PublishRealm; onClose: () => void }) {
const t = useT();
const { localId } = realm;
const { status, refresh } = useRegistryStatus();
const mine = status?.realms.find((r) => r.local_id === localId);
const published = !!mine?.enabled;
const [name, setName] = useState(realm.defaultName);
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// New listings start with portable characters allowed and accounts created for new players; the choice is shown before publishing.
const [allowPortable, setAllowPortable] = useState(true);
const [existingOnly, setExistingOnly] = useState(false);
const [route, setRoute] = useState("");
const [accessSaved, setAccessSaved] = useState(false);
const [portableEnabled, setPortableEnabled] = useState<boolean | null>(null);
const primaryRealm = !localId.includes(":");
const [ctl, setCtl] = useState<ControlStatus | null>(null);
const host = ctl?.hosting.find((h) => h.local_id === localId);
const link = host?.link;
useEffect(() => {
if (!primaryRealm) return;
let active = true;
void api.allSettings(localId.slice(4)).then((items) => {
const item = items.find((i) => i.key === "PortableSession.Enable");
if (active && item) setPortableEnabled(item.value === "1" || item.value.toLowerCase() === "true");
}).catch((e) => { if (active) setError(asUiError(e).technical); });
return () => { active = false; };
}, [localId, primaryRealm]);
useEffect(() => {
const load = () => void control.status().then(setCtl).catch(() => {});
load();
const timer = setInterval(load, 3000);
return () => clearInterval(timer);
}, []);
useEffect(() => { if (mine) { setExistingOnly(mine.existing_only); setAllowPortable(mine.allow_portable); setRoute(mine.route ?? ""); } }, [mine?.existing_only, mine?.allow_portable, mine?.route]);
useEffect(() => {
if (mine && mine.display_name) { setName(mine.display_name); setDescription(mine.description); setLanguage(mine.language || "en"); setRegion(mine.region ?? ""); }
}, [mine?.display_name, mine?.description, mine?.language]);
async function saveAccess() {
setBusy(true); setError(null); setAccessSaved(false);
try {
if (primaryRealm && portableEnabled !== null) {
await api.allSettingsSave(localId.slice(4), {
"PortableSession.Enable": portableEnabled ? "1" : "0",
...(portableEnabled ? { "CharacterDatabase.WorkerThreads": "1" } : {}),
});
}
await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim());
await refresh();
setAccessSaved(true);
} catch (e) { setError(asControlError(e).message); } finally { setBusy(false); }
}
async function run(action: () => Promise<void>) {
setBusy(true);
setError(null);
try { await action(); await refresh(); } catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
async function publish() {
setBusy(true);
setError(null);
try {
await realmRegistry.publish(localId, name, description, language, region.trim() === "" ? null : region.trim());
// Saving the joining options needs the listing to exist; if it cannot be saved now (for example the server is running), the options stay available below.
try { await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim()); }
catch (e) { setError(t("registry.accessFailed", { reason: asControlError(e).message })); }
await refresh();
} catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
return (
<Modal title={t("registry.dialogTitle", { realm: realm.label })} onClose={onClose}>
<p className="text-sm text-muted">{t("registry.text")}</p>
{!published && <div className="mt-4">
<ListingFields idPrefix={`pub-${localId}`} name={name} setName={setName} description={description} setDescription={setDescription} language={language} setLanguage={setLanguage} region={region} setRegion={setRegion} />
<JoinChoices existingOnly={existingOnly} setExistingOnly={setExistingOnly} allowPortable={allowPortable} setAllowPortable={setAllowPortable} />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url || name.trim() === ""} onClick={() => void publish()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publish")}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</div>}
{mine && isListed(mine) && <div className="mt-4 rounded-md border border-line p-3 text-sm" role="status">
<p className={cn("font-medium", stateTone(mine.state))} data-state={mine.state}>{t(`registry.state.${mine.state}` as Key)}</p>
{mine.state === "realm_stopped" && <p className="mt-2 text-xs text-warn">{t("registry.realmStoppedHint")}</p>}
<p className="mt-1 text-xs text-muted">{mine.display_name}{mine.metadata_revision ? ` · ${t("registry.revision", { n: mine.metadata_revision })}` : ""}</p>
{mine.last_error && <p className="mt-1 text-xs text-warn">{mine.last_error}</p>}
{mine.state === "retrying" && mine.retry_in_secs !== null && <p className="mt-1 text-xs text-muted">{t("registry.retryIn", { s: mine.retry_in_secs })}</p>}
<div className="mt-3 flex gap-2">
{mine.state === "rejected" && <Button size="sm" onClick={() => void run(async () => { await realmRegistry.retry(localId); })}>{t("registry.retry")}</Button>}
<Button size="sm" disabled={busy} onClick={() => void run(() => realmRegistry.unpublish(localId))}>{t("registry.stop")}</Button>
</div>
</div>}
{mine && isListed(mine) && <div className="mt-4 rounded-md border border-line p-3 text-sm" data-testid="access-options">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
{primaryRealm && <label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={portableEnabled ?? false} disabled={portableEnabled === null} onChange={(e) => setPortableEnabled(e.target.checked)} className="mt-1" data-testid="portable-enabled" /><span>{t("access.portableEnabled")}<span className="block text-xs text-muted">{t("access.portableEnabledHint")}</span></span></label>}
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" data-testid="existing-only" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" data-testid="allow-portable" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
<label htmlFor={`access-route-${localId}`} className="mt-3 block font-medium">{t("access.route")}</label>
<input id={`access-route-${localId}`} value={route} placeholder="play.example.org:3724" onChange={(e) => setRoute(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" data-testid="access-route" />
<p className="mt-1 text-xs text-muted">{t("access.routeHint")}</p>
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy} onClick={() => void saveAccess()}>{t("access.save")}</Button>
{accessSaved && <span className="text-xs text-ok" role="status">{t("access.saved")}</span>}
</div>
<p className={cn("mt-3 text-xs", link?.connected ? "text-ok" : "text-muted")} data-testid="control-link" data-connected={link?.connected ? "yes" : "no"}>
{link?.connected ? t("access.linkUp") : t("access.linkDown")}{link?.last_error && !link.connected ? ` — ${link.last_error}` : ""}
</p>
<p className={cn("mt-2 text-xs", host?.relay?.connected ? "text-ok" : "text-warn")} data-testid="relay-link">{host?.relay?.connected ? t("access.relayUp") : t("access.relayDown")}{host?.relay?.last_error ? ` — ${host.relay.last_error}` : ""}</p>
{ctl && ctl.secret_store === "file" && <p className="mt-1 text-xs text-warn">{t("access.fileStore")}</p>}
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Modal>
);
}
/** One description, language and region for every realm that is not listed yet. */
export function PublishAllDialog({ realms, onClose }: { realms: PublishRealm[]; onClose: () => void }) {
const t = useT();
const { status, refresh } = useRegistryStatus();
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [allowPortable, setAllowPortable] = useState(true);
const [existingOnly, setExistingOnly] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const todo = realms.filter((r) => !isListed(status?.realms.find((s) => s.local_id === r.localId)));
async function publishAll() {
setBusy(true); setError(null);
try {
for (const r of todo) await realmRegistry.publish(r.localId, r.defaultName, description, language, region.trim() === "" ? null : region.trim());
// The joining options are saved realm by realm; one that cannot be saved now (for example the server is running) does not stop the others.
const failed: string[] = [];
for (const r of todo) {
try { await control.setAccess(r.localId, existingOnly, allowPortable, null); }
catch (e) { failed.push(`${r.label}: ${asControlError(e).message}`); }
}
await refresh();
if (failed.length === 0) onClose();
else setError(t("registry.accessFailed", { reason: failed.join(" · ") }));
} catch (e) { setError(asUiError(e).technical); await refresh(); } finally { setBusy(false); }
}
return (
<Modal title={t("registry.publishAll")} onClose={onClose}>
<p className="text-sm text-muted">{t("registry.publishAllText")}</p>
<ul className="mt-3 space-y-1 text-sm">
{realms.map((r) => <li key={r.localId} className="flex justify-between gap-3"><span>{r.defaultName}</span><span className="text-muted">{todo.includes(r) ? t("registry.short.disabled") : t("registry.alreadyListed")}</span></li>)}
</ul>
{todo.length > 0 && <div className="mt-4">
<ListingFields idPrefix="pub-all" name="" setName={() => undefined} description={description} setDescription={setDescription} language={language} setLanguage={setLanguage} region={region} setRegion={setRegion} hideName />
<JoinChoices existingOnly={existingOnly} setExistingOnly={setExistingOnly} allowPortable={allowPortable} setAllowPortable={setAllowPortable} />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url} onClick={() => void publishAll()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publishAllButton", { n: todo.length })}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Modal>
);
}
+1 -1
View File
@@ -33,7 +33,7 @@ export function RealmStartupSettings({ serverId }: { serverId: string }) {
{view?.with_reborn && <p className="mt-1 text-sm text-muted">{t("realm.rebornPort", { port: view.reborn_world_port ?? "—" })}</p>}
{view && view.active !== "coa" && !view.with_reborn && <p className="mt-1 text-sm text-warn">{t("realm.rebornNeedsCoa")}</p>}
{view?.simultaneous && view.with_reborn && <p className="mt-3 text-sm">{t("realm.allThree")}</p>}
<p className="mt-3 text-sm text-muted">{t("realm.simultaneousHint")}</p>
<details className="mt-4 text-sm text-muted"><summary className="cursor-pointer">{t("settings.startupHelp")}</summary><p className="mt-2 leading-relaxed">{t("realm.simultaneousHint")}</p></details>
{busy && <p className="mt-2 text-sm" role="status">{t("realm.preparing")}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Card>;
+1 -1
View File
@@ -92,7 +92,7 @@ export function RealmlistMenu({ serverId, className }: { serverId: string; class
onClick={() => setOpen((v) => !v)}
aria-haspopup="menu"
aria-expanded={open}
className="flex h-16 cursor-pointer items-center gap-3 rounded-md border border-line bg-card-2 px-4 text-left transition-colors hover:border-gold/50"
className="flex h-12 cursor-pointer items-center gap-3 rounded-md border border-line bg-card-2 px-4 text-left transition-colors hover:border-gold/50"
>
<span>
<span className="block text-[11px] uppercase tracking-wide text-muted">{t("realm.label")}</span>
+76
View File
@@ -0,0 +1,76 @@
import { useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { getVersion } from "@tauri-apps/api/app";
import { useI18n, LOCALES, type Locale } from "@/i18n";
import { useSelfUpdate } from "@/lib/selfUpdate";
import { bundledHistories, compareVersions, releasesForUpdate, repositories, translatedNotes, type Component, type History } from "@/lib/releaseHistory";
import { api } from "@/lib/api";
import { Card } from "@/components/ui/card";
export interface HistorySelection { component: Component; from?: string; to?: string }
export function ReleaseHistory({ selection, onSelect }: { selection: HistorySelection; onSelect: (selection: HistorySelection) => void }) {
const { locale, t } = useI18n();
const [language, setLanguage] = useState<Locale>(locale);
const [feeds, setFeeds] = useState(bundledHistories);
const [fresh, setFresh] = useState<Partial<Record<Component, boolean>>>({});
const [mode, setMode] = useState<"all" | "range">("all");
const [selected, setSelected] = useState("");
const [installed, setInstalled] = useState<string>();
const updater = useSelfUpdate();
const { component } = selection;
const lastServer = useRef<HistorySelection>({ component: "server" });
const [linkError, setLinkError] = useState<string>();
useEffect(() => { if (component === "server") lastServer.current = selection; setLinkError(undefined); }, [selection, component]);
const target = component === "manager" ? updater.version : selection.to;
const from = component === "manager" ? installed : selection.from;
useEffect(() => setLanguage(locale), [locale]);
useEffect(() => { void getVersion().then(setInstalled).catch(() => {}); }, []);
useEffect(() => {
setSelected("");
setMode(selection.to || (component === "manager" && updater.version) ? "range" : "all");
}, [selection, component, updater.version]);
useEffect(() => {
let live = true;
void invoke<History>("release_history", { component, target }).then(feed => {
if (live && feed.component === component && Array.isArray(feed.releases)) {
setFeeds(previous => ({ ...previous, [component]: feed }));
setFresh(previous => ({ ...previous, [component]: feed.source === "remote" }));
}
}).catch(() => {}); // Bundled reviewed notes remain visible offline.
return () => { live = false; };
}, [component, target]);
const releases = [...(mode === "range" ? releasesForUpdate(feeds[component].releases, from, target) : feeds[component].releases)]
.sort((a, b) => compareVersions(b.version.split("-")[0], a.version.split("-")[0]) || b.date.localeCompare(a.date));
const record = releases.find(r => r.version === selected) ?? releases[0];
const notes = record ? translatedNotes(component, record, language) : undefined;
return <Card id="release-history" tabIndex={-1} className="mt-6 scroll-mt-4 overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-4 border-b border-line p-5">
<h2 className="font-semibold">{t("history.title")}</h2>
<div className="flex rounded-md border border-line p-1" aria-label={t("history.title")}>
{(["server", "manager"] as const).map(c => <button key={c} aria-pressed={component === c} onClick={() => onSelect(c === "server" ? lastServer.current : { component: c })} className={`cursor-pointer rounded px-3 py-1.5 text-sm ${component === c ? "bg-gold/10 text-gold" : "text-muted hover:text-ink"}`}>{t(`history.${c}`)}</button>)}
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-5 py-3 text-sm">
<div className="flex gap-3">
<button className={mode === "all" ? "text-gold" : "cursor-pointer text-muted"} aria-pressed={mode === "all"} onClick={() => setMode("all")}>{t("history.all")}</button>
{target && <button className={mode === "range" ? "text-gold" : "cursor-pointer text-muted"} aria-pressed={mode === "range"} onClick={() => setMode("range")}>{t("history.range")}{from ? ` · ${from} → ${target}` : ` · ${target}`}</button>}
</div>
<label className="flex items-center gap-2 text-muted">{t("history.language")}<select value={language} onChange={e => setLanguage(e.target.value as Locale)} className="rounded border border-line bg-panel px-2 py-1 text-ink">{LOCALES.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}</select></label>
</div>
<div className="grid min-h-64 md:grid-cols-[180px_1fr]">
<div className="flex max-h-96 gap-1 overflow-auto border-b border-line p-3 md:block md:border-r md:border-b-0" aria-label={t("history.all")}>
{releases.map(r => <button key={r.tag} aria-pressed={r.version === record?.version} onClick={() => setSelected(r.version)} className={`mb-1 block shrink-0 cursor-pointer rounded-md px-3 py-2 text-left text-sm md:w-full ${r.version === record?.version ? "bg-gold/10 text-gold" : "text-muted hover:bg-white/5"}`}><span className="block font-medium">{r.version}</span><span className="text-xs text-muted">{r.date}{r.prerelease ? " · Pre-release" : ""}</span></button>)}
</div>
<div className="min-w-0 p-5" aria-live="polite">
{record && notes ? <><h3 className="text-lg font-semibold">{t(`history.${component}`)} {record.version}</h3>
{notes.fallback && <p className="mt-2 text-xs text-warn">{t("history.fallback")}</p>}
<ul lang={notes.fallback ? "en" : language} className="mt-4 list-disc space-y-2 pl-5 text-sm leading-relaxed">{notes.notes.map((note, i) => <li key={i}>{note}</li>)}</ul>
{record.experimentalFeatures?.includes("portable-characters") && <p className="mt-4 rounded border border-warn/30 p-3 text-sm text-warn">{t("history.experimental")}</p>}
<a className="mt-5 inline-block text-sm text-gold hover:underline" href={`https://github.com/${repositories[component]}/releases/tag/${encodeURIComponent(record.tag)}`} onClick={e => { e.preventDefault(); void api.openLink(e.currentTarget.href).catch(error => setLinkError(String(error))); }}>GitHub ↗</a>
{linkError && <p className="mt-2 break-words text-xs text-bad" role="alert">{linkError}</p>}
</> : <p className="text-sm text-muted">{t("history.empty")}</p>}
</div>
</div>
<p className="border-t border-line px-5 py-3 text-xs text-muted">{fresh[component] ? t("history.refreshed") : t("history.offline")}</p>
</Card>;
}
+3 -1
View File
@@ -7,6 +7,8 @@ import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { AboutCard } from "@/screens/AboutCard";
import { PortablePage } from "@/screens/PortablePage";
import { BrowsePage } from "@/screens/BrowsePage";
import { WindowSettings } from "./WindowSettings";
import { PublicServerSettings } from "./PublicServerSettings";
import { LanguagePicker } from "@/components/LanguagePicker";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -65,7 +67,7 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
<div className="mt-auto border-t border-line pt-3"><Button variant="ghost" size="sm" className="w-full justify-start" onClick={onHost}>{t("remote.hostInstead")}</Button></div>
</nav>
<main className="h-full flex-1 overflow-y-auto px-10 py-8">
{page === "servers" ? <BrowsePage /> : page === "characters" ? <PortablePage /> : page === "settings" ? <><div className="flex items-center justify-between"><h1 className="text-2xl font-semibold">{t("nav.settings")}</h1><LanguagePicker /></div><AboutCard /></> : <>
{page === "servers" ? <BrowsePage /> : page === "characters" ? <PortablePage /> : page === "settings" ? <><div className="flex items-center justify-between"><h1 className="text-2xl font-semibold">{t("nav.settings")}</h1><LanguagePicker /></div><WindowSettings /><PublicServerSettings /><AboutCard /></> : <>
<div className="flex items-center justify-between"><h1 className="text-2xl font-semibold">{t("welcome.connect.title")}</h1><LanguagePicker /></div>
<p className="mt-2 text-muted">{t("remote.intro")}</p>
<Card className="mt-6 p-6">
+2
View File
@@ -12,6 +12,8 @@ const TARGET_LABEL: Record<ReportTargetId, Key> = {
manager: "rep.target.manager",
companions: "rep.target.companions",
squid: "rep.target.squid",
"custom-races": "rep.target.custom-races",
"content-scaling": "rep.target.content-scaling",
};
const FALLBACK: ReportTarget = { id: "manager", repo: "Corfirean/coa-server-manager", ours: true };
+256
View File
@@ -0,0 +1,256 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { ChevronDown, ChevronRight, Loader2, RefreshCw, Server } from "lucide-react";
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
import { isUpdateCurrent } from "@/lib/serverUpdateStatus";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useStartAfterUpdate } from "@/lib/updatePrefs";
import { hasKey, useHuman, useI18n, type Key } from "@/i18n";
function mb(bytes: number) {
return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverId: string; onHistory: (from?: string | null, to?: string) => void; onAttention: (value: boolean) => void }) {
const { t } = useI18n();
const upd = useServerUpdate(serverId);
const human = useHuman();
const [preview, setPreview] = useState<UpdatePreview | null>(upd.preview);
const [pending, setPending] = useState<UpdateTxn | null>(null);
const [pendingChecked, setPendingChecked] = useState(false);
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null);
// an update keeps running in the background when this tab is left, so its state is the shared one
const busy = upd.applying ? "update" : localBusy;
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null;
const [localError, setError] = useState<UiError | null>(null);
const error = pendingStateError ?? localError ?? upd.uiError;
const [localDone, setDone] = useState<string | null>(null);
const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone;
const [choices, setChoices] = useState<Record<string, "keep" | "replace">>(() => Object.fromEntries((upd.preview?.conflicts ?? []).map(c => [c, "keep" as const])));
const [advanced, setAdvanced] = useState(false);
const [source, setSource] = useState("");
const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId);
useEffect(() => {
let active = true;
setPendingChecked(false);
setPending(null);
setPendingStateError(null);
void api.pendingUpdate(serverId).then((txn) => {
if (active) { setPending(txn); setPendingChecked(true); }
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
return () => { active = false; };
}, [serverId]);
// Every finished attempt refreshes the disk state, including failures in the background.
useEffect(() => {
if (!upd.stateRevision) return;
setPreview(null);
setPendingChecked(!upd.stateError);
setPendingStateError(upd.stateError);
if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null);
}, [upd.stateRevision, serverId]);
useEffect(() => { onAttention(!!pending || !!pendingStateError); }, [pending, pendingStateError, onAttention]);
async function refreshPending() {
setPendingChecked(false);
try {
const txn = await refreshServerUpdateState(serverId);
setPending(txn);
setPendingStateError(null);
setPendingChecked(true);
return txn;
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
}
async function check() {
setBusy("check");
setError(null);
setDone(null);
clearServerUpdateResult(serverId);
setPreview(null);
try {
const txn = await refreshPending();
if (txn) return;
const p = await api.checkUpdate(serverId, source.trim() || undefined);
setPreview(p);
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const])));
} catch (e) {
setError(asUiError(e));
} finally {
setBusy(null);
}
}
async function update() {
if (!pendingChecked || pendingStateError || pending) return;
setError(null);
setDone(null);
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
}
async function rollback(txn: UpdateTxn) {
if (!window.confirm(t("upd.confirmBack"))) return;
setBusy("rollback");
setError(null);
try {
await api.rollbackUpdate(serverId, txn.id);
setPending(null);
setDone(t("upd.wentBack"));
} catch (e) {
setError(asUiError(e));
} finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function retryValidation(txn: UpdateTxn) {
setBusy("retry");
setError(null);
try {
const result = await api.retryUpdateValidation(serverId, txn.id);
if (result.state === "committed") {
setPending(null);
setPreview(null);
setDone(t("upd.updatedTo", { v: result.to_version }));
clearServerUpdateResult(serverId);
} else setPending(result);
} catch (e) { setError(asUiError(e)); }
finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function browse() {
const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") });
if (typeof p === "string") setSource(p);
}
return (
<div>
{pending && (
<Card className="mt-6 border-warn/40 p-5" role="alert">
<p className="font-medium text-warn">
{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}
</p>
<p className="mt-1 whitespace-pre-wrap text-sm text-muted">{pending.message ?? t("upd.safeBack")}</p>
{pending.state === "needs-decision" && (
<Button className="mt-3 mr-3" size="sm" disabled={!!busy} onClick={() => void retryValidation(pending)}>
{busy === "retry" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.retryValidation")}
</Button>
)}
<p className="mt-1 text-sm text-muted">{t("upd.backNote")}</p>
<Button className="mt-3" size="sm" disabled={!!busy} onClick={() => void rollback(pending)}>
{busy === "rollback" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{pending.from_version ? t("upd.goBackTo", { v: pending.from_version }) : t("upd.goBackBefore")}
</Button>
</Card>
)}
<Card className="mt-6 p-6">
<div className="flex items-start justify-between gap-3">
<div><h2 className="flex items-center gap-2 font-semibold"><Server className="h-4 w-4 text-gold" aria-hidden />{t("history.server")}</h2>
<p className="mt-2 text-sm text-muted">{preview?.from_version ? t("settings.version", { v: preview.from_version }) : "…"}</p></div>
<Button size="sm" disabled={!!busy} onClick={() => void check()} aria-label={t("upd.check")} title={t("upd.check")}><RefreshCw className={`h-4 w-4 ${busy === "check" ? "animate-spin" : ""}`} aria-hidden /></Button>
</div>
<button className="mt-3 cursor-pointer text-sm text-gold hover:underline" onClick={() => onHistory(preview?.from_version, preview && !isUpdateCurrent(preview) ? preview.to_version : undefined)}>{t(preview && !isUpdateCurrent(preview) ? "history.open" : "history.title")}</button>
<div className="mt-3"><button onClick={() => setAdvanced((v) => !v)} aria-expanded={advanced} className="flex cursor-pointer items-center gap-1 text-xs text-muted hover:text-ink">
{advanced ? <ChevronDown className="h-3 w-3" aria-hidden /> : <ChevronRight className="h-3 w-3" aria-hidden />}{t("install.advanced")}
</button></div>
{advanced && (
<div className="mt-3 flex gap-2">
<input aria-label={t("upd.folderLabel")} value={source} onChange={(e) => setSource(e.target.value)} placeholder={t("upd.folderHint")} className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />
<Button size="sm" onClick={browse}>{t("install.browse")}</Button>
</div>
)}
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{error && (
<div className="mt-4" role="alert">
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
{error.human.code === "unknown" ? error.technical : human(error.human).message}
</p>
<button className="mt-1 cursor-pointer text-xs text-muted underline" onClick={() => void navigator.clipboard.writeText(error.technical)}>
{t("common.copyError")}
</button>
</div>
)}
{preview?.database_check_error && (
<p className="selectable mt-4 break-words text-sm text-warn" role="status">{t("upd.dbUnchecked", { why: preview.database_check_error })}</p>
)}
{preview && isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
</div>
)}
{preview && !isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium">
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
</p>
{preview.latest_version && <p className="mt-1 text-sm text-warn" role="status">{t("upd.intermediate", { to: preview.to_version, latest: preview.latest_version })}</p>}
<p className="mt-1 text-sm text-muted">
{!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
</p>
<details className="mt-3" open={preview.items.some(i => i.action === "conflict")}><summary className="cursor-pointer text-sm text-muted">{t("history.files")}</summary><ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
{preview.items.filter((i) => i.action !== "skip").map((i) => (
<li key={i.path} className="py-2">
<div className="flex justify-between gap-3">
<span className="selectable break-all">{i.path}</span>
<span className={i.action === "conflict" ? "shrink-0 text-warn" : "shrink-0 text-muted"}>{t(`upd.act.${i.action}` as Key)}</span>
</div>
{i.action === "conflict" && (
<fieldset className="mt-2 flex flex-wrap gap-4 text-xs text-muted">
<legend className="sr-only">{t("upd.conflict")}</legend>
<span className="text-warn">{t("upd.conflict")}</span>
{(["keep", "replace"] as const).map((c) => (
<label key={c} className="flex cursor-pointer items-center gap-1">
<input type="radio" name={i.path} checked={choices[i.path] === c} onChange={() => setChoices((x) => ({ ...x, [i.path]: c }))} />
{c === "keep" ? t("upd.keep") : t("upd.replace")}
</label>
))}
</fieldset>
)}
</li>
))}
</ul></details>
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.now")}
</Button>
<p className="mt-2 text-xs text-muted">{t("upd.stopNote")}</p>
</div>
)}
{busy === "update" && progress && (
<div className="mt-5">
<div className="flex justify-between text-sm">
<span role="status">{hasKey(`ustep.${progress.step}`) ? t(`ustep.${progress.step}` as Key) : progress.step}</span>
<span className="text-muted">{progress.percent}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={progress.percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${progress.percent}%` }} />
</div>
</div>
)}
<label className="mt-5 flex cursor-pointer items-center justify-between gap-3 border-t border-line pt-4 text-sm" title={t("upd.startAfter")}>
<span>{t("settings.startServer")}</span><input type="checkbox" role="switch" checked={startAfter} onChange={(e) => setStartAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
</label>
</Card>
</div>
);
}
+51 -285
View File
@@ -1,291 +1,57 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
import { isUpdateCurrent } from "@/lib/serverUpdateStatus";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ClientCard } from "@/screens/ClientCard";
import { GameDataCard } from "@/screens/GameDataCard";
import { DiagnosticsCard } from "@/screens/DiagnosticsCard";
import { AboutCard } from "@/screens/AboutCard";
import { RemoveServerCard } from "@/screens/RemoveServerCard";
import { useStartAfterUpdate } from "@/lib/updatePrefs";
import { hasKey, useHuman, useI18n, type Key } from "@/i18n";
import { useState } from "react";
import { Download, Power, FolderOpen, Wrench, Languages } from "lucide-react";
import { useI18n } from "@/i18n";
import { WindowSettings } from "./WindowSettings";
import { PublicServerSettings } from "./PublicServerSettings";
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";
import { Card } from "@/components/ui/card";
import { useServerUpdate } from "@/lib/serverUpdate";
import { ServerUpdateCard } from "./ServerUpdateCard";
import { AboutCard } from "./AboutCard";
import { ReleaseHistory, type HistorySelection } from "./ReleaseHistory";
import { ClientCard } from "./ClientCard";
import { GameDataCard } from "./GameDataCard";
import { RealmStartupSettings } from "./RealmStartupSettings";
import { AutoRestartSettings } from "./AutoRestartSettings";
import { DiagnosticsCard } from "./DiagnosticsCard";
import { RepairCard } from "./RepairCard";
import { RemoveServerCard } from "./RemoveServerCard";
function mb(bytes: number) {
return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
export function SettingsHome({ serverId, serverName = "", path, onForget }: { serverId: string; serverName?: string; path: string; onForget: () => Promise<void> }) {
const sections = [["updates", Download], ["startup", Power], ["client", FolderOpen], ["service", Wrench], ["interface", Languages]] as const;
export function SettingsHome({ serverId, path, onForget }: { serverId: string; serverName?: string; path: string; onForget: () => Promise<void> }) {
const { t } = useI18n();
const upd = useServerUpdate(serverId);
const human = useHuman();
const [preview, setPreview] = useState<UpdatePreview | null>(null);
const [pending, setPending] = useState<UpdateTxn | null>(null);
const [pendingChecked, setPendingChecked] = useState(false);
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null);
// an update keeps running in the background when this tab is left, so its state is the shared one
const busy = upd.applying ? "update" : localBusy;
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null;
const [localError, setError] = useState<UiError | null>(null);
const error = pendingStateError ?? localError ?? upd.uiError;
const [localDone, setDone] = useState<string | null>(null);
const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone;
const [choices, setChoices] = useState<Record<string, "keep" | "replace">>({});
const [advanced, setAdvanced] = useState(false);
const [source, setSource] = useState("");
const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId);
useEffect(() => {
let active = true;
setPendingChecked(false);
setPending(null);
setPreview(null);
setPendingStateError(null);
void api.pendingUpdate(serverId).then((txn) => {
if (active) { setPending(txn); setPendingChecked(true); }
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
return () => { active = false; };
}, [serverId]);
// Every finished attempt refreshes the disk state, including failures in the background.
useEffect(() => {
if (!upd.stateRevision) return;
setPreview(null);
setPendingChecked(!upd.stateError);
setPendingStateError(upd.stateError);
if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null);
}, [upd.stateRevision, serverId]);
async function refreshPending() {
setPendingChecked(false);
try {
const txn = await refreshServerUpdateState(serverId);
setPending(txn);
setPendingStateError(null);
setPendingChecked(true);
return txn;
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
const [section, setSection] = useState<(typeof sections)[number][0]>("updates");
const [attention, setAttention] = useState(false);
const update = useServerUpdate(serverId);
const [history, setHistory] = useState<HistorySelection>(() => ({ component: "server", from: update.preview?.from_version ?? undefined, to: update.available ? update.preview?.to_version : undefined }));
function showHistory(selection: HistorySelection) {
setHistory(selection);
requestAnimationFrame(() => {
const element = document.getElementById("release-history");
element?.scrollIntoView({ behavior: "smooth", block: "start" });
element?.focus({ preventScroll: true });
});
}
async function check() {
setBusy("check");
setError(null);
setDone(null);
clearServerUpdateResult(serverId);
setPreview(null);
try {
const txn = await refreshPending();
if (txn) return;
const p = await api.checkUpdate(serverId, source.trim() || undefined);
setPreview(p);
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const])));
} catch (e) {
setError(asUiError(e));
} finally {
setBusy(null);
}
}
async function update() {
if (!pendingChecked || pendingStateError || pending) return;
setError(null);
setDone(null);
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
}
async function rollback(txn: UpdateTxn) {
if (!window.confirm(t("upd.confirmBack"))) return;
setBusy("rollback");
setError(null);
try {
await api.rollbackUpdate(serverId, txn.id);
setPending(null);
setDone(t("upd.wentBack"));
} catch (e) {
setError(asUiError(e));
} finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function retryValidation(txn: UpdateTxn) {
setBusy("retry");
setError(null);
try {
const result = await api.retryUpdateValidation(serverId, txn.id);
if (result.state === "committed") {
setPending(null);
setPreview(null);
setDone(t("upd.updatedTo", { v: result.to_version }));
clearServerUpdateResult(serverId);
} else setPending(result);
} catch (e) { setError(asUiError(e)); }
finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function browse() {
const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") });
if (typeof p === "string") setSource(p);
}
return (
<div className="max-w-2xl">
<h1 className="text-2xl font-semibold">{t("settings.title")}</h1>
<p className="mt-1 text-muted">{t("q.settings")}</p>
{pending && (
<Card className="mt-6 border-warn/40 p-5" role="alert">
<p className="font-medium text-warn">
{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}
</p>
<p className="mt-1 whitespace-pre-wrap text-sm text-muted">{pending.message ?? t("upd.safeBack")}</p>
{pending.state === "needs-decision" && (
<Button className="mt-3 mr-3" size="sm" disabled={!!busy} onClick={() => void retryValidation(pending)}>
{busy === "retry" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.retryValidation")}
</Button>
)}
<p className="mt-1 text-sm text-muted">{t("upd.backNote")}</p>
<Button className="mt-3" size="sm" disabled={!!busy} onClick={() => void rollback(pending)}>
{busy === "rollback" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{pending.from_version ? t("upd.goBackTo", { v: pending.from_version }) : t("upd.goBackBefore")}
</Button>
</Card>
)}
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("settings.language")}</h2>
<p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p>
<LanguagePicker className="mt-3" />
</Card>
<ClientCard serverId={serverId} />
<RealmStartupSettings serverId={serverId} />
<AutoRestartSettings serverId={serverId} />
<GameDataCard serverId={serverId} />
<DiagnosticsCard serverId={serverId} />
<RepairCard key={serverId} serverId={serverId} />
<PublishCard key={`publish-${serverId}`} serverId={serverId} serverName={serverName} />
<AboutCard />
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("upd.title")}</h2>
<p className="mt-1 text-sm text-muted">{t("upd.text")}</p>
<label className="mt-3 flex cursor-pointer items-center gap-2 text-sm">
<input type="checkbox" checked={startAfter} onChange={(e) => setStartAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
<span>{t("upd.startAfter")}</span>
</label>
<div className="mt-4 flex items-center gap-3">
<Button variant="primary" disabled={!!busy} onClick={() => void check()}>
{busy === "check" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.check")}
</Button>
<button onClick={() => setAdvanced((v) => !v)} aria-expanded={advanced} className="flex cursor-pointer items-center gap-1 text-sm text-muted hover:text-ink">
{advanced ? <ChevronDown className="h-4 w-4" aria-hidden /> : <ChevronRight className="h-4 w-4" aria-hidden />}
{t("install.advanced")}
</button>
</div>
{advanced && (
<div className="mt-3 flex gap-2">
<input aria-label={t("upd.folderLabel")} value={source} onChange={(e) => setSource(e.target.value)} placeholder={t("upd.folderHint")} className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />
<Button size="sm" onClick={browse}>{t("install.browse")}</Button>
</div>
)}
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{error && (
<div className="mt-4" role="alert">
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
{error.human.code === "unknown" ? error.technical : human(error.human).message}
</p>
<button className="mt-1 cursor-pointer text-xs text-muted underline" onClick={() => void navigator.clipboard.writeText(error.technical)}>
{t("common.copyError")}
</button>
</div>
)}
{preview?.database_check_error && (
<p className="selectable mt-4 break-words text-sm text-warn" role="status">{t("upd.dbUnchecked", { why: preview.database_check_error })}</p>
)}
{preview && isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
</div>
)}
{preview && !isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium">
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
</p>
{preview.latest_version && <p className="mt-1 text-sm text-warn" role="status">{t("upd.intermediate", { to: preview.to_version, latest: preview.latest_version })}</p>}
<p className="mt-1 text-sm text-muted">
{!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
</p>
<ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
{preview.items.filter((i) => i.action !== "skip").map((i) => (
<li key={i.path} className="py-2">
<div className="flex justify-between gap-3">
<span className="selectable break-all">{i.path}</span>
<span className={i.action === "conflict" ? "shrink-0 text-warn" : "shrink-0 text-muted"}>{t(`upd.act.${i.action}` as Key)}</span>
</div>
{i.action === "conflict" && (
<fieldset className="mt-2 flex flex-wrap gap-4 text-xs text-muted">
<legend className="sr-only">{t("upd.conflict")}</legend>
<span className="text-warn">{t("upd.conflict")}</span>
{(["keep", "replace"] as const).map((c) => (
<label key={c} className="flex cursor-pointer items-center gap-1">
<input type="radio" name={i.path} checked={choices[i.path] === c} onChange={() => setChoices((x) => ({ ...x, [i.path]: c }))} />
{c === "keep" ? t("upd.keep") : t("upd.replace")}
</label>
))}
</fieldset>
)}
</li>
))}
</ul>
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.now")}
</Button>
<p className="mt-2 text-xs text-muted">{t("upd.stopNote")}</p>
</div>
)}
{busy === "update" && progress && (
<div className="mt-5">
<div className="flex justify-between text-sm">
<span role="status">{hasKey(`ustep.${progress.step}`) ? t(`ustep.${progress.step}` as Key) : progress.step}</span>
<span className="text-muted">{progress.percent}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={progress.percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${progress.percent}%` }} />
</div>
</div>
)}
</Card>
<RemoveServerCard serverId={serverId} path={path} onForget={onForget} />
return <div className="mx-auto w-full max-w-5xl pb-8">
<h1 className="text-2xl font-semibold">{t("settings.title")}</h1>
<p className="mt-1 text-sm text-muted">{t("settings.organized")}</p>
<nav aria-label={t("settings.title")} className="mt-6 flex flex-wrap gap-1 border-b border-line pb-3">
{sections.map(([id, Icon]) => <button key={id} aria-current={section === id ? "page" : undefined} onClick={() => setSection(id)} className={`flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm ${section === id ? "bg-gold/10 text-gold" : "text-muted hover:bg-white/5 hover:text-ink"}`}>
<Icon className="h-4 w-4" aria-hidden />{t(`settings.section.${id}`)}
</button>)}
</nav>
{attention && section !== "updates" && <button role="alert" onClick={() => setSection("updates")} className="mt-4 w-full cursor-pointer rounded-lg border border-warn/40 p-4 text-left text-sm text-warn">{t("settings.attention")}</button>}
<div hidden={section !== "updates"}>
<div className="grid items-start gap-x-5 lg:grid-cols-2">
<ServerUpdateCard onAttention={setAttention} serverId={serverId} onHistory={(from, to) => showHistory({ component: "server", from: from ?? undefined, to })} />
<AboutCard onHistory={() => showHistory({ component: "manager" })} />
</div>
<button onClick={() => setSection("client")} className="mt-5 flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg border border-line px-5 py-4 text-left text-sm hover:bg-white/5"><span>{t("settings.clientLink")}</span><span aria-hidden>→</span></button>
<ReleaseHistory selection={history} onSelect={setHistory} />
</div>
);
<div hidden={section !== "startup"} className="max-w-3xl"><RealmStartupSettings serverId={serverId} /><AutoRestartSettings serverId={serverId} /></div>
<div hidden={section !== "client"} className="max-w-3xl"><ClientCard serverId={serverId} /><GameDataCard serverId={serverId} /></div>
<div hidden={section !== "service"} className="max-w-3xl"><DiagnosticsCard serverId={serverId} /><RepairCard serverId={serverId} /><RemoveServerCard serverId={serverId} path={path} onForget={onForget} /></div>
<div hidden={section !== "interface"} className="max-w-3xl"><Card className="mt-6 p-6"><h2 className="font-semibold">{t("settings.language")}</h2><p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p><LanguagePicker className="mt-4" /></Card><WindowSettings /><PublicServerSettings /></div>
</div>;
}
+1 -1
View File
@@ -284,8 +284,8 @@ export function SettingsPage(props: {
const q = query.trim().toLowerCase();
const searching = q !== "";
const hit = (...parts: string[]) => parts.some((x) => x.toLowerCase().includes(q));
const curatedKeys = new Set(view.settings.map((s) => s.key));
const collections = collectionsOf(cols);
const curatedKeys = new Set([...view.settings.map((s) => s.key), ...collections.map((c) => c.item.key)]);
const curatedHits = searching ? view.settings.filter((s) => hit(s.key, sx.title(s), sx.description(s))) : [];
const collectionHits = searching ? collections.filter((c) => hit(c.item.key, t(c.label), t(c.text))) : [];
const rawHits = (raw ?? []).filter(
+1 -1
View File
@@ -166,7 +166,7 @@ export function Shell(props: {
) : page === "report" ? (
<ReportPage key={server.id} serverId={server.id} />
) : page === "friends" ? (
<PlayWithFriends key={server.id} serverId={server.id} path={server.path} />
<PlayWithFriends key={server.id} serverName={server.name} serverId={server.id} path={server.path} />
) : page === "settings" ? (
<SettingsHome key={server.id} serverId={server.id} serverName={server.name} path={server.path} onForget={() => props.onForget(server.id)} />
) : page === "characters" ? (
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { Card } from "@/components/ui/card";
import { useI18n } from "@/i18n";
import { asUiError } from "@/lib/api";
export function WindowSettings() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void invoke<boolean>("close_to_tray").then(setEnabled).catch(e => setError(asUiError(e).technical)); }, []);
async function change(next: boolean) {
setBusy(true); setError(null);
try { await invoke("set_close_to_tray", { enabled: next }); setEnabled(next); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
return <Card className="mt-6 p-6">
<label className="flex items-center gap-3 font-semibold"><input type="checkbox" checked={enabled === true} disabled={enabled === null || busy} onChange={e => void change(e.target.checked)} aria-describedby="close-window-hint" />{t("settings.closeToTray")}</label>
<p id="close-window-hint" className="mt-2 text-sm text-muted">{t("settings.closeToTrayHint")}</p>
{error && <p role="alert" className="mt-2 text-sm text-bad">{error}</p>}
</Card>;
}