diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index 1e4f9a1..a650935 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -1,2245 +1,2891 @@ -import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react"; -import { listen } from "@tauri-apps/api/event"; -import { - AlertTriangle, - Bot, - CheckCircle2, - Database, - Download, - Flame, - FolderPlus, - Gavel, - Hammer, - Info, - Layers, - Loader2, - Plug, - Puzzle, - Scaling, - Search, - Settings2, - Shield, - Snowflake, - Sparkles, - Swords, - Terminal, - Trash2, - Users, - X, - XCircle, - type LucideProps, -} from "lucide-react"; -import { - api, - asUiError, - type BuildResult, - type CompatibilityReport, - type CustomRacesClientStatus, - type CustomRacesProgress, - type InstalledPreviewPlugin, - type ModuleSetting, - type ModuleView, - type ToolchainStatus, - 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 { RaceAvailabilitySettings } from "@/screens/RaceAvailabilitySettings"; -import type { UnsavedChangesGuard } from "@/lib/unsavedGuard"; - -/** The GitHub mark */ -function GithubMark(props: { className?: string }) { - return ( - - - - ); -} - -/** Icon and colors of a module's square tile */ -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 ( -
- -
- ); -} - -export type TabId = "installed" | "catalog" | "builds" | "toolchain" | "github"; - -interface VerifiedCatalogModule { - id: string; - name: string; - repo: string; - category: "official" | "utility" | "economy" | "social" | "profession" | "scaling"; - description: { ru: string; en: string }; - qualification: "OFFICIAL_CORE" | "INSTALL_VERIFIED" | "LINK_VERIFIED" | "BUILT"; - tier: string; - verificationLevel: string; - notes: { ru: string; en: string }; - sqlRequired: boolean; - canInstall: boolean; - isOfficial?: boolean; - icon?: string; -} - -const OFFICIAL_IDS = new Set([ - "companions", - "content-scaling", - "tbc-content", - "wotlk-content", - "ah-bot", - "npc-enchanter", - "playerbots", - "custom-races", - "time-is-time", - "client-compat", -]); - -function cleanModuleName(name: string, id: string): string { - if (name && (name.length !== 40 || !/^[0-9a-f]+$/i.test(name))) { - return name; - } - if (id === "npc-buffer" || id.includes("npc_buffer") || name.includes("npc_buffer")) return "NPC Buffer"; - if (id === "ah-bot" || id.includes("ah_bot") || name.includes("ah_bot")) return "Auction House Bot"; - if (id === "npc-enchanter" || id.includes("enchanter")) return "NPC Enchanter"; - if (id === "congrats-on-level" || id.includes("congrats")) return "Congrats On Level"; - if (id === "reward-played-time" || id.includes("reward_played")) return "Reward Played Time"; - if (id === "solocraft" || id.includes("solocraft")) return "Solocraft"; - if (id && id.length === 40 && /^[0-9a-f]+$/i.test(id)) return `Module (${id.slice(0, 8)})`; - return id || name; -} - -const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ - // Official Core Modules - { - id: "companions", - name: "CoA Companions", - repo: "https://github.com/Corfirean/mod-coa-playerbots", - category: "official", - description: { - ru: "Боты-компаньоны для групп, подземелий и гильдии.", - en: "Companion bots for groups, dungeons and your guild.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный официальный модуль сервера. Взаимоисключение со SQUID's Playerbots.", - en: "Official built-in server module. Mutually exclusive with Playerbots.", - }, - sqlRequired: false, - canInstall: true, - isOfficial: true, - icon: "bot", - }, - { - id: "content-scaling", - name: "Content Scaling", - repo: "https://github.com/Corfirean/mod-coa-content-scaling", - category: "official", - description: { - ru: "Подстраивает подземелья и рейды под вашу группу, есть соло-режимы.", - en: "Scales dungeons and raids to your group, with solo modes.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный официальный модуль динамического масштабирования подземелий.", - en: "Official built-in dynamic dungeon scaling module.", - }, - sqlRequired: false, - canInstall: true, - isOfficial: true, - icon: "scaling", - }, - { - id: "tbc-content", - name: "TBC Content", - repo: "https://github.com/Corfirean/mod-coa-content-scaling", - category: "official", - description: { - ru: "Подземелья и рейды Запределья, подогнанные под ваши уровни.", - en: "Outland dungeons and raids, scaled to your level range.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный пакет контента Burning Crusade.", - en: "Built-in Burning Crusade content pack.", - }, - sqlRequired: false, - canInstall: true, - isOfficial: true, - icon: "tbc", - }, - { - id: "wotlk-content", - name: "WotLK Content", - repo: "https://github.com/Corfirean/mod-coa-content-scaling", - category: "official", - description: { - ru: "Подземелья и рейды Нордскола, подогнанные под ваши уровни.", - en: "Northrend dungeons and raids, scaled to your level range.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный пакет контента Wrath of the Lich King.", - en: "Built-in Wrath of the Lich King content pack.", - }, - sqlRequired: false, - canInstall: true, - isOfficial: true, - icon: "wotlk", - }, - { - id: "playerbots", - name: "SQUID's Playerbots", - repo: "https://github.com/Zyth45/mod-playerbots", - category: "official", - description: { - ru: "Альтернативная система ботов со случайными ботами и полным ИИ.", - en: "An alternative bot system with random bots and full AI.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенная система случайных ботов SQUID. Взаимоисключение с CoA Companions.", - en: "Built-in SQUID random bots system. Mutually exclusive with CoA Companions.", - }, - sqlRequired: true, - canInstall: true, - isOfficial: true, - icon: "swords", - }, - { - id: "custom-races", - name: "Custom Races", - repo: "https://github.com/Corfirean/azerothcore-wotlk-coa", - category: "official", - description: { - ru: "Пользовательские расы (Esteria и другие) с расширенной внешностью и патчем клиента.", - en: "Playable custom races (Esteria and additional races) with extended appearances.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный модуль рас. Требуется установка клиентского MPQ-патча.", - en: "Built-in custom races module. Requires client MPQ patch.", - }, - sqlRequired: true, - canInstall: true, - isOfficial: true, - icon: "races", - }, - { - id: "time-is-time", - name: "TimeIsTime", - repo: "https://github.com/Corfirean/azerothcore-wotlk-coa", - category: "official", - description: { - ru: "Настройка скорости смены дня и ночи и начального времени игрового мира.", - en: "Adjust the day and night cycle speed and starting game time.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный модуль синхронизации игрового времени с сервером.", - en: "Built-in world time synchronization module.", - }, - sqlRequired: false, - canInstall: true, - isOfficial: true, - icon: "sparkles", - }, - - // Supported Dynamic DLL Modules (Verified & Compiling) - { - id: "npc-buffer", - name: "NPC Buffer", - repo: "https://github.com/azerothcore/mod-npc-buffer", - category: "utility", - description: { - ru: "NPC-баффер для наложения положительных эффектов, снятия усталости и лечения персонажей.", - en: "NPC buff master offering spells, resurrection sickness removal, and player restoration.", - }, - qualification: "INSTALL_VERIFIED", - tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L4 PASS, L6 PASS", - notes: { - ru: "Сборка, связывание и динамическая загрузка в реалм подтверждены. Требуется импорт SQL.", - en: "Compilation, linking and dynamic realm load verified. Requires SQL migration.", - }, - sqlRequired: true, - canInstall: true, - icon: "plug", - }, - { - id: "ah-bot", - name: "Auction House Bot", - repo: "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-ah-bot-plus", - category: "official", - description: { - ru: "Наполняет аукцион реалистичными настраиваемыми лотами.", - en: "Fills the auction house with realistic, adjustable listings.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный официальный модуль аукциона виртуальных персонажей.", - en: "Built-in official virtual characters auction house module.", - }, - sqlRequired: false, - canInstall: true, - isOfficial: true, - icon: "gavel", - }, - { - id: "congrats-on-level", - name: "Congrats On Level", - repo: "https://github.com/azerothcore/mod-congrats-on-level", - category: "social", - description: { - ru: "Анимации, салюты и оповещения в чат при повышении уровня игрока.", - en: "Server-wide or local celebrations, fireworks and announcements on level up.", - }, - qualification: "INSTALL_VERIFIED", - tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L4 PASS, L6 PASS", - notes: { - ru: "Полный цикл жизненного цикла динамического плагина проверен на SDK v0.3.", - en: "Full lifecycle verified against CoA Plugin SDK v0.3.", - }, - sqlRequired: false, - canInstall: true, - icon: "sparkles", - }, - { - id: "npc-enchanter", - name: "NPC Enchanter", - repo: "https://github.com/azerothcore/mod-npc-enchanter", - category: "official", - description: { - ru: "НПС, который зачаровывает ваше снаряжение.", - en: "An NPC that enchants your gear for you.", - }, - qualification: "OFFICIAL_CORE", - tier: "Core Module", - verificationLevel: "PRODUCTION_SUPPORTED", - notes: { - ru: "Встроенный официальный модуль зачарования экипировки у НПС.", - en: "Built-in official NPC equipment enchanting module.", - }, - sqlRequired: false, - canInstall: true, - isOfficial: true, - icon: "sparkles", - }, - { - id: "reward-played-time", - name: "Reward Played Time", - repo: "https://github.com/azerothcore/mod-reward-played-time", - category: "social", - description: { - ru: "Периодическая выдача наград и валюты игрокам за время, проведённое на сервере.", - en: "Periodic rewards and tokens granted to players based on active playtime.", - }, - qualification: "INSTALL_VERIFIED", - tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L4 PASS, L6 PASS", - notes: { - ru: "Сборка и установка подтверждены. Содержит миграции базы данных characters.", - en: "Build and install verified. Contains characters DB migrations.", - }, - sqlRequired: true, - canInstall: true, - icon: "plug", - }, - - { - id: "solocraft", - name: "Solocraft", - repo: "https://github.com/azerothcore/mod-solocraft", - category: "scaling", - description: { - ru: "Масштабирование характеристик персонажа при одиночном прохождении группового контента.", - en: "Dynamically boosts player stats in group dungeons and raids for solo play.", - }, - qualification: "BUILT", - tier: "Tier 1: Dynamic DLL", - verificationLevel: "L0-L2 PASS", - notes: { - ru: "Сборка и связывание успешны. Параметры настраиваются через конфигурационный файл.", - en: "Build and link successful. Configurable via settings.", - }, - sqlRequired: true, - canInstall: true, - icon: "scaling", - }, -]; - -export function ModulesPage({ - serverId, - onChanged, - onRegisterGuard, -}: { - serverId: string; - onChanged?: () => void; - onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void; -}) { - const { t, locale } = useI18n(); - const human = useHuman(); - - // Navigation tab - const [activeTab, setActiveTab] = useState("installed"); - - // Official modules state - const [modules, setModules] = useState(null); - const [openSettings, setOpenSettings] = useState(null); - const toggleLock = useRef(false); - const [toggling, setToggling] = useState(null); - const [changed, setChanged] = useState(false); - const [racesPatchStatus, setRacesPatchStatus] = useState(null); - const [racesInstalling, setRacesInstalling] = useState(false); - const [racesProgress, setRacesProgress] = useState(null); - const [guard, setGuard] = useState(null); - - // Installed dynamic plugins - const [installedPlugins, setInstalledPlugins] = useState([]); - const [error, setError] = useState(null); - const [notification, setNotification] = useState(null); - - // Catalog search & filter - const [catalogQuery, setCatalogQuery] = useState(""); - const [catalogFilter, setCatalogFilter] = useState("all"); - const [selectedCatalogModule, setSelectedCatalogModule] = useState(null); - - // GitHub Intake & Analysis state - const [githubUrl, setGithubUrl] = useState(""); - const [analyzing, setAnalyzing] = useState(false); - const [analysisError, setAnalysisError] = useState(null); - const [report, setReport] = useState(null); - - // Toolchain state - const [toolchain, setToolchain] = useState(null); - - // Controlled Build state - const [building, setBuilding] = useState(false); - const [buildResult, setBuildResult] = useState(null); - const [buildLogs, setBuildLogs] = useState([]); - - // Installation & SQL confirmation modal - const [installing, setInstalling] = useState(false); - const [showSqlDialog, setShowSqlDialog] = useState(false); - - // Action busy indicators - const [actionInProgress, setActionInProgress] = useState(null); - - const [racesGuard, setRacesGuard] = useState(null); - - useEffect(() => { - const guards = [guard, racesGuard].filter((item): item is UnsavedChangesGuard => item !== null); - onRegisterGuard?.(guards.length ? { - isDirty: () => guards.some(item => item.isDirty()), - save: async () => { for (const item of guards) if (item.isDirty() && !await item.save()) return false; return true; }, - discard: () => guards.forEach(item => item.discard()), - } : null); - return () => onRegisterGuard?.(null); - }, [guard, racesGuard, onRegisterGuard]); - - const loadToolchain = useCallback(async () => { - try { - const tc = await api.previewToolchainStatus(); - setToolchain(tc); - } catch (e) { - console.error("Failed to load toolchain status", e); - } - }, []); - - const loadInstalledPlugins = useCallback(async () => { - try { - const plugins = await api.previewListInstalledPlugins(serverId); - setInstalledPlugins(plugins); - } catch { - // not critical if realm has no plugins yet - } - }, [serverId]); - - const loadRacesStatus = useCallback(async () => { - try { - const st = await api.customRacesStatus(serverId); - setRacesPatchStatus(st); - } catch { - // ignore - } - }, [serverId]); - - const load = useCallback(async () => { - try { - const mods = await api.modulesList(serverId); - setModules(mods.filter((m) => !m.hidden)); - await loadRacesStatus(); - await loadInstalledPlugins(); - await loadToolchain(); - } catch (e) { - setError(asUiError(e)); - } - }, [serverId, loadRacesStatus, loadInstalledPlugins, loadToolchain]); - - useEffect(() => { - void load(); - }, [load]); - - useEffect(() => { - let unlisten: (() => void) | undefined; - void listen("custom-races-progress", (e) => { - setRacesProgress(e.payload); - }).then((un) => { - unlisten = un; - }); - return () => { - unlisten?.(); - }; - }, []); - - async function installClientPatch() { - setRacesInstalling(true); - setError(null); - try { - await api.customRacesInstall(serverId); - await loadRacesStatus(); - onChanged?.(); - } catch (e) { - setError(asUiError(e)); - } finally { - setRacesInstalling(false); - setRacesProgress(null); - } - } - - async function uninstallClientPatch() { - setRacesInstalling(true); - setError(null); - try { - await api.customRacesUninstall(serverId); - await loadRacesStatus(); - onChanged?.(); - } catch (e) { - setError(asUiError(e)); - } finally { - setRacesInstalling(false); - } - } - - async function toggleOfficialModule(m: ModuleView) { - if (toggleLock.current || racesInstalling) return; - toggleLock.current = true; - setToggling(m.id); - setError(null); - try { - // Mutual exclusion check between companions and squid - if (m.id === "companions" && !m.enabled) { - const squidMod = modules?.find((x) => x.id === "squid"); - if (squidMod?.enabled) { - await api.moduleSetEnabled(serverId, "squid", false); - } - } else if (m.id === "squid" && !m.enabled) { - const compMod = modules?.find((x) => x.id === "companions"); - if (compMod?.enabled) { - await api.moduleSetEnabled(serverId, "companions", false); - } - } - 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)); - await load(); - } finally { - toggleLock.current = false; - setToggling(null); - } - } - - async function registerTestRealm() { - setActionInProgress("register-realm"); - setError(null); - try { - await api.previewRegisterTestRealm(); - setNotification( - locale === "ru" - ? "Экспериментальный тестовый реалм server-v03 успешно зарегистрирован!" - : "Experimental server-v03 test realm registered successfully!" - ); - onChanged?.(); - await load(); - } catch (e) { - setError(asUiError(e)); - } finally { - setActionInProgress(null); - } - } - - async function exportDiagnostics() { - setActionInProgress("export-diag"); - try { - const p = await api.previewExportDiagnostics(serverId); - setNotification( - locale === "ru" ? `Диагностический отчёт сохранён: ${p}` : `Diagnostic report saved: ${p}` - ); - } catch (e) { - setError(asUiError(e)); - } finally { - setActionInProgress(null); - } - } - - async function runAnalysis(urlToAnalyze?: string) { - const targetUrl = (urlToAnalyze || githubUrl).trim(); - if (!targetUrl) return; - setGithubUrl(targetUrl); - setAnalyzing(true); - setAnalysisError(null); - setReport(null); - setBuildResult(null); - try { - const rep = await api.analyzeGithubModule(targetUrl, serverId); - setReport(rep); - } catch (e: unknown) { - setAnalysisError(e instanceof Error ? e.message : String(e)); - } finally { - setAnalyzing(false); - } - } - - async function startControlledBuild(urlToBuildParam?: string) { - const target = (urlToBuildParam || (report ? report.repository_name : githubUrl)).trim(); - if (!target) return; - setBuilding(true); - setActiveTab("builds"); - setBuildLogs(["[CSM Controlled Build Engine] Initializing build environment..."]); - try { - setBuildLogs((prev) => [ - ...prev, - `Target module: ${target}`, - "Compiling C++ sources against CoA Plugin SDK v0.3 via MSVC...", - ]); - const res = await api.previewBuildModule(serverId, target); - setBuildResult(res); - setBuildLogs(res.log_output); - if (res.success) { - setNotification( - locale === "ru" - ? `Сборка успешно завершена! DLL '${res.display_name || res.module_id}' квалифицирована: ${res.dll_sha256?.substring(0, 16)}...` - : `Build succeeded! DLL '${res.display_name || res.module_id}' qualified: ${res.dll_sha256?.substring(0, 16)}...` - ); - } else { - setAnalysisError( - locale === "ru" - ? "Сборка завершилась ошибкой. Проверьте диагностику компилятора во вкладке 'Сборка & логи MSVC'." - : "Build failed. Check compiler diagnostics in the 'Builds & MSVC Logs' tab." - ); - } - } catch (e: unknown) { - setAnalysisError(e instanceof Error ? e.message : String(e)); - setBuildLogs((prev) => [...prev, `[FATAL BUILD ERROR]: ${String(e)}`]); - } finally { - setBuilding(false); - } - } - - function handleInstallClick() { - if (!buildResult || !buildResult.success) return; - if (report && report.sql_files.length > 0) { - setShowSqlDialog(true); - } else { - void performInstall(false); - } - } - - async function performInstall(applySql: boolean) { - if (!buildResult) return; - setShowSqlDialog(false); - setInstalling(true); - setError(null); - try { - const res = await api.previewInstallModule( - serverId, - buildResult.module_id, - buildResult.version, - applySql - ); - setNotification(res.message); - await load(); - setActiveTab("installed"); - onChanged?.(); - } catch (e) { - setError(asUiError(e)); - } finally { - setInstalling(false); - } - } - - async function removePlugin(moduleId: string) { - if ( - !confirm( - locale === "ru" - ? `Удалить плагин '${moduleId}'? Базы данных и пользовательские настройки будут сохранены.` - : `Remove plugin '${moduleId}'? Databases and configurations will be preserved.` - ) - ) { - return; - } - setActionInProgress(`remove-${moduleId}`); - setError(null); - try { - const msg = await api.previewRemoveModule(serverId, moduleId); - setNotification(msg); - await loadInstalledPlugins(); - onChanged?.(); - } catch (e) { - setError(asUiError(e)); - } finally { - setActionInProgress(null); - } - } - - function exportReportJson() { - if (!report) return; - const blob = new Blob([JSON.stringify(report, null, 2)], { type: "application/json" }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = `${report.repository_name}-compatibility-report.json`; - a.click(); - URL.revokeObjectURL(url); - } - - const installedModules = modules?.filter((m) => m.installed) ?? []; - const selectedModule = modules?.find((m) => m.id === openSettings) ?? null; - const selectedModuleIndex = installedModules.findIndex((m) => m.id === openSettings); - - const filteredCatalog = VERIFIED_CATALOG.filter((item) => { - if (catalogFilter === "official" && !item.isOfficial) return false; - if (catalogFilter === "verified" && item.isOfficial) return false; - if (!catalogQuery.trim()) return true; - const q = catalogQuery.toLowerCase(); - return ( - item.name.toLowerCase().includes(q) || - item.id.toLowerCase().includes(q) || - item.description.ru.toLowerCase().includes(q) || - item.description.en.toLowerCase().includes(q) - ); - }); - - return ( -
- {/* Header & Sub-navigation */} -
-
-

