feat(i18n): add english and german message catalogs
Tests fail on catalogs with diverging keys and on message IDs used in code or templates that no catalog defines. Refs #42 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
db44fedc72
commit
7dd1f87ffe
6 files changed
+436
No files matched your search
@@ -0,0 +1,164 @@
|
||||
// Package i18n translates user-facing text. Message catalogs are embedded
|
||||
// JSON files, one per language, keyed by message ID. English is the source
|
||||
// language and the fallback for missing translations.
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
//go:embed locales/*.json
|
||||
var locales embed.FS
|
||||
|
||||
// Catalog holds all translations and picks the best supported language for
|
||||
// a list of preferences.
|
||||
type Catalog struct {
|
||||
bundle *goi18n.Bundle
|
||||
tags []language.Tag
|
||||
matcher language.Matcher
|
||||
}
|
||||
|
||||
// Load parses the embedded catalogs. English is always listed first so the
|
||||
// matcher falls back to it.
|
||||
func Load() (*Catalog, error) {
|
||||
b := goi18n.NewBundle(language.English)
|
||||
b.RegisterUnmarshalFunc("json", json.Unmarshal)
|
||||
files, err := fs.Glob(locales, "locales/*.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tags := []language.Tag{language.English}
|
||||
for _, f := range files {
|
||||
data, err := locales.ReadFile(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mf, err := b.ParseMessageFileBytes(data, path.Base(f))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("i18n: parse %s: %w", f, err)
|
||||
}
|
||||
if mf.Tag != language.English {
|
||||
tags = append(tags, mf.Tag)
|
||||
}
|
||||
}
|
||||
return &Catalog{bundle: b, tags: tags, matcher: language.NewMatcher(tags)}, nil
|
||||
}
|
||||
|
||||
// Supported returns the base language codes, e.g. "en" and "de".
|
||||
func (c *Catalog) Supported() []string {
|
||||
out := make([]string, len(c.tags))
|
||||
for i, t := range c.tags {
|
||||
out[i] = t.String()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// IsSupported reports whether code names one of the catalog languages exactly.
|
||||
func (c *Catalog) IsSupported(code string) bool {
|
||||
for _, t := range c.tags {
|
||||
if t.String() == code {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Match picks a language from preferences in priority order. Each entry may
|
||||
// be a single code or an Accept-Language header value; empty entries are
|
||||
// skipped.
|
||||
func (c *Catalog) Match(prefs ...string) *Localizer {
|
||||
for _, p := range prefs {
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
tags, _, err := language.ParseAcceptLanguage(p)
|
||||
if err != nil || len(tags) == 0 {
|
||||
continue
|
||||
}
|
||||
if _, idx, conf := c.matcher.Match(tags...); conf > language.No {
|
||||
return c.localizer(c.tags[idx])
|
||||
}
|
||||
}
|
||||
return c.localizer(language.English)
|
||||
}
|
||||
|
||||
func (c *Catalog) localizer(t language.Tag) *Localizer {
|
||||
return &Localizer{lang: t.String(), l: goi18n.NewLocalizer(c.bundle, t.String())}
|
||||
}
|
||||
|
||||
// Localizer translates into one language.
|
||||
type Localizer struct {
|
||||
lang string
|
||||
l *goi18n.Localizer
|
||||
}
|
||||
|
||||
// Lang returns the language code, suitable for <html lang>.
|
||||
func (l *Localizer) Lang() string { return l.lang }
|
||||
|
||||
// T translates id. data fills template placeholders such as {{.Min}}; an
|
||||
// integer "Count" entry also selects the plural form. A missing ID is
|
||||
// returned unchanged so it stands out instead of rendering empty text.
|
||||
func (l *Localizer) T(id string, data map[string]any) string {
|
||||
cfg := &goi18n.LocalizeConfig{MessageID: id, TemplateData: data}
|
||||
if n, ok := data["Count"].(int); ok {
|
||||
cfg.PluralCount = n
|
||||
}
|
||||
s, err := l.l.Localize(cfg)
|
||||
if err != nil && s == "" {
|
||||
return id
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// NewContext returns ctx carrying l.
|
||||
func NewContext(ctx context.Context, l *Localizer) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, l)
|
||||
}
|
||||
|
||||
// FromContext returns the localizer in ctx, or nil.
|
||||
func FromContext(ctx context.Context) *Localizer {
|
||||
l, _ := ctx.Value(ctxKey{}).(*Localizer)
|
||||
return l
|
||||
}
|
||||
|
||||
// T translates id with the localizer in ctx. It is the entry point for
|
||||
// templates, which always have ctx in scope.
|
||||
func T(ctx context.Context, id string, kv ...any) string {
|
||||
l := FromContext(ctx)
|
||||
if l == nil {
|
||||
return id
|
||||
}
|
||||
return l.T(id, pairs(kv))
|
||||
}
|
||||
|
||||
// Lang returns the language of the localizer in ctx, defaulting to "en".
|
||||
func Lang(ctx context.Context) string {
|
||||
if l := FromContext(ctx); l != nil {
|
||||
return l.Lang()
|
||||
}
|
||||
return "en"
|
||||
}
|
||||
|
||||
func pairs(kv []any) map[string]any {
|
||||
if len(kv) == 0 {
|
||||
return nil
|
||||
}
|
||||
m := make(map[string]any, len(kv)/2)
|
||||
for i := 0; i+1 < len(kv); i += 2 {
|
||||
if k, ok := kv[i].(string); ok {
|
||||
m[strings.TrimSpace(k)] = kv[i+1]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
Reference in new issue
Block a user