feat(i18n): add Localizer with fallback chain and change event

This commit is contained in:
mika kuns
2026-06-03 11:38:49 +02:00
parent a83a0c41e8
commit d22b50e171
3 changed files with 126 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
namespace ClaudeDo.Localization;
public readonly record struct LanguageOption(string Code, string Name);
public interface ILocalizer
{
string this[string key] { get; }
string Get(string key, params object[] args);
string CurrentCode { get; }
IReadOnlyList<LanguageOption> AvailableLanguages { get; }
void SetLanguage(string code);
event EventHandler? LanguageChanged;
}

View File

@@ -0,0 +1,55 @@
namespace ClaudeDo.Localization;
public sealed class Localizer : ILocalizer
{
private readonly LocaleStore _store;
private readonly string _fallbackCode;
private LocaleFile? _active;
private LocaleFile? _fallback;
public Localizer(LocaleStore store, string code, string fallbackCode = "en")
{
_store = store;
_fallbackCode = fallbackCode;
_store.TryGet(fallbackCode, out _fallback);
SetLanguage(code);
}
public string CurrentCode { get; private set; } = "";
public IReadOnlyList<LanguageOption> AvailableLanguages =>
_store.Available.Select(f => new LanguageOption(f.Code, f.Name)).ToList();
public event EventHandler? LanguageChanged;
public string this[string key]
{
get
{
if (_active is not null && _active.Strings.TryGetValue(key, out var v)) return v;
if (_fallback is not null && _fallback.Strings.TryGetValue(key, out var fv)) return fv;
return key;
}
}
public string Get(string key, params object[] args)
{
var fmt = this[key];
return args.Length == 0 ? fmt : string.Format(fmt, args);
}
public void SetLanguage(string code)
{
if (_store.TryGet(code, out var f) && f is not null)
{
_active = f;
CurrentCode = f.Code;
}
else
{
_active = _fallback;
CurrentCode = _fallback?.Code ?? code;
}
LanguageChanged?.Invoke(this, EventArgs.Empty);
}
}