-
-
Notifications
You must be signed in to change notification settings - Fork 315
/
localization.dart
216 lines (182 loc) · 5.97 KB
/
localization.dart
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/widgets.dart';
import 'plural_rules.dart';
import 'translations.dart';
class Localization {
Translations? _translations, _fallbackTranslations;
late Locale _locale;
final RegExp _replaceArgRegex = RegExp('{}');
final RegExp _linkKeyMatcher =
RegExp(r'(?:@(?:\.[a-z]+)?:(?:[\w\-_|.]+|\([\w\-_|.]+\)))');
final RegExp _linkKeyPrefixMatcher = RegExp(r'^@(?:\.([a-z]+))?:');
final RegExp _bracketsMatcher = RegExp('[()]');
final _modifiers = <String, String Function(String?)>{
'upper': (String? val) => val!.toUpperCase(),
'lower': (String? val) => val!.toLowerCase(),
'capitalize': (String? val) => '${val![0].toUpperCase()}${val.substring(1)}'
};
Localization();
static Localization? _instance;
static Localization get instance => _instance ?? (_instance = Localization());
static Localization? of(BuildContext context) =>
Localizations.of<Localization>(context, Localization);
static bool load(
Locale locale, {
Translations? translations,
Translations? fallbackTranslations,
}) {
instance._locale = locale;
instance._translations = translations;
instance._fallbackTranslations = fallbackTranslations;
return translations == null ? false : true;
}
String tr(
String key, {
List<String>? args,
Map<String, String>? namedArgs,
String? gender,
}) {
late String res;
if (gender != null) {
res = _gender(key, gender: gender);
} else {
res = _resolve(key);
}
res = _replaceLinks(res);
res = _replaceNamedArgs(res, namedArgs);
return _replaceArgs(res, args);
}
String _replaceLinks(String res, {bool logging = true}) {
// TODO: add recursion detection and a resolve stack.
final matches = _linkKeyMatcher.allMatches(res);
var result = res;
for (final match in matches) {
final link = match[0]!;
final linkPrefixMatches = _linkKeyPrefixMatcher.allMatches(link);
final linkPrefix = linkPrefixMatches.first[0]!;
final formatterName = linkPrefixMatches.first[1];
// Remove the leading @:, @.case: and the brackets
final linkPlaceholder =
link.replaceAll(linkPrefix, '').replaceAll(_bracketsMatcher, '');
var translated = _resolve(linkPlaceholder);
if (formatterName != null) {
if (_modifiers.containsKey(formatterName)) {
translated = _modifiers[formatterName]!(translated);
} else {
if (logging) {
EasyLocalization.logger.warning(
'Undefined modifier $formatterName, available modifiers: ${_modifiers.keys.toString()}');
}
}
}
result =
translated.isEmpty ? result : result.replaceAll(link, translated);
}
return result;
}
String _replaceArgs(String res, List<String>? args) {
if (args == null || args.isEmpty) return res;
for (var str in args) {
res = res.replaceFirst(_replaceArgRegex, str);
}
return res;
}
String _replaceNamedArgs(String res, Map<String, String>? args) {
if (args == null || args.isEmpty) return res;
args.forEach((String key, String value) =>
res = res.replaceAll(RegExp('{$key}'), value));
return res;
}
static PluralRule? _pluralRule(String? locale, num howMany) {
startRuleEvaluation(howMany);
return pluralRules[locale];
}
static PluralCase _pluralCaseFallback(num value) {
switch (value) {
case 0:
return PluralCase.ZERO;
case 1:
return PluralCase.ONE;
case 2:
return PluralCase.TWO;
default:
return PluralCase.OTHER;
}
}
String plural(
String key,
num value, {
List<String>? args,
Map<String, String>? namedArgs,
String? name,
NumberFormat? format,
}) {
late String res;
final pluralRule = _pluralRule(_locale.languageCode, value);
final pluralCase = pluralRule != null ? pluralRule() : _pluralCaseFallback(value);
switch (pluralCase) {
case PluralCase.ZERO:
res = _resolvePlural(key, 'zero');
break;
case PluralCase.ONE:
res = _resolvePlural(key, 'one');
break;
case PluralCase.TWO:
res = _resolvePlural(key, 'two');
break;
case PluralCase.FEW:
res = _resolvePlural(key, 'few');
break;
case PluralCase.MANY:
res = _resolvePlural(key, 'many');
break;
case PluralCase.OTHER:
res = _resolvePlural(key, 'other');
break;
default:
throw ArgumentError.value(value, 'howMany', 'Invalid plural argument');
}
final formattedValue = format == null ? '$value' : format.format(value);
if (name != null) {
namedArgs = {...?namedArgs, name: formattedValue};
}
res = _replaceNamedArgs(res, namedArgs);
return _replaceArgs(res, args ?? [formattedValue]);
}
String _gender(String key, {required String gender}) {
return _resolve('$key.$gender');
}
String _resolvePlural(String key, String subKey) {
if (subKey == 'other') return _resolve('$key.other');
final tag = '$key.$subKey';
var resource = _resolve(tag, logging: false, fallback: _fallbackTranslations != null);
if (resource == tag) {
resource = _resolve('$key.other');
}
return resource;
}
String _resolve(String key, {bool logging = true, bool fallback = true}) {
var resource = _translations?.get(key);
if (resource == null) {
if (logging) {
EasyLocalization.logger.warning('Localization key [$key] not found');
}
if (_fallbackTranslations == null || !fallback) {
return key;
} else {
resource = _fallbackTranslations?.get(key);
if (resource == null) {
if (logging) {
EasyLocalization.logger
.warning('Fallback localization key [$key] not found');
}
return key;
}
}
}
return resource;
}
bool exists(String key){
return _translations?.get(key) != null;
}
}