import { useCallback, useEffect, useRef, useState } from "react"; import { Check, ChevronDown, Pencil, Plus, Trash2 } from "lucide-react"; import { api, asUiError, type RealmProfile, type UiError } from "@/lib/api"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useHuman, useT } from "@/i18n"; /** The first `set realmlist` value of a realmlist text, for the small caption under a name. */ function host(data: string): string { const m = data.match(/^\s*set\s+realmlist\s+(\S+)/im); return m ? m[1].replace(/"/g, "") : ""; } /** Named realmlists for the game client, switched with one click: "Solo" for your own server, "PTR" for the shared one, and so on. */ export function RealmlistMenu({ serverId, className }: { serverId: string; className?: string }) { const t = useT(); const human = useHuman(); const [profiles, setProfiles] = useState([]); const [active, setActive] = useState(null); const [open, setOpen] = useState(false); const [editing, setEditing] = useState<{ id: string | null; name: string; data: string } | null>(null); const [error, setError] = useState(null); const [note, setNote] = useState(null); const box = useRef(null); const load = useCallback(async () => { try { const v = await api.realmlistProfiles(serverId); setProfiles(v.profiles); setActive(v.active); } catch (e) { setError(asUiError(e)); } }, [serverId]); useEffect(() => { void load(); }, [load]); useEffect(() => { if (!open) return; const away = (e: MouseEvent) => { if (box.current && !box.current.contains(e.target as Node)) setOpen(false); }; document.addEventListener("mousedown", away); return () => document.removeEventListener("mousedown", away); }, [open]); async function choose(p: RealmProfile) { setError(null); setNote(null); try { await api.realmlistActivate(serverId, p.id); setActive(p.id); setNote(t("realm.switched", { name: p.name })); } catch (e) { setError(asUiError(e)); } } async function remove(p: RealmProfile) { if (!window.confirm(t("realm.confirmDelete", { name: p.name }))) return; setError(null); try { await api.realmlistDelete(serverId, p.id); await load(); } catch (e) { setError(asUiError(e)); } } async function save() { if (!editing) return; setError(null); try { await api.realmlistSave(serverId, editing.id, editing.name, editing.data); setEditing(null); await load(); } catch (e) { setError(asUiError(e)); } } const current = profiles.find((p) => p.id === active); const message = error ? (error.human.code === "unknown" ? error.technical : human(error.human).message) : null; return (
{open && (
    {profiles.map((p) => (
  • ))}
{note &&

{note}

} {message && !editing &&

{message}

}
)} {editing && (

{editing.id ? t("realm.editTitle") : t("realm.addTitle")}

setEditing({ ...editing, name: e.target.value })} placeholder={t("realm.nameHint")} className="mt-1 block w-full rounded-md border border-line bg-bg px-3 py-2.5 text-[15px] outline-none focus:border-gold" />