diff options
| author | RblSb <msrblsb@gmail.com> | 2020-02-13 16:28:18 +0300 |
|---|---|---|
| committer | RblSb <msrblsb@gmail.com> | 2020-02-15 19:45:40 +0300 |
| commit | 07d1955cefc093ffb12002902ed45e963030746e (patch) | |
| tree | 8833eca2dc2ef07891aa8eb66daf7ad90f2ab0ce /src/Lang.hx | |
Initial commit
Diffstat (limited to 'src/Lang.hx')
| -rw-r--r-- | src/Lang.hx | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/Lang.hx b/src/Lang.hx new file mode 100644 index 0000000..8632812 --- /dev/null +++ b/src/Lang.hx @@ -0,0 +1,62 @@ +package; + +import haxe.Json; +import haxe.io.Path; +#if (sys || nodejs) +import sys.io.File; +#else +import haxe.Http; +#end + +private typedef LangMap = Map<String, String>; + +class Lang { + + static final ids = ["en", "ru"]; + static final langs:Map<String, LangMap> = []; + + static function request(path:String, callback:(data:String)->Void):Void { + #if (sys || nodejs) + callback(File.getContent(path)); + #else + final http = new Http(path); + http.onData = callback; + http.request(); + #end + } + + public static function init(folderPath:String, ?callback:()->Void):Void { + langs.clear(); + var count = 0; + for (name in ids) { + request('$folderPath/$name.json', data -> { + final data = Json.parse(data); + final lang = new LangMap(); + for (key in Reflect.fields(data)) { + lang[key] = Reflect.field(data, key); + } + final id = Path.withoutExtension(name); + langs[id] = lang; + count++; + if (count == ids.length && callback != null) callback(); + }); + } + } + + #if (sys || nodejs) + public static function get(lang:String, ?key:String):String { + if (langs[lang] == null) lang = "en"; + final text = langs[lang][key]; + return text == null ? key : text; + } + #else + static var lang = js.Browser.navigator.language.substr(0, 2).toLowerCase(); + + public static function get(key:String):String { + if (langs[lang] == null) lang = "en"; + final text = langs[lang][key]; + return text == null ? key : text; + } + #end + +} |
