feat(i18n): add Localizer with fallback chain and change event
This commit is contained in:
13
src/ClaudeDo.Localization/ILocalizer.cs
Normal file
13
src/ClaudeDo.Localization/ILocalizer.cs
Normal 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;
|
||||
}
|
||||
55
src/ClaudeDo.Localization/Localizer.cs
Normal file
55
src/ClaudeDo.Localization/Localizer.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user