From e62aac03cf75c6a0f221bc91b7034539be772390 Mon Sep 17 00:00:00 2001 From: Virgil Date: Thu, 2 Apr 2026 03:07:51 +0000 Subject: [PATCH] feat(i18n): support nested map extras Co-Authored-By: Virgil --- service.go | 26 ++++++++++++++++++++++++++ service_test.go | 22 ++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/service.go b/service.go index 188de6a..d47edd4 100644 --- a/service.go +++ b/service.go @@ -487,6 +487,9 @@ func (s *Service) getEffectiveContextExtra(data any) map[string]any { switch key { case "Context", "Gender", "Location", "Formality": continue + case "Extra", "extra", "Extras", "extras": + mergeContextExtra(extra, value) + continue default: extra[key] = value } @@ -500,6 +503,29 @@ func (s *Service) getEffectiveContextExtra(data any) map[string]any { } } +func mergeContextExtra(dst map[string]any, value any) { + if dst == nil || value == nil { + return + } + switch extra := value.(type) { + case map[string]any: + for key, item := range extra { + dst[key] = item + } + case map[string]string: + for key, item := range extra { + dst[key] = item + } + case *TranslationContext: + if extra == nil || len(extra.Extra) == 0 { + return + } + for key, item := range extra.Extra { + dst[key] = item + } + } +} + func (s *Service) getEffectiveFormality(data any) Formality { if ctx, ok := data.(*TranslationContext); ok && ctx != nil { if ctx.Formality != FormalityNeutral { diff --git a/service_test.go b/service_test.go index 250fd4c..f608281 100644 --- a/service_test.go +++ b/service_test.go @@ -106,6 +106,28 @@ func TestServiceTPluralMessage(t *testing.T) { } } +func TestServiceTMapContextNestedExtra(t *testing.T) { + svc, err := New() + if err != nil { + t.Fatalf("New() failed: %v", err) + } + SetDefault(svc) + + svc.AddMessages("en", map[string]string{ + "welcome._nav._scope._admin": "Admin navigation", + }) + + got := svc.T("welcome", map[string]any{ + "Context": "nav", + "Extra": map[string]any{ + "Scope": "admin", + }, + }) + if got != "Admin navigation" { + t.Fatalf("T(welcome, nested extra) = %q, want %q", got, "Admin navigation") + } +} + func TestServiceRaw(t *testing.T) { svc, err := New() if err != nil { -- 2.45.3