-
Notifications
You must be signed in to change notification settings - Fork 0
/
language.go
119 lines (96 loc) · 2.5 KB
/
language.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package feapi
import (
"context"
"errors"
"io/fs"
"strings"
"github.com/KarpelesLab/apirouter"
"github.com/KarpelesLab/contexter"
"github.com/KarpelesLab/lngdb"
"github.com/KarpelesLab/pjson"
"github.com/KarpelesLab/pobj"
"github.com/KarpelesLab/putil"
"golang.org/x/text/collate"
"golang.org/x/text/language"
)
func init() {
pobj.RegisterStatic("Language:local", languageLocal)
pobj.RegisterActions[Language]("Language", &pobj.ObjectActions{
Fetch: pobj.Static(languageGet),
List: pobj.Static(languageList),
})
}
type Language lngdb.Lng
func (ln Language) MarshalJSON() ([]byte, error) {
ctx := contexter.Context()
if ctx == nil {
return nil, errors.New("could not fetch context")
}
return ln.MarshalContextJSON(ctx)
}
func (ln Language) MarshalContextJSON(ctx context.Context) ([]byte, error) {
var curlng language.Tag
ctx.Value(&curlng)
l := lngdb.Lng(ln)
lngStr := l.Tag.String()
nameShort := putil.LookupI18N(ctx, "language_"+lngStr[:2], nil, true)
countryName := putil.LookupI18N(ctx, "country_"+strings.ToLower(lngStr[3:]), nil, true)
res := map[string]any{
"Language__": lngStr,
"Local_Name": l.LocalName,
"Locale": l.Locale,
"Selected": l.Tag == curlng,
"Name_Short": nameShort,
"Name_Med": putil.Concat(nameShort, " (", countryName, ")"),
"Name_Long": putil.Concat(nameShort, " (", countryName, ")"),
}
return pjson.MarshalContext(ctx, res)
}
func languageLocal(ctx *apirouter.Context) (any, error) {
var lngs []language.Tag
ctx.Value(&lngs)
var res []any
for _, lng := range lngs {
// grab from lngdb
lngStr := lng.String()
l := lngdb.Languages[lngStr]
res = append(res, (*Language)(l))
}
return res, nil
}
func languageList(ctx *apirouter.Context) (any, error) {
curlng := language.English
ctx.Value(&curlng)
var res []*Language
// return all languages
for _, l := range lngdb.Languages {
res = append(res, (*Language)(l))
}
col := collate.New(curlng, collate.Loose)
col.Sort(LanguagesSort(res))
return res, nil
}
func languageGet(ctx *apirouter.Context, id string) (any, error) {
if id == "@" {
// grab current language
var curlng language.Tag
ctx.Value(&curlng)
id = curlng.String()
}
// find a language
l, ok := lngdb.Languages[id]
if !ok {
return nil, fs.ErrNotExist
}
return (*Language)(l), nil
}
type LanguagesSort []*Language
func (l LanguagesSort) Len() int {
return len(l)
}
func (l LanguagesSort) Bytes(i int) []byte {
return []byte(l[i].LocalName)
}
func (l LanguagesSort) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}