- - {locale === "ru" ? "Модули и плагины" : "Modules & Plugins"} - - MODULES PREVIEW - -

-

- {locale === "ru" - ? "Автономная тестовая редакция для управления официальными модулями и установки сторонних модулей AzerothCore в виде DLL." - : "Standalone preview for official module management and dynamic third-party DLL plugin installation."} -

-
- - {/* Global actions */} -
- - - -
-
- - {/* Notification Banner */} - {notification && ( -
- ✓ {notification} - -
- )} - - {/* Error Banner */} - {error && ( -
- ⚠ {error.technical || (error.human ? human(error.human).message : "Unknown error")} - -
- )} - - {/* Toolchain Health Status Bar */} - {toolchain && ( -
-
- {toolchain.msvc_available ? ( - - ) : ( - - )} - - MSVC (vcvars64): {toolchain.msvc_available ? "Ready" : "Missing"} - -
-
- {toolchain.cmake_available ? ( - - ) : ( - - )} - - CMake: {toolchain.cmake_available ? "Ready" : "Missing"} - -
-
- {toolchain.ninja_available ? ( - - ) : ( - - )} - - Ninja: {toolchain.ninja_available ? "Ready" : "Missing"} - -
-
- {toolchain.sdk_available ? ( - - ) : ( - - )} - - Plugin SDK v0.3: {toolchain.sdk_available ? "Ready" : "Missing"} - -
-
- )} - - {/* GitHub URL Intake Bar on General Modules Screen */} - -
-
- - setGithubUrl(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter" && githubUrl.trim()) { - void runAnalysis(); - } - }} - placeholder={ - locale === "ru" - ? "Укажите ссылку на GitHub-репозиторий модуля (например, https://github.com/azerothcore/mod-npc-buffer)..." - : "Enter GitHub repository URL (e.g., https://github.com/azerothcore/mod-npc-buffer)..." - } - className="w-full rounded border border-line bg-bg pl-9 pr-3 py-1.5 text-xs text-ink placeholder:text-muted/60 focus:border-gold focus:outline-none" - /> -
- -
- - - -
-
- - {/* Compact analysis banner when report is ready */} - {report && ( -
-
- {report.repository_name} - @{report.commit.substring(0, 8)} - - {report.classification} - - {report.sql_files.length > 0 && ( - - {report.sql_files.length} SQL - - )} -
- -
- - - {buildResult?.success && ( - - )} - -
-
- )} - - {analysisError && ( -
- ⚠ {analysisError} - -
- )} -
- - {/* Tabs Header */} -
- - - - - - - -
- - {/* TAB 0: INSTALLED MODULES */} - {activeTab === "installed" && ( -
-
-
-

- {locale === "ru" - ? "Установленные модули и динамические плагины сервера. Включайте, выключайте и настраивайте параметры каждого модуля." - : "Installed server modules and dynamic DLL plugins. Enable, disable, and configure parameters for each module."} -

-
- {changed && ( - - {t("mod.restart")} - - )} -
- -
- {modules === null && !error && ( -
- - {t("overview.checking")} -
- )} - {modules !== null && installedModules.length === 0 && ( - -

- {locale === "ru" ? "Нет установленных модулей" : "No installed modules"} -

-

- {locale === "ru" - ? "Выберите модули из Каталога или укажите ссылку на GitHub выше для установки." - : "Choose modules from the Catalog or provide a GitHub URL above to install."} -

- -
- )} - {installedModules.map((m, i) => { - const isDynamic = m.component_type === "DYNAMIC_DLL" || (!OFFICIAL_IDS.has(m.id) && (installedPlugins.some((p) => p.id === m.id) || m.id.length === 40)); - const canRemove = m.can_remove ?? isDynamic; - return ( - - -
- -
-
-

{cleanModuleName(m.name, m.id)}

- {m.version && ( - {m.version} - )} - - {m.component_type === "DYNAMIC_DLL" && ( - - DLL - - )} - {m.component_type === "CORE_EMBEDDED" && ( - - EMBEDDED - - )} - {m.component_type === "CONTENT_PACK" && ( - - CONTENT - - )} - {m.component_type === "CLIENT_PATCH" && ( - - CLIENT PATCH - - )} -
-

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

- {m.id === "companions" && ( -

- {locale === "ru" - ? "Взаимоисключение: не работает одновременно со SQUID's Playerbots." - : "Mutual exclusion: cannot run concurrently with SQUID's Playerbots."} -

- )} - {(m.id === "playerbots" || m.id === "squid") && ( -

- {locale === "ru" - ? "Взаимоисключение: отключает CoA Companions при активации." - : "Mutual exclusion: disables CoA Companions upon activation."} -

- )} -
- {m.installed && m.switchable && ( - - )} - {m.installed && !m.switchable && m.status !== "soon" && ( - {t("mod.alwaysOn")} - )} -
- - {toggling === m.id && ( -

- - {t("mod.switching")} -

- )} - - {/* Custom Races Client Patch status & actions */} - {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 && 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" && ( - - )} -
- - {canRemove && ( - - )} -
- - - {/* Inline settings drawer */} - {selectedModule?.has_settings && - !selectedModule.page && - selectedModuleIndex >= 0 && - Math.floor(selectedModuleIndex / 2) === Math.floor(i / 2) && - (i % 2 === 1 || i === installedModules.length - 1) && ( - -
-

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

- -
- setChanged(true)} - onRegisterGuard={setGuard} - /> - {selectedModule.id === "custom-races" && ( - setChanged(true)} - onRegisterGuard={setRacesGuard} - /> - )} -
- )} - - ); - })} -
-
- )} - - {/* TAB 1: VERIFIED MODULES CATALOG */} - {activeTab === "catalog" && ( -
-
-
-

- {locale === "ru" ? "Каталог проверенных модулей" : "Verified Modules Catalog"} -

-

- {locale === "ru" - ? "Официальные модули и сторонние DLL, протестированные с платформой и готовые к работе." - : "Official modules and third-party DLL plugins verified and fully compatible with the platform."} -

-
- - {/* Category filter pills */} -
- - - -
-
- - {/* Search box */} -
- - setCatalogQuery(e.target.value)} - placeholder={ - locale === "ru" - ? "Поиск по каталогу (например, buffer, enchanter, companions, scaling)..." - : "Search modules catalog..." - } - className="w-full rounded-md border border-line bg-bg pl-9 pr-4 py-2 text-xs text-ink placeholder:text-muted/60 focus:border-gold focus:outline-none" - /> -
- - {/* Catalog Grid */} -
- {filteredCatalog.map((item) => { - const matchedModule = modules?.find( - (m) => m.id === item.id || m.name.toLowerCase() === item.name.toLowerCase() - ); - const isInstalled = Boolean(matchedModule?.installed); - const isEnabled = Boolean(matchedModule?.enabled); - - return ( - -
-
-
- -
-

- {item.name} - ({item.id}) -

-

{locale === "ru" ? item.description.ru : item.description.en}

-
-
-
- - {/* Qualification Badges */} -
- {item.isOfficial ? ( - - ✓ OFFICIAL_CORE - - ) : item.qualification === "INSTALL_VERIFIED" ? ( - - ✓ INSTALL_VERIFIED - - ) : item.qualification === "LINK_VERIFIED" ? ( - - ✓ LINK_VERIFIED - - ) : ( - - ● BUILT - - )} - - {item.tier} - {item.sqlRequired && ( - SQL - )} -
- -

- {locale === "ru" ? item.notes.ru : item.notes.en} -

-
- -
- - -
- - - {isInstalled ? ( -
- - ✓ {locale === "ru" ? (isEnabled ? "Включен" : "Установлен") : (isEnabled ? "Active" : "Installed")} - - -
- ) : item.isOfficial ? ( - - ) : ( - - )} -
-
-
- ); - })} -
- - {/* Details Modal */} - {selectedCatalogModule && ( -
- -
-

- {selectedCatalogModule.name} - ({selectedCatalogModule.id}) -

- -
- -
-
- {locale === "ru" ? "Описание:" : "Description:"} -

- {locale === "ru" ? selectedCatalogModule.description.ru : selectedCatalogModule.description.en} -

-
- -
-
- {locale === "ru" ? "Уровень верификации:" : "Verification Level:"} - {selectedCatalogModule.verificationLevel} -
-
- {locale === "ru" ? "Уровень архитектуры:" : "Architecture Tier:"} - {selectedCatalogModule.tier} -
-
- -
- - {locale === "ru" ? "Инженерные примечания и статус:" : "Engineering Notes & Status:"} - -

- {locale === "ru" ? selectedCatalogModule.notes.ru : selectedCatalogModule.notes.en} -

-
-
- -
- - {selectedCatalogModule.canInstall && ( - - )} -
-
-
- )} -
- )} - - {/* TAB 4: BUILDS & MSVC LOGS */} - {activeTab === "builds" && ( -
- {/* Build Result Card */} - {buildResult && ( - -
-
- {buildResult.success ? ( - - ) : ( - - )} -
-

- {buildResult.display_name || buildResult.module_name} ({buildResult.duration_seconds.toFixed(1)}s) -

-

- {buildResult.success - ? `DLL Qualified: ${buildResult.dll_sha256?.substring(0, 24)}... (x64 /MD)` - : `Build failed with ${buildResult.errors.length} diagnostic error(s)`} -

-
-
- - {buildResult.success && ( - - )} -
- - {/* Error diagnostics */} - {buildResult.errors.length > 0 && ( -
-
MSVC Compiler / Linker Errors:
-
    - {buildResult.errors.map((err, i) => ( -
  • -
    - [{err.error_code}] {err.file}:{err.line} - {err.message} -
    - {err.actionable_resolution && ( -
    - ➜ {err.actionable_resolution} -
    - )} -
  • - ))} -
-
- )} -
- )} - - {/* Real-time Terminal Output */} -
-
- - - MSVC / CMake Build Output - - {buildLogs.length} lines -
-

-              {buildLogs.length === 0

-                ? "No build logs recorded yet. Start a build from the 'GitHub' tab."

-                : buildLogs.join("\n")}

-            
-
-
- )} - - {/* TAB 5: TOOLCHAIN & ENVIRONMENT */} - {activeTab === "toolchain" && toolchain && ( - -

- {locale === "ru" ? "Среда компиляции и Plugin SDK" : "Compilation Environment & Plugin SDK"} -

-

- {locale === "ru" - ? "Controlled Build Engine использует изолированные рецепты сборки, MSVC x64 и заголовки SDK v0.3. Исходные CMakeLists.txt модулей не исполняются." - : "Controlled Build Engine uses isolated build recipes, MSVC x64 compiler, and SDK v0.3 headers. Upstream CMakeLists.txt is never executed."} -

- -
-
- MSVC Toolchain (vcvars64.bat) - {toolchain.vcvars64_path || "NOT FOUND"} -
-
- CMake Executable - {toolchain.cmake_path || "NOT FOUND"} -
-
- Ninja Build Driver - {toolchain.ninja_path || "NOT FOUND"} -
-
- CoA Plugin SDK Directory - {toolchain.sdk_dir || "NOT FOUND"} -
-
- Host SDK ABI Fingerprint - {toolchain.sdk_abi_fingerprint || "UNKNOWN"} -
-
-
- )} - - {/* SQL Review & Confirmation Dialog Modal */} - {showSqlDialog && ( -
- -
- -

- {locale === "ru" ? "Проверка SQL-миграций" : "SQL Migrations Review"} -

-
-

- {locale === "ru" - ? "Этот модуль содержит SQL-файлы данных или структуры. MySQL DDL не поддерживает откат через обычные транзакции." - : "This module contains SQL structure or data files. MySQL DDL does not support rollback via standard transactions."} -

- - {report && ( -
-
- - {locale === "ru" ? "Файлы миграций:" : "Migration Files:"} - -
    - {report.sql_files.map((s, idx) => ( -
  • - • {s.file_path} ({s.statement_count} statements) -
  • - ))} -
-
- -
- - - {locale === "ru" - ? "Миграции будут применены к тестовой БД реалма. Удаление плагина сохранит таблицы нетронутыми." - : "Migrations will be applied to the realm test DB. Removing the plugin will preserve tables."} - -
-
- )} - -
- - -
-
-
- )} -
- ); -} - -/** Settings sub-component for official modules */ -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 ? human(error.human).message : error.technical} -

