From 89be57b4e489c2614b08c59190fede1ecdea36ab Mon Sep 17 00:00:00 2001 From: Corfirean Date: Fri, 2 Oct 2026 16:33:00 +0500 Subject: [PATCH] feat(ui): one search, tabs and save bar on the Server page; no module legend The collection switches and every other documented setting become tabs of the same panel, are searched together with the curated settings and are saved by the same bar. The Modules page drops the status legend; Playerbots is named SQUID's Playerbots. Co-Authored-By: Claude Sonnet 5.5 --- modules/catalog.json | 2 +- src/dev/mock.ts | 15 +- src/i18n/locales/de.ts | 4 + src/i18n/locales/en.ts | 4 + src/i18n/locales/es.ts | 4 + src/i18n/locales/fr.ts | 4 + src/i18n/locales/ru.ts | 4 + src/screens/AllSettingsCard.tsx | 149 ------------------- src/screens/CollectionsCard.tsx | 83 ----------- src/screens/ExtraRows.tsx | 110 ++++++++++++++ src/screens/ModulesPage.tsx | 9 -- src/screens/SettingsPage.tsx | 252 +++++++++++++++++++++++--------- 12 files changed, 324 insertions(+), 316 deletions(-) delete mode 100644 src/screens/AllSettingsCard.tsx delete mode 100644 src/screens/CollectionsCard.tsx create mode 100644 src/screens/ExtraRows.tsx diff --git a/modules/catalog.json b/modules/catalog.json index 4bf3e09..810a4a4 100644 --- a/modules/catalog.json +++ b/modules/catalog.json @@ -102,7 +102,7 @@ }, { "id": "playerbots", - "name": "Playerbots", + "name": "SQUID's Playerbots", "description": { "en": "An alternative bot system with random bots and full AI.", "ru": "Альтернативная система ботов со случайными ботами и полным ИИ.", diff --git a/src/dev/mock.ts b/src/dev/mock.ts index f85cab2..addeee6 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -55,12 +55,21 @@ export {}; if(cmd==="realmlist_save"){const w=window as any;const rl=w.__rl;if(args.profileId){const p=rl.profiles.find((x: any)=>x.id===args.profileId);p.name=args.name;p.data=args.data;return p;}if(rl.profiles.some((x: any)=>x.name.toLowerCase()===String(args.name).toLowerCase()))throw {human:{code:"unknown",title:"",message:"",actions:[]},technical:"A realmlist with that name already exists."};const p={id:String(args.name).toLowerCase().replace(/[^a-z0-9]+/g,"-"),name:args.name,data:(/\s/.test(args.data.trim())?args.data.trim():"set realmlist "+args.data.trim())+"\r\n"};rl.profiles.push(p);return p;} if(cmd==="realmlist_delete"){const rl=(window as any).__rl;rl.profiles=rl.profiles.filter((x: any)=>x.id!==args.profileId);return null;} if(cmd==="account_delete") return null; - if(cmd==="modules_list") return [{id:"companions",name:"CoA Companions",description:{en:"Companion bots for groups, dungeons and your guild.",ru:"Боты-компаньоны для групп, подземелий и гильдии."},repo:"https://github.com/Corfirean/mod-coa-playerbots",installed:true,enabled:modState["companions"],switchable:true,status:"beta",icon:"bot",page:"bots"},{id:"content-scaling",name:"Content Scaling",description:{en:"Scales dungeons and raids to your group, with solo modes.",ru:"Подстраивает подземелья и рейды под вашу группу, есть соло-режимы."},repo:"https://github.com/Corfirean/mod-coa-content-scaling",installed:true,enabled:modState["content-scaling"],switchable:true,status:"early",icon:"scaling",page:null},{id:"tbc-content",name:"TBC Content",description:{en:"Outland dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Запределья, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-tbc-content",installed:true,enabled:modState["tbc-content"],switchable:true,status:"early",icon:"tbc",page:null},{id:"wotlk-content",name:"WotLK Content",description:{en:"Northrend dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Нордскола, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-wotlk-content",installed:true,enabled:modState["wotlk-content"],switchable:true,status:"early",icon:"wotlk",page:null},{id:"ah-bot",name:"Auction House Bot",description:{en:"Fills the auction house with realistic, adjustable listings.",ru:"Наполняет аукцион реалистичными настраиваемыми лотами."},repo:"https://github.com/NathanHandley/mod-ah-bot-plus",installed:false,enabled:false,switchable:false,status:"soon",icon:"gavel",page:null,hidden:false},{id:"npc-enchanter",name:"NPC Enchanter",description:{en:"An NPC that enchants your gear for you.",ru:"НПС, который зачаровывает ваше снаряжение."},repo:"https://github.com/azerothcore/mod-npc-enchanter",installed:true,enabled:modState["npc-enchanter"],switchable:true,status:"early",icon:"sparkles",page:null,hidden:false},{id:"playerbots",name:"Playerbots",description:{en:"An alternative bot system with random bots and full AI.",ru:"Альтернативная система ботов со случайными ботами и полным ИИ."},repo:"https://github.com/Zyth45/mod-playerbots",installed:false,enabled:false,switchable:false,status:"soon",icon:"swords",page:null,hidden:false},{id:"client-compat",name:"Client compatibility",description:{en:"Client-server link and appearance unlocks.",ru:"Связь клиента с сервером и разблокировка внешних видов."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa",installed:true,enabled:modState["client-compat"],switchable:false,status:"release",icon:"plug",page:null,hidden:true}]; + if(cmd==="modules_list") return [{id:"companions",name:"CoA Companions",description:{en:"Companion bots for groups, dungeons and your guild.",ru:"Боты-компаньоны для групп, подземелий и гильдии."},repo:"https://github.com/Corfirean/mod-coa-playerbots",installed:true,enabled:modState["companions"],switchable:true,status:"beta",icon:"bot",page:"bots"},{id:"content-scaling",name:"Content Scaling",description:{en:"Scales dungeons and raids to your group, with solo modes.",ru:"Подстраивает подземелья и рейды под вашу группу, есть соло-режимы."},repo:"https://github.com/Corfirean/mod-coa-content-scaling",installed:true,enabled:modState["content-scaling"],switchable:true,status:"early",icon:"scaling",page:null},{id:"tbc-content",name:"TBC Content",description:{en:"Outland dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Запределья, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-tbc-content",installed:true,enabled:modState["tbc-content"],switchable:true,status:"early",icon:"tbc",page:null},{id:"wotlk-content",name:"WotLK Content",description:{en:"Northrend dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Нордскола, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-wotlk-content",installed:true,enabled:modState["wotlk-content"],switchable:true,status:"early",icon:"wotlk",page:null},{id:"ah-bot",name:"Auction House Bot",description:{en:"Fills the auction house with realistic, adjustable listings.",ru:"Наполняет аукцион реалистичными настраиваемыми лотами."},repo:"https://github.com/NathanHandley/mod-ah-bot-plus",installed:false,enabled:false,switchable:false,status:"soon",icon:"gavel",page:null,hidden:false},{id:"npc-enchanter",name:"NPC Enchanter",description:{en:"An NPC that enchants your gear for you.",ru:"НПС, который зачаровывает ваше снаряжение."},repo:"https://github.com/azerothcore/mod-npc-enchanter",installed:true,enabled:modState["npc-enchanter"],switchable:true,status:"early",icon:"sparkles",page:null,hidden:false},{id:"playerbots",name:"SQUID's Playerbots",description:{en:"An alternative bot system with random bots and full AI.",ru:"Альтернативная система ботов со случайными ботами и полным ИИ."},repo:"https://github.com/Zyth45/mod-playerbots",installed:false,enabled:false,switchable:false,status:"soon",icon:"swords",page:null,hidden:false},{id:"client-compat",name:"Client compatibility",description:{en:"Client-server link and appearance unlocks.",ru:"Связь клиента с сервером и разблокировка внешних видов."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa",installed:true,enabled:modState["client-compat"],switchable:false,status:"release",icon:"plug",page:null,hidden:true}]; if(cmd==="module_set_enabled"){ modState[args.module]=args.enabled; return null; } - if(cmd==="all_settings") return [{key:"Rate.Drop.Item.Epic",value:"3",default:"1",doc:"Description: Drop rates for money and items based on quality. Default: 1",changed:true},{key:"Instance.ResetTimeHour",value:"4",default:"4",doc:"Description: Hour of the day when the global instance reset occurs. Range: 0-23 Default: 4 - (04:00 AM)",changed:false},{key:"PlayerLimit",value:"1000",default:"1000",doc:"Description: Maximum number of players in the world.",changed:false}]; + if(cmd==="all_settings") return [{key:"Visibility.Distance.Continents",value:"100",default:"90",doc:"Description: Visibility distance on continents. Range: 45-250 Default: 90",changed:true},{key:"Death.SicknessLevel",value:"11",default:"11",doc:"Description: Character level up to which characters get resurrection sickness. Default: 11",changed:false},{key:"Rate.Drop.Item.Epic",value:"3",default:"1",doc:"Description: Drop rates for money and items based on quality. Default: 1",changed:true},{key:"Instance.ResetTimeHour",value:"4",default:"4",doc:"Description: Hour of the day when the global instance reset occurs. Range: 0-23 Default: 4 - (04:00 AM)",changed:false},{key:"PlayerLimit",value:"1000",default:"1000",doc:"Description: Maximum number of players in the world.",changed:false}]; if(cmd==="all_settings_save") return Object.keys(args&&args.changes||{}); if(cmd==="module_settings" && args.module==="client-compat") return [{key:"CoA.UnlockLocalAppearanceCatalog",value:"1",default:"1",doc:""},{key:"CoA.UnlockAllVanity",value:"1",default:"1",doc:""},{key:"CoA.AutoCollectAppearances",value:"0",default:"1",doc:""},{key:"CoA.LearnOwnedCompanions",value:"1",default:"1",doc:""},{key:"CoA.MaxRidingFromStart",value:"1",default:"1",doc:""}]; - if(cmd==="module_settings") return [{key:"WarGames.Enable",value:"1",default:"1",doc:"Turns War Games on."},{key:"WarGames.ChallengeSeconds",value:"60",default:"60",doc:"How long a challenge stays open."}]; + if(cmd==="module_settings"){ + const S:Record={ + "npc-enchanter":[{key:"Enchanter.Enable",value:"1",default:"1",doc:"Enable the module."},{key:"Enchanter.Announce",value:"0",default:"0",doc:"Announce the module when the player logs in."},{key:"Enchanter.CostCopper",value:"0",default:"0",doc:"What one enchantment costs, in copper (10000 = 1 gold). 0 = free."},{key:"Enchanter.MessageTimer",value:"60000",default:"60000",doc:"How often the NPC emotes, in milliseconds."}], + "companions":[{key:"CoaBots.Enable",value:"1",default:"1",doc:"Master switch of the companion bots."},{key:"CoaBots.MaxPerPlayer",value:"4",default:"4",doc:"How many bots one player can have at a time."}], + "content-scaling":[{key:"CoAContentScaling.Enable",value:"1",default:"1",doc:"Scale dungeons and raids to the group."}], + "tbc-content":[{key:"CoATBC.Enable",value:"1",default:"1",doc:"Outland dungeons and raids."}], + "wotlk-content":[{key:"CoAWotLK.Enable",value:"1",default:"1",doc:"Northrend dungeons and raids."}], + }; + return S[args.module]??[]; + } if(cmd==="module_save_settings") return Object.keys(args.changes); if(cmd==="report_context") return {manager_version:"0.3.1",windows:"Windows 11 (build 26200)",install_kind:"new",server_version:"0.261001.10"}; if(cmd==="open_link"){(window as any).__lastLink=args.url;return null;} diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 4d0206f..1868b9e 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -768,6 +768,10 @@ const de: Partial> = { "col.riding.text": "Alle Reitstufen und Kaltwetterflug, schon auf Stufe 1.", "mod.status.soon": "Bald", "mod.hint.soon": "Geplant: noch nicht verfügbar.", + "set.tab.collections": "Sammlungen", + "set.tab.all": "Alle Einstellungen", + "set.searchAll": "Alle Einstellungen nach Name oder Beschreibung durchsuchen…", + "set.search": "Einstellungen durchsuchen…", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 4868c4b..f751a52 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -768,6 +768,10 @@ const en = { "col.riding.text": "All riding ranks and Cold Weather Flying, even at level 1.", "mod.status.soon": "Soon", "mod.hint.soon": "Planned: not available yet.", + "set.tab.collections": "Collections", + "set.tab.all": "All settings", + "set.searchAll": "Search all settings by name or description…", + "set.search": "Search settings…", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 4f8c0ed..14f2668 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -768,6 +768,10 @@ const es: Partial> = { "col.riding.text": "Todos los rangos de equitación y vuelo en clima frío, desde el nivel 1.", "mod.status.soon": "Pronto", "mod.hint.soon": "Previsto: aún no disponible.", + "set.tab.collections": "Colecciones", + "set.tab.all": "Todos los ajustes", + "set.searchAll": "Buscar en todos los ajustes por nombre o descripción…", + "set.search": "Buscar ajustes…", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index dd420f5..56e7830 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -768,6 +768,10 @@ const fr: Partial> = { "col.riding.text": "Tous les rangs de monte et le vol par temps froid, dès le niveau 1.", "mod.status.soon": "Bientôt", "mod.hint.soon": "Prévu : pas encore disponible.", + "set.tab.collections": "Collections", + "set.tab.all": "Tous les réglages", + "set.searchAll": "Rechercher dans tous les réglages par nom ou description…", + "set.search": "Rechercher un réglage…", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 8a723f3..ddc1e21 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -768,6 +768,10 @@ const ru: Partial> = { "col.riding.text": "Все ранги верховой езды и полёт в холодных краях даже на 1 уровне.", "mod.status.soon": "Скоро", "mod.hint.soon": "В планах: пока недоступен.", + "set.tab.collections": "Коллекции", + "set.tab.all": "Все настройки", + "set.searchAll": "Поиск по всем настройкам: название или описание…", + "set.search": "Поиск по настройкам…", }; export default ru; diff --git a/src/screens/AllSettingsCard.tsx b/src/screens/AllSettingsCard.tsx deleted file mode 100644 index de3876f..0000000 --- a/src/screens/AllSettingsCard.tsx +++ /dev/null @@ -1,149 +0,0 @@ -import { useEffect, useMemo, useState } from "react"; -import { ChevronDown, ChevronRight, Loader2, Search } from "lucide-react"; -import { api, asUiError, type AllSetting, type UiError } from "@/lib/api"; -import { Button } from "@/components/ui/button"; -import { Card } from "@/components/ui/card"; -import { useHuman, useT } from "@/i18n"; - -/** How many matches are drawn at once; the rest is reached by searching. */ -const SHOWN = 40; - -/** Every documented setting of the world server, searchable. For people who want more than the curated list above. */ -export function AllSettingsCard({ serverId }: { serverId: string }) { - const t = useT(); - const human = useHuman(); - const [open, setOpen] = useState(false); - const [items, setItems] = useState(null); - const [query, setQuery] = useState(""); - const [onlyChanged, setOnlyChanged] = useState(false); - const [edits, setEdits] = useState>({}); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); - const [note, setNote] = useState(null); - - useEffect(() => { - if (!open || items) return; - void api.allSettings(serverId).then(setItems).catch((e) => setError(asUiError(e))); - }, [open, items, serverId]); - - const matches = useMemo(() => { - const q = query.trim().toLowerCase(); - return (items ?? []).filter((s) => (!onlyChanged || s.changed) && (!q || s.key.toLowerCase().includes(q) || s.doc.toLowerCase().includes(q))); - }, [items, query, onlyChanged]); - - const dirty = Object.keys(edits); - - async function save() { - setBusy(true); - setError(null); - setNote(null); - try { - const done = await api.allSettingsSave(serverId, edits); - setEdits({}); - setItems(await api.allSettings(serverId)); - setNote(done.length ? t("all.saved") : t("set.nothingChanged")); - } catch (e) { - setError(asUiError(e)); - } finally { - setBusy(false); - } - } - - return ( - - -

