From 0eb4a8c1b8870788a65d46a5a485ee3dea20bda9 Mon Sep 17 00:00:00 2001 From: Jo Vandeginste Date: Wed, 15 Jan 2025 08:05:42 +0100 Subject: [PATCH] Sort languages automatically Simplify other parts of the related code. Signed-off-by: Jo Vandeginste --- views/helpers/language.go | 54 +++++++++++++++------ views/partials/partials.templ | 4 +- views/partials/partials_templ.go | 4 +- views/user/profile_preferred_units.templ | 4 +- views/user/profile_preferred_units_templ.go | 4 +- 5 files changed, 46 insertions(+), 24 deletions(-) diff --git a/views/helpers/language.go b/views/helpers/language.go index cd514fa7..43084c8a 100644 --- a/views/helpers/language.go +++ b/views/helpers/language.go @@ -1,8 +1,10 @@ package helpers import ( + "cmp" "context" "fmt" + "slices" "strings" "time" @@ -13,7 +15,23 @@ import ( "golang.org/x/text/language/display" ) -var englishTag = display.English.Languages() +var ( + englishTag = display.English.Languages() + + languagesSorted = false + languages = []language.Tag{ + language.Dutch, + language.English, + language.Finnish, + language.French, + language.German, + language.Indonesian, + language.Italian, + language.Norwegian, + language.Persian, + language.Russian, + } +) func THas(ctx context.Context, key string, args ...any) string { if i18n.Has(ctx, key) { @@ -34,22 +52,26 @@ func Language(ctx context.Context) string { return translator(ctx).Code().String() } -func SupportedLanguages(ctx context.Context) []language.Tag { - return []language.Tag{ - language.Dutch, - language.English, - language.French, - language.German, - language.Indonesian, - language.Italian, - language.Norwegian, - language.Persian, - language.Russian, +func SupportedLanguages() []language.Tag { + sortLanguages() + + return languages +} + +func sortLanguages() { + if languagesSorted { + return } + + slices.SortFunc(languages, func(a, b language.Tag) int { + return cmp.Compare(a.String(), b.String()) + }) + + languagesSorted = true } -func ToLanguageInformation(code string) LanguageInformation { - cc := code +func ToLanguageInformation(code language.Tag) LanguageInformation { + cc := code.String() if strings.Contains(cc, "-") { cc = strings.Split(cc, "-")[1] } @@ -59,7 +81,7 @@ func ToLanguageInformation(code string) LanguageInformation { } l := LanguageInformation{ - Code: code, + Code: code.String(), Flag: emojiflag.GetFlag(cc), } @@ -67,7 +89,7 @@ func ToLanguageInformation(code string) LanguageInformation { l.Flag = "👽" } - localTag := language.MustParse(code) + localTag := language.MustParse(code.String()) l.LocalName = display.Self.Name(localTag) l.EnglishName = englishTag.Name(localTag) diff --git a/views/partials/partials.templ b/views/partials/partials.templ index 311505da..d748fabd 100644 --- a/views/partials/partials.templ +++ b/views/partials/partials.templ @@ -43,8 +43,8 @@ templ Alerts() { templ Language() {