- )} - {dirty && ( -
- {tn("set.unsaved", Object.keys(edits).length)} -
- - -
-
- )} -
- ); -} +import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { + AlertTriangle, + Ban, + Bot, + CheckCircle2, + Database, + Download, + ExternalLink, + Flame, + FolderPlus, + Gavel, + GitFork, + Hammer, + Info, + Layers, + Loader2, + Plug, + Puzzle, + RefreshCw, + Scaling, + Search, + Settings2, + Shield, + Snowflake, + Sparkles, + Star, + Swords, + Terminal, + Trash2, + Users, + X, + XCircle, + type LucideProps, +} from "lucide-react"; +import { + api, + asUiError, + type BuildResult, + type CoaCompatibilityStatus, + type CompatibilityReport, + type CustomRacesClientStatus, + type CustomRacesProgress, + type InstalledPreviewPlugin, + type ModuleSetting, + type ModuleView, + type PublicCatalogueItem, + type PublicCatalogueResponse, + type ToolchainStatus, + 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 { RaceAvailabilitySettings } from "@/screens/RaceAvailabilitySettings"; +import type { UnsavedChangesGuard } from "@/lib/unsavedGuard"; + +/** The GitHub mark */ +function GithubMark(props: { className?: string }) { + return ( + + + + ); +} + +/** Icon and colors of a module's square tile */ +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 ( +
+ +
+ ); +} + +export type TabId = "installed" | "catalog" | "builds" | "toolchain" | "github"; + +interface VerifiedCatalogModule { + id: string; + name: string; + repo: string; + category: "official" | "utility" | "economy" | "social" | "profession" | "scaling"; + description: { ru: string; en: string }; + qualification: "OFFICIAL_CORE" | "INSTALL_VERIFIED" | "LINK_VERIFIED" | "BUILT"; + tier: string; + verificationLevel: string; + notes: { ru: string; en: string }; + sqlRequired: boolean; + canInstall: boolean; + isOfficial?: boolean; + icon?: string; +} + +const OFFICIAL_IDS = new Set([ + "companions", + "content-scaling", + "tbc-content", + "wotlk-content", + "ah-bot", + "npc-enchanter", + "playerbots", + "custom-races", + "time-is-time", + "client-compat", +]); + +function cleanModuleName(name: string, id: string): string { + if (name && (name.length !== 40 || !/^[0-9a-f]+$/i.test(name))) { + return name; + } + if (id === "npc-buffer" || id.includes("npc_buffer") || name.includes("npc_buffer")) return "NPC Buffer"; + if (id === "ah-bot" || id.includes("ah_bot") || name.includes("ah_bot")) return "Auction House Bot"; + if (id === "npc-enchanter" || id.includes("enchanter")) return "NPC Enchanter"; + if (id === "congrats-on-level" || id.includes("congrats")) return "Congrats On Level"; + if (id === "reward-played-time" || id.includes("reward_played")) return "Reward Played Time"; + if (id === "solocraft" || id.includes("solocraft")) return "Solocraft"; + if (id && id.length === 40 && /^[0-9a-f]+$/i.test(id)) return `Module (${id.slice(0, 8)})`; + return id || name; +} + +const VERIFIED_CATALOG: VerifiedCatalogModule[] = [ + // Official Core Modules + { + id: "companions", + name: "CoA Companions", + repo: "https://github.com/Corfirean/mod-coa-playerbots", + category: "official", + description: { + ru: "Боты-компаньоны для групп, подземелий и гильдии.", + en: "Companion bots for groups, dungeons and your guild.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный официальный модуль сервера. Взаимоисключение со SQUID's Playerbots.", + en: "Official built-in server module. Mutually exclusive with Playerbots.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "bot", + }, + { + id: "content-scaling", + name: "Content Scaling", + repo: "https://github.com/Corfirean/mod-coa-content-scaling", + category: "official", + description: { + ru: "Подстраивает подземелья и рейды под вашу группу, есть соло-режимы.", + en: "Scales dungeons and raids to your group, with solo modes.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный официальный модуль динамического масштабирования подземелий.", + en: "Official built-in dynamic dungeon scaling module.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "scaling", + }, + { + id: "tbc-content", + name: "TBC Content", + repo: "https://github.com/Corfirean/mod-coa-content-scaling", + category: "official", + description: { + ru: "Подземелья и рейды Запределья, подогнанные под ваши уровни.", + en: "Outland dungeons and raids, scaled to your level range.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный пакет контента Burning Crusade.", + en: "Built-in Burning Crusade content pack.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "tbc", + }, + { + id: "wotlk-content", + name: "WotLK Content", + repo: "https://github.com/Corfirean/mod-coa-content-scaling", + category: "official", + description: { + ru: "Подземелья и рейды Нордскола, подогнанные под ваши уровни.", + en: "Northrend dungeons and raids, scaled to your level range.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный пакет контента Wrath of the Lich King.", + en: "Built-in Wrath of the Lich King content pack.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "wotlk", + }, + { + id: "playerbots", + name: "SQUID's Playerbots", + repo: "https://github.com/Zyth45/mod-playerbots", + category: "official", + description: { + ru: "Альтернативная система ботов со случайными ботами и полным ИИ.", + en: "An alternative bot system with random bots and full AI.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенная система случайных ботов SQUID. Взаимоисключение с CoA Companions.", + en: "Built-in SQUID random bots system. Mutually exclusive with CoA Companions.", + }, + sqlRequired: true, + canInstall: true, + isOfficial: true, + icon: "swords", + }, + { + id: "custom-races", + name: "Custom Races", + repo: "https://github.com/Corfirean/azerothcore-wotlk-coa", + category: "official", + description: { + ru: "Пользовательские расы (Esteria и другие) с расширенной внешностью и патчем клиента.", + en: "Playable custom races (Esteria and additional races) with extended appearances.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный модуль рас. Требуется установка клиентского MPQ-патча.", + en: "Built-in custom races module. Requires client MPQ patch.", + }, + sqlRequired: true, + canInstall: true, + isOfficial: true, + icon: "races", + }, + { + id: "time-is-time", + name: "TimeIsTime", + repo: "https://github.com/Corfirean/azerothcore-wotlk-coa", + category: "official", + description: { + ru: "Настройка скорости смены дня и ночи и начального времени игрового мира.", + en: "Adjust the day and night cycle speed and starting game time.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный модуль синхронизации игрового времени с сервером.", + en: "Built-in world time synchronization module.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "sparkles", + }, + + // Supported Dynamic DLL Modules (Verified & Compiling) + { + id: "npc-buffer", + name: "NPC Buffer", + repo: "https://github.com/azerothcore/mod-npc-buffer", + category: "utility", + description: { + ru: "NPC-баффер для наложения положительных эффектов, снятия усталости и лечения персонажей.", + en: "NPC buff master offering spells, resurrection sickness removal, and player restoration.", + }, + qualification: "INSTALL_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L4 PASS, L6 PASS", + notes: { + ru: "Сборка, связывание и динамическая загрузка в реалм подтверждены. Требуется импорт SQL.", + en: "Compilation, linking and dynamic realm load verified. Requires SQL migration.", + }, + sqlRequired: true, + canInstall: true, + icon: "plug", + }, + { + id: "ah-bot", + name: "Auction House Bot", + repo: "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-ah-bot-plus", + category: "official", + description: { + ru: "Наполняет аукцион реалистичными настраиваемыми лотами.", + en: "Fills the auction house with realistic, adjustable listings.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный официальный модуль аукциона виртуальных персонажей.", + en: "Built-in official virtual characters auction house module.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "gavel", + }, + { + id: "congrats-on-level", + name: "Congrats On Level", + repo: "https://github.com/azerothcore/mod-congrats-on-level", + category: "social", + description: { + ru: "Анимации, салюты и оповещения в чат при повышении уровня игрока.", + en: "Server-wide or local celebrations, fireworks and announcements on level up.", + }, + qualification: "INSTALL_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L4 PASS, L6 PASS", + notes: { + ru: "Полный цикл жизненного цикла динамического плагина проверен на SDK v0.3.", + en: "Full lifecycle verified against CoA Plugin SDK v0.3.", + }, + sqlRequired: false, + canInstall: true, + icon: "sparkles", + }, + { + id: "npc-enchanter", + name: "NPC Enchanter", + repo: "https://github.com/azerothcore/mod-npc-enchanter", + category: "official", + description: { + ru: "НПС, который зачаровывает ваше снаряжение.", + en: "An NPC that enchants your gear for you.", + }, + qualification: "OFFICIAL_CORE", + tier: "Core Module", + verificationLevel: "PRODUCTION_SUPPORTED", + notes: { + ru: "Встроенный официальный модуль зачарования экипировки у НПС.", + en: "Built-in official NPC equipment enchanting module.", + }, + sqlRequired: false, + canInstall: true, + isOfficial: true, + icon: "sparkles", + }, + { + id: "reward-played-time", + name: "Reward Played Time", + repo: "https://github.com/azerothcore/mod-reward-played-time", + category: "social", + description: { + ru: "Периодическая выдача наград и валюты игрокам за время, проведённое на сервере.", + en: "Periodic rewards and tokens granted to players based on active playtime.", + }, + qualification: "INSTALL_VERIFIED", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L4 PASS, L6 PASS", + notes: { + ru: "Сборка и установка подтверждены. Содержит миграции базы данных characters.", + en: "Build and install verified. Contains characters DB migrations.", + }, + sqlRequired: true, + canInstall: true, + icon: "plug", + }, + + { + id: "solocraft", + name: "Solocraft", + repo: "https://github.com/azerothcore/mod-solocraft", + category: "scaling", + description: { + ru: "Масштабирование характеристик персонажа при одиночном прохождении группового контента.", + en: "Dynamically boosts player stats in group dungeons and raids for solo play.", + }, + qualification: "BUILT", + tier: "Tier 1: Dynamic DLL", + verificationLevel: "L0-L2 PASS", + notes: { + ru: "Сборка и связывание успешны. Параметры настраиваются через конфигурационный файл.", + en: "Build and link successful. Configurable via settings.", + }, + sqlRequired: true, + canInstall: true, + icon: "scaling", + }, +]; + + +function CoaStatusBadge({ status, conflictReason }: { status: CoaCompatibilityStatus; conflictReason?: string | null }) { + const { locale } = useI18n(); + switch (status) { + case "Recommended": + return ( + + + {locale === "ru" ? "Рекомендовано CoA" : "CoA Recommended"} + + ); + case "Verified": + return ( + + + {locale === "ru" ? "Проверен CoA" : "CoA Verified"} + + ); + case "RequiresAdapter": + return ( + + + {locale === "ru" ? "Требует адаптер" : "Requires Adapter"} + + ); + case "Incompatible": + return ( + + + {locale === "ru" ? "Несовместим" : "Incompatible"} + + ); + case "Blocked": + return ( + + + {locale === "ru" ? "Заблокирован" : "Blocked"} + + ); + default: + return ( + + {locale === "ru" ? "Сообщество AC" : "AC Community"} + + ); + } +} + +function formatDate(dateStr?: string | null): string { + if (!dateStr) return "—"; + try { + const d = new Date(dateStr); + return d.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" }); + } catch { + return dateStr; + } +} + +export function ModulesPage({ + serverId, + onChanged, + onRegisterGuard, +}: { + serverId: string; + onChanged?: () => void; + onRegisterGuard?: (guard: UnsavedChangesGuard | null) => void; +}) { + const { t, locale } = useI18n(); + const human = useHuman(); + + // Navigation tab + const [activeTab, setActiveTab] = useState("installed"); + + // Official modules state + const [modules, setModules] = useState(null); + const [openSettings, setOpenSettings] = useState(null); + const toggleLock = useRef(false); + const [toggling, setToggling] = useState(null); + const [changed, setChanged] = useState(false); + const [racesPatchStatus, setRacesPatchStatus] = useState(null); + const [racesInstalling, setRacesInstalling] = useState(false); + const [racesProgress, setRacesProgress] = useState(null); + const [guard, setGuard] = useState(null); + + // Installed dynamic plugins + const [installedPlugins, setInstalledPlugins] = useState([]); + const [error, setError] = useState(null); + const [notification, setNotification] = useState(null); + + // Catalog search & filter + const [catalogQuery, setCatalogQuery] = useState(""); + const [catalogFilter, setCatalogFilter] = useState("all"); + const [selectedCatalogModule, setSelectedCatalogModule] = useState(null); + + // Public AzerothCore Catalog state + const [publicCatalog, setPublicCatalog] = useState(null); + const [publicLoading, setPublicLoading] = useState(false); + const [publicError, setPublicError] = useState(null); + const [selectedPublicModule, setSelectedPublicModule] = useState(null); + const [catalogSort, setCatalogSort] = useState<"stars" | "name" | "updated">("stars"); + const [communityDisplayLimit, setCommunityDisplayLimit] = useState(24); + + // GitHub Intake & Analysis state + const [githubUrl, setGithubUrl] = useState(""); + const [analyzing, setAnalyzing] = useState(false); + const [analysisError, setAnalysisError] = useState(null); + const [report, setReport] = useState(null); + + // Toolchain state + const [toolchain, setToolchain] = useState(null); + + // Controlled Build state + const [building, setBuilding] = useState(false); + const [buildResult, setBuildResult] = useState(null); + const [buildLogs, setBuildLogs] = useState([]); + + // Installation & SQL confirmation modal + const [installing, setInstalling] = useState(false); + const [showSqlDialog, setShowSqlDialog] = useState(false); + + // Action busy indicators + const [actionInProgress, setActionInProgress] = useState(null); + + const [racesGuard, setRacesGuard] = useState(null); + + useEffect(() => { + const guards = [guard, racesGuard].filter((item): item is UnsavedChangesGuard => item !== null); + onRegisterGuard?.(guards.length ? { + isDirty: () => guards.some(item => item.isDirty()), + save: async () => { for (const item of guards) if (item.isDirty() && !await item.save()) return false; return true; }, + discard: () => guards.forEach(item => item.discard()), + } : null); + return () => onRegisterGuard?.(null); + }, [guard, racesGuard, onRegisterGuard]); + + const loadPublicCatalog = useCallback(async (forceRefresh = false) => { + setPublicLoading(true); + setPublicError(null); + try { + const res = await api.getPublicModuleCatalog(forceRefresh); + setPublicCatalog(res); + } catch (e) { + console.error("Failed to load public module catalog:", e); + setPublicError(e instanceof Error ? e.message : String(e)); + } finally { + setPublicLoading(false); + } + }, []); + + useEffect(() => { + if (activeTab === "catalog" && !publicCatalog && !publicLoading) { + void loadPublicCatalog(false); + } + }, [activeTab, publicCatalog, publicLoading, loadPublicCatalog]); + + const loadToolchain = useCallback(async () => { + try { + const tc = await api.previewToolchainStatus(); + setToolchain(tc); + } catch (e) { + console.error("Failed to load toolchain status", e); + } + }, []); + + const loadInstalledPlugins = useCallback(async () => { + try { + const plugins = await api.previewListInstalledPlugins(serverId); + setInstalledPlugins(plugins); + } catch { + // not critical if realm has no plugins yet + } + }, [serverId]); + + const loadRacesStatus = useCallback(async () => { + try { + const st = await api.customRacesStatus(serverId); + setRacesPatchStatus(st); + } catch { + // ignore + } + }, [serverId]); + + const load = useCallback(async () => { + try { + const mods = await api.modulesList(serverId); + setModules(mods.filter((m) => !m.hidden)); + await loadRacesStatus(); + await loadInstalledPlugins(); + await loadToolchain(); + } catch (e) { + setError(asUiError(e)); + } + }, [serverId, loadRacesStatus, loadInstalledPlugins, loadToolchain]); + + useEffect(() => { + void load(); + }, [load]); + + useEffect(() => { + let unlisten: (() => void) | undefined; + void listen("custom-races-progress", (e) => { + setRacesProgress(e.payload); + }).then((un) => { + unlisten = un; + }); + return () => { + unlisten?.(); + }; + }, []); + + async function installClientPatch() { + setRacesInstalling(true); + setError(null); + try { + await api.customRacesInstall(serverId); + await loadRacesStatus(); + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + } finally { + setRacesInstalling(false); + setRacesProgress(null); + } + } + + async function uninstallClientPatch() { + setRacesInstalling(true); + setError(null); + try { + await api.customRacesUninstall(serverId); + await loadRacesStatus(); + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + } finally { + setRacesInstalling(false); + } + } + + async function toggleOfficialModule(m: ModuleView) { + if (toggleLock.current || racesInstalling) return; + toggleLock.current = true; + setToggling(m.id); + setError(null); + try { + // Mutual exclusion check between companions and squid + if (m.id === "companions" && !m.enabled) { + const squidMod = modules?.find((x) => x.id === "squid"); + if (squidMod?.enabled) { + await api.moduleSetEnabled(serverId, "squid", false); + } + } else if (m.id === "squid" && !m.enabled) { + const compMod = modules?.find((x) => x.id === "companions"); + if (compMod?.enabled) { + await api.moduleSetEnabled(serverId, "companions", false); + } + } + 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)); + await load(); + } finally { + toggleLock.current = false; + setToggling(null); + } + } + + async function registerTestRealm() { + setActionInProgress("register-realm"); + setError(null); + try { + await api.previewRegisterTestRealm(); + setNotification( + locale === "ru" + ? "Экспериментальный тестовый реалм server-v03 успешно зарегистрирован!" + : "Experimental server-v03 test realm registered successfully!" + ); + onChanged?.(); + await load(); + } catch (e) { + setError(asUiError(e)); + } finally { + setActionInProgress(null); + } + } + + async function exportDiagnostics() { + setActionInProgress("export-diag"); + try { + const p = await api.previewExportDiagnostics(serverId); + setNotification( + locale === "ru" ? `Диагностический отчёт сохранён: ${p}` : `Diagnostic report saved: ${p}` + ); + } catch (e) { + setError(asUiError(e)); + } finally { + setActionInProgress(null); + } + } + + async function runAnalysis(urlToAnalyze?: string) { + const targetUrl = (urlToAnalyze || githubUrl).trim(); + if (!targetUrl) return; + setGithubUrl(targetUrl); + setAnalyzing(true); + setAnalysisError(null); + setReport(null); + setBuildResult(null); + try { + const rep = await api.analyzeGithubModule(targetUrl, serverId); + setReport(rep); + } catch (e: unknown) { + setAnalysisError(e instanceof Error ? e.message : String(e)); + } finally { + setAnalyzing(false); + } + } + + async function startControlledBuild(urlToBuildParam?: string) { + const target = (urlToBuildParam || (report ? report.repository_name : githubUrl)).trim(); + if (!target) return; + setBuilding(true); + setActiveTab("builds"); + setBuildLogs(["[CSM Controlled Build Engine] Initializing build environment..."]); + try { + setBuildLogs((prev) => [ + ...prev, + `Target module: ${target}`, + "Compiling C++ sources against CoA Plugin SDK v0.3 via MSVC...", + ]); + const res = await api.previewBuildModule(serverId, target); + setBuildResult(res); + setBuildLogs(res.log_output); + if (res.success) { + setNotification( + locale === "ru" + ? `Сборка успешно завершена! DLL '${res.display_name || res.module_id}' квалифицирована: ${res.dll_sha256?.substring(0, 16)}...` + : `Build succeeded! DLL '${res.display_name || res.module_id}' qualified: ${res.dll_sha256?.substring(0, 16)}...` + ); + } else { + setAnalysisError( + locale === "ru" + ? "Сборка завершилась ошибкой. Проверьте диагностику компилятора во вкладке 'Сборка & логи MSVC'." + : "Build failed. Check compiler diagnostics in the 'Builds & MSVC Logs' tab." + ); + } + } catch (e: unknown) { + setAnalysisError(e instanceof Error ? e.message : String(e)); + setBuildLogs((prev) => [...prev, `[FATAL BUILD ERROR]: ${String(e)}`]); + } finally { + setBuilding(false); + } + } + + function handleInstallClick() { + if (!buildResult || !buildResult.success) return; + if (report && report.sql_files.length > 0) { + setShowSqlDialog(true); + } else { + void performInstall(false); + } + } + + async function performInstall(applySql: boolean) { + if (!buildResult) return; + setShowSqlDialog(false); + setInstalling(true); + setError(null); + try { + const res = await api.previewInstallModule( + serverId, + buildResult.module_id, + buildResult.version, + applySql + ); + setNotification(res.message); + await load(); + setActiveTab("installed"); + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + } finally { + setInstalling(false); + } + } + + async function removePlugin(moduleId: string) { + if ( + !confirm( + locale === "ru" + ? `Удалить плагин '${moduleId}'? Базы данных и пользовательские настройки будут сохранены.` + : `Remove plugin '${moduleId}'? Databases and configurations will be preserved.` + ) + ) { + return; + } + setActionInProgress(`remove-${moduleId}`); + setError(null); + try { + const msg = await api.previewRemoveModule(serverId, moduleId); + setNotification(msg); + await loadInstalledPlugins(); + onChanged?.(); + } catch (e) { + setError(asUiError(e)); + } finally { + setActionInProgress(null); + } + } + + function exportReportJson() { + if (!report) return; + const blob = new Blob([JSON.stringify(report, null, 2)], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `${report.repository_name}-compatibility-report.json`; + a.click(); + URL.revokeObjectURL(url); + } + + const installedModules = modules?.filter((m) => m.installed) ?? []; + const selectedModule = modules?.find((m) => m.id === openSettings) ?? null; + const selectedModuleIndex = installedModules.findIndex((m) => m.id === openSettings); + + // Normalize repo URL to "owner/repo" slug + function normalizeUrlSlug(url: string): string { + const clean = url.trim().toLowerCase().replace(/^https?:\/\/github\.com\//, "").replace(/\.git$/, ""); + const parts = clean.split("/tree/")[0].split("/"); + return parts.length >= 2 ? `${parts[parts.length - 2]}/${parts[parts.length - 1]}` : clean; + } + + // Set of slugs from VERIFIED_CATALOG to avoid duplicate cards in community list + const verifiedRepoSlugs = new Set( + VERIFIED_CATALOG.map((m) => normalizeUrlSlug(m.repo)) + ); + + // Group A: Recommended / Verified for CoA + const filteredVerifiedCatalog = VERIFIED_CATALOG.filter((item) => { + if (catalogFilter === "official" && !item.isOfficial) return false; + if (catalogFilter === "verified" && item.isOfficial) return false; + if (catalogFilter === "community" || catalogFilter === "incompatible") return false; + if (!catalogQuery.trim()) return true; + const q = catalogQuery.toLowerCase(); + return ( + item.name.toLowerCase().includes(q) || + item.id.toLowerCase().includes(q) || + item.description.ru.toLowerCase().includes(q) || + item.description.en.toLowerCase().includes(q) + ); + }); + + // Group B: AzerothCore Community Modules + const filteredCommunityCatalog = (publicCatalog?.items ?? []) + .filter((item) => { + // Exclude items already curated in Group A + const slug = item.id.toLowerCase(); + if (verifiedRepoSlugs.has(slug) || verifiedRepoSlugs.has(item.repo.toLowerCase())) { + return false; + } + + // Filter by category / status + if (catalogFilter === "official" || catalogFilter === "verified") { + return false; + } + if (catalogFilter === "recommended") { + if (item.coa_status !== "Recommended" && item.coa_status !== "Verified") return false; + } + if (catalogFilter === "community") { + if (item.coa_status === "Incompatible" || item.coa_status === "Blocked") return false; + } + if (catalogFilter === "incompatible") { + if (item.coa_status !== "Incompatible" && item.coa_status !== "Blocked") return false; + } + + if (!catalogQuery.trim()) return true; + const q = catalogQuery.toLowerCase(); + return ( + item.name.toLowerCase().includes(q) || + item.repo.toLowerCase().includes(q) || + item.owner.toLowerCase().includes(q) || + item.description.toLowerCase().includes(q) || + item.topics.some((t) => t.toLowerCase().includes(q)) + ); + }) + .sort((a, b) => { + if (catalogSort === "stars") { + return b.stars - a.stars; + } + if (catalogSort === "updated") { + return (b.pushed_at || "").localeCompare(a.pushed_at || ""); + } + return a.name.localeCompare(b.name); + }); + + // Helper to check whether any module/plugin is installed + function checkModuleInstalled(repoOrId: string, name: string) { + const slug = normalizeUrlSlug(repoOrId); + const shortName = slug.split("/").pop() || slug; + + const plug = installedPlugins.find((p) => { + const pId = p.id.toLowerCase(); + const pName = p.name.toLowerCase(); + return pId === slug || pId === shortName || pName === name.toLowerCase() || pName === shortName; + }); + if (plug) { + return { installed: true, enabled: plug.enabled, version: plug.version }; + } + + const mod = modules?.find((m) => { + const mId = m.id.toLowerCase(); + const mName = m.name.toLowerCase(); + return mId === slug || mId === shortName || mName === name.toLowerCase() || mName === shortName; + }); + if (mod && mod.installed) { + return { installed: true, enabled: mod.enabled }; + } + + return { installed: false, enabled: false }; + } + + return ( +
+ {/* Header & Sub-navigation */} +
+
+

+ + {locale === "ru" ? "Модули и плагины" : "Modules & Plugins"} + + MODULES PREVIEW + +

+

+ {locale === "ru" + ? "Автономная тестовая редакция для управления официальными модулями и установки сторонних модулей AzerothCore в виде DLL." + : "Standalone preview for official module management and dynamic third-party DLL plugin installation."} +

+
+ + {/* Global actions */} +
+ + + +
+
+ + {/* Notification Banner */} + {notification && ( +
+ ✓ {notification} + +
+ )} + + {/* Error Banner */} + {error && ( +
+ ⚠ {error.technical || (error.human ? human(error.human).message : "Unknown error")} + +
+ )} + + {/* Toolchain Health Status Bar */} + {toolchain && ( +
+
+ {toolchain.msvc_available ? ( + + ) : ( + + )} + + MSVC (vcvars64): {toolchain.msvc_available ? "Ready" : "Missing"} + +
+
+ {toolchain.cmake_available ? ( + + ) : ( + + )} + + CMake: {toolchain.cmake_available ? "Ready" : "Missing"} + +
+
+ {toolchain.ninja_available ? ( + + ) : ( + + )} + + Ninja: {toolchain.ninja_available ? "Ready" : "Missing"} + +
+
+ {toolchain.sdk_available ? ( + + ) : ( + + )} + + Plugin SDK v0.3: {toolchain.sdk_available ? "Ready" : "Missing"} + +
+
+ )} + + {/* GitHub URL Intake Bar on General Modules Screen */} + +
+
+ + setGithubUrl(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && githubUrl.trim()) { + void runAnalysis(); + } + }} + placeholder={ + locale === "ru" + ? "Укажите ссылку на GitHub-репозиторий модуля (например, https://github.com/azerothcore/mod-npc-buffer)..." + : "Enter GitHub repository URL (e.g., https://github.com/azerothcore/mod-npc-buffer)..." + } + className="w-full rounded border border-line bg-bg pl-9 pr-3 py-1.5 text-xs text-ink placeholder:text-muted/60 focus:border-gold focus:outline-none" + /> +
+ +
+ + + +
+
+ + {/* Compact analysis banner when report is ready */} + {report && ( +
+
+ {report.repository_name} + @{report.commit.substring(0, 8)} + + {report.classification} + + {report.sql_files.length > 0 && ( + + {report.sql_files.length} SQL + + )} +
+ +
+ + + {buildResult?.success && ( + + )} + +
+
+ )} + + {analysisError && ( +
+ ⚠ {analysisError} + +
+ )} +
+ + {/* Tabs Header */} +
+ + + + + + + +
+ + {/* TAB 0: INSTALLED MODULES */} + {activeTab === "installed" && ( +
+
+
+

+ {locale === "ru" + ? "Установленные модули и динамические плагины сервера. Включайте, выключайте и настраивайте параметры каждого модуля." + : "Installed server modules and dynamic DLL plugins. Enable, disable, and configure parameters for each module."} +

+
+ {changed && ( + + {t("mod.restart")} + + )} +
+ +
+ {modules === null && !error && ( +
+ + {t("overview.checking")} +
+ )} + {modules !== null && installedModules.length === 0 && ( + +

+ {locale === "ru" ? "Нет установленных модулей" : "No installed modules"} +

+

+ {locale === "ru" + ? "Выберите модули из Каталога или укажите ссылку на GitHub выше для установки." + : "Choose modules from the Catalog or provide a GitHub URL above to install."} +

+ +
+ )} + {installedModules.map((m, i) => { + const isDynamic = m.component_type === "DYNAMIC_DLL" || (!OFFICIAL_IDS.has(m.id) && (installedPlugins.some((p) => p.id === m.id) || m.id.length === 40)); + const canRemove = m.can_remove ?? isDynamic; + return ( + + +
+ +
+
+

{cleanModuleName(m.name, m.id)}

+ {m.version && ( + {m.version} + )} + + {m.component_type === "DYNAMIC_DLL" && ( + + DLL + + )} + {m.component_type === "CORE_EMBEDDED" && ( + + EMBEDDED + + )} + {m.component_type === "CONTENT_PACK" && ( + + CONTENT + + )} + {m.component_type === "CLIENT_PATCH" && ( + + CLIENT PATCH + + )} +
+

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

+ {m.id === "companions" && ( +

+ {locale === "ru" + ? "Взаимоисключение: не работает одновременно со SQUID's Playerbots." + : "Mutual exclusion: cannot run concurrently with SQUID's Playerbots."} +

+ )} + {(m.id === "playerbots" || m.id === "squid") && ( +

+ {locale === "ru" + ? "Взаимоисключение: отключает CoA Companions при активации." + : "Mutual exclusion: disables CoA Companions upon activation."} +

+ )} +
+ {m.installed && m.switchable && ( + + )} + {m.installed && !m.switchable && m.status !== "soon" && ( + {t("mod.alwaysOn")} + )} +
+ + {toggling === m.id && ( +

+ + {t("mod.switching")} +

+ )} + + {/* Custom Races Client Patch status & actions */} + {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 && 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" && ( + + )} +
+ + {canRemove && ( + + )} +
+ + + {/* Inline settings drawer */} + {selectedModule?.has_settings && + !selectedModule.page && + selectedModuleIndex >= 0 && + Math.floor(selectedModuleIndex / 2) === Math.floor(i / 2) && + (i % 2 === 1 || i === installedModules.length - 1) && ( + +
+

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

+ +
+ setChanged(true)} + onRegisterGuard={setGuard} + /> + {selectedModule.id === "custom-races" && ( + setChanged(true)} + onRegisterGuard={setRacesGuard} + /> + )} +
+ )} + + ); + })} +
+
+ )} + + {/* TAB 1: AZEROTHCORE & COA MODULE CATALOG */} + {activeTab === "catalog" && ( +
+ {/* Top header & offline/refresh bar */} +
+
+

+ + {locale === "ru" ? "Каталог модулей AzerothCore & CoA" : "AzerothCore & CoA Module Catalogue"} +

+

+ {locale === "ru" + ? "Рекомендованные модули Conquest of Azeroth и публичный каталог сообщества AzerothCore (500+ модулей)." + : "Curated Conquest of Azeroth modules alongside the official AzerothCore community catalog (500+ modules)."} +

+
+ +
+ +
+
+ + {/* Offline notice banner */} + {publicCatalog?.is_offline && ( +
+
+ + + {locale === "ru" + ? `Автономный режим: официальный каталог загружен из локального кэша (${formatDate(publicCatalog.cached_at)})` + : `Offline mode: official catalog loaded from local cache (${formatDate(publicCatalog.cached_at)})`} + +
+ +
+ )} + + {/* Catalog error notice */} + {publicError && ( +
+ {publicError} + +
+ )} + + {/* Controls: Filter pills, Search, Sort */} +
+ {/* Filter pills */} +
+ + + + + + +
+ + {/* Search and Sort */} +
+
+ + setCatalogQuery(e.target.value)} + placeholder={ + locale === "ru" + ? "Поиск по каталогу (название, автор, тег)..." + : "Search catalogue (name, author, topic)..." + } + className="w-full rounded-md border border-line bg-bg pl-8 pr-3 py-1.5 text-xs text-ink placeholder:text-muted/60 focus:border-gold focus:outline-none" + /> +
+ + +
+
+ + {/* GROUP A: RECOMMENDED FOR COA (ALWAYS ON TOP) */} + {filteredVerifiedCatalog.length > 0 && ( +
+
+
+ +

+ {locale === "ru" ? "Группа A: Рекомендовано для CoA" : "Group A: Recommended for CoA"} +

+ + {filteredVerifiedCatalog.length} + +
+ + {locale === "ru" ? "Проверенная интеграция и поддержка CoA" : "Verified compatibility with CoA"} + +
+ +
+ {filteredVerifiedCatalog.map((item) => { + const matchedModule = modules?.find( + (m) => m.id === item.id || m.name.toLowerCase() === item.name.toLowerCase() + ); + const isInstalled = Boolean(matchedModule?.installed); + const isEnabled = Boolean(matchedModule?.enabled); + + return ( + +
+
+
+ +
+
+

{item.name}

+ + ★ CoA + +
+ ({item.id}) +

{locale === "ru" ? item.description.ru : item.description.en}

+
+
+
+ + {/* Qualification Badges */} +
+ {item.isOfficial ? ( + + ✓ OFFICIAL_CORE + + ) : item.qualification === "INSTALL_VERIFIED" ? ( + + ✓ INSTALL_VERIFIED + + ) : item.qualification === "LINK_VERIFIED" ? ( + + ✓ LINK_VERIFIED + + ) : ( + + ● BUILT + + )} + + {item.tier} + {item.sqlRequired && ( + SQL + )} +
+ +

+ {locale === "ru" ? item.notes.ru : item.notes.en} +

+
+ +
+ + +
+ + + {isInstalled ? ( +
+ + ✓ {locale === "ru" ? (isEnabled ? "Включен" : "Установлен") : (isEnabled ? "Active" : "Installed")} + + +
+ ) : item.isOfficial ? ( + + ) : ( + + )} +
+
+
+ ); + })} +
+
+ )} + + {/* GROUP B: AZEROTHCORE COMMUNITY MODULES */} +
+
+
+ +

+ {locale === "ru" ? "Группа B: Каталог сообщества AzerothCore" : "Group B: AzerothCore Community Modules"} +

+ + {filteredCommunityCatalog.length} + +
+ + {locale === "ru" ? "Официальный каталог azerothcore.org" : "Official azerothcore.org catalogue"} + +
+ + {publicLoading && !publicCatalog && ( +
+ + {locale === "ru" ? "Загрузка каталога AzerothCore..." : "Loading AzerothCore catalogue..."} +
+ )} + + {filteredCommunityCatalog.length === 0 && !publicLoading && ( +
+ {locale === "ru" ? "Модули сообщества по заданным фильтрам не найдены." : "No community modules match the active filters."} +
+ )} + +
+ {filteredCommunityCatalog.slice(0, communityDisplayLimit).map((item) => { + const status = checkModuleInstalled(item.html_url, item.name); + const isBlocked = item.coa_status === "Blocked"; + const isIncompatible = item.coa_status === "Incompatible"; + + return ( + +
+ {/* Card Header: Icon, Name, Metrics */} +
+
+ +
+

+ {item.name} +

+ {item.id} +

+ {item.description || (locale === "ru" ? "Нет описания репозитория." : "No description provided.")} +

+
+
+
+ + {/* Status and Metric Badges */} +
+ + + + + {item.stars} + + + + + {item.forks} + + + {item.category && ( + + {item.category} + + )} + + {item.license_spdx && ( + + {item.license_spdx} + + )} +
+ + {/* Conflict / Engineering Notes */} + {item.conflict_reason ? ( +
+ + {item.conflict_reason} +
+ ) : item.coa_notes ? ( +
+ {item.coa_notes} +
+ ) : item.topics.length > 0 ? ( +
+ {item.topics.slice(0, 3).map((topic) => ( + + #{topic} + + ))} +
+ ) : null} +
+ + {/* Card Footer: GitHub Link, Details, Action */} +
+ + +
+ + + {status.installed ? ( +
+ + ✓ {locale === "ru" ? (status.enabled ? "Включен" : "Установлен") : (status.enabled ? "Active" : "Installed")} + + +
+ ) : isBlocked ? ( + + ) : ( + + )} +
+
+
+ ); + })} +
+ + {/* Pagination / Load more button */} + {filteredCommunityCatalog.length > communityDisplayLimit && ( +
+ + + {locale === "ru" + ? `Показано ${Math.min(communityDisplayLimit, filteredCommunityCatalog.length)} из ${filteredCommunityCatalog.length}` + : `Showing ${Math.min(communityDisplayLimit, filteredCommunityCatalog.length)} of ${filteredCommunityCatalog.length}`} + +
+ )} +
+ + {/* Details Modal for Verified Modules */} + {selectedCatalogModule && ( +
+ +
+

+ {selectedCatalogModule.name} + ({selectedCatalogModule.id}) +

+ +
+ +
+
+ {locale === "ru" ? "Описание:" : "Description:"} +

+ {locale === "ru" ? selectedCatalogModule.description.ru : selectedCatalogModule.description.en} +

+
+ +
+
+ {locale === "ru" ? "Уровень верификации:" : "Verification Level:"} + {selectedCatalogModule.verificationLevel} +
+
+ {locale === "ru" ? "Уровень архитектуры:" : "Architecture Tier:"} + {selectedCatalogModule.tier} +
+
+ +
+ + {locale === "ru" ? "Инженерные примечания и статус:" : "Engineering Notes & Status:"} + +

+ {locale === "ru" ? selectedCatalogModule.notes.ru : selectedCatalogModule.notes.en} +

+
+
+ +
+ + {selectedCatalogModule.canInstall && ( + + )} +
+
+
+ )} + + {/* Details Modal for Public Community Modules */} + {selectedPublicModule && ( +
+ +
+
+

+ {selectedPublicModule.name} +

+ {selectedPublicModule.id} +
+ +
+ +
+
+ {locale === "ru" ? "Описание:" : "Description:"} +

+ {selectedPublicModule.description || (locale === "ru" ? "Нет описания." : "No description.")} +

+
+ + {/* Metadata grid */} +
+
+ {locale === "ru" ? "Звёзды" : "Stars"} + + + {selectedPublicModule.stars} + +
+ +
+ {locale === "ru" ? "Форки" : "Forks"} + + + {selectedPublicModule.forks} + +
+ +
+ {locale === "ru" ? "Лицензия" : "License"} + + {selectedPublicModule.license_spdx || "—"} + +
+ +
+ {locale === "ru" ? "Обновлён" : "Pushed"} + + {formatDate(selectedPublicModule.pushed_at)} + +
+
+ + {/* Compatibility status */} +
+
+ + {locale === "ru" ? "Совместимость с Conquest of Azeroth:" : "CoA Compatibility Status:"} + + +
+ + {selectedPublicModule.conflict_reason && ( +
+ {locale === "ru" ? "Причина блокировки / конфликта:" : "Conflict / Block Reason:"} +

{selectedPublicModule.conflict_reason}

+
+ )} + + {selectedPublicModule.coa_notes && ( +

+ {selectedPublicModule.coa_notes} +

+ )} +
+ + {/* Topics */} + {selectedPublicModule.topics.length > 0 && ( +
+ {locale === "ru" ? "Темы (Topics):" : "Topics:"} +
+ {selectedPublicModule.topics.map((t) => ( + + #{t} + + ))} +
+
+ )} +
+ +
+ + +
+ + + {selectedPublicModule.coa_status !== "Blocked" && ( + + )} +
+
+
+
+ )} +
+ )} + + {/* TAB 4: BUILDS & MSVC LOGS */} + {activeTab === "builds" && ( +
+ {/* Build Result Card */} + {buildResult && ( + +
+
+ {buildResult.success ? ( + + ) : ( + + )} +
+

+ {buildResult.display_name || buildResult.module_name} ({buildResult.duration_seconds.toFixed(1)}s) +

+

+ {buildResult.success + ? `DLL Qualified: ${buildResult.dll_sha256?.substring(0, 24)}... (x64 /MD)` + : `Build failed with ${buildResult.errors.length} diagnostic error(s)`} +

+
+
+ + {buildResult.success && ( + + )} +
+ + {/* Error diagnostics */} + {buildResult.errors.length > 0 && ( +
+
MSVC Compiler / Linker Errors:
+
    + {buildResult.errors.map((err, i) => ( +
  • +
    + [{err.error_code}] {err.file}:{err.line} - {err.message} +
    + {err.actionable_resolution && ( +
    + ➜ {err.actionable_resolution} +
    + )} +
  • + ))} +
+
+ )} +
+ )} + + {/* Real-time Terminal Output */} +
+
+ + + MSVC / CMake Build Output + + {buildLogs.length} lines +
+
+              {buildLogs.length === 0
+                ? "No build logs recorded yet. Start a build from the 'GitHub' tab."
+                : buildLogs.join("\n")}
+            
+
+
+ )} + + {/* TAB 5: TOOLCHAIN & ENVIRONMENT */} + {activeTab === "toolchain" && toolchain && ( + +

+ {locale === "ru" ? "Среда компиляции и Plugin SDK" : "Compilation Environment & Plugin SDK"} +

+

+ {locale === "ru" + ? "Controlled Build Engine использует изолированные рецепты сборки, MSVC x64 и заголовки SDK v0.3. Исходные CMakeLists.txt модулей не исполняются." + : "Controlled Build Engine uses isolated build recipes, MSVC x64 compiler, and SDK v0.3 headers. Upstream CMakeLists.txt is never executed."} +

+ +
+
+ MSVC Toolchain (vcvars64.bat) + {toolchain.vcvars64_path || "NOT FOUND"} +
+
+ CMake Executable + {toolchain.cmake_path || "NOT FOUND"} +
+
+ Ninja Build Driver + {toolchain.ninja_path || "NOT FOUND"} +
+
+ CoA Plugin SDK Directory + {toolchain.sdk_dir || "NOT FOUND"} +
+
+ Host SDK ABI Fingerprint + {toolchain.sdk_abi_fingerprint || "UNKNOWN"} +
+
+
+ )} + + {/* SQL Review & Confirmation Dialog Modal */} + {showSqlDialog && ( +
+ +
+ +

+ {locale === "ru" ? "Проверка SQL-миграций" : "SQL Migrations Review"} +

+
+

+ {locale === "ru" + ? "Этот модуль содержит SQL-файлы данных или структуры. MySQL DDL не поддерживает откат через обычные транзакции." + : "This module contains SQL structure or data files. MySQL DDL does not support rollback via standard transactions."} +

+ + {report && ( +
+
+ + {locale === "ru" ? "Файлы миграций:" : "Migration Files:"} + +
    + {report.sql_files.map((s, idx) => ( +
  • + • {s.file_path} ({s.statement_count} statements) +
  • + ))} +
+
+ +
+ + + {locale === "ru" + ? "Миграции будут применены к тестовой БД реалма. Удаление плагина сохранит таблицы нетронутыми." + : "Migrations will be applied to the realm test DB. Removing the plugin will preserve tables."} + +
+
+ )} + +
+ + +
+
+
+ )} +
+ ); +} + +/** Settings sub-component for official modules */ +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 ? human(error.human).message : error.technical} +

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