29
29
'use strict' ;
30
30
31
31
async function setupI18n ( ) {
32
+ // present it to i18next
33
+ const i18nextOptions = {
34
+ lng : 'en' ,
35
+ fallbackLng : false ,
36
+ load : 'currentOnly' ,
37
+ returnEmptyString : false
38
+ } ;
39
+ // Pre-render HTML with default language and don't wait for the network response
40
+ await i18next . init ( i18nextOptions , replaceI18nText ) ;
41
+
32
42
const languages = ( ( ) => {
33
43
const langs = new Set ( ) ;
34
44
for ( const lang of navigator . languages ) {
@@ -53,43 +63,35 @@ async function setupI18n() {
53
63
data : ( translations . length > 0 ) ? ( await translations [ 0 ] . result . value . json ( ) ) : { }
54
64
} ;
55
65
56
- // present it to i18next
57
- const i18nextOptions = {
58
- lng : translation . lang ,
59
- fallbackLng : false ,
60
- load : 'currentOnly' ,
61
- resources : {
62
- [ translation . lang ] : { translation : translation . data }
63
- } ,
64
- returnEmptyString : false
65
- } ;
66
- i18next . init ( i18nextOptions , replaceI18nText ) ;
66
+ i18next . addResources ( translation . lang , "translation" , translation . data ) ;
67
+ i18next . changeLanguage ( translation . lang , replaceI18nText ) ;
67
68
}
68
69
69
70
function replaceI18nText ( ) {
70
71
const tr = i18next . t ; // workaround for warnings from i18next-parser
71
- const re = / ^ ( \[ ( [ a - z A - Z 0 - 9 _ - ] + ) \] ) ? ( .* ) $ / ;
72
+ const re = / ^ ( \[ ( [ a - z A - Z 0 - 9 _ - ] + ) \] ) ? ( .+ ? ) ( _ ( . + ) ) ? $ / ;
72
73
73
74
for ( const element of document . querySelectorAll ( '[data-i18n]' ) ) {
74
- const i18nData = element . getAttribute ( 'data-i18n' ) ;
75
- if ( ! i18nData ) {
76
- element . textContent = tr ( element . textContent ) ;
77
- continue ;
78
- }
75
+ const translationKeys = element . getAttribute ( 'data-i18n' ) . split ( ';' ) ;
79
76
80
- const translationKeys = i18nData . split ( ';' ) ;
81
77
for ( const key of translationKeys ) {
82
78
const matches = key . match ( re ) ;
83
79
if ( matches [ 2 ] ) {
84
- element . setAttribute ( matches [ 2 ] , tr ( matches [ 3 ] ) ) ;
80
+ if ( matches [ 5 ] )
81
+ element . setAttribute ( matches [ 2 ] , tr ( matches [ 3 ] , { context : matches [ 5 ] } ) ) ;
82
+ else
83
+ element . setAttribute ( matches [ 2 ] , tr ( matches [ 3 ] ) ) ;
85
84
continue ;
86
85
}
87
86
88
- element . textContent = tr ( matches [ 3 ] ) ;
87
+ if ( matches [ 5 ] )
88
+ element . textContent = tr ( matches [ 3 ] , { context : matches [ 5 ] } ) ;
89
+ else
90
+ element . textContent = tr ( matches [ 3 ] ) ;
89
91
}
90
92
}
91
93
92
- document . documentElement . lang = i18next . language . split ( '-' ) [ 0 ] ;
94
+ document . documentElement . lang = i18next . language ;
93
95
}
94
96
95
97
function submitLoginForm ( event ) {
0 commit comments