{t("all.intro")}

- - {open && ( -
- {items === null && !error && } - {items && ( - <> -
- - -
-

{t("all.count", { shown: Math.min(matches.length, SHOWN), total: matches.length })}

- - {matches.length === 0 &&

{t("all.none")}

} -
    - {matches.slice(0, SHOWN).map((s) => { - const value = edits[s.key] ?? s.value; - return ( -
  • -
    - - { - const v = e.target.value; - setEdits((x) => { - const n = { ...x }; - if (v === s.value) delete n[s.key]; - else n[s.key] = v; - return n; - }); - }} - className="selectable w-56 rounded-md border border-line bg-bg px-2.5 py-1.5 text-sm outline-none focus:border-gold" - /> -
    -

    {s.doc}

    - {value !== s.default && ( - - )} -
  • - ); - })} -
- -
- - {dirty.length > 0 && ( - - )} - {note && {note}} -
- - )} - {error &&

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

} -
- )} -
- ); -} diff --git a/src/screens/CollectionsCard.tsx b/src/screens/CollectionsCard.tsx deleted file mode 100644 index cb2f34b..0000000 --- a/src/screens/CollectionsCard.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import { useCallback, useEffect, useState } from "react"; -import { api, asUiError, type ModuleSetting, type UiError } from "@/lib/api"; -import { cn } from "@/lib/utils"; -import { Card } from "@/components/ui/card"; -import { useHuman, useT, type Key } from "@/i18n"; - -/** The collection and convenience switches of the client compatibility part (the same file holds them under either name). */ -const SWITCHES: { name: string; label: Key; text: Key }[] = [ - { name: "UnlockLocalAppearanceCatalog", label: "col.appearances", text: "col.appearances.text" }, - { name: "UnlockAllVanity", label: "col.vanity", text: "col.vanity.text" }, - { name: "AutoCollectAppearances", label: "col.auto", text: "col.auto.text" }, - { name: "LearnOwnedCompanions", label: "col.companions", text: "col.companions.text" }, - { name: "MaxRidingFromStart", label: "col.riding", text: "col.riding.text" }, -]; - -/** Appearances (transmog), vanity and a few solo conveniences: plain switches for what lives in the compatibility file. */ -export function CollectionsCard({ serverId }: { serverId: string }) { - const t = useT(); - const human = useHuman(); - const [items, setItems] = useState(null); - const [error, setError] = useState(null); - const [changed, setChanged] = useState(false); - - const load = useCallback(async () => { - try { - setItems(await api.moduleSettings(serverId, "client-compat")); - } catch { - setItems([]); // an older build without the file: nothing to offer - } - }, [serverId]); - - useEffect(() => { - void load(); - }, [load]); - - const find = (name: string) => items?.find((i) => i.key.endsWith("." + name)); - const shown = SWITCHES.filter((s) => find(s.name)); - if (!items || shown.length === 0) return null; - - async function toggle(name: string) { - const item = find(name); - if (!item) return; - setError(null); - try { - await api.moduleSaveSettings(serverId, "client-compat", { [item.key]: item.value.trim() === "1" ? "0" : "1" }); - setChanged(true); - await load(); - } catch (e) { - setError(asUiError(e)); - } - } - - return ( - -

{t("col.title")}

-

{t("col.intro")}

-
    - {shown.map((s) => { - const on = find(s.name)?.value.trim() === "1"; - return ( -
  • -
    -

    {t(s.label)}

    -

    {t(s.text)}

    -
    - -
  • - ); - })} -
- {changed &&

{t("mod.restart")}

} - {error &&

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

} -
- ); -} diff --git a/src/screens/ExtraRows.tsx b/src/screens/ExtraRows.tsx new file mode 100644 index 0000000..ed96a05 --- /dev/null +++ b/src/screens/ExtraRows.tsx @@ -0,0 +1,110 @@ +import { RotateCcw } from "lucide-react"; +import type { AllSetting, ModuleSetting } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import { useT, type Key } from "@/i18n"; + +/** The collection and convenience switches of the client compatibility part (the same file holds them under either name). */ +const SWITCHES: { name: string; label: Key; text: Key }[] = [ + { name: "UnlockLocalAppearanceCatalog", label: "col.appearances", text: "col.appearances.text" }, + { name: "UnlockAllVanity", label: "col.vanity", text: "col.vanity.text" }, + { name: "AutoCollectAppearances", label: "col.auto", text: "col.auto.text" }, + { name: "LearnOwnedCompanions", label: "col.companions", text: "col.companions.text" }, + { name: "MaxRidingFromStart", label: "col.riding", text: "col.riding.text" }, +]; + +export interface Collection { + item: ModuleSetting; + label: Key; + text: Key; +} + +/** The switches the compatibility file actually has; an older build without the file offers none. */ +export function collectionsOf(items: ModuleSetting[]): Collection[] { + return SWITCHES.flatMap((s) => { + const item = items.find((i) => i.key.endsWith("." + s.name)); + return item ? [{ item, label: s.label, text: s.text }] : []; + }); +} + +const ROW = "grid grid-cols-[1fr_auto] items-start gap-x-6 gap-y-1 py-3.5"; + +/** Appearances (transmog), vanity and a few solo conveniences, in the look of every other setting row. */ +export function CollectionRows(props: { items: Collection[]; edits: Record; onChange: (key: string, value: string | null) => void }) { + const t = useT(); + return ( +
+ {props.items.map(({ item, label, text }) => { + const value = props.edits[item.key] ?? item.value; + const on = value.trim() === "1"; + return ( +
+
+ +

{t(text)}

+
+
+ +
+
+ ); + })} +
+ ); +} + +/** Documented world server settings that have no friendlier control: the name, its explanation, a text box. */ +export function RawRows(props: { items: AllSetting[]; edits: Record; onChange: (key: string, value: string | null) => void }) { + const t = useT(); + return ( +
+ {props.items.map((s) => { + const value = props.edits[s.key] ?? s.value; + const set = (v: string) => props.onChange(s.key, v === s.value ? null : v); + return ( +
+
+ +

{s.doc}

+

{t("set.default", { v: s.default })}

+
+
+ set(e.target.value)} + className="selectable w-56 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" + /> + +
+
+ ); + })} +
+ ); +} diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index ae6934a..937db02 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -104,15 +104,6 @@ export function ModulesPage({ serverId, onChanged }: { serverId: string; onChang

{t("q.modules")}

{t("mod.intro")}

-
- {(["soon", "early", "beta", "release"] as const).map((s) => ( - - - {t(STATUS[s].hint)} - - ))} -
- {changed &&

{t("mod.restart")}

} {error &&

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

} diff --git a/src/screens/SettingsPage.tsx b/src/screens/SettingsPage.tsx index f6222c8..ec2c1eb 100644 --- a/src/screens/SettingsPage.tsx +++ b/src/screens/SettingsPage.tsx @@ -1,10 +1,12 @@ import { useCallback, useEffect, useMemo, useState } from "react"; -import { AlertTriangle, ChevronDown, ChevronRight, RotateCcw } from "lucide-react"; +import { AlertTriangle, ChevronDown, ChevronRight, RotateCcw, Search } from "lucide-react"; import { api, asUiError, + type AllSetting, type FieldError, type JsonValue, + type ModuleSetting, type PresetInfo, type PresetPreview, type SaveReport, @@ -16,8 +18,7 @@ import { import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; -import { AllSettingsCard } from "@/screens/AllSettingsCard"; -import { CollectionsCard } from "@/screens/CollectionsCard"; +import { CollectionRows, RawRows, collectionsOf } from "@/screens/ExtraRows"; import { CompanionsCard } from "@/screens/CompanionsCard"; import { useHuman, useI18n, useSchemaText, useT, type Key } from "@/i18n"; @@ -164,6 +165,14 @@ export function SettingsPage(props: { serverId: string; scope: Scope; title: str const [showAdvanced, setShowAdvanced] = useState(false); const [busy, setBusy] = useState(false); const [running, setRunning] = useState(false); + // Beside the curated settings the server page offers the collection switches and every other documented setting. They are + // searched together and saved with the rest, so the page has one search box, one set of tabs and one save bar. + const [query, setQuery] = useState(""); + const [raw, setRaw] = useState(null); + const [rawEdits, setRawEdits] = useState>({}); + const [onlyChanged, setOnlyChanged] = useState(false); + const [cols, setCols] = useState([]); + const [colEdits, setColEdits] = useState>({}); const load = useCallback(async () => { try { @@ -181,13 +190,40 @@ export function SettingsPage(props: { serverId: string; scope: Scope; title: str useEffect(() => { setView(null); setSaved(null); + setCategory(""); void load(); void api.presets(scope).then(setPresets); void api.status(serverId).then((s) => setRunning(s.observed.world.state === "running")); + setQuery(""); + setRaw(null); + setRawEdits({}); + setColEdits({}); + setCols([]); + if (scope === "server") void api.moduleSettings(serverId, "client-compat").then(setCols).catch(() => setCols([])); }, [load, scope, serverId]); + const needRaw = scope === "server" && (category === "@all" || query.trim() !== ""); + useEffect(() => { + if (needRaw && !raw) void api.allSettings(serverId).then(setRaw).catch(() => setRaw([])); + }, [needRaw, raw, serverId]); + const valueOf = (s: SettingView): JsonValue => (s.key in draft ? draft[s.key] : s.value); const dirtyKeys = useMemo(() => Object.keys(draft).filter((k) => view && draft[k] !== view.settings.find((s) => s.key === k)?.value), [draft, view]); + const editRaw = (key: string, value: string | null) => + setRawEdits((e) => { + const n = { ...e }; + if (value === null) delete n[key]; + else n[key] = value; + return n; + }); + const editCol = (key: string, value: string | null) => + setColEdits((e) => { + const n = { ...e }; + if (value === null) delete n[key]; + else n[key] = value; + return n; + }); + const pending = dirtyKeys.length + Object.keys(rawEdits).length + Object.keys(colEdits).length; if (fatal) { return ( @@ -208,7 +244,34 @@ export function SettingsPage(props: { serverId: string; scope: Scope; title: str const advancedCount = (id: string) => view.settings.filter((s) => s.category === id && s.advanced).length; const basicCount = (id: string) => view.settings.filter((s) => s.category === id && !s.advanced).length; - async function save(changes: Record) { + const SHOWN = 40; // the long list of other settings is drawn in part; searching narrows it + const q = query.trim().toLowerCase(); + const searching = q !== ""; + const hit = (...parts: string[]) => parts.some((x) => x.toLowerCase().includes(q)); + const curatedKeys = new Set(view.settings.map((s) => s.key)); + const collections = collectionsOf(cols); + const curatedHits = searching ? view.settings.filter((s) => hit(s.key, sx.title(s), sx.description(s))) : []; + const collectionHits = searching ? collections.filter((c) => hit(c.item.key, t(c.label), t(c.text))) : []; + const rawHits = (raw ?? []).filter( + (s) => !curatedKeys.has(s.key) && (!onlyChanged || s.changed || s.key in rawEdits) && (!searching || hit(s.key, s.doc)), + ); + const rowOf = (s: SettingView) => ( + setDraft((d) => ({ ...d, [s.key]: v }))} + onReset={() => setDraft((d) => ({ ...d, [s.key]: s.default }))} + /> + ); + const tabs = [ + ...view.categories.filter((c) => basicCount(c.id) + advancedCount(c.id) > 0).map((c) => ({ id: c.id, label: sx.category(scope, c) })), + ...(collections.length ? [{ id: "@collections", label: t("set.tab.collections") }] : []), + ...(scope === "server" ? [{ id: "@all", label: t("set.tab.all") }] : []), + ]; + + async function save(changes: Record): Promise { const local: Record = {}; for (const [k, v] of Object.entries(changes)) { const s = view!.settings.find((x) => x.key === k)!; @@ -216,9 +279,9 @@ export function SettingsPage(props: { serverId: string; scope: Scope; title: str if (m) local[k] = m; } setErrors(local); - if (Object.keys(local).length) return; + if (Object.keys(local).length) return false; const dangerous = Object.keys(changes).filter((k) => view!.settings.find((s) => s.key === k)?.dangerous); - if (dangerous.length && !window.confirm(t("set.confirmCareful", { n: dangerous.length }))) return; + if (dangerous.length && !window.confirm(t("set.confirmCareful", { n: dangerous.length }))) return false; setBusy(true); setSaveErr(null); try { @@ -227,12 +290,42 @@ export function SettingsPage(props: { serverId: string; scope: Scope; title: str setPreview(null); await load(); void api.status(serverId).then((s) => setRunning(s.observed.world.state === "running")); + return true; } catch (e) { const ui = asUiError(e); setSaveErr(ui); const map: Record = {}; (ui.fields ?? ([] as FieldError[])).forEach((f) => (map[f.key] = f.message)); setErrors(map); + return false; + } finally { + setBusy(false); + } + } + + /** The save bar saves all three kinds of edits: the curated settings, the collection switches and the other documented ones. */ + async function saveEverything() { + if (dirtyKeys.length && !(await save(Object.fromEntries(dirtyKeys.map((k) => [k, draft[k]]))))) return; + const extra = [...Object.keys(rawEdits), ...Object.keys(colEdits)]; + if (!extra.length) return; + setBusy(true); + setSaveErr(null); + try { + if (Object.keys(rawEdits).length) { + await api.allSettingsSave(serverId, rawEdits); + setRawEdits({}); + setRaw(await api.allSettings(serverId)); + } + if (Object.keys(colEdits).length) { + await api.moduleSaveSettings(serverId, "client-compat", colEdits); + setColEdits({}); + setCols(await api.moduleSettings(serverId, "client-compat")); + } + const more = extra.map((key) => ({ key, title: key, restart: "world" as const, dangerous: false })); + setSaved((prev) => ({ changed: [...(prev?.changed ?? []), ...more], restart: prev?.restart ?? "world", snapshot: prev?.snapshot ?? null })); + void api.status(serverId).then((st) => setRunning(st.observed.world.state === "running")); + } catch (e) { + setSaveErr(asUiError(e)); } finally { setBusy(false); } @@ -363,83 +456,100 @@ export function SettingsPage(props: { serverId: string; scope: Scope; title: str )} -
- {view.categories - .filter((c) => basicCount(c.id) + advancedCount(c.id) > 0) - .map((c) => ( - + ))} +
+ + +
+ {searching ? ( + <> + {curatedHits.length + collectionHits.length + rawHits.length === 0 &&

{t("all.none")}

} +
{curatedHits.map(rowOf)}
+ {collectionHits.length > 0 && } + + {rawHits.length > SHOWN &&

{t("all.count", { shown: SHOWN, total: rawHits.length })}

} + + ) : category === "@collections" ? ( + <> +

{t("col.intro")}

+ + + ) : category === "@all" ? ( + <> +

{t("all.intro")}

+ + {raw === null ?

{t("set.loading")}

: } + {rawHits.length > SHOWN &&

{t("all.count", { shown: SHOWN, total: rawHits.length })}

} + + ) : ( + <> +
{basic.map(rowOf)}
+ + {advanced.length > 0 && ( +
+ {/* A tab whose settings are all advanced has nothing else to show, so its settings are listed directly. */} + {basic.length > 0 && ( + + )} + {(showAdvanced || basic.length === 0) &&
{advanced.map(rowOf)}
} +
)} - > - {sx.category(scope, c)} - - ))} -
- -
- {basic.map((s) => ( - setDraft((d) => ({ ...d, [s.key]: v }))} - onReset={() => setDraft((d) => ({ ...d, [s.key]: s.default }))} - /> - ))} -
- - {advanced.length > 0 && ( -
- {/* A tab whose settings are all advanced has nothing else to show, so its settings are listed directly. */} - {basic.length > 0 && ( - - )} - {(showAdvanced || basic.length === 0) && ( -
- {advanced.map((s) => ( - setDraft((d) => ({ ...d, [s.key]: v }))} - onReset={() => setDraft((d) => ({ ...d, [s.key]: s.default }))} - /> - ))} -
+ )}
- )} + {view.unknown_keys > 0 && (

{t("set.unknownKept", { n: view.unknown_keys })}

)} - {scope === "server" && } - {scope === "server" && } - - {dirtyKeys.length > 0 && ( + {pending > 0 && (
- {tn("set.unsaved", dirtyKeys.length)} + {tn("set.unsaved", pending)}
- -