diff --git a/go.mod b/go.mod index 6d3d9d8..6efc2e3 100644 --- a/go.mod +++ b/go.mod @@ -44,6 +44,7 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect + github.com/nicksnyder/go-i18n/v2 v2.7.0 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pquerna/otp v1.5.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect diff --git a/go.sum b/go.sum index 22633bb..dc44847 100644 --- a/go.sum +++ b/go.sum @@ -97,6 +97,8 @@ github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0 github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVHwut+J0= +github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go new file mode 100644 index 0000000..2a68e32 --- /dev/null +++ b/internal/i18n/i18n.go @@ -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 . +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 +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go new file mode 100644 index 0000000..614fe8c --- /dev/null +++ b/internal/i18n/i18n_test.go @@ -0,0 +1,155 @@ +package i18n + +import ( + "context" + "encoding/json" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" +) + +func catalogKeys(t *testing.T) map[string]map[string]bool { + t.Helper() + files, err := fs.Glob(locales, "locales/*.json") + if err != nil { + t.Fatal(err) + } + out := map[string]map[string]bool{} + for _, f := range files { + data, err := locales.ReadFile(f) + if err != nil { + t.Fatal(err) + } + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("%s: %v", f, err) + } + keys := map[string]bool{} + for k := range m { + keys[k] = true + } + out[strings.TrimSuffix(filepath.Base(f), ".json")] = keys + } + return out +} + +func TestCatalogsHaveSameKeys(t *testing.T) { + cats := catalogKeys(t) + en := cats["en"] + for lang, keys := range cats { + for k := range en { + if !keys[k] { + t.Errorf("%s.json is missing %q", lang, k) + } + } + for k := range keys { + if !en[k] { + t.Errorf("%s.json has %q which en.json lacks", lang, k) + } + } + } +} + +var usagePatterns = []struct { + re *regexp.Regexp + prefix string +}{ + {regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`), ""}, + {regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), "error."}, + {regexp.MustCompile(`\b(?:pageFor\(c|s\.page\()(?:, )?"([a-z0-9_.]+)"`), ""}, +} + +// TestUsedKeysExist scans the source tree for literal message IDs so a typo +// fails the build instead of showing a raw ID in production. +func TestUsedKeysExist(t *testing.T) { + en := catalogKeys(t)["en"] + var missing []string + err := filepath.WalkDir("..", func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + if !strings.HasSuffix(p, ".go") && !strings.HasSuffix(p, ".templ") { + return nil + } + if strings.HasSuffix(p, "_templ.go") || strings.HasSuffix(p, "_test.go") { + return nil + } + src, err := os.ReadFile(p) + if err != nil { + return err + } + for _, u := range usagePatterns { + for _, m := range u.re.FindAllStringSubmatch(string(src), -1) { + if id := u.prefix + m[1]; !en[id] { + missing = append(missing, p+": "+id) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(missing) + for _, m := range missing { + t.Errorf("unknown message ID %s", m) + } +} + +// The language switcher builds "lang." dynamically. +func TestEveryLanguageHasAName(t *testing.T) { + c, err := Load() + if err != nil { + t.Fatal(err) + } + en := catalogKeys(t)["en"] + for _, l := range c.Supported() { + if !en["lang."+l] { + t.Errorf("en.json is missing %q", "lang."+l) + } + } +} + +func TestMatch(t *testing.T) { + c, err := Load() + if err != nil { + t.Fatal(err) + } + tests := []struct { + prefs []string + want string + }{ + {nil, "en"}, + {[]string{"de"}, "de"}, + {[]string{"", "de-AT,en;q=0.5"}, "de"}, + {[]string{"fr-FR,fr;q=0.9"}, "en"}, + {[]string{"en", "de"}, "en"}, + {[]string{"garbage", "de"}, "de"}, + } + for _, tt := range tests { + if got := c.Match(tt.prefs...).Lang(); got != tt.want { + t.Errorf("Match(%q) = %q, want %q", tt.prefs, got, tt.want) + } + } +} + +func TestT(t *testing.T) { + c, err := Load() + if err != nil { + t.Fatal(err) + } + ctx := NewContext(context.Background(), c.Match("de")) + if got, want := T(ctx, "error.password_too_short", "Min", 12), "Das Passwort braucht mindestens 12 Zeichen."; got != want { + t.Errorf("T(de, password_too_short) = %q, want %q", got, want) + } + if got, want := T(ctx, "no.such.key"), "no.such.key"; got != want { + t.Errorf("T(missing) = %q, want %q", got, want) + } + if got, want := T(context.Background(), "auth.login.title"), "auth.login.title"; got != want { + t.Errorf("T(no localizer) = %q, want %q", got, want) + } +} diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json new file mode 100644 index 0000000..b59be86 --- /dev/null +++ b/internal/i18n/locales/de.json @@ -0,0 +1,57 @@ +{ + "app.network_error": "Verbindung fehlgeschlagen.", + "lang.en": "English", + "lang.de": "Deutsch", + + "auth.login.title": "Anmelden", + "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.", + "auth.login.submit": "Weiter", + "auth.login.no_account": "Noch kein Konto?", + "auth.login.to_signup": "Registrieren", + "auth.signup.title": "Konto anlegen", + "auth.signup.submit": "Anlegen", + "auth.signup.to_login": "Zur Anmeldung", + "auth.field.name": "Name", + "auth.field.email": "E-Mail", + "auth.field.password": "Passwort", + "auth.field.new_password": "Passwort (min. {{.Min}} Zeichen)", + "auth.field.org_name": "Organisation", + "auth.field.org_slug": "Kurzname (a–z, 0–9, -)", + "auth.field.code": "Code", + + "console.nav.security": "Sicherheit", + "console.nav.logout": "Abmelden", + "console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.", + "console.totp_missing_action": "Jetzt einrichten", + "console.monitors.title": "Monitore", + "console.monitors.empty": "Noch keine Monitore angelegt.", + + "security.title": "Sicherheit", + "security.totp.heading": "Zwei-Faktor (TOTP)", + "security.totp.active": "aktiv", + "security.totp.inactive": "nicht eingerichtet", + "security.totp.disable": "Deaktivieren", + "security.totp.current_code": "Aktueller Code", + "security.totp.start": "Einrichten", + "security.totp.qr_alt": "QR-Code für die Authenticator-App", + "security.totp.app_code": "Code aus der App", + "security.totp.confirm": "Bestätigen", + + "error.internal": "Interner Fehler.", + "error.invalid_input": "Eingaben prüfen.", + "error.rate_limited": "Zu viele Versuche, bitte später erneut.", + "error.signup_closed": "Registrierung ist deaktiviert.", + "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", + "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", + "error.slug_taken": "Dieser Kurzname ist bereits vergeben.", + "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", + "error.invalid_credentials": "E-Mail oder Passwort falsch.", + "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", + "error.invalid_code": "Code ungültig.", + "error.org_not_found": "Organisation nicht gefunden.", + "error.totp_already_enabled": "TOTP ist bereits aktiv.", + "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", + "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.", + "error.no_password": "Konto ohne Passwort.", + "error.unsupported_locale": "Sprache wird nicht unterstützt." +} diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json new file mode 100644 index 0000000..8023c23 --- /dev/null +++ b/internal/i18n/locales/en.json @@ -0,0 +1,57 @@ +{ + "app.network_error": "Connection failed.", + "lang.en": "English", + "lang.de": "Deutsch", + + "auth.login.title": "Sign in", + "auth.login.totp_hint": "Enter the code from your authenticator app.", + "auth.login.submit": "Continue", + "auth.login.no_account": "No account yet?", + "auth.login.to_signup": "Sign up", + "auth.signup.title": "Create account", + "auth.signup.submit": "Create", + "auth.signup.to_login": "Back to sign in", + "auth.field.name": "Name", + "auth.field.email": "Email", + "auth.field.password": "Password", + "auth.field.new_password": "Password (min. {{.Min}} characters)", + "auth.field.org_name": "Organization", + "auth.field.org_slug": "Short name (a–z, 0–9, -)", + "auth.field.code": "Code", + + "console.nav.security": "Security", + "console.nav.logout": "Sign out", + "console.totp_missing": "Your organization requires two-factor sign-in.", + "console.totp_missing_action": "Set up now", + "console.monitors.title": "Monitors", + "console.monitors.empty": "No monitors yet.", + + "security.title": "Security", + "security.totp.heading": "Two-factor (TOTP)", + "security.totp.active": "active", + "security.totp.inactive": "not set up", + "security.totp.disable": "Disable", + "security.totp.current_code": "Current code", + "security.totp.start": "Set up", + "security.totp.qr_alt": "QR code for your authenticator app", + "security.totp.app_code": "Code from the app", + "security.totp.confirm": "Confirm", + + "error.internal": "Internal error.", + "error.invalid_input": "Please check your input.", + "error.rate_limited": "Too many attempts, please try again later.", + "error.signup_closed": "Sign-up is disabled.", + "error.password_too_short": "The password needs at least {{.Min}} characters.", + "error.email_taken": "This email address is already registered.", + "error.slug_taken": "This short name is already taken.", + "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", + "error.invalid_credentials": "Wrong email or password.", + "error.mfa_expired": "Sign-in expired, please start again.", + "error.invalid_code": "Invalid code.", + "error.org_not_found": "Organization not found.", + "error.totp_already_enabled": "TOTP is already active.", + "error.totp_setup_expired": "Setup expired, please start again.", + "error.totp_required_by_org": "One of your organizations requires TOTP.", + "error.no_password": "This account has no password.", + "error.unsupported_locale": "Unsupported language." +}