From 94444347347eaf14cd6d708e13ae6d347896da14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Thu, 1 Oct 2026 22:54:36 +0500 Subject: [PATCH] Settings: full searchable list of every documented world-server setting (575), edited in place with a snapshot before each save Co-Authored-By: Claude Sonnet 5.5 --- crates/coa-core/src/allsettings.rs | 239 +++++++++++++++++++++++++++++ crates/coa-core/src/lib.rs | 1 + src-tauri/src/lib.rs | 18 +++ src/dev/mock.ts | 2 + src/i18n/locales/de.ts | 11 ++ src/i18n/locales/en.ts | 11 ++ src/i18n/locales/es.ts | 11 ++ src/i18n/locales/fr.ts | 11 ++ src/i18n/locales/ru.ts | 11 ++ src/lib/api.ts | 11 ++ src/screens/AllSettingsCard.tsx | 149 ++++++++++++++++++ src/screens/SettingsPage.tsx | 3 + tools/add_all_keys.py | 79 ++++++++++ 13 files changed, 557 insertions(+) create mode 100644 crates/coa-core/src/allsettings.rs create mode 100644 src/screens/AllSettingsCard.tsx create mode 100644 tools/add_all_keys.py diff --git a/crates/coa-core/src/allsettings.rs b/crates/coa-core/src/allsettings.rs new file mode 100644 index 0000000..4b5ea65 --- /dev/null +++ b/crates/coa-core/src/allsettings.rs @@ -0,0 +1,239 @@ +//! Every setting of the world server's configuration, for people who want more than the curated list: the documented +//! settings come from `worldserver.conf.dist` (the file that ships with the server and explains each one), the current +//! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or +//! the database connection is left out; the Manager owns those. + +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; + +use serde::Serialize; + +use crate::config::parser::ConfFile; +use crate::config::{take_snapshot, targets, Scope}; +use crate::error::{Error, Result}; +use crate::fsx; + +#[derive(Debug, Serialize, PartialEq, Eq)] +pub struct Item { + pub key: String, + /// What the server uses now (the documented default when the file does not mention the setting). + pub value: String, + pub default: String, + pub doc: String, + /// The file sets it to something other than the documented default. + pub changed: bool, +} + +/// Settings the Manager (or the launcher) owns. +fn hidden(key: &str) -> bool { + let k = key.to_ascii_lowercase(); + k.contains("password") + || k.contains("databaseinfo") + || k.ends_with("port") + || k.starts_with("ra.") + || k.starts_with("logger.") + || k.starts_with("appender.") + || k.starts_with("updates.") + || k.starts_with("logindatabase.") + || k.starts_with("worlddatabase.") + || k.starts_with("characterdatabase.") + || ["bindip", "realmid", "datadir", "logsdir", "tempdir", "sourcedirectory", "mysqlexecutable", "cmakecommand", "builddirectory", "pidfile", "vmapdir", "mmapdir"].contains(&k.as_str()) +} + +fn doc_of(block: &[String]) -> String { + let mut parts: Vec = Vec::new(); + for l in block { + let body = l.trim_start_matches('#').trim(); + if body.is_empty() { + continue; + } + // the lines that only name the settings the block describes + let named = l.starts_with("# ") && !l.starts_with("# ") && body.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')); + if named { + continue; + } + parts.push(body.split_whitespace().collect::>().join(" ")); + } + let mut doc = parts.join(" "); + if doc.chars().count() > 900 { + doc = doc.chars().take(900).collect::() + "…"; + } + doc +} + +/// The documented settings of a `.dist` file: (key, default, description), in file order. +fn parse_dist(text: &str) -> Vec<(String, String, String)> { + let mut out = Vec::new(); + let mut block: Vec = Vec::new(); + let mut in_comment = false; + let mut doc = String::new(); + for line in text.lines() { + let t = line.trim(); + if t.starts_with('#') { + if !in_comment { + block.clear(); + in_comment = true; + } + block.push(line.trim_end().to_string()); + continue; + } + if in_comment { + doc = doc_of(&block); + in_comment = false; + } + if t.is_empty() || t.starts_with('[') { + continue; + } + if let Some((k, v)) = t.split_once('=') { + let k = k.trim(); + if !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) { + out.push((k.to_string(), v.trim().to_string(), doc.clone())); + } + } + } + out +} + +fn dist_path(root: &Path) -> std::path::PathBuf { + root.join("Core/configs/worldserver.conf.dist") +} + +pub fn list(root: &Path) -> Result> { + let dist = fs::read_to_string(dist_path(root)).map_err(|_| Error::Invalid("The documented settings file (worldserver.conf.dist) was not found on this server.".into()))?; + let t = targets(root, Scope::Server)?; + let active = ConfFile::parse_bytes(&fs::read(&t.read)?)?; + Ok(parse_dist(&dist) + .into_iter() + .filter(|(k, _, _)| !hidden(k)) + .map(|(key, default, doc)| { + let value = active.get(&key).map(|v| v.trim().to_string()).unwrap_or_else(|| default.clone()); + let changed = value != default; + Item { key, value, default, doc, changed } + }) + .collect()) +} + +/// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys +/// that actually changed; the previous files are snapshotted first (and can be restored from Settings). +pub fn save(root: &Path, meta: &Path, changes: &BTreeMap) -> Result> { + let known: BTreeMap = parse_dist(&fs::read_to_string(dist_path(root)).map_err(|_| Error::Invalid("worldserver.conf.dist was not found on this server.".into()))?) + .into_iter() + .map(|(k, d, _)| (k, d)) + .collect(); + let t = targets(root, Scope::Server)?; + let mut originals: Vec<(std::path::PathBuf, Vec)> = Vec::new(); + let mut confs: Vec = Vec::new(); + for p in &t.writes { + let bytes = fs::read(p)?; + confs.push(ConfFile::parse_bytes(&bytes)?); + originals.push((p.clone(), bytes)); + } + let mut changed = Vec::new(); + for (key, value) in changes { + let value = value.trim(); + if hidden(key) || !known.contains_key(key) { + return Err(Error::Invalid(format!("{key} is not a setting that can be changed here."))); + } + if value.is_empty() || value.len() > 500 || value.chars().any(char::is_control) { + return Err(Error::Invalid(format!("The value of {key} must be one line of text."))); + } + let same = confs.iter().all(|c| match c.get(key) { + Some(v) => v.trim() == value, + None => known[key] == value, + }); + if !same { + changed.push((key.clone(), value.to_string())); + } + } + if changed.is_empty() { + return Ok(Vec::new()); + } + for c in &mut confs { + for (k, v) in &changed { + c.set(k, v, &["Added by CoA Server Manager"]); + } + } + let texts: Vec = confs.iter().map(ConfFile::to_text).collect(); + for text in &texts { + let reread = ConfFile::parse(text); + for (k, v) in &changed { + if reread.get(k).map(str::trim) != Some(v.as_str()) { + return Err(Error::Invalid(format!("internal check failed for {k}"))); + } + } + } + take_snapshot(meta, Scope::Server, &format!("before changing {} setting(s) in the full list", changed.len()), &originals)?; + let mut written = 0; + for (i, (path, _)) in originals.iter().enumerate() { + if let Err(e) = fsx::atomic_write(path, texts[i].as_bytes()) { + for (p, bytes) in originals.iter().take(written) { + let _ = fsx::atomic_write(p, bytes); + } + return Err(e); + } + written += 1; + } + Ok(changed.into_iter().map(|(k, _)| k).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n"; + + fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) { + let (root, meta) = (d.join("srv"), d.join("meta")); + fs::create_dir_all(root.join("Core/configs")).unwrap(); + fs::create_dir_all(root.join("Settings")).unwrap(); + fs::create_dir_all(&meta).unwrap(); + fs::write(root.join("Core/configs/worldserver.conf.dist"), DIST).unwrap(); + let conf = "[worldserver]\r\nRate.Drop.Item.Epic = 3\r\nLoginDatabaseInfo = \"x\"\r\n"; + fs::write(root.join("Settings/worldserver.conf.template"), conf).unwrap(); + fs::write(root.join("Core/configs/worldserver.conf"), conf).unwrap(); + (root, meta) + } + + #[test] + fn the_documentation_of_a_block_is_shared_by_its_settings_and_secrets_are_left_out() { + let d = tempfile::tempdir().unwrap(); + let (root, _) = server(d.path()); + let items = list(&root).unwrap(); + let keys: Vec<&str> = items.iter().map(|i| i.key.as_str()).collect(); + assert_eq!(keys, ["Rate.Drop.Item.Rare", "Rate.Drop.Item.Epic", "Instance.ResetTimeHour"], "the database connection is hidden"); + assert_eq!(items[0].doc, "Description: Drop rates by quality. Default: 1"); + assert_eq!(items[0].doc, items[1].doc); + assert_eq!(items[2].doc, "Description: Hour of the reset. Important: Use 0-23. Default: 4"); + assert!(!items[0].changed && items[0].value == "1", "absent from the file: documented default"); + assert!(items[1].changed && items[1].value == "3"); + } + + #[test] + fn only_documented_visible_settings_with_one_line_values_can_be_saved_and_both_files_change() { + let d = tempfile::tempdir().unwrap(); + let (root, meta) = server(d.path()); + let ok = BTreeMap::from([("Instance.ResetTimeHour".to_string(), "6".to_string())]); + assert_eq!(save(&root, &meta, &ok).unwrap(), ["Instance.ResetTimeHour"]); + for f in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] { + let t = fs::read_to_string(root.join(f)).unwrap(); + assert!(t.contains("Instance.ResetTimeHour = 6") && t.contains("Rate.Drop.Item.Epic = 3"), "{f}: {t}"); + } + assert!(save(&root, &meta, &ok).unwrap().is_empty(), "same value: nothing to do"); + let same_as_default = BTreeMap::from([("Rate.Drop.Item.Rare".to_string(), "1".to_string())]); + assert!(save(&root, &meta, &same_as_default).unwrap().is_empty(), "the default is already in effect"); + for bad in [("LoginDatabaseInfo", "\"evil\""), ("Nope.Key", "1"), ("Rate.Drop.Item.Rare", ""), ("Rate.Drop.Item.Rare", "1\n2")] { + assert!(save(&root, &meta, &BTreeMap::from([(bad.0.to_string(), bad.1.to_string())])).is_err(), "{bad:?}"); + } + } + + #[test] + fn what_belongs_to_the_manager_is_hidden() { + for k in ["LoginDatabaseInfo", "WorldServerPort", "BindIP", "Ra.Enable", "Ra.Password", "Logger.root", "Appender.Console", "DataDir", "Updates.EnableDatabases", "LoginDatabase.WorkerThreads", "InstanceServerPort"] { + assert!(hidden(k), "{k}"); + } + for k in ["Rate.XP.Kill", "PlayerLimit", "SupportEnabled", "Instance.ResetTimeHour", "Warden.Enabled", "CharacterCreating.Disabled"] { + assert!(!hidden(k), "{k}"); + } + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 59a022b..e2bf73a 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -26,6 +26,7 @@ pub mod migrations; pub mod net; pub mod package; pub mod ra; +pub mod allsettings; pub mod modules; pub mod realmlist; pub mod registry; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 7c5acb5..ab0be19 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -535,6 +535,22 @@ async fn module_save_settings(state: State<'_, AppState>, id: String, module: St .await } +#[tauri::command] +async fn all_settings(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || coa_core::allsettings::list(&root)).await +} + +#[tauri::command] +async fn all_settings_save(state: State<'_, AppState>, id: String, changes: BTreeMap) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + coa_core::allsettings::save(&root, &dir, &changes) + }) + .await +} + #[tauri::command] async fn list_accounts(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { let root = path_of(&state, &id)?; @@ -1367,6 +1383,8 @@ pub fn run() { module_set_enabled, module_settings, module_save_settings, + all_settings, + all_settings_save, account_set_password, account_set_access, account_rename, diff --git a/src/dev/mock.ts b/src/dev/mock.ts index e1ff60d..ae1dbae 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -54,6 +54,8 @@ 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==="modules_list") return []; + 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_save") return Object.keys(args&&args.changes||{}); if(cmd==="module_set_enabled"){const m=(window as any).__mods.find((x: any)=>x.id===args.module);m.enabled=args.enabled;return null;} 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_save_settings") return Object.keys(args.changes); diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index f22b818..c85a3c3 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -724,6 +724,17 @@ const de: Partial> = { // Modules page: nothing yet "mod.empty": "Hier ist noch nichts. Optionale Module erscheinen auf dieser Seite, sobald sie hinzugefügt werden.", + // Settings page: the full searchable list + "all.title": "Alle Servereinstellungen", + "all.intro": "Jede dokumentierte Einstellung des Weltservers mit Erklärung. Ändere nur, was du verstehst: Ein falscher Wert kann den Server beschädigen. Die bisherige Konfiguration wird vorher gesichert und kann wiederhergestellt werden.", + "all.search": "Nach Name oder Beschreibung suchen…", + "all.onlyChanged": "Nur geänderte", + "all.count": "{shown} von {total} werden angezeigt. Suche, um die Liste einzugrenzen.", + "all.none": "Keine Einstellungen gefunden.", + "all.changed": "geändert", + "all.useDefault": "Standardwert verwenden ({v})", + "all.save": "{n} Änderung(en) speichern", + "all.saved": "Gespeichert. Starte den Server neu, um die Änderungen zu übernehmen.", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 6f379fc..29cbe8b 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -724,6 +724,17 @@ const en = { // Modules page: nothing yet "mod.empty": "There is nothing here yet. Optional modules will appear on this page as they are added.", + // Settings page: the full searchable list + "all.title": "All server settings", + "all.intro": "Every documented setting of the world server, with its explanation. Change only what you understand: a wrong value can break the server. The previous configuration is saved first and can be restored.", + "all.search": "Search by name or description…", + "all.onlyChanged": "Only changed", + "all.count": "Showing {shown} of {total}. Search to narrow it down.", + "all.none": "No settings match.", + "all.changed": "changed", + "all.useDefault": "Use the default ({v})", + "all.save": "Save {n} change(s)", + "all.saved": "Saved. Restart the server to apply the changes.", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index b2ae3e0..ed940b5 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -724,6 +724,17 @@ const es: Partial> = { // Modules page: nothing yet "mod.empty": "Aquí todavía no hay nada. Los módulos opcionales aparecerán en esta página a medida que se añadan.", + // Settings page: the full searchable list + "all.title": "Todos los ajustes del servidor", + "all.intro": "Cada ajuste documentado del servidor del mundo, con su explicación. Cambia solo lo que entiendas: un valor incorrecto puede romper el servidor. La configuración anterior se guarda antes y se puede restaurar.", + "all.search": "Buscar por nombre o descripción…", + "all.onlyChanged": "Solo los cambiados", + "all.count": "Mostrando {shown} de {total}. Usa la búsqueda para acotar.", + "all.none": "Ningún ajuste coincide.", + "all.changed": "cambiado", + "all.useDefault": "Usar el valor predeterminado ({v})", + "all.save": "Guardar {n} cambio(s)", + "all.saved": "Guardado. Reinicia el servidor para aplicar los cambios.", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index a712223..91d1812 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -724,6 +724,17 @@ const fr: Partial> = { // Modules page: nothing yet "mod.empty": "Il n’y a encore rien ici. Les modules optionnels apparaîtront sur cette page au fur et à mesure de leur ajout.", + // Settings page: the full searchable list + "all.title": "Tous les réglages du serveur", + "all.intro": "Chaque réglage documenté du serveur de monde, avec son explication. Ne modifiez que ce que vous comprenez : une mauvaise valeur peut casser le serveur. La configuration précédente est sauvegardée d'abord et peut être restaurée.", + "all.search": "Rechercher par nom ou description…", + "all.onlyChanged": "Seulement les modifiés", + "all.count": "{shown} sur {total} affichés. Utilisez la recherche pour affiner.", + "all.none": "Aucun réglage ne correspond.", + "all.changed": "modifié", + "all.useDefault": "Utiliser la valeur par défaut ({v})", + "all.save": "Enregistrer {n} modification(s)", + "all.saved": "Enregistré. Redémarrez le serveur pour appliquer les changements.", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 3e981c9..81e457c 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -724,6 +724,17 @@ const ru: Partial> = { // Modules page: nothing yet "mod.empty": "Здесь пока пусто. Дополнительные модули появятся на этой странице по мере добавления.", + // Settings page: the full searchable list + "all.title": "Все настройки сервера", + "all.intro": "Все документированные настройки мирового сервера с пояснениями. Меняйте только то, что понимаете: неверное значение может сломать сервер. Прежняя конфигурация сохраняется заранее, её можно восстановить.", + "all.search": "Поиск по названию или описанию…", + "all.onlyChanged": "Только изменённые", + "all.count": "Показано {shown} из {total}. Используйте поиск, чтобы сузить список.", + "all.none": "Ничего не найдено.", + "all.changed": "изменено", + "all.useDefault": "Вернуть значение по умолчанию ({v})", + "all.save": "Сохранить изменения: {n}", + "all.saved": "Сохранено. Перезапустите сервер, чтобы изменения вступили в силу.", }; export default ru; diff --git a/src/lib/api.ts b/src/lib/api.ts index a25cda5..92ef6cb 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -190,6 +190,15 @@ export interface ModuleSetting { doc: string; } +export interface AllSetting { + key: string; + value: string; + default: string; + doc: string; + /** the configuration sets it to something other than the documented default */ + changed: boolean; +} + export interface ReportContext { manager_version: string; windows: string; @@ -367,6 +376,8 @@ export const api = { moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke("module_set_enabled", { id, module, enabled }), moduleSettings: (id: string, module: string) => invoke("module_settings", { id, module }), moduleSaveSettings: (id: string, module: string, changes: Record) => invoke("module_save_settings", { id, module, changes }), + allSettings: (id: string) => invoke("all_settings", { id }), + allSettingsSave: (id: string, changes: Record) => invoke("all_settings_save", { id, changes }), reportContext: (id: string) => invoke("report_context", { id }), listAccounts: (id: string) => invoke("list_accounts", { id }), accountSetPassword: (id: string, name: string, password: string) => invoke("account_set_password", { id, name, password }), diff --git a/src/screens/AllSettingsCard.tsx b/src/screens/AllSettingsCard.tsx new file mode 100644 index 0000000..de3876f --- /dev/null +++ b/src/screens/AllSettingsCard.tsx @@ -0,0 +1,149 @@ +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/SettingsPage.tsx b/src/screens/SettingsPage.tsx index 80100ad..dea6032 100644 --- a/src/screens/SettingsPage.tsx +++ b/src/screens/SettingsPage.tsx @@ -16,6 +16,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 { CompanionsCard } from "@/screens/CompanionsCard"; import { useHuman, useI18n, useSchemaText, useT, type Key } from "@/i18n"; @@ -427,6 +428,8 @@ export function SettingsPage(props: { serverId: string; scope: Scope; title: str

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

)} + {scope === "server" && } + {dirtyKeys.length > 0 && (
{tn("set.unsaved", dirtyKeys.length)} diff --git a/tools/add_all_keys.py b/tools/add_all_keys.py new file mode 100644 index 0000000..60c583d --- /dev/null +++ b/tools/add_all_keys.py @@ -0,0 +1,79 @@ +"""One-off: appends the 'all settings' UI strings to every locale file.""" +import os + +ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +K = { + "en": { + "all.title": "All server settings", + "all.intro": "Every documented setting of the world server, with its explanation. Change only what you understand: a wrong value can break the server. The previous configuration is saved first and can be restored.", + "all.search": "Search by name or description…", + "all.onlyChanged": "Only changed", + "all.count": "Showing {shown} of {total}. Search to narrow it down.", + "all.none": "No settings match.", + "all.changed": "changed", + "all.useDefault": "Use the default ({v})", + "all.save": "Save {n} change(s)", + "all.saved": "Saved. Restart the server to apply the changes.", + }, + "ru": { + "all.title": "Все настройки сервера", + "all.intro": "Все документированные настройки мирового сервера с пояснениями. Меняйте только то, что понимаете: неверное значение может сломать сервер. Прежняя конфигурация сохраняется заранее, её можно восстановить.", + "all.search": "Поиск по названию или описанию…", + "all.onlyChanged": "Только изменённые", + "all.count": "Показано {shown} из {total}. Используйте поиск, чтобы сузить список.", + "all.none": "Ничего не найдено.", + "all.changed": "изменено", + "all.useDefault": "Вернуть значение по умолчанию ({v})", + "all.save": "Сохранить изменения: {n}", + "all.saved": "Сохранено. Перезапустите сервер, чтобы изменения вступили в силу.", + }, + "de": { + "all.title": "Alle Servereinstellungen", + "all.intro": "Jede dokumentierte Einstellung des Weltservers mit Erklärung. Ändere nur, was du verstehst: Ein falscher Wert kann den Server beschädigen. Die bisherige Konfiguration wird vorher gesichert und kann wiederhergestellt werden.", + "all.search": "Nach Name oder Beschreibung suchen…", + "all.onlyChanged": "Nur geänderte", + "all.count": "{shown} von {total} werden angezeigt. Suche, um die Liste einzugrenzen.", + "all.none": "Keine Einstellungen gefunden.", + "all.changed": "geändert", + "all.useDefault": "Standardwert verwenden ({v})", + "all.save": "{n} Änderung(en) speichern", + "all.saved": "Gespeichert. Starte den Server neu, um die Änderungen zu übernehmen.", + }, + "fr": { + "all.title": "Tous les réglages du serveur", + "all.intro": "Chaque réglage documenté du serveur de monde, avec son explication. Ne modifiez que ce que vous comprenez : une mauvaise valeur peut casser le serveur. La configuration précédente est sauvegardée d'abord et peut être restaurée.", + "all.search": "Rechercher par nom ou description…", + "all.onlyChanged": "Seulement les modifiés", + "all.count": "{shown} sur {total} affichés. Utilisez la recherche pour affiner.", + "all.none": "Aucun réglage ne correspond.", + "all.changed": "modifié", + "all.useDefault": "Utiliser la valeur par défaut ({v})", + "all.save": "Enregistrer {n} modification(s)", + "all.saved": "Enregistré. Redémarrez le serveur pour appliquer les changements.", + }, + "es": { + "all.title": "Todos los ajustes del servidor", + "all.intro": "Cada ajuste documentado del servidor del mundo, con su explicación. Cambia solo lo que entiendas: un valor incorrecto puede romper el servidor. La configuración anterior se guarda antes y se puede restaurar.", + "all.search": "Buscar por nombre o descripción…", + "all.onlyChanged": "Solo los cambiados", + "all.count": "Mostrando {shown} de {total}. Usa la búsqueda para acotar.", + "all.none": "Ningún ajuste coincide.", + "all.changed": "cambiado", + "all.useDefault": "Usar el valor predeterminado ({v})", + "all.save": "Guardar {n} cambio(s)", + "all.saved": "Guardado. Reinicia el servidor para aplicar los cambios.", + }, +} + +for lang, keys in K.items(): + p = os.path.join(ROOT, "src", "i18n", "locales", lang + ".ts") + s = open(p, encoding="utf-8").read() + if '"all.title"' in s: + continue + lines = s.split("\n") + idx = max(i for i, l in enumerate(lines) if l.startswith("}")) + add = [" // Settings page: the full searchable list"] + for k, v in keys.items(): + add.append(' %s: %s,' % ('"' + k + '"', '"' + v.replace("\\", "\\\\").replace('"', '\\"') + '"')) + lines[idx:idx] = add + open(p, "w", encoding="utf-8", newline="\n").write("\n".join(lines))