import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react"; import { listen } from "@tauri-apps/api/event"; import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react"; import { api, asUiError, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useHuman, useI18n, useSchemaText, type Key } from "@/i18n"; import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField } from "@/lib/moduleSettings"; import { AuctionTypes } from "@/screens/AuctionTypes"; import type { UnsavedChangesGuard } from "@/lib/unsavedGuard"; /** The GitHub mark (lucide dropped its brand icons). */ function GithubMark(props: { className?: string }) { return ( ); } /** Icon and colours of a module's square tile, by the name the catalog gives it. */ const TILES: Record; from: string; to: string }> = { 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" }, tbc: { icon: Flame, from: "from-lime-500", to: "to-emerald-800" }, wotlk: { icon: Snowflake, from: "from-sky-400", to: "to-blue-700" }, gavel: { icon: Gavel, from: "from-yellow-500", to: "to-amber-700" }, sparkles: { icon: Sparkles, from: "from-fuchsia-500", to: "to-purple-700" }, swords: { icon: Swords, from: "from-rose-500", to: "to-red-800" }, races: { icon: Users, from: "from-cyan-500", to: "to-blue-800" }, }; const DEFAULT_TILE = { icon: Puzzle, from: "from-slate-500", to: "to-slate-700" }; const STATUS: Record = { soon: { label: "mod.status.soon", hint: "mod.hint.soon", tone: "border-violet-400/50 bg-violet-400/10 text-violet-300" }, early: { label: "mod.status.early", hint: "mod.hint.early", tone: "border-warn/50 bg-warn/10 text-warn" }, beta: { label: "mod.status.beta", hint: "mod.hint.beta", tone: "border-sky-400/50 bg-sky-400/10 text-sky-300" }, release: { label: "mod.status.release", hint: "mod.hint.release", tone: "border-ok/50 bg-ok/10 text-ok" }, }; function SettingsPanel({ className, children }: { className?: string; children: ReactNode }) { const ref = useRef(null); useEffect(() => { ref.current?.scrollIntoView({ block: "nearest", behavior: "smooth" }); }, []); return (
{children}
); } function StatusBadge({ status }: { status: string }) { const { t } = useI18n(); const s = STATUS[status] ?? STATUS.release; return ( {t(s.label)} ); } function Tile({ icon, off }: { icon: string; off: boolean }) { const tile = TILES[icon] ?? DEFAULT_TILE; const Icon = tile.icon; return (
); } /** The server's optional modules: square cards with a switch, the module's status, a link to GitHub and its settings. */ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId: string; onChanged?: () => void; onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void }) { const { t, locale } = useI18n(); const human = useHuman(); const [modules, setModules] = useState(null); const [open, setOpen] = useState(null); const [error, setError] = useState(null); const [changed, setChanged] = useState(false); const [racesPatchStatus, setRacesPatchStatus] = useState(null); const [racesInstalling, setRacesInstalling] = useState(false); const [racesProgress, setRacesProgress] = useState(null); const loadRacesStatus = useCallback(async () => { try { const st = await api.customRacesStatus(serverId); setRacesPatchStatus(st); } catch { // ignore } }, [serverId]); const [guard, setGuard] = useState(null); useEffect(() => { onRegisterGuard?.(guard); return () => onRegisterGuard?.(null); }, [guard, onRegisterGuard]); const load = useCallback(async () => { try { setModules((await api.modulesList(serverId)).filter((m) => !m.hidden)); await loadRacesStatus(); } catch (e) { setError(asUiError(e)); } }, [serverId, loadRacesStatus]); useEffect(() => { void load(); const un = listen("custom-races-progress", (e) => { if (e.payload.id === serverId) { setRacesProgress(e.payload); } }); return () => { void un.then((f) => f()); }; }, [load, serverId]); async function installClientPatch() { setRacesInstalling(true); setError(null); try { await api.customRacesInstall(serverId); await loadRacesStatus(); await load(); onChanged?.(); } catch (e) { setError(asUiError(e)); } finally { setRacesInstalling(false); setRacesProgress(null); } } async function uninstallClientPatch() { setRacesInstalling(true); setError(null); try { await api.customRacesUninstall(serverId); await load(); onChanged?.(); } catch (e) { setError(asUiError(e)); } finally { setRacesInstalling(false); } } async function toggle(m: ModuleView) { setError(null); try { await api.moduleSetEnabled(serverId, m.id, !m.enabled); setChanged(true); await load(); if (m.id === "custom-races") { await loadRacesStatus(); } onChanged?.(); } catch (e) { setError(asUiError(e)); } } const selected = modules?.find((m) => m.id === open) ?? null; const selectedAt = modules?.findIndex((m) => m.id === open) ?? -1; return (

{t("mod.title")}

{t("q.modules")}

{t("mod.intro")}

{changed &&

{t("mod.restart")}

} {error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

}
{modules === null && !error &&

{t("overview.checking")}

} {modules?.length === 0 && {t("mod.empty")}} {modules?.map((m, i) => (

{m.name}

{m.version && {m.version}}

{m.description[locale] ?? m.description.en}

{m.compatibility === "unsupported" &&

{t("realm.unsupported")}

} {m.compatibility === "experimental" &&

{t("realm.experimental")}

}
{m.installed && m.switchable && ( )} {m.installed && !m.switchable && m.status !== "soon" && m.compatibility !== "unsupported" && {t("mod.alwaysOn")}} {!m.installed && m.status !== "soon" && {t("mod.notHere")}}
{m.id === "custom-races" && (

{locale === "ru" ? "Установленная версия патча клиента: " : "Installed client patch version: "}{racesPatchStatus?.version ?? (locale === "ru" ? "не записана" : "not recorded")}

{racesInstalling && racesProgress ? (
{racesProgress.step} {Math.round(racesProgress.percent * 100)}%
) : (
{racesPatchStatus?.state === "enabled" && ( {locale === "ru" ? "Патч клиента: Включен" : "Client Patch: Active"} )} {racesPatchStatus?.state === "disabled" && ( {locale === "ru" ? "Патч клиента: Отключен (.disabled)" : "Client Patch: Disabled (.disabled)"} )} {racesPatchStatus?.state === "not-installed" && ( {locale === "ru" ? "Патч клиента: Не установлен" : "Client Patch: Not Installed"} )} {racesPatchStatus?.state === "partially-installed" && ( {locale === "ru" ? `Патч клиента: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ` : `Client Patch: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ`} )}
{racesPatchStatus?.state === "partially-installed" &&

{locale === "ru" ? "Файлы отсутствуют или изменены. Восстановите патч клиента." : "Files are missing or changed. Repair the client patch."}

} {( )} {racesPatchStatus && racesPatchStatus.state !== "not-installed" && }

{locale === "ru" ? (m.enabled ? "После установки патч будет включён." : "После установки патч останется отключённым: модуль сервера выключен или отсутствует.") : (m.enabled ? "The patch will be enabled after installation." : "The patch will stay disabled after installation: the server module is off or missing.")}

)}
)}
{!m.page && m.installed && m.has_settings && m.status !== "soon" && m.compatibility !== "unsupported" && ( )}
{/* The settings open right under the row of the card they belong to, so they are never out of sight below a long grid. */} {selected?.has_settings && !selected.page && selectedAt >= 0 && Math.floor(selectedAt / 2) === Math.floor(i / 2) && (i % 2 === 1 || i === modules.length - 1) && (

{t("mod.settingsOf", { name: selected.name })}

setChanged(true)} onRegisterGuard={setGuard} />
)} ))}
); } function ModuleSettings({ serverId, module, onSaved, onRegisterGuard }: { serverId: string; module: ModuleView; onSaved: () => void; onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void }) { const { t, tn, locale } = useI18n(); const sx = useSchemaText(); const human = useHuman(); const [advanced, setAdvanced] = useState(false); const [items, setItems] = useState(null); const [edits, setEdits] = useState>({}); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [note, setNote] = useState(null); const [query, setQuery] = useState(""); const [fieldErrors, setFieldErrors] = useState>({}); useEffect(() => { let cancelled = false; setItems(null); setEdits({}); setNote(null); setError(null); setFieldErrors({}); void api.moduleSettings(serverId, module.id).then((s) => { if (!cancelled) setItems(s); }).catch((e) => { if (!cancelled) setError(asUiError(e)); }); return () => { cancelled = true; }; }, [serverId, module.id]); async function save(): Promise { const errors: Record = {}; for (const [key, value] of Object.entries(edits)) { const field = moduleField(key, locale, items?.find(item => item.key === key)?.field); if (field && ["int", "float", "range"].includes(field.type)) { const number = Number(value); const message = !value.trim() || !Number.isFinite(number) ? t("set.enterNumber") : field.type === "int" && !Number.isInteger(number) ? t("set.enterInt") : field.min !== undefined && number < field.min ? t("set.atLeast", { n: field.min }) : field.max !== undefined && number > field.max ? t("set.atMost", { n: field.max }) : null; if (message) errors[key] = message; } } setFieldErrors(errors); if (Object.keys(errors).length) return false; setBusy(true); setError(null); setNote(null); try { const done = await api.moduleSaveSettings(serverId, module.id, edits); setEdits({}); setItems(await api.moduleSettings(serverId, module.id)); if (done.length) { onSaved(); setNote(t("mod.saved", { n: done.length })); } return true; } catch (e) { setError(asUiError(e)); return false; } finally { setBusy(false); } } const dirty = Object.keys(edits).length > 0; useEffect(() => { if (dirty) { onRegisterGuard?.({ isDirty: () => Object.keys(edits).length > 0, save: () => save(), discard: () => { setEdits({}); setFieldErrors({}); setNote(null); }, }); } else { onRegisterGuard?.(null); } return () => onRegisterGuard?.(null); }, [dirty, edits, onRegisterGuard]); const edit = (key: string, value: string) => setEdits(previous => { const next = { ...previous }; if (value === items?.find(item => item.key === key)?.value) delete next[key]; else next[key] = value; return next; }); const available = items?.filter(s => s.key !== moduleEnableKey(module.id)) ?? []; const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale, s.field) || moduleField(s.key, locale, s.field)?.advanced)).length; const visible = available.filter(s => { if (module.id === "ah-bot" && auctionWeightKey(s.key)) return false; const field = moduleField(s.key, locale, s.field); if (!advanced && !query.trim() && (!field || field.advanced)) return false; const title = field ? (s.field ? field.title : sx.title({ key: s.key, title: field.title })) : s.key; const description = field ? (s.field ? field.description : sx.description({ key: s.key, description: field.description })) : s.doc; return `${title} ${description} ${s.key}`.toLocaleLowerCase(locale).includes(query.trim().toLocaleLowerCase(locale)); }); return (
{items === null && !error && } {module.id === "npc-enchanter" && (

{t("mod.enchanter.add")}

{t("mod.enchanter.remove")}

)} {module.id === "ah-bot" && (

{t("mod.ahbot.setup")}

)} {available.length >= 10 && setQuery(e.target.value)} aria-label={t("set.search")} placeholder={t("set.search")} className="mb-3 w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />} {advancedCount > 0 && } {module.id === "ah-bot" && setEdits(previous => { const next = { ...previous }; for (const [key, value] of Object.entries(changes)) { if (value === items?.find(item => item.key === key)?.value) delete next[key]; else next[key] = value; } return next; })} />} {items && !visible.length && !available.some(s => module.id === "ah-bot" && auctionWeightKey(s.key)) &&

{t(available.length ? "all.none" : "mod.noSettings")}

}
    {visible.map((s) => { const field = moduleField(s.key, locale, s.field); const title = field ? (s.field ? field.title : sx.title({ key: s.key, title: field.title })) : s.key; const description = field ? (s.field ? field.description : sx.description({ key: s.key, description: field.description })) : s.doc; const value = edits[s.key] ?? s.value; const normalized = canonicalModuleValue(s.key, value); const options = field?.options ?? []; const bool = field?.type === "bool" || /^(true|false)$/i.test(normalized) || (/^(0|1)$/.test(normalized) && /(?:\.Enable(?:d)?$|Enable\/Disable)/i.test(s.key + " " + s.doc)); const on = /^(1|true|yes|on)$/i.test(normalized); const id = `${module.id}-${s.key}`; const controlClass = "selectable w-56 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold"; return (
  • {s.key in edits && {t("set.changed")}}
    {bool ? : options.length ? : field?.type === "range" ?
    edit(s.key, e.target.value)} aria-valuetext={`${Math.round(Number(normalized) * 100)}%`} className="min-w-0 flex-1 accent-gold" />{Math.round(Number(normalized) * 100)}%
    : edit(s.key, e.target.value)} className={controlClass} />}
    {description &&

    {description}

    } {fieldErrors[s.key] &&

    {fieldErrors[s.key]}

    } {advanced &&

    {s.key}

    } {s.default !== null && (edits[s.key] ?? s.value) !== s.default && ( )}
  • ); })}
{available.length > 0 &&
{dirty && } {note && {note}}
} {error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

} {dirty && (
{tn("set.unsaved", Object.keys(edits).length)}
)}
); }