From 2fdf7fc85e9f2587e9393cc74e38fe9c181aae12 Mon Sep 17 00:00:00 2001 From: Usevalad Buben Date: Wed, 28 Oct 2026 10:42:20 +0300 Subject: [PATCH 1/2] Add variable dropdown and Add All to the Smart Parameter Types editor A property drawer for SmartParameterTypes lists the variables the entry uses in any locale. Row names are a dropdown labelled with formatters and locales, Add Parameter adds one variable, and Add All Parameters adds every variable without a row with its inferred type. Rows that generation would warn about show a warning icon with the reason. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 + README.md | 5 +- Unity-Package/Assets/root/CHANGELOG.md | 9 + .../root/Editor/SmartParameterMapping.cs | 6 +- .../root/Editor/SmartParameterTypesDrawer.cs | 300 ++++++++++++++++++ .../Editor/SmartParameterTypesDrawer.cs.meta | 11 + .../root/Editor/SmartVariableCatalog.cs | 216 +++++++++++++ .../root/Editor/SmartVariableCatalog.cs.meta | 11 + Unity-Package/Assets/root/README.md | 5 +- .../Tests/Editor/SmartVariableCatalogTests.cs | 109 +++++++ .../Editor/SmartVariableCatalogTests.cs.meta | 11 + 11 files changed, 687 insertions(+), 5 deletions(-) create mode 100644 Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs create mode 100644 Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs.meta create mode 100644 Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs create mode 100644 Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs.meta create mode 100644 Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs create mode 100644 Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs.meta diff --git a/CHANGELOG.md b/CHANGELOG.md index bec9902..3726588 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [Unreleased] + +### Added +- The **Smart Parameter Types** metadata editor lists the variables an entry uses in any locale: each row's name is + a dropdown labelled with formatters and locales, **Add Parameter** adds one variable, and **Add All Parameters** + adds every variable without a row with its inferred type, so only the types are left to pick. +- Rows that generation would warn about (wrong type for `plural` / `list`, unknown or duplicate names) show a + warning icon with the reason. + ## [1.3.1] - 2026-10-28 ### Added diff --git a/README.md b/README.md index 76c8662..cedb422 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,10 @@ With **Smart Parameter Types = Mapping**, you choose parameter types per entry. 1. Open the collection in **Window > Asset Management > Localization Tables** and open the metadata of the key (shared by all locales). 2. Add **Localization Codegen / Smart Parameter Types**. -3. Add one row per parameter: the variable name as written in the string (`count`, or `0` for `{0}`) and a type. +3. Click **Add All Parameters** to add a row for every variable the entry uses in any locale, pre-filled with the inferred type, then change the types you care about. **Add Parameter** adds a single variable. +4. Each row's name is a dropdown of the entry's variables, labelled with their formatters and locales (`count (plural; en, ru)`). A warning icon marks a row that generation would warn about; hover it for the reason. + +Rows you delete simply fall back to the inferred type. Outside the Table Editor, names can be typed by hand: the variable name as written in the string (`count`, or `0` for `{0}`). ```csharp // "{player} has {count:plural:one coin|{} coins}" with player = String, count = Int diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index bec9902..3726588 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [Unreleased] + +### Added +- The **Smart Parameter Types** metadata editor lists the variables an entry uses in any locale: each row's name is + a dropdown labelled with formatters and locales, **Add Parameter** adds one variable, and **Add All Parameters** + adds every variable without a row with its inferred type, so only the types are left to pick. +- Rows that generation would warn about (wrong type for `plural` / `list`, unknown or duplicate names) show a + warning icon with the reason. + ## [1.3.1] - 2026-10-28 ### Added diff --git a/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs b/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs index 1363fad..672405e 100644 --- a/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs +++ b/Unity-Package/Assets/root/Editor/SmartParameterMapping.cs @@ -114,7 +114,7 @@ public static void Apply( } /// Accepts count, 0 and {0}. - static string NormalizeName(string name) + internal static string NormalizeName(string name) { return (name ?? "").Trim().TrimStart('{').TrimEnd('}').Trim(); } @@ -130,11 +130,11 @@ static List FormattersOf(EntryModel entry, SmartParam param) .ToList(); } - static bool IsPlural(string formatter) => + internal static bool IsPlural(string formatter) => string.Equals(formatter, "plural", StringComparison.OrdinalIgnoreCase) || string.Equals(formatter, "p", StringComparison.OrdinalIgnoreCase); - static bool IsList(string formatter) => + internal static bool IsList(string formatter) => string.Equals(formatter, "list", StringComparison.OrdinalIgnoreCase) || string.Equals(formatter, "l", StringComparison.OrdinalIgnoreCase); } diff --git a/Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs b/Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs new file mode 100644 index 0000000..ccb5120 --- /dev/null +++ b/Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs @@ -0,0 +1,300 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace Severnbli.LocalizationCodegen.Editor +{ + /// + /// Editor for : picks names from the variables the entry uses in any locale, + /// adds every variable at once, and shows the warnings generation would report. + /// + [CustomPropertyDrawer(typeof(SmartParameterTypes))] + sealed class SmartParameterTypesDrawer : PropertyDrawer + { + const float TypeWidth = 90f; + const float IconWidth = 18f; + const float RemoveWidth = 22f; + const float Gap = 4f; + + static class Content + { + public static readonly GUIContent AddParameter = new GUIContent("Add Parameter", + "Add a row for one of the variables this entry uses."); + public static readonly GUIContent AddAll = new GUIContent("Add All Parameters", + "Add a row with the inferred type for every variable that has no row yet."); + public static readonly GUIContent Remove = new GUIContent("−", "Remove this row."); + public static readonly GUIContent SelectVariable = new GUIContent("Select variable"); + public static readonly GUIContent Header = new GUIContent("Name / Type", + "Variables without a row keep the inferred type. Applies when Smart Parameter Types is Mapping."); + public const string NoContext = + "Variables can be listed only for a string table entry. Type the variable name (or 0 for {0})."; + public const string NoVariables = + "This entry has no smart string placeholders. Enable Smart on a locale and add placeholders first."; + } + + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + var line = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; + if (!property.isExpanded) + return line; + + var variables = SmartVariableCatalog.ForProperty(property); + var rows = Parameters(property)?.arraySize ?? 0; + var height = line; + if (variables == null || variables.Count == 0) + height += HelpBoxHeight + EditorGUIUtility.standardVerticalSpacing; + if (variables != null) + height += line; + height += line * (rows + 1); + return height; + } + + static float HelpBoxHeight => EditorGUIUtility.singleLineHeight * 2; + + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + var parameters = Parameters(property); + var line = EditorGUIUtility.singleLineHeight; + var step = line + EditorGUIUtility.standardVerticalSpacing; + var rect = new Rect(position.x, position.y, position.width, line); + + property.isExpanded = EditorGUI.Foldout(rect, property.isExpanded, label, true); + if (!property.isExpanded || parameters == null) + return; + + rect.y += step; + var indent = EditorGUI.indentLevel; + EditorGUI.indentLevel++; + rect = EditorGUI.IndentedRect(rect); + // The rows are already indented; fields would indent themselves again. + EditorGUI.indentLevel = 0; + try + { + DrawBody(rect, property, parameters, step); + } + finally + { + EditorGUI.indentLevel = indent; + } + } + + static void DrawBody(Rect rect, SerializedProperty property, SerializedProperty parameters, float step) + { + var variables = SmartVariableCatalog.ForProperty(property); + if (variables == null || variables.Count == 0) + { + var box = new Rect(rect.x, rect.y, rect.width, HelpBoxHeight); + EditorGUI.HelpBox(box, variables == null ? Content.NoContext : Content.NoVariables, MessageType.Info); + rect.y += HelpBoxHeight + EditorGUIUtility.standardVerticalSpacing; + } + + var names = new List(); + for (var i = 0; i < parameters.arraySize; i++) + names.Add(parameters.GetArrayElementAtIndex(i).FindPropertyRelative("m_Name").stringValue); + + if (variables != null) + { + DrawButtons(rect, property, variables, names); + rect.y += step; + } + + EditorGUI.LabelField(rect, Content.Header, EditorStyles.miniBoldLabel); + rect.y += step; + + var seen = new HashSet(StringComparer.Ordinal); + var remove = -1; + for (var i = 0; i < parameters.arraySize; i++) + { + if (DrawRow(rect, property, parameters.GetArrayElementAtIndex(i), i, variables, names, seen)) + remove = i; + rect.y += step; + } + + if (remove >= 0) + { + parameters.DeleteArrayElementAtIndex(remove); + CodegenHooks.MarkDirtyExternal(); + } + } + + /// + /// Where a callback writes. Menu callbacks run after the drawing pass, when the + /// may no longer be valid, so they keep the serialized object and the property path instead. + /// + readonly struct Target + { + public readonly SerializedObject SerializedObject; + public readonly string Path; + + public Target(SerializedProperty property) + { + SerializedObject = property.serializedObject; + Path = property.propertyPath; + } + } + + static SerializedProperty Parameters(SerializedProperty property) => property.FindPropertyRelative("m_Parameters"); + + static void DrawButtons(Rect rect, SerializedProperty property, List variables, List names) + { + var missing = SmartVariableCatalog.Missing(variables, names); + var half = (rect.width - Gap) / 2; + var addRect = new Rect(rect.x, rect.y, half, rect.height); + var allRect = new Rect(rect.x + half + Gap, rect.y, half, rect.height); + + var target = new Target(property); + if (EditorGUI.DropdownButton(addRect, Content.AddParameter, FocusType.Passive)) + { + var menu = new GenericMenu(); + if (missing.Count == 0) + menu.AddDisabledItem(new GUIContent("Every variable has a row")); + foreach (var variable in missing) + { + var add = variable; + menu.AddItem(new GUIContent(add.Label), false, () => AddRows(target, new[] { add })); + } + menu.DropDown(addRect); + } + + using (new EditorGUI.DisabledScope(missing.Count == 0)) + { + // Applied after this pass, like the menu items, so the rows drawn below stay consistent. + if (GUI.Button(allRect, Content.AddAll)) + EditorApplication.delayCall += () => AddRows(target, missing); + } + } + + /// Draws one row and returns true when its remove button was clicked. + static bool DrawRow( + Rect rect, + SerializedProperty property, + SerializedProperty element, + int index, + List variables, + List names, + HashSet seen) + { + var nameProperty = element.FindPropertyRelative("m_Name"); + var typeProperty = element.FindPropertyRelative("m_Type"); + + var nameWidth = rect.width - TypeWidth - IconWidth - RemoveWidth - Gap * 3; + var nameRect = new Rect(rect.x, rect.y, nameWidth, rect.height); + var typeRect = new Rect(nameRect.xMax + Gap, rect.y, TypeWidth, rect.height); + var iconRect = new Rect(typeRect.xMax + Gap, rect.y, IconWidth, rect.height); + var removeRect = new Rect(iconRect.xMax + Gap, rect.y, RemoveWidth, rect.height); + + var name = nameProperty.stringValue; + var variable = variables != null ? SmartVariableCatalog.Find(variables, name) : null; + + if (variables == null) + { + EditorGUI.BeginChangeCheck(); + var typed = EditorGUI.TextField(nameRect, name); + if (EditorGUI.EndChangeCheck()) + { + nameProperty.stringValue = typed; + CodegenHooks.MarkDirtyExternal(); + } + } + else + { + var content = variable != null + ? new GUIContent(variable.Label) + : string.IsNullOrEmpty(name) ? Content.SelectVariable : new GUIContent(name); + if (EditorGUI.DropdownButton(nameRect, content, FocusType.Keyboard)) + ShowNameMenu(nameRect, new Target(property), index, name, variables, names); + } + + EditorGUI.BeginChangeCheck(); + EditorGUI.PropertyField(typeRect, typeProperty, GUIContent.none); + if (EditorGUI.EndChangeCheck()) + CodegenHooks.MarkDirtyExternal(); + + var normalized = SmartParameterMapping.NormalizeName(name); + var duplicate = normalized.Length > 0 && !seen.Add(normalized); + if (variables != null) + { + var problem = SmartVariableCatalog.Problem(name, (SmartParameterType)typeProperty.intValue, variable, duplicate); + if (problem != null) + { + var icon = EditorGUIUtility.IconContent("console.warnicon.sml"); + GUI.Label(iconRect, new GUIContent(icon.image, problem)); + } + } + + return GUI.Button(removeRect, Content.Remove, EditorStyles.miniButton); + } + + static void ShowNameMenu( + Rect rect, + Target target, + int index, + string current, + List variables, + List names) + { + var normalizedCurrent = SmartParameterMapping.NormalizeName(current); + var taken = new HashSet( + names.Where((_, i) => i != index).Select(SmartParameterMapping.NormalizeName), + StringComparer.Ordinal); + + var menu = new GenericMenu(); + foreach (var variable in variables) + { + var content = new GUIContent(variable.Label); + var selected = variable.Name == normalizedCurrent; + if (taken.Contains(variable.Name)) + { + menu.AddDisabledItem(content, selected); + continue; + } + + var pick = variable.Name; + menu.AddItem(content, selected, () => Modify(target, parameters => + { + if (index < parameters.arraySize) + parameters.GetArrayElementAtIndex(index).FindPropertyRelative("m_Name").stringValue = pick; + })); + } + menu.DropDown(rect); + } + + static void AddRows(Target target, IEnumerable variables) + { + var toAdd = variables.ToList(); + Modify(target, parameters => + { + foreach (var variable in toAdd) + { + parameters.InsertArrayElementAtIndex(parameters.arraySize); + var element = parameters.GetArrayElementAtIndex(parameters.arraySize - 1); + element.FindPropertyRelative("m_Name").stringValue = variable.Name; + element.FindPropertyRelative("m_Type").intValue = (int)variable.InferredType; + } + }); + } + + /// + /// Changes the parameter list from a menu or button callback, which can run outside the drawing pass, so the + /// serialized object is updated and applied here (which also records undo). + /// + static void Modify(Target target, Action change) + { + var serializedObject = target.SerializedObject; + if (serializedObject == null || serializedObject.targetObject == null) + return; + + var path = target.Path; + serializedObject.Update(); + var parameters = serializedObject.FindProperty(path)?.FindPropertyRelative("m_Parameters"); + if (parameters == null) + return; + + change(parameters); + serializedObject.ApplyModifiedProperties(); + CodegenHooks.MarkDirtyExternal(); + } + } +} diff --git a/Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs.meta b/Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs.meta new file mode 100644 index 0000000..418de66 --- /dev/null +++ b/Unity-Package/Assets/root/Editor/SmartParameterTypesDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69d863c098214dacb305570ee025cce1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs b/Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs new file mode 100644 index 0000000..210ead3 --- /dev/null +++ b/Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditor.Localization; +using UnityEngine.Localization.Tables; + +namespace Severnbli.LocalizationCodegen.Editor +{ + /// A smart string variable of one entry, gathered from every locale. + internal sealed class SmartVariableInfo + { + /// Name as used in : the source name, or the index of {0}. + public string Name; + + public bool IsPositional; + public int Index; + public readonly SortedSet Locales = new SortedSet(StringComparer.Ordinal); + public readonly SortedSet Formatters = new SortedSet(StringComparer.OrdinalIgnoreCase); + + public bool UsedWithPlural => Formatters.Any(SmartParameterMapping.IsPlural); + public bool UsedWithList => Formatters.Any(SmartParameterMapping.IsList); + + /// The type would generate. + public SmartParameterType InferredType + { + get + { + if (Formatters.Count > 0 && Formatters.All(SmartParameterMapping.IsPlural)) + return SmartParameterType.Int; + if (Formatters.Count > 0 && Formatters.All(SmartParameterMapping.IsList)) + return SmartParameterType.List; + return SmartParameterType.Object; + } + } + + /// Menu label, e.g. count (plural; en, ru). Slashes would create submenus, so they are replaced. + public string Label + { + get + { + var details = new List(); + if (Formatters.Count > 0) + details.Add(string.Join(", ", Formatters)); + details.Add(Locales.Count > 0 ? string.Join(", ", Locales) : "unused"); + var name = IsPositional ? "{" + Name + "}" : Name; + return (name + " (" + string.Join("; ", details) + ")").Replace('/', '∕'); + } + } + } + + /// + /// Lists the variables of a smart string entry the way the generator does, for the + /// editor. + /// + internal static class SmartVariableCatalog + { + static readonly Regex s_EntryIndex = new Regex(@"^m_Entries\.Array\.data\[(\d+)\]", RegexOptions.Compiled); + + /// + /// Collects the variables of the given locale texts: positional ones first (gaps included, since the generated + /// method has a parameter for them), then named ones. Variables of Global Variables Groups are skipped. + /// + public static List Collect( + IEnumerable> localeTexts, + ICollection globalVariableGroups) + { + var positional = new SortedDictionary(); + var named = new SortedDictionary(StringComparer.Ordinal); + + foreach (var pair in localeTexts) + { + var parsed = SmartStringParser.Parse(pair.Value, pair.Key); + if (parsed.Failed) + continue; + + foreach (var usage in parsed.Usages) + { + SmartVariableInfo info; + if (usage.IsPositional) + { + if (!positional.TryGetValue(usage.Index, out info)) + { + info = new SmartVariableInfo { Name = usage.Index.ToString(), IsPositional = true, Index = usage.Index }; + positional.Add(usage.Index, info); + } + } + else + { + if (string.IsNullOrEmpty(usage.SourceName) || + (globalVariableGroups != null && globalVariableGroups.Contains(usage.SourceName))) + continue; + + if (!named.TryGetValue(usage.SourceName, out info)) + { + info = new SmartVariableInfo { Name = usage.SourceName }; + named.Add(usage.SourceName, info); + } + } + + info.Locales.Add(pair.Key); + if (!string.IsNullOrEmpty(usage.FormatterName)) + info.Formatters.Add(usage.FormatterName); + } + } + + var result = new List(); + var maxIndex = positional.Count > 0 ? positional.Keys.Max() : -1; + for (var i = 0; i <= maxIndex; i++) + { + SmartVariableInfo info; + result.Add(positional.TryGetValue(i, out info) + ? info + : new SmartVariableInfo { Name = i.ToString(), IsPositional = true, Index = i }); + } + result.AddRange(named.Values); + return result; + } + + /// Finds a variable by a name as written in . + public static SmartVariableInfo Find(IEnumerable variables, string name) + { + var normalized = SmartParameterMapping.NormalizeName(name); + return variables.FirstOrDefault(v => string.Equals(v.Name, normalized, StringComparison.Ordinal)); + } + + /// Variables without a row yet, in display order. + public static List Missing(IEnumerable variables, IEnumerable existingNames) + { + var existing = new HashSet(existingNames.Select(SmartParameterMapping.NormalizeName), StringComparer.Ordinal); + return variables.Where(v => !existing.Contains(v.Name)).ToList(); + } + + /// + /// Why a row would produce a warning during generation, or . + /// is null when the name matches no variable. + /// + public static string Problem(string name, SmartParameterType type, SmartVariableInfo variable, bool duplicate) + { + if (SmartParameterMapping.NormalizeName(name).Length == 0) + return "Pick a variable."; + if (duplicate) + return "This variable is listed more than once; the first row is used."; + if (variable == null) + return "This entry has no such variable in any locale."; + if (variable.UsedWithPlural && !SmartParameterMapping.AcceptsPlural(type)) + return $"Used with plural, which cannot format {type}. Use a number or List."; + if (variable.UsedWithList && !SmartParameterMapping.AcceptsList(type)) + return $"Used with list, which cannot format {type}. Use List."; + return null; + } + + /// + /// Collects the variables of the shared entry a property belongs to. + /// Returns when the property is not on a string table collection's shared entry. + /// + public static List ForProperty(SerializedProperty property) + { + var sharedData = property.serializedObject.targetObject as SharedTableData; + if (sharedData == null) + return null; + + var match = s_EntryIndex.Match(property.propertyPath); + int index; + if (!match.Success || !int.TryParse(match.Groups[1].Value, out index) || + index < 0 || index >= sharedData.Entries.Count) + return null; + + var collection = LocalizationEditorSettings.GetCollectionForSharedTableData(sharedData) as StringTableCollection; + if (collection == null) + return null; + + var id = sharedData.Entries[index].Id; + var texts = new List>(); + foreach (var table in collection.StringTables) + { + var entry = table != null ? table.GetEntry(id) : null; + if (entry != null && entry.IsSmart && !string.IsNullOrEmpty(entry.Value)) + texts.Add(new KeyValuePair(table.LocaleIdentifier.Code, entry.Value)); + } + + return Collect(texts, GlobalVariableGroups()); + } + + static HashSet s_GlobalVariableGroups; + static double s_GlobalVariableGroupsTime = double.MinValue; + + /// Names of the Global Variables Groups, refreshed at most every few seconds. + static HashSet GlobalVariableGroups() + { + if (s_GlobalVariableGroups != null && EditorApplication.timeSinceStartup - s_GlobalVariableGroupsTime < 5) + return s_GlobalVariableGroups; + + var groups = new HashSet(StringComparer.Ordinal); + try + { + foreach (var guid in AssetDatabase.FindAssets("t:VariablesGroupAsset")) + { + var path = AssetDatabase.GUIDToAssetPath(guid); + if (!string.IsNullOrEmpty(path)) + groups.Add(Path.GetFileNameWithoutExtension(path)); + } + } + catch + { + // Global variables only hide variables from the list. + } + + s_GlobalVariableGroups = groups; + s_GlobalVariableGroupsTime = EditorApplication.timeSinceStartup; + return groups; + } + } +} diff --git a/Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs.meta b/Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs.meta new file mode 100644 index 0000000..8e93de3 --- /dev/null +++ b/Unity-Package/Assets/root/Editor/SmartVariableCatalog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66fdcb6dd4c5401dad7d48013c178659 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index 76c8662..cedb422 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -268,7 +268,10 @@ With **Smart Parameter Types = Mapping**, you choose parameter types per entry. 1. Open the collection in **Window > Asset Management > Localization Tables** and open the metadata of the key (shared by all locales). 2. Add **Localization Codegen / Smart Parameter Types**. -3. Add one row per parameter: the variable name as written in the string (`count`, or `0` for `{0}`) and a type. +3. Click **Add All Parameters** to add a row for every variable the entry uses in any locale, pre-filled with the inferred type, then change the types you care about. **Add Parameter** adds a single variable. +4. Each row's name is a dropdown of the entry's variables, labelled with their formatters and locales (`count (plural; en, ru)`). A warning icon marks a row that generation would warn about; hover it for the reason. + +Rows you delete simply fall back to the inferred type. Outside the Table Editor, names can be typed by hand: the variable name as written in the string (`count`, or `0` for `{0}`). ```csharp // "{player} has {count:plural:one coin|{} coins}" with player = String, count = Int diff --git a/Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs b/Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs new file mode 100644 index 0000000..6c7c93a --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs @@ -0,0 +1,109 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; + +namespace Severnbli.LocalizationCodegen.Editor.Tests +{ + public class SmartVariableCatalogTests + { + static List Collect(params (string Locale, string Text)[] texts) + { + return SmartVariableCatalog.Collect( + texts.Select(t => new KeyValuePair(t.Locale, t.Text)), + new HashSet { "global" }); + } + + [Test] + public void Collect_MergesLocalesAndOrdersPositionalFirst() + { + var variables = Collect( + ("en", "{1}: {player} has {count:plural:one coin|{} coins}"), + ("de", "{player} hat {count:plural:eine Münze|{} Münzen} {bonus}")); + + CollectionAssert.AreEqual(new[] { "0", "1", "bonus", "count", "player" }, variables.Select(v => v.Name)); + + var gap = variables[0]; + Assert.IsTrue(gap.IsPositional); + CollectionAssert.IsEmpty(gap.Locales, "A positional gap is listed, since the method has a parameter for it."); + + CollectionAssert.AreEqual(new[] { "de" }, variables.Single(v => v.Name == "bonus").Locales); + CollectionAssert.AreEqual(new[] { "de", "en" }, variables.Single(v => v.Name == "count").Locales); + } + + [Test] + public void Collect_SkipsGlobalVariables() + { + var variables = Collect(("en", "{global.score} {name}"), ("de", "no placeholders")); + + CollectionAssert.AreEqual(new[] { "name" }, variables.Select(v => v.Name)); + } + + [Test] + public void InferredType_MatchesInferredMode() + { + var variables = Collect( + ("en", "{count:plural:a|b} {items:list:{}|, } {name} {mixed:plural:a|b}"), + ("de", "{mixed:list:{}|, }")); + + Assert.AreEqual(SmartParameterType.Int, variables.Single(v => v.Name == "count").InferredType); + Assert.AreEqual(SmartParameterType.List, variables.Single(v => v.Name == "items").InferredType); + Assert.AreEqual(SmartParameterType.Object, variables.Single(v => v.Name == "name").InferredType); + Assert.AreEqual(SmartParameterType.Object, variables.Single(v => v.Name == "mixed").InferredType); + } + + [Test] + public void Label_ShowsFormattersAndLocales() + { + var variables = Collect(("en", "{0} {count:plural:a|b}"), ("ru", "{count:plural:a|b|c}")); + + Assert.AreEqual("{0} (en)", variables.Single(v => v.Name == "0").Label); + Assert.AreEqual("count (plural; en, ru)", variables.Single(v => v.Name == "count").Label); + } + + [Test] + public void Label_ReplacesSlashes() + { + var variables = Collect(("en", "{0}"), ("pt/BR", "{0}")); + + StringAssert.DoesNotContain("/", variables[0].Label); + } + + [Test] + public void Missing_SkipsNamesThatHaveARow() + { + var variables = Collect(("en", "{0} {count} {player}")); + + var missing = SmartVariableCatalog.Missing(variables, new[] { "{0}", " player " }); + + CollectionAssert.AreEqual(new[] { "count" }, missing.Select(v => v.Name)); + } + + [Test] + public void Find_AcceptsBracedIndex() + { + var variables = Collect(("en", "{0}")); + + Assert.AreSame(variables[0], SmartVariableCatalog.Find(variables, "{0}")); + Assert.IsNull(SmartVariableCatalog.Find(variables, "1")); + } + + [Test] + public void Problem_ReportsWhatGenerationWouldWarnAbout() + { + var variables = Collect(("en", "{count:plural:a|b} {items:list:{}|, } {name}")); + var count = variables.Single(v => v.Name == "count"); + var items = variables.Single(v => v.Name == "items"); + var name = variables.Single(v => v.Name == "name"); + + Assert.IsNull(SmartVariableCatalog.Problem("count", SmartParameterType.Int, count, false)); + Assert.IsNull(SmartVariableCatalog.Problem("items", SmartParameterType.List, items, false)); + Assert.IsNull(SmartVariableCatalog.Problem("name", SmartParameterType.String, name, false)); + + StringAssert.Contains("plural", SmartVariableCatalog.Problem("count", SmartParameterType.String, count, false)); + StringAssert.Contains("list", SmartVariableCatalog.Problem("items", SmartParameterType.Int, items, false)); + StringAssert.Contains("no such variable", SmartVariableCatalog.Problem("score", SmartParameterType.Int, null, false)); + StringAssert.Contains("more than once", SmartVariableCatalog.Problem("name", SmartParameterType.String, name, true)); + StringAssert.Contains("Pick a variable", SmartVariableCatalog.Problem(" ", SmartParameterType.Int, null, false)); + } + } +} diff --git a/Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs.meta b/Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs.meta new file mode 100644 index 0000000..7012854 --- /dev/null +++ b/Unity-Package/Assets/root/Tests/Editor/SmartVariableCatalogTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 835e86fd44364982ab0b9cbcb0d8152b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 2e82ca0137bedf64e0a8e547ad36dd2e42c6731d Mon Sep 17 00:00:00 2001 From: Usevalad Buben Date: Wed, 28 Oct 2026 10:58:24 +0300 Subject: [PATCH 2/2] Bump version to 1.3.2 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../Assets/Editor/Localization Codegen Installer/Installer.cs | 2 +- README.md | 2 +- Unity-Package/Assets/root/CHANGELOG.md | 2 +- Unity-Package/Assets/root/README.md | 2 +- Unity-Package/Assets/root/package.json | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3726588..9b26b28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [Unreleased] +## [1.3.2] - 2026-10-28 ### Added - The **Smart Parameter Types** metadata editor lists the variables an entry uses in any locale: each row's name is diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs index b74a798..1044794 100644 --- a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs +++ b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs @@ -16,7 +16,7 @@ namespace Severnbli.LocalizationCodegen.Installer public static partial class Installer { public const string PackageId = "com.severnbli.localization-codegen"; - public const string Version = "1.3.1"; + public const string Version = "1.3.2"; static Installer() { diff --git a/README.md b/README.md index cedb422..619151d 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.3.1" + "com.severnbli.localization-codegen": "1.3.2" } } ``` diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index 3726588..9b26b28 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [Unreleased] +## [1.3.2] - 2026-10-28 ### Added - The **Smart Parameter Types** metadata editor lists the variables an entry uses in any locale: each row's name is diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index cedb422..619151d 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.3.1" + "com.severnbli.localization-codegen": "1.3.2" } } ``` diff --git a/Unity-Package/Assets/root/package.json b/Unity-Package/Assets/root/package.json index f884520..39dede0 100644 --- a/Unity-Package/Assets/root/package.json +++ b/Unity-Package/Assets/root/package.json @@ -10,7 +10,7 @@ "Generation", "Code Generation" ], - "version": "1.3.1", + "version": "1.3.2", "unity": "2021.3", "description": "C# classes and properties generator from Unity Localization tables", "documentationUrl": "https://github.com/Severnbli/localization-codegen/blob/main/README.md",