mirror of
https://codeberg.org/davrot/forgejo.git
synced 2025-05-22 20:00:03 +02:00
Replace the 'relative-time' element scripting with custom, translatable rewrite (#6154)
This is my take to fix #6078 Should also resolve #6111 As far as I can tell, Forgejo uses only a subset of the relative-time functionality, and as far as I can see, this subset can be implemented using browser built-in date conversion and arithmetic. So I wrote a JavaScript to format the relative-time element accordingly, and a Go binding to generate the translated elements. This is my first time writing Go code, and my first time coding for a large-scale server application, so please tell me if I'm doing something wrong, or if the whole approach is not acceptable. --- Screenshot: Localized times in Low German  Screenshot: The same with Forgejo in English  --- ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests - I added test coverage for Go changes... - [x] in their respective `*_test.go` for unit tests. - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I added test coverage for JavaScript changes... - [x] in `web_src/js/*.test.js` if it can be unit tested. - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)). ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. ### Release notes - [x] I do not want this change to show in the release notes. - [ ] I want the title to show in the release notes with a link to this pull request. - [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title. Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/6154 Reviewed-by: 0ko <0ko@noreply.codeberg.org> Reviewed-by: Michael Kriese <michael.kriese@gmx.de> Co-authored-by: Benedikt Straub <benedikt-straub@web.de> Co-committed-by: Benedikt Straub <benedikt-straub@web.de>
This commit is contained in:
parent
37d566bdb0
commit
cf03286b5b
19 changed files with 698 additions and 35 deletions
|
@ -188,6 +188,7 @@ forgejo.org/modules/translation
|
||||||
MockLocale.Tr
|
MockLocale.Tr
|
||||||
MockLocale.TrN
|
MockLocale.TrN
|
||||||
MockLocale.TrPluralString
|
MockLocale.TrPluralString
|
||||||
|
MockLocale.TrPluralStringAllForms
|
||||||
MockLocale.TrSize
|
MockLocale.TrSize
|
||||||
MockLocale.HasKey
|
MockLocale.HasKey
|
||||||
MockLocale.PrettyNumber
|
MockLocale.PrettyNumber
|
||||||
|
|
|
@ -15,6 +15,10 @@ type KeyLocale struct{}
|
||||||
|
|
||||||
var _ Locale = (*KeyLocale)(nil)
|
var _ Locale = (*KeyLocale)(nil)
|
||||||
|
|
||||||
|
func (k *KeyLocale) Language() string {
|
||||||
|
return "dummy"
|
||||||
|
}
|
||||||
|
|
||||||
// HasKey implements Locale.
|
// HasKey implements Locale.
|
||||||
func (k *KeyLocale) HasKey(trKey string) bool {
|
func (k *KeyLocale) HasKey(trKey string) bool {
|
||||||
return true
|
return true
|
||||||
|
@ -35,6 +39,11 @@ func (k *KeyLocale) TrPluralString(count any, trKey string, trArgs ...any) templ
|
||||||
return template.HTML(FormatDummy(trKey, PrepareArgsForHTML(trArgs...)...))
|
return template.HTML(FormatDummy(trKey, PrepareArgsForHTML(trArgs...)...))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TrPluralStringAllForms implements Locale.
|
||||||
|
func (k *KeyLocale) TrPluralStringAllForms(trKey string) ([]string, []string) {
|
||||||
|
return []string{trKey}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func FormatDummy(trKey string, args ...any) string {
|
func FormatDummy(trKey string, args ...any) string {
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
return fmt.Sprintf("(%s)", trKey)
|
return fmt.Sprintf("(%s)", trKey)
|
||||||
|
|
|
@ -25,6 +25,7 @@ const (
|
||||||
var DefaultLocales = NewLocaleStore()
|
var DefaultLocales = NewLocaleStore()
|
||||||
|
|
||||||
type Locale interface {
|
type Locale interface {
|
||||||
|
Language() string
|
||||||
// TrString translates a given key and arguments for a language
|
// TrString translates a given key and arguments for a language
|
||||||
TrString(trKey string, trArgs ...any) string
|
TrString(trKey string, trArgs ...any) string
|
||||||
// TrPluralString translates a given pluralized key and arguments for a language.
|
// TrPluralString translates a given pluralized key and arguments for a language.
|
||||||
|
@ -34,6 +35,9 @@ type Locale interface {
|
||||||
TrHTML(trKey string, trArgs ...any) template.HTML
|
TrHTML(trKey string, trArgs ...any) template.HTML
|
||||||
// HasKey reports if a locale has a translation for a given key
|
// HasKey reports if a locale has a translation for a given key
|
||||||
HasKey(trKey string) bool
|
HasKey(trKey string) bool
|
||||||
|
// TrPluralStringAllForms returns all plural form variants for a given string, and also
|
||||||
|
// the fallbacks for the default language if the translation is incomplete.
|
||||||
|
TrPluralStringAllForms(trKey string) ([]string, []string)
|
||||||
}
|
}
|
||||||
|
|
||||||
// LocaleStore provides the functions common to all locale stores
|
// LocaleStore provides the functions common to all locale stores
|
||||||
|
@ -42,6 +46,8 @@ type LocaleStore interface {
|
||||||
|
|
||||||
// SetDefaultLang sets the default language to fall back to
|
// SetDefaultLang sets the default language to fall back to
|
||||||
SetDefaultLang(lang string)
|
SetDefaultLang(lang string)
|
||||||
|
// GetDefaultLang returns the name of the default language to fall back to
|
||||||
|
GetDefaultLang() string
|
||||||
// ListLangNameDesc provides paired slices of language names to descriptors
|
// ListLangNameDesc provides paired slices of language names to descriptors
|
||||||
ListLangNameDesc() (names, desc []string)
|
ListLangNameDesc() (names, desc []string)
|
||||||
// Locale return the locale for the provided language or the default language if not found
|
// Locale return the locale for the provided language or the default language if not found
|
||||||
|
@ -49,7 +55,7 @@ type LocaleStore interface {
|
||||||
// HasLang returns whether a given language is present in the store
|
// HasLang returns whether a given language is present in the store
|
||||||
HasLang(langName string) bool
|
HasLang(langName string) bool
|
||||||
// AddLocaleByIni adds a new old-style language to the store
|
// AddLocaleByIni adds a new old-style language to the store
|
||||||
AddLocaleByIni(langName, langDesc string, pluralRule PluralFormRule, source, moreSource []byte) error
|
AddLocaleByIni(langName, langDesc string, pluralRule PluralFormRule, usedPluralForms []PluralFormIndex, source, moreSource []byte) error
|
||||||
// AddLocaleByJSON adds new-style content to an existing language to the store
|
// AddLocaleByJSON adds new-style content to an existing language to the store
|
||||||
AddToLocaleFromJSON(langName string, source []byte) error
|
AddToLocaleFromJSON(langName string, source []byte) error
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,6 +32,11 @@ var MockPluralRuleEnglish PluralFormRule = func(n int64) PluralFormIndex {
|
||||||
return PluralFormOther
|
return PluralFormOther
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
UsedPluralFormsEnglish = []PluralFormIndex{PluralFormOne, PluralFormOther}
|
||||||
|
UsedPluralFormsMock = []PluralFormIndex{PluralFormZero, PluralFormOne, PluralFormFew, PluralFormOther}
|
||||||
|
)
|
||||||
|
|
||||||
func TestLocaleStore(t *testing.T) {
|
func TestLocaleStore(t *testing.T) {
|
||||||
testData1 := []byte(`
|
testData1 := []byte(`
|
||||||
.dot.name = Dot Name
|
.dot.name = Dot Name
|
||||||
|
@ -85,8 +90,8 @@ commits = fallback value for commits
|
||||||
`)
|
`)
|
||||||
|
|
||||||
ls := NewLocaleStore()
|
ls := NewLocaleStore()
|
||||||
require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", MockPluralRuleEnglish, testData1, nil))
|
require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", MockPluralRuleEnglish, UsedPluralFormsEnglish, testData1, nil))
|
||||||
require.NoError(t, ls.AddLocaleByIni("lang2", "Lang2", MockPluralRule, testData2, nil))
|
require.NoError(t, ls.AddLocaleByIni("lang2", "Lang2", MockPluralRule, UsedPluralFormsMock, testData2, nil))
|
||||||
require.NoError(t, ls.AddToLocaleFromJSON("lang1", testDataJSON1))
|
require.NoError(t, ls.AddToLocaleFromJSON("lang1", testDataJSON1))
|
||||||
require.NoError(t, ls.AddToLocaleFromJSON("lang2", testDataJSON2))
|
require.NoError(t, ls.AddToLocaleFromJSON("lang2", testDataJSON2))
|
||||||
ls.SetDefaultLang("lang1")
|
ls.SetDefaultLang("lang1")
|
||||||
|
@ -182,7 +187,7 @@ c=22
|
||||||
`)
|
`)
|
||||||
|
|
||||||
ls := NewLocaleStore()
|
ls := NewLocaleStore()
|
||||||
require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", MockPluralRule, testData1, testData2))
|
require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", MockPluralRule, UsedPluralFormsMock, testData1, testData2))
|
||||||
lang1, _ := ls.Locale("lang1")
|
lang1, _ := ls.Locale("lang1")
|
||||||
assert.Equal(t, "11", lang1.TrString("a"))
|
assert.Equal(t, "11", lang1.TrString("a"))
|
||||||
assert.Equal(t, "21", lang1.TrString("b"))
|
assert.Equal(t, "21", lang1.TrString("b"))
|
||||||
|
@ -223,7 +228,7 @@ func (e *errorPointerReceiver) Error() string {
|
||||||
|
|
||||||
func TestLocaleWithTemplate(t *testing.T) {
|
func TestLocaleWithTemplate(t *testing.T) {
|
||||||
ls := NewLocaleStore()
|
ls := NewLocaleStore()
|
||||||
require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", MockPluralRule, []byte(`key=<a>%s</a>`), nil))
|
require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", MockPluralRule, UsedPluralFormsMock, []byte(`key=<a>%s</a>`), nil))
|
||||||
lang1, _ := ls.Locale("lang1")
|
lang1, _ := ls.Locale("lang1")
|
||||||
|
|
||||||
tmpl := template.New("test").Funcs(template.FuncMap{"tr": lang1.TrHTML})
|
tmpl := template.New("test").Funcs(template.FuncMap{"tr": lang1.TrHTML})
|
||||||
|
@ -286,7 +291,7 @@ func TestLocaleStoreQuirks(t *testing.T) {
|
||||||
|
|
||||||
for _, testData := range testDataList {
|
for _, testData := range testDataList {
|
||||||
ls := NewLocaleStore()
|
ls := NewLocaleStore()
|
||||||
err := ls.AddLocaleByIni("lang1", "Lang1", nil, []byte("a="+testData.in), nil)
|
err := ls.AddLocaleByIni("lang1", "Lang1", nil, nil, []byte("a="+testData.in), nil)
|
||||||
lang1, _ := ls.Locale("lang1")
|
lang1, _ := ls.Locale("lang1")
|
||||||
require.NoError(t, err, testData.hint)
|
require.NoError(t, err, testData.hint)
|
||||||
assert.Equal(t, testData.out, lang1.TrString("a"), testData.hint)
|
assert.Equal(t, testData.out, lang1.TrString("a"), testData.hint)
|
||||||
|
|
|
@ -24,6 +24,7 @@ type locale struct {
|
||||||
|
|
||||||
newStyleMessages map[string]string
|
newStyleMessages map[string]string
|
||||||
pluralRule PluralFormRule
|
pluralRule PluralFormRule
|
||||||
|
usedPluralForms []PluralFormIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ Locale = (*locale)(nil)
|
var _ Locale = (*locale)(nil)
|
||||||
|
@ -56,7 +57,7 @@ const (
|
||||||
// the correct plural form for a given count and language.
|
// the correct plural form for a given count and language.
|
||||||
|
|
||||||
// AddLocaleByIni adds locale by ini into the store
|
// AddLocaleByIni adds locale by ini into the store
|
||||||
func (store *localeStore) AddLocaleByIni(langName, langDesc string, pluralRule PluralFormRule, source, moreSource []byte) error {
|
func (store *localeStore) AddLocaleByIni(langName, langDesc string, pluralRule PluralFormRule, usedPluralForms []PluralFormIndex, source, moreSource []byte) error {
|
||||||
if _, ok := store.localeMap[langName]; ok {
|
if _, ok := store.localeMap[langName]; ok {
|
||||||
return ErrLocaleAlreadyExist
|
return ErrLocaleAlreadyExist
|
||||||
}
|
}
|
||||||
|
@ -64,7 +65,7 @@ func (store *localeStore) AddLocaleByIni(langName, langDesc string, pluralRule P
|
||||||
store.langNames = append(store.langNames, langName)
|
store.langNames = append(store.langNames, langName)
|
||||||
store.langDescs = append(store.langDescs, langDesc)
|
store.langDescs = append(store.langDescs, langDesc)
|
||||||
|
|
||||||
l := &locale{store: store, langName: langName, idxToMsgMap: make(map[int]string), pluralRule: pluralRule, newStyleMessages: make(map[string]string)}
|
l := &locale{store: store, langName: langName, idxToMsgMap: make(map[int]string), pluralRule: pluralRule, usedPluralForms: usedPluralForms, newStyleMessages: make(map[string]string)}
|
||||||
store.localeMap[l.langName] = l
|
store.localeMap[l.langName] = l
|
||||||
|
|
||||||
iniFile, err := setting.NewConfigProviderForLocale(source, moreSource)
|
iniFile, err := setting.NewConfigProviderForLocale(source, moreSource)
|
||||||
|
@ -118,7 +119,7 @@ func (l *locale) LookupNewStyleMessage(trKey string) string {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *locale) LookupPlural(trKey string, count any) string {
|
func (l *locale) LookupPluralByCount(trKey string, count any) string {
|
||||||
n, err := util.ToInt64(count)
|
n, err := util.ToInt64(count)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Invalid plural count '%s'", count)
|
log.Error("Invalid plural count '%s'", count)
|
||||||
|
@ -126,6 +127,10 @@ func (l *locale) LookupPlural(trKey string, count any) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
pluralForm := l.pluralRule(n)
|
pluralForm := l.pluralRule(n)
|
||||||
|
return l.LookupPluralByForm(trKey, pluralForm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *locale) LookupPluralByForm(trKey string, pluralForm PluralFormIndex) string {
|
||||||
suffix := ""
|
suffix := ""
|
||||||
switch pluralForm {
|
switch pluralForm {
|
||||||
case PluralFormZero:
|
case PluralFormZero:
|
||||||
|
@ -141,7 +146,7 @@ func (l *locale) LookupPlural(trKey string, count any) string {
|
||||||
case PluralFormOther:
|
case PluralFormOther:
|
||||||
// No suffix for the "other" string.
|
// No suffix for the "other" string.
|
||||||
default:
|
default:
|
||||||
log.Error("Invalid plural form index %d for count %d", pluralForm, count)
|
log.Error("Invalid plural form index %d", pluralForm)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -149,7 +154,7 @@ func (l *locale) LookupPlural(trKey string, count any) string {
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Error("Missing translation for plural form index %d for count %d", pluralForm, count)
|
log.Error("Missing translation for plural form %s", suffix)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -167,6 +172,10 @@ func (store *localeStore) SetDefaultLang(lang string) {
|
||||||
store.defaultLang = lang
|
store.defaultLang = lang
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (store *localeStore) GetDefaultLang() string {
|
||||||
|
return store.defaultLang
|
||||||
|
}
|
||||||
|
|
||||||
// Locale returns the locale for the lang or the default language
|
// Locale returns the locale for the lang or the default language
|
||||||
func (store *localeStore) Locale(lang string) (Locale, bool) {
|
func (store *localeStore) Locale(lang string) (Locale, bool) {
|
||||||
l, found := store.localeMap[lang]
|
l, found := store.localeMap[lang]
|
||||||
|
@ -185,6 +194,10 @@ func (store *localeStore) Close() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (l *locale) Language() string {
|
||||||
|
return l.langName
|
||||||
|
}
|
||||||
|
|
||||||
func (l *locale) TrString(trKey string, trArgs ...any) string {
|
func (l *locale) TrString(trKey string, trArgs ...any) string {
|
||||||
format := trKey
|
format := trKey
|
||||||
|
|
||||||
|
@ -251,11 +264,11 @@ func (l *locale) TrHTML(trKey string, trArgs ...any) template.HTML {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *locale) TrPluralString(count any, trKey string, trArgs ...any) template.HTML {
|
func (l *locale) TrPluralString(count any, trKey string, trArgs ...any) template.HTML {
|
||||||
message := l.LookupPlural(trKey, count)
|
message := l.LookupPluralByCount(trKey, count)
|
||||||
|
|
||||||
if message == "" {
|
if message == "" {
|
||||||
if defaultLang, ok := l.store.localeMap[l.store.defaultLang]; ok {
|
if defaultLang, ok := l.store.localeMap[l.store.defaultLang]; ok {
|
||||||
message = defaultLang.LookupPlural(trKey, count)
|
message = defaultLang.LookupPluralByCount(trKey, count)
|
||||||
}
|
}
|
||||||
if message == "" {
|
if message == "" {
|
||||||
message = trKey
|
message = trKey
|
||||||
|
@ -269,6 +282,36 @@ func (l *locale) TrPluralString(count any, trKey string, trArgs ...any) template
|
||||||
return template.HTML(message)
|
return template.HTML(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (l *locale) TrPluralStringAllForms(trKey string) ([]string, []string) {
|
||||||
|
defaultLang, hasDefaultLang := l.store.localeMap[l.store.defaultLang]
|
||||||
|
|
||||||
|
var fallback []string
|
||||||
|
fallback = nil
|
||||||
|
|
||||||
|
result := make([]string, len(l.usedPluralForms))
|
||||||
|
allPresent := true
|
||||||
|
|
||||||
|
for i, form := range l.usedPluralForms {
|
||||||
|
result[i] = l.LookupPluralByForm(trKey, form)
|
||||||
|
if result[i] == "" {
|
||||||
|
allPresent = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !allPresent {
|
||||||
|
if hasDefaultLang {
|
||||||
|
fallback = make([]string, len(defaultLang.usedPluralForms))
|
||||||
|
for i, form := range defaultLang.usedPluralForms {
|
||||||
|
fallback[i] = defaultLang.LookupPluralByForm(trKey, form)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Error("Plural set for '%s' is incomplete and no fallback language is set.", trKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, fallback
|
||||||
|
}
|
||||||
|
|
||||||
// HasKey returns whether a key is present in this locale or not
|
// HasKey returns whether a key is present in this locale or not
|
||||||
func (l *locale) HasKey(trKey string) bool {
|
func (l *locale) HasKey(trKey string) bool {
|
||||||
_, ok := l.newStyleMessages[trKey]
|
_, ok := l.newStyleMessages[trKey]
|
||||||
|
|
|
@ -6,11 +6,15 @@ package translation
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
|
|
||||||
|
"forgejo.org/modules/translation/i18n"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MockLocale provides a mocked locale without any translations
|
// MockLocale provides a mocked locale without any translations, other than those inserted into MockTranslations by a testcase
|
||||||
type MockLocale struct {
|
type MockLocale struct {
|
||||||
Lang, LangName string // these fields are used directly in templates: ctx.Locale.Lang
|
Lang, LangName string // these fields are used directly in templates: ctx.Locale.Lang
|
||||||
|
|
||||||
|
MockTranslations map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ Locale = (*MockLocale)(nil)
|
var _ Locale = (*MockLocale)(nil)
|
||||||
|
@ -20,11 +24,14 @@ func (l MockLocale) Language() string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l MockLocale) TrString(s string, _ ...any) string {
|
func (l MockLocale) TrString(s string, _ ...any) string {
|
||||||
|
if val, ok := l.MockTranslations[s]; ok {
|
||||||
|
return val
|
||||||
|
}
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l MockLocale) Tr(s string, a ...any) template.HTML {
|
func (l MockLocale) Tr(s string, a ...any) template.HTML {
|
||||||
return template.HTML(s)
|
return template.HTML(l.TrString(s))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l MockLocale) TrN(cnt any, key1, keyN string, args ...any) template.HTML {
|
func (l MockLocale) TrN(cnt any, key1, keyN string, args ...any) template.HTML {
|
||||||
|
@ -35,6 +42,11 @@ func (l MockLocale) TrPluralString(count any, trKey string, trArgs ...any) templ
|
||||||
return template.HTML(trKey)
|
return template.HTML(trKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TrPluralStringAllForms implements Locale.
|
||||||
|
func (l MockLocale) TrPluralStringAllForms(trKey string) ([]string, []string) {
|
||||||
|
return []string{l.TrString(trKey + i18n.PluralFormSeparator + "one"), l.TrString(trKey + i18n.PluralFormSeparator + "other")}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (l MockLocale) TrSize(s int64) ReadableSize {
|
func (l MockLocale) TrSize(s int64) ReadableSize {
|
||||||
return ReadableSize{fmt.Sprint(s), ""}
|
return ReadableSize{fmt.Sprint(s), ""}
|
||||||
}
|
}
|
||||||
|
|
|
@ -251,3 +251,34 @@ var PluralRules = []i18n.PluralFormRule{
|
||||||
return i18n.PluralFormOther
|
return i18n.PluralFormOther
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var UsedPluralForms = [][]i18n.PluralFormIndex{
|
||||||
|
// [ 0] Common 2-form, e.g. English, German
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormOther},
|
||||||
|
// [ 1] Bengali
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormOther},
|
||||||
|
// [ 2] Icelandic
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormOther},
|
||||||
|
// [ 3] Filipino
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormOther},
|
||||||
|
// [ 4] OneForm
|
||||||
|
{i18n.PluralFormOther},
|
||||||
|
// [ 5] Czech
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormFew, i18n.PluralFormOther},
|
||||||
|
// [ 6] Russian
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormFew, i18n.PluralFormMany},
|
||||||
|
// [ 7] Polish
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormFew, i18n.PluralFormOther},
|
||||||
|
// [ 8] Latvian
|
||||||
|
{i18n.PluralFormZero, i18n.PluralFormOne, i18n.PluralFormOther},
|
||||||
|
// [ 9] Lithuanian
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormFew, i18n.PluralFormMany},
|
||||||
|
// [10] French
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormMany, i18n.PluralFormOther},
|
||||||
|
// [11] Catalan
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormMany, i18n.PluralFormOther},
|
||||||
|
// [12] Slovenian
|
||||||
|
{i18n.PluralFormOne, i18n.PluralFormTwo, i18n.PluralFormFew, i18n.PluralFormOther},
|
||||||
|
// [13] Arabic
|
||||||
|
{i18n.PluralFormZero, i18n.PluralFormOne, i18n.PluralFormTwo, i18n.PluralFormFew, i18n.PluralFormMany, i18n.PluralFormOther},
|
||||||
|
}
|
||||||
|
|
|
@ -46,6 +46,8 @@ type Locale interface {
|
||||||
HasKey(trKey string) bool
|
HasKey(trKey string) bool
|
||||||
|
|
||||||
PrettyNumber(v any) string
|
PrettyNumber(v any) string
|
||||||
|
|
||||||
|
TrPluralStringAllForms(trKey string) ([]string, []string)
|
||||||
}
|
}
|
||||||
|
|
||||||
// LangType represents a lang type
|
// LangType represents a lang type
|
||||||
|
@ -108,8 +110,9 @@ func InitLocales(ctx context.Context) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pluralRuleIndex := GetPluralRuleImpl(setting.Langs[i])
|
||||||
key := "locale_" + setting.Langs[i] + ".ini"
|
key := "locale_" + setting.Langs[i] + ".ini"
|
||||||
if err = i18n.DefaultLocales.AddLocaleByIni(setting.Langs[i], setting.Names[i], PluralRules[GetPluralRuleImpl(setting.Langs[i])], localeDataBase, localeData[key]); err != nil {
|
if err = i18n.DefaultLocales.AddLocaleByIni(setting.Langs[i], setting.Names[i], PluralRules[pluralRuleIndex], UsedPluralForms[pluralRuleIndex], localeDataBase, localeData[key]); err != nil {
|
||||||
log.Error("Failed to set old-style messages to %s: %v", setting.Langs[i], err)
|
log.Error("Failed to set old-style messages to %s: %v", setting.Langs[i], err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -324,6 +327,14 @@ func (l *locale) PrettyNumber(v any) string {
|
||||||
return l.msgPrinter.Sprintf("%v", number.Decimal(v))
|
return l.msgPrinter.Sprintf("%v", number.Decimal(v))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetPluralRule(l Locale) int {
|
||||||
|
return GetPluralRuleImpl(l.Language())
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetDefaultPluralRule() int {
|
||||||
|
return GetPluralRuleImpl(i18n.DefaultLocales.GetDefaultLang())
|
||||||
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
// prepare a default matcher, especially for tests
|
// prepare a default matcher, especially for tests
|
||||||
supportedTags = []language.Tag{language.English}
|
supportedTags = []language.Tag{language.English}
|
||||||
|
|
|
@ -4,6 +4,40 @@
|
||||||
"home.explore_repos": "Explore repositories",
|
"home.explore_repos": "Explore repositories",
|
||||||
"home.explore_users": "Explore users",
|
"home.explore_users": "Explore users",
|
||||||
"home.explore_orgs": "Explore organizations",
|
"home.explore_orgs": "Explore organizations",
|
||||||
|
"relativetime.now": "now",
|
||||||
|
"relativetime.future": "in future",
|
||||||
|
"relativetime.mins": {
|
||||||
|
"one": "%d minute ago",
|
||||||
|
"other": "%d minutes ago"
|
||||||
|
},
|
||||||
|
"relativetime.hours": {
|
||||||
|
"one": "%d hour ago",
|
||||||
|
"other": "%d hours ago"
|
||||||
|
},
|
||||||
|
"relativetime.days": {
|
||||||
|
"one": "%d day ago",
|
||||||
|
"other": "%d days ago"
|
||||||
|
},
|
||||||
|
"relativetime.weeks": {
|
||||||
|
"one": "%d week ago",
|
||||||
|
"other": "%d weeks ago"
|
||||||
|
},
|
||||||
|
"relativetime.months": {
|
||||||
|
"one": "%d month ago",
|
||||||
|
"other": "%d months ago"
|
||||||
|
},
|
||||||
|
"relativetime.years": {
|
||||||
|
"one": "%d year ago",
|
||||||
|
"other": "%d years ago"
|
||||||
|
},
|
||||||
|
"relativetime.1day": "yesterday",
|
||||||
|
"relativetime.2days": "two days ago",
|
||||||
|
"relativetime.1week": "last week",
|
||||||
|
"relativetime.2weeks": "two weeks ago",
|
||||||
|
"relativetime.1month": "last month",
|
||||||
|
"relativetime.2months": "two months ago",
|
||||||
|
"relativetime.1year": "last year",
|
||||||
|
"relativetime.2years": "two years ago",
|
||||||
"repo.pulls.merged_title_desc": {
|
"repo.pulls.merged_title_desc": {
|
||||||
"one": "merged %[1]d commit from <code>%[2]s</code> into <code>%[3]s</code> %[4]s",
|
"one": "merged %[1]d commit from <code>%[2]s</code> into <code>%[3]s</code> %[4]s",
|
||||||
"other": "merged %[1]d commits from <code>%[2]s</code> into <code>%[3]s</code> %[4]s"
|
"other": "merged %[1]d commits from <code>%[2]s</code> into <code>%[3]s</code> %[4]s"
|
||||||
|
|
15
package-lock.json
generated
15
package-lock.json
generated
|
@ -11,7 +11,6 @@
|
||||||
"@citation-js/plugin-software-formats": "0.6.1",
|
"@citation-js/plugin-software-formats": "0.6.1",
|
||||||
"@github/markdown-toolbar-element": "2.2.3",
|
"@github/markdown-toolbar-element": "2.2.3",
|
||||||
"@github/quote-selection": "2.1.0",
|
"@github/quote-selection": "2.1.0",
|
||||||
"@github/relative-time-element": "4.4.6",
|
|
||||||
"@github/text-expander-element": "2.8.0",
|
"@github/text-expander-element": "2.8.0",
|
||||||
"@mcaptcha/vanilla-glue": "0.1.0-alpha-3",
|
"@mcaptcha/vanilla-glue": "0.1.0-alpha-3",
|
||||||
"@primer/octicons": "19.14.0",
|
"@primer/octicons": "19.14.0",
|
||||||
|
@ -1223,20 +1222,6 @@
|
||||||
"integrity": "sha512-zyTvG6GpfWuVrRnxa/JpWPlTyj8ItTCMHXNrdXrvNPrSFCsDAiqEaxTW+644lwxXNfzTPQeN11paR9SRRvE2zg==",
|
"integrity": "sha512-zyTvG6GpfWuVrRnxa/JpWPlTyj8ItTCMHXNrdXrvNPrSFCsDAiqEaxTW+644lwxXNfzTPQeN11paR9SRRvE2zg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@github/relative-time-element": {
|
|
||||||
"version": "4.4.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/@github/relative-time-element/-/relative-time-element-4.4.6.tgz",
|
|
||||||
"integrity": "sha512-KgrkxVWb/qcBBSDumGhRzieqtSzGJyyEF4D5to+OVJf/nTExU5sSlPKiNEzN8Nh6Kj0SGlq8UdIJjEgPxZzUhQ==",
|
|
||||||
"license": "MIT",
|
|
||||||
"peerDependencies": {
|
|
||||||
"@types/react": "18 || 19"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"@types/react": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@github/text-expander-element": {
|
"node_modules/@github/text-expander-element": {
|
||||||
"version": "2.8.0",
|
"version": "2.8.0",
|
||||||
"resolved": "https://registry.npmjs.org/@github/text-expander-element/-/text-expander-element-2.8.0.tgz",
|
"resolved": "https://registry.npmjs.org/@github/text-expander-element/-/text-expander-element-2.8.0.tgz",
|
||||||
|
|
|
@ -10,7 +10,6 @@
|
||||||
"@citation-js/plugin-software-formats": "0.6.1",
|
"@citation-js/plugin-software-formats": "0.6.1",
|
||||||
"@github/markdown-toolbar-element": "2.2.3",
|
"@github/markdown-toolbar-element": "2.2.3",
|
||||||
"@github/quote-selection": "2.1.0",
|
"@github/quote-selection": "2.1.0",
|
||||||
"@github/relative-time-element": "4.4.6",
|
|
||||||
"@github/text-expander-element": "2.8.0",
|
"@github/text-expander-element": "2.8.0",
|
||||||
"@mcaptcha/vanilla-glue": "0.1.0-alpha-3",
|
"@mcaptcha/vanilla-glue": "0.1.0-alpha-3",
|
||||||
"@primer/octicons": "19.14.0",
|
"@primer/octicons": "19.14.0",
|
||||||
|
|
|
@ -121,6 +121,18 @@ func NewWebContext(base *Base, render Render, session session.Store) *Context {
|
||||||
return ctx
|
return ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ctx *Context) AddPluralStringsToPageData(keys []string) {
|
||||||
|
for _, key := range keys {
|
||||||
|
array, fallback := ctx.Locale.TrPluralStringAllForms(key)
|
||||||
|
|
||||||
|
ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)[key] = array
|
||||||
|
|
||||||
|
if fallback != nil {
|
||||||
|
ctx.PageData["PLURALSTRINGS_FALLBACK"].(map[string][]string)[key] = fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Contexter initializes a classic context for a request.
|
// Contexter initializes a classic context for a request.
|
||||||
func Contexter() func(next http.Handler) http.Handler {
|
func Contexter() func(next http.Handler) http.Handler {
|
||||||
rnd := templates.HTMLRenderer()
|
rnd := templates.HTMLRenderer()
|
||||||
|
@ -208,6 +220,25 @@ func Contexter() func(next http.Handler) http.Handler {
|
||||||
|
|
||||||
ctx.Data["AllLangs"] = translation.AllLangs()
|
ctx.Data["AllLangs"] = translation.AllLangs()
|
||||||
|
|
||||||
|
ctx.PageData["PLURAL_RULE_LANG"] = translation.GetPluralRule(ctx.Locale)
|
||||||
|
ctx.PageData["PLURAL_RULE_FALLBACK"] = translation.GetDefaultPluralRule()
|
||||||
|
ctx.PageData["PLURALSTRINGS_LANG"] = map[string][]string{}
|
||||||
|
ctx.PageData["PLURALSTRINGS_FALLBACK"] = map[string][]string{}
|
||||||
|
|
||||||
|
ctx.AddPluralStringsToPageData([]string{"relativetime.mins", "relativetime.hours", "relativetime.days", "relativetime.weeks", "relativetime.months", "relativetime.years"})
|
||||||
|
|
||||||
|
ctx.PageData["DATETIMESTRINGS"] = map[string]string{
|
||||||
|
"FUTURE": ctx.Locale.TrString("relativetime.future"),
|
||||||
|
"NOW": ctx.Locale.TrString("relativetime.now"),
|
||||||
|
}
|
||||||
|
for _, key := range []string{"relativetime.1day", "relativetime.1week", "relativetime.1month", "relativetime.1year", "relativetime.2days", "relativetime.2weeks", "relativetime.2months", "relativetime.2years"} {
|
||||||
|
// These keys are used for special-casing some time words. We only add keys that are actually translated, so that we
|
||||||
|
// can fall back to the generic pluralized time word in the correct language if the special case is untranslated.
|
||||||
|
if ctx.Locale.HasKey(key) {
|
||||||
|
ctx.PageData["DATETIMESTRINGS"].(map[string]string)[key] = ctx.Locale.TrString(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
next.ServeHTTP(ctx.Resp, ctx.Req)
|
next.ServeHTTP(ctx.Resp, ctx.Req)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
63
services/contexttest/pagedata_test.go
Normal file
63
services/contexttest/pagedata_test.go
Normal file
|
@ -0,0 +1,63 @@
|
||||||
|
// Copyright 2024 The Forgejo Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package contexttest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"forgejo.org/modules/translation"
|
||||||
|
"forgejo.org/modules/translation/i18n"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPluralStringsForClient(t *testing.T) {
|
||||||
|
mockLocale := translation.MockLocale{}
|
||||||
|
mockLocale.MockTranslations = map[string]string{
|
||||||
|
"relativetime.mins" + i18n.PluralFormSeparator + "one": "%d minute ago",
|
||||||
|
"relativetime.hours" + i18n.PluralFormSeparator + "one": "%d hour ago",
|
||||||
|
"relativetime.days" + i18n.PluralFormSeparator + "one": "%d day ago",
|
||||||
|
"relativetime.weeks" + i18n.PluralFormSeparator + "one": "%d week ago",
|
||||||
|
"relativetime.months" + i18n.PluralFormSeparator + "one": "%d month ago",
|
||||||
|
"relativetime.years" + i18n.PluralFormSeparator + "one": "%d year ago",
|
||||||
|
"relativetime.mins" + i18n.PluralFormSeparator + "other": "%d minutes ago",
|
||||||
|
"relativetime.hours" + i18n.PluralFormSeparator + "other": "%d hours ago",
|
||||||
|
"relativetime.days" + i18n.PluralFormSeparator + "other": "%d days ago",
|
||||||
|
"relativetime.weeks" + i18n.PluralFormSeparator + "other": "%d weeks ago",
|
||||||
|
"relativetime.months" + i18n.PluralFormSeparator + "other": "%d months ago",
|
||||||
|
"relativetime.years" + i18n.PluralFormSeparator + "other": "%d years ago",
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, _ := MockContext(t, "/")
|
||||||
|
ctx.Locale = mockLocale
|
||||||
|
assert.True(t, ctx.Locale.HasKey("relativetime.mins"))
|
||||||
|
assert.True(t, ctx.Locale.HasKey("relativetime.weeks"))
|
||||||
|
assert.Equal(t, "%d minutes ago", ctx.Locale.TrString("relativetime.mins"+i18n.PluralFormSeparator+"other"))
|
||||||
|
assert.Equal(t, "%d week ago", ctx.Locale.TrString("relativetime.weeks"+i18n.PluralFormSeparator+"one"))
|
||||||
|
|
||||||
|
assert.Empty(t, ctx.PageData)
|
||||||
|
ctx.PageData["PLURALSTRINGS_LANG"] = map[string][]string{}
|
||||||
|
assert.Empty(t, ctx.PageData["PLURALSTRINGS_LANG"])
|
||||||
|
|
||||||
|
ctx.AddPluralStringsToPageData([]string{"relativetime.mins", "relativetime.hours"})
|
||||||
|
assert.Len(t, ctx.PageData["PLURALSTRINGS_LANG"], 2)
|
||||||
|
assert.Len(t, ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.mins"], 2)
|
||||||
|
assert.Len(t, ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.hours"], 2)
|
||||||
|
assert.Equal(t, "%d minute ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.mins"][0])
|
||||||
|
assert.Equal(t, "%d minutes ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.mins"][1])
|
||||||
|
assert.Equal(t, "%d hour ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.hours"][0])
|
||||||
|
assert.Equal(t, "%d hours ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.hours"][1])
|
||||||
|
|
||||||
|
ctx.AddPluralStringsToPageData([]string{"relativetime.years", "relativetime.days"})
|
||||||
|
assert.Len(t, ctx.PageData["PLURALSTRINGS_LANG"], 4)
|
||||||
|
assert.Len(t, ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.mins"], 2)
|
||||||
|
assert.Len(t, ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.days"], 2)
|
||||||
|
assert.Len(t, ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.years"], 2)
|
||||||
|
assert.Equal(t, "%d minute ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.mins"][0])
|
||||||
|
assert.Equal(t, "%d minutes ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.mins"][1])
|
||||||
|
assert.Equal(t, "%d day ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.days"][0])
|
||||||
|
assert.Equal(t, "%d days ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.days"][1])
|
||||||
|
assert.Equal(t, "%d year ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.years"][0])
|
||||||
|
assert.Equal(t, "%d years ago", ctx.PageData["PLURALSTRINGS_LANG"].(map[string][]string)["relativetime.years"][1])
|
||||||
|
}
|
|
@ -24,7 +24,7 @@ func TestMissingTranslationHandling(t *testing.T) {
|
||||||
// Currently new languages can only be added to localestore via AddLocaleByIni
|
// Currently new languages can only be added to localestore via AddLocaleByIni
|
||||||
// so this line is here to make the other one work. When INI locales are removed,
|
// so this line is here to make the other one work. When INI locales are removed,
|
||||||
// it will not be needed by this test.
|
// it will not be needed by this test.
|
||||||
i18n.DefaultLocales.AddLocaleByIni("fun", "Funlang", nil, []byte(""), nil)
|
i18n.DefaultLocales.AddLocaleByIni("fun", "Funlang", nil, nil, []byte(""), nil)
|
||||||
|
|
||||||
// Add a testing locale to the store
|
// Add a testing locale to the store
|
||||||
i18n.DefaultLocales.AddToLocaleFromJSON("fun", []byte(`{
|
i18n.DefaultLocales.AddToLocaleFromJSON("fun", []byte(`{
|
||||||
|
|
75
web_src/js/webcomponents/i18n.js
Normal file
75
web_src/js/webcomponents/i18n.js
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
const {pageData} = window.config;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A list of plural rules for all languages.
|
||||||
|
* `plural_rules.go` defines the index for each of the 14 known plural rules.
|
||||||
|
*
|
||||||
|
* `pageData.PLURAL_RULE_LANG` is the index of the plural rule for the current language.
|
||||||
|
* `pageData.PLURAL_RULE_FALLBACK` is the index of the plural rule for the default language,
|
||||||
|
* to be used when a string is not translated in the current language.
|
||||||
|
*
|
||||||
|
* Each plural rule is a function that maps an amount `n` to the appropriate plural form index.
|
||||||
|
* Which index means which rule is specific for each language and also defined in `plural_rules.go`.
|
||||||
|
* The actual strings are in `pageData.PLURALSTRINGS_LANG` and `pageData.PLURALSTRINGS_FALLBACK`
|
||||||
|
* respectively, which is an array indexed by the plural form index.
|
||||||
|
*
|
||||||
|
* Links to the language plural rule and form definitions:
|
||||||
|
* https://codeberg.org/forgejo/forgejo/src/branch/forgejo/modules/translation/plural_rules.go
|
||||||
|
* https://www.unicode.org/cldr/charts/46/supplemental/language_plural_rules.html
|
||||||
|
* https://translate.codeberg.org/languages/$LANGUAGE_CODE/#information
|
||||||
|
* https://github.com/WeblateOrg/language-data/blob/main/languages.csv
|
||||||
|
*/
|
||||||
|
const PLURAL_RULES = [
|
||||||
|
// [ 0] Common 2-form, e.g. English, German
|
||||||
|
function (n) { return n !== 1 ? 1 : 0 },
|
||||||
|
|
||||||
|
// [ 1] Bengali 2-form
|
||||||
|
function (n) { return n > 1 ? 1 : 0 },
|
||||||
|
|
||||||
|
// [ 2] Icelandic 2-form
|
||||||
|
function (n) { return n % 10 !== 1 || n % 100 === 11 ? 1 : 0 },
|
||||||
|
|
||||||
|
// [ 3] Filipino 2-form
|
||||||
|
function (n) { return n !== 1 && n !== 2 && n !== 3 && (n % 10 === 4 || n % 10 === 6 || n % 10 === 9) ? 1 : 0 },
|
||||||
|
|
||||||
|
// [ 4] One form
|
||||||
|
function (_) { return 0 },
|
||||||
|
|
||||||
|
// [ 5] Czech 3-form
|
||||||
|
function (n) { return (n === 1) ? 0 : (n >= 2 && n <= 4) ? 1 : 2 },
|
||||||
|
|
||||||
|
// [ 6] Russian 3-form
|
||||||
|
function (n) { return n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2 },
|
||||||
|
|
||||||
|
// [ 7] Polish 3-form
|
||||||
|
function (n) { return n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2 },
|
||||||
|
|
||||||
|
// [ 8] Latvian 3-form
|
||||||
|
function (n) { return (n % 10 === 0 || n % 100 >= 11 && n % 100 <= 19) ? 0 : ((n % 10 === 1 && n % 100 !== 11) ? 1 : 2) },
|
||||||
|
|
||||||
|
// [ 9] Lithunian 3-form
|
||||||
|
function (n) { return (n % 10 === 1 && (n % 100 < 11 || n % 100 > 19)) ? 0 : ((n % 10 >= 2 && n % 10 <= 9 && (n % 100 < 11 || n % 100 > 19)) ? 1 : 2) },
|
||||||
|
|
||||||
|
// [10] French 3-form
|
||||||
|
function (n) { return (n === 0 || n === 1) ? 0 : ((n !== 0 && n % 1000000 === 0) ? 1 : 2) },
|
||||||
|
|
||||||
|
// [11] Catalan 3-form
|
||||||
|
function (n) { return (n === 1) ? 0 : ((n !== 0 && n % 1000000 === 0) ? 1 : 2) },
|
||||||
|
|
||||||
|
// [12] Slovenian 4-form
|
||||||
|
function (n) { return n % 100 === 1 ? 0 : n % 100 === 2 ? 1 : n % 100 === 3 || n % 100 === 4 ? 2 : 3 },
|
||||||
|
|
||||||
|
// [13] Arabic 6-form
|
||||||
|
function (n) { return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5 },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Look up the correct localized plural form for amount `n` for the string with the translation key `key`.
|
||||||
|
* If the current language does not contain a translation for this key, returns the text in the default language,
|
||||||
|
* or `null` if `suppress_fallback` is set to `true`.
|
||||||
|
*/
|
||||||
|
export function GetPluralizedString(key, n, suppress_fallback) {
|
||||||
|
const result = pageData.PLURALSTRINGS_LANG[key]?.[PLURAL_RULES[pageData.PLURAL_RULE_LANG](n)];
|
||||||
|
if (result || suppress_fallback) return result;
|
||||||
|
return pageData.PLURALSTRINGS_FALLBACK[key][PLURAL_RULES[pageData.PLURAL_RULE_FALLBACK](n)];
|
||||||
|
}
|
|
@ -1,5 +1,6 @@
|
||||||
import './polyfills.js';
|
import './polyfills.js';
|
||||||
import '@github/relative-time-element';
|
import './i18n.js';
|
||||||
|
import './relative-time.js';
|
||||||
import './origin-url.js';
|
import './origin-url.js';
|
||||||
import './overflow-menu.js';
|
import './overflow-menu.js';
|
||||||
import './absolute-date.js';
|
import './absolute-date.js';
|
||||||
|
|
144
web_src/js/webcomponents/relative-time.js
Normal file
144
web_src/js/webcomponents/relative-time.js
Normal file
|
@ -0,0 +1,144 @@
|
||||||
|
import {GetPluralizedString} from './i18n.js';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
const {pageData} = window.config;
|
||||||
|
|
||||||
|
export const HALF_MINUTE = 30 * 1000;
|
||||||
|
export const ONE_MINUTE = 60 * 1000;
|
||||||
|
export const ONE_HOUR = 60 * ONE_MINUTE;
|
||||||
|
export const ONE_DAY = 24 * ONE_HOUR;
|
||||||
|
|
||||||
|
const ABSOLUTE_DATETIME_FORMAT = new Intl.DateTimeFormat(navigator.language, {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
timeZoneName: 'short',
|
||||||
|
});
|
||||||
|
const FALLBACK_DATETIME_FORMAT = new Intl.RelativeTimeFormat(navigator.language, {style: 'long'});
|
||||||
|
|
||||||
|
function GetPluralizedStringOrFallback(key, n, unit) {
|
||||||
|
const translation = GetPluralizedString(key, n, true);
|
||||||
|
if (translation) return translation.replace('%d', n);
|
||||||
|
return FALLBACK_DATETIME_FORMAT.format(-n, unit);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the displayed text of the given relative-time DOM element with its
|
||||||
|
* human-readable, localized relative time string.
|
||||||
|
* Returns the recommended interval in milliseconds until the object should be updated again,
|
||||||
|
* or null if the object is invalid.
|
||||||
|
*/
|
||||||
|
export function DoUpdateRelativeTime(object, now) {
|
||||||
|
const absoluteTime = object.getAttribute('datetime');
|
||||||
|
if (!absoluteTime) {
|
||||||
|
return null; // Object does not contain a datetime.
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!now) now = Date.now();
|
||||||
|
|
||||||
|
const nowJS = dayjs(now);
|
||||||
|
const thenJS = dayjs(absoluteTime);
|
||||||
|
|
||||||
|
object.setAttribute('data-tooltip-content', ABSOLUTE_DATETIME_FORMAT.format(thenJS.toDate()));
|
||||||
|
|
||||||
|
if (nowJS.isBefore(thenJS)) {
|
||||||
|
// Datetime is in the future.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS.FUTURE;
|
||||||
|
return -Math.floor(nowJS.diff(thenJS, 'millisecond'));
|
||||||
|
}
|
||||||
|
|
||||||
|
const years = Math.floor(nowJS.diff(thenJS, 'year'));
|
||||||
|
if (years >= 1) {
|
||||||
|
// Datetime is at least one year ago.
|
||||||
|
if (years === 1 && pageData.DATETIMESTRINGS['relativetime.1year']) {
|
||||||
|
// Datetime is one year ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.1year'];
|
||||||
|
} else if (years === 2 && pageData.DATETIMESTRINGS['relativetime.2years']) {
|
||||||
|
// Datetime is two year ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.2years'];
|
||||||
|
} else {
|
||||||
|
// Datetime is more than a year ago.
|
||||||
|
object.textContent = GetPluralizedStringOrFallback('relativetime.years', years, 'year');
|
||||||
|
}
|
||||||
|
return ONE_DAY;
|
||||||
|
}
|
||||||
|
|
||||||
|
const months = Math.floor(nowJS.diff(thenJS, 'month'));
|
||||||
|
if (months >= 1) {
|
||||||
|
// Datetime is at least one month but less than a year ago.
|
||||||
|
if (months === 1 && pageData.DATETIMESTRINGS['relativetime.1month']) {
|
||||||
|
// Datetime is one month ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.1month'];
|
||||||
|
} else if (months === 2 && pageData.DATETIMESTRINGS['relativetime.2months']) {
|
||||||
|
// Datetime is two months ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.2months'];
|
||||||
|
} else {
|
||||||
|
// Datetime is several months ago (but less than a year).
|
||||||
|
object.textContent = GetPluralizedStringOrFallback('relativetime.months', months, 'month');
|
||||||
|
}
|
||||||
|
return ONE_DAY;
|
||||||
|
}
|
||||||
|
|
||||||
|
const weeks = Math.floor(nowJS.diff(thenJS, 'week'));
|
||||||
|
if (weeks >= 1) {
|
||||||
|
// Datetime is at least one week but less than a month ago.
|
||||||
|
if (weeks === 1 && pageData.DATETIMESTRINGS['relativetime.1week']) {
|
||||||
|
// Datetime is one week ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.1week'];
|
||||||
|
} else if (weeks === 2 && pageData.DATETIMESTRINGS['relativetime.2weeks']) {
|
||||||
|
// Datetime is two week ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.2weeks'];
|
||||||
|
} else {
|
||||||
|
// Datetime is several weeks ago (but less than a month).
|
||||||
|
object.textContent = GetPluralizedStringOrFallback('relativetime.weeks', weeks, 'week');
|
||||||
|
}
|
||||||
|
return ONE_DAY;
|
||||||
|
}
|
||||||
|
|
||||||
|
const days = Math.floor(nowJS.diff(thenJS, 'day'));
|
||||||
|
if (days >= 1) {
|
||||||
|
if (days === 1 && pageData.DATETIMESTRINGS['relativetime.1day']) {
|
||||||
|
// Datetime is one day ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.1day'];
|
||||||
|
} else if (days === 2 && pageData.DATETIMESTRINGS['relativetime.2days']) {
|
||||||
|
// Datetime is two days ago.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS['relativetime.2days'];
|
||||||
|
} else {
|
||||||
|
// Datetime is several days but less than a week ago.
|
||||||
|
object.textContent = GetPluralizedStringOrFallback('relativetime.days', days, 'day');
|
||||||
|
}
|
||||||
|
return ONE_DAY;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hours = Math.floor(nowJS.diff(thenJS, 'hour'));
|
||||||
|
if (hours >= 1) {
|
||||||
|
// Datetime is one or more hours but less than a day ago.
|
||||||
|
object.textContent = GetPluralizedStringOrFallback('relativetime.hours', hours, 'hour');
|
||||||
|
return ONE_HOUR;
|
||||||
|
}
|
||||||
|
|
||||||
|
const minutes = Math.floor(nowJS.diff(thenJS, 'minute'));
|
||||||
|
if (minutes >= 1) {
|
||||||
|
// Datetime is one or more minutes but less than an hour ago.
|
||||||
|
object.textContent = GetPluralizedStringOrFallback('relativetime.mins', minutes, 'minute');
|
||||||
|
return ONE_MINUTE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Datetime is very recent.
|
||||||
|
object.textContent = pageData.DATETIMESTRINGS.NOW;
|
||||||
|
return HALF_MINUTE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Update the displayed text of one relative-time DOM element with its human-readable, localized relative time string. */
|
||||||
|
function UpdateRelativeTime(object) {
|
||||||
|
const next = DoUpdateRelativeTime(object);
|
||||||
|
if (next !== null) setTimeout(() => { UpdateRelativeTime(object) }, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Update the displayed text of all relative-time DOM elements with their respective human-readable, localized relative time string. */
|
||||||
|
function UpdateAllRelativeTimes() {
|
||||||
|
for (const object of document.querySelectorAll('relative-time')) UpdateRelativeTime(object);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', UpdateAllRelativeTimes);
|
212
web_src/js/webcomponents/relative-time.test.js
Normal file
212
web_src/js/webcomponents/relative-time.test.js
Normal file
|
@ -0,0 +1,212 @@
|
||||||
|
import {DoUpdateRelativeTime, HALF_MINUTE, ONE_MINUTE, ONE_HOUR, ONE_DAY} from './relative-time.js';
|
||||||
|
|
||||||
|
test('CalculateRelativeTimes', () => {
|
||||||
|
window.config.pageData.PLURAL_RULE_LANG = 0;
|
||||||
|
window.config.pageData.DATETIMESTRINGS = {
|
||||||
|
'FUTURE': 'in future',
|
||||||
|
'NOW': 'now',
|
||||||
|
'relativetime.1day': 'yesterday',
|
||||||
|
'relativetime.1week': 'last week',
|
||||||
|
'relativetime.1month': 'last month',
|
||||||
|
'relativetime.1year': 'last year',
|
||||||
|
'relativetime.2days': 'two days ago',
|
||||||
|
'relativetime.2weeks': 'two weeks ago',
|
||||||
|
'relativetime.2months': 'two months ago',
|
||||||
|
'relativetime.2years': 'two years ago',
|
||||||
|
};
|
||||||
|
window.config.pageData.PLURALSTRINGS_LANG = {
|
||||||
|
'relativetime.mins': ['%d minute ago', '%d minutes ago'],
|
||||||
|
'relativetime.hours': ['%d hour ago', '%d hours ago'],
|
||||||
|
'relativetime.days': ['%d day ago', '%d days ago'],
|
||||||
|
'relativetime.weeks': ['%d week ago', '%d weeks ago'],
|
||||||
|
'relativetime.months': ['%d month ago', '%d months ago'],
|
||||||
|
'relativetime.years': ['%d year ago', '%d years ago'],
|
||||||
|
};
|
||||||
|
const mock = document.createElement('relative-time');
|
||||||
|
|
||||||
|
const now = Date.parse('2024-10-27T04:05:30+01:00'); // One hour after DST switchover, CET.
|
||||||
|
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(null);
|
||||||
|
expect(mock.textContent).toEqual('');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:06:40+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(70000);
|
||||||
|
expect(mock.textContent).toEqual('in future');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:05:10+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(HALF_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('now');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:04:30+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('1 minute ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:04:00+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('1 minute ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:03:20+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('2 minutes ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:00:00+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('5 minutes ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T03:59:30+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('6 minutes ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T03:01:00+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('1 hour ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('4 hours ago'); // This tests DST switchover
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T00:01:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('5 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-26T22:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('7 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-26T05:08:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('23 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-26T04:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('yesterday');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-25T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('two days ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-21T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('6 days ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-20T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('last week');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-14T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('last week');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-13T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('two weeks ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-06T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('3 weeks ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-09-25T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('last month');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-08-30T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('last month');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-07-30T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('two months ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-05-30T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('4 months ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-03-01T01:00:00+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('7 months ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-02-29T01:00:00+01:00'); // Leap day handling
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('7 months ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-02-27T01:00:00-03:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('7 months ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-02-27T01:00:00+01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('8 months ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2023-11-15T01:00:00+03:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('11 months ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2023-10-20T01:00:00+08:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('last year');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2022-10-30T01:00:00-05:30');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('last year');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2022-10-20T01:00:00+10:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('two years ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2021-10-20T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('3 years ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2014-10-20T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_DAY);
|
||||||
|
expect(mock.textContent).toEqual('10 years ago');
|
||||||
|
|
||||||
|
// Timezone tests
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T01:05:30-05:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(3 * ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('in future');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T05:05:25+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(HALF_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('now');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T05:04:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('1 minute ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T05:02:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('3 minutes ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:06:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_MINUTE);
|
||||||
|
expect(mock.textContent).toEqual('59 minutes ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T04:05:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('1 hour ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T01:00:00+02:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('4 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T01:00:00+04:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('6 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T01:00:00+10:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('12 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-27T01:00:00Z');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('2 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-26T15:00:00-01:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('11 hours ago');
|
||||||
|
|
||||||
|
mock.setAttribute('datetime', '2024-10-25T19:00:00-11:00');
|
||||||
|
expect(DoUpdateRelativeTime(mock, now)).toEqual(ONE_HOUR);
|
||||||
|
expect(mock.textContent).toEqual('21 hours ago');
|
||||||
|
});
|
|
@ -80,12 +80,13 @@ if ('ENABLE_SOURCEMAP' in env) {
|
||||||
// define which web components we use for Vue to not interpret them as Vue components
|
// define which web components we use for Vue to not interpret them as Vue components
|
||||||
const webComponents = new Set([
|
const webComponents = new Set([
|
||||||
// our own, in web_src/js/webcomponents
|
// our own, in web_src/js/webcomponents
|
||||||
|
'i18n',
|
||||||
'overflow-menu',
|
'overflow-menu',
|
||||||
'origin-url',
|
'origin-url',
|
||||||
'absolute-date',
|
'absolute-date',
|
||||||
|
'relative-time',
|
||||||
// from dependencies
|
// from dependencies
|
||||||
'markdown-toolbar',
|
'markdown-toolbar',
|
||||||
'relative-time',
|
|
||||||
'text-expander',
|
'text-expander',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue