From 831a47f1d33c4faa24f3f9cf2bcf1b21da41774f Mon Sep 17 00:00:00 2001 From: Virgil Date: Fri, 3 Apr 2026 23:35:13 +0000 Subject: [PATCH] feat(html): add context locale setters Co-Authored-By: Virgil --- context.go | 28 ++++++++++++++++++++++++++++ context_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/context.go b/context.go index b797579..8cb262a 100644 --- a/context.go +++ b/context.go @@ -87,3 +87,31 @@ func NewContextWithService(svc Translator, locale ...string) *Context { applyLocaleToService(ctx.service, ctx.Locale) return ctx } + +// SetService swaps the translator used by the context and reapplies the +// current locale to it. +// Example: ctx.SetService(svc). +func (ctx *Context) SetService(svc Translator) *Context { + if ctx == nil { + return nil + } + + ensureContextDefaults(ctx) + ctx.service = svc + applyLocaleToService(ctx.service, ctx.Locale) + return ctx +} + +// SetLocale updates the context locale and reapplies it to the active +// translator. +// Example: ctx.SetLocale("en-US"). +func (ctx *Context) SetLocale(locale string) *Context { + if ctx == nil { + return nil + } + + ensureContextDefaults(ctx) + ctx.Locale = locale + applyLocaleToService(ctx.service, ctx.Locale) + return ctx +} diff --git a/context_test.go b/context_test.go index ba64800..b86d1a3 100644 --- a/context_test.go +++ b/context_test.go @@ -62,6 +62,51 @@ func TestContext_NewContextWithService_UsesLocale(t *testing.T) { } } +func TestContext_SetLocale_ReappliesToTranslator(t *testing.T) { + svc := &localeTranslator{} + ctx := NewContextWithService(svc, "en-GB") + + ctx.SetLocale("fr-FR") + + if ctx.Locale != "fr-FR" { + t.Fatalf("SetLocale should update context locale, got %q", ctx.Locale) + } + if svc.language != "fr" { + t.Fatalf("SetLocale should reapply locale to translator, got %q", svc.language) + } + if got := Text("prompt.yes").Render(ctx); got != "o" { + t.Fatalf("SetLocale translation = %q, want %q", got, "o") + } +} + +func TestContext_SetService_ReappliesCurrentLocale(t *testing.T) { + ctx := NewContext("fr-FR") + svc := &localeTranslator{} + + ctx.SetService(svc) + + if ctx.service != svc { + t.Fatalf("SetService should replace the active translator") + } + if svc.language != "fr" { + t.Fatalf("SetService should apply the existing locale to the new translator, got %q", svc.language) + } + if got := Text("prompt.yes").Render(ctx); got != "o" { + t.Fatalf("SetService translation = %q, want %q", got, "o") + } +} + +func TestContext_Setters_NilReceiver(t *testing.T) { + var ctx *Context + + if got := ctx.SetLocale("en-GB"); got != nil { + t.Fatalf("nil Context.SetLocale should return nil, got %v", got) + } + if got := ctx.SetService(&localeTranslator{}); got != nil { + t.Fatalf("nil Context.SetService should return nil, got %v", got) + } +} + func TestText_RenderFallsBackToDefaultTranslator(t *testing.T) { svc, _ := i18n.New() i18n.SetDefault(svc)