@@ -15,19 +15,51 @@ use std::io::prelude::*;
15
15
use std:: path:: Path ;
16
16
17
17
use fluent_bundle:: { FluentBundle , FluentResource , FluentValue } ;
18
+ use fluent_locale:: negotiate_languages;
18
19
19
20
lazy_static ! {
20
21
static ref RESOURCES : HashMap <String , Vec <FluentResource >> = build_resources( ) ;
21
22
static ref BUNDLES : HashMap <String , FluentBundle <' static >> = build_bundles( ) ;
22
23
}
23
24
25
+ pub struct Fallback < A : AsRef < str > > {
26
+ default : Option < & ' static str > ,
27
+ availables : Vec < A > ,
28
+ }
29
+
30
+ impl < A : AsRef < str > > Fallback < A > {
31
+ pub fn new ( available_locales : Vec < A > ) -> Self {
32
+ Self {
33
+ default : Some ( "en-US" ) ,
34
+ availables : available_locales,
35
+ }
36
+ }
37
+
38
+ pub fn order < ' t , T : AsRef < str > > ( & ' t self , targets : & ' t [ T ] ) -> Vec < & ' t str > {
39
+ negotiate_languages (
40
+ targets,
41
+ & self . availables ,
42
+ self . default ,
43
+ & fluent_locale:: NegotiationStrategy :: Filtering ,
44
+ )
45
+ }
46
+ }
47
+
24
48
pub struct I18NHelper {
25
49
bundles : & ' static HashMap < String , FluentBundle < ' static > > ,
50
+ fallback : Fallback < String > ,
26
51
}
27
52
28
53
impl I18NHelper {
29
54
pub fn new ( ) -> Self {
30
- Self { bundles : & * BUNDLES }
55
+ let mut availables: Vec < String > = Vec :: new ( ) ;
56
+ for key in RESOURCES . keys ( ) {
57
+ availables. push ( key. clone ( ) ) ;
58
+ }
59
+ Self {
60
+ bundles : & * BUNDLES ,
61
+ fallback : Fallback :: new ( availables) ,
62
+ }
31
63
}
32
64
33
65
pub fn lookup (
@@ -58,17 +90,12 @@ impl I18NHelper {
58
90
text_id : & str ,
59
91
args : Option < & HashMap < & str , FluentValue > > ,
60
92
) -> String {
61
- if let Some ( val) = self . lookup ( lang, text_id, args) {
62
- val
63
- } else if lang != "en-US" {
64
- if let Some ( val) = self . lookup ( "en-US" , text_id, args) {
65
- val
66
- } else {
67
- format ! ( "Unknown localization {}" , text_id)
93
+ for l in self . fallback . order ( & [ lang] ) {
94
+ if let Some ( val) = self . lookup ( l, text_id, args) {
95
+ return val;
68
96
}
69
- } else {
70
- format ! ( "Unknown localization {}" , text_id)
71
97
}
98
+ format ! ( "Unknown localization {}" , text_id)
72
99
}
73
100
}
74
101
0 commit comments