From 07d1955cefc093ffb12002902ed45e963030746e Mon Sep 17 00:00:00 2001 From: RblSb Date: Thu, 13 Feb 2020 16:28:18 +0300 Subject: Initial commit --- src/Lang.hx | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/Lang.hx (limited to 'src/Lang.hx') 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; + +class Lang { + + static final ids = ["en", "ru"]; + static final langs:Map = []; + + 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 + +} -- cgit v1.2.3