aboutsummaryrefslogtreecommitdiffstats
path: root/src/Lang.hx
blob: 597e4d97b8b8c74cb91938e740fa9de4e05a50b7 (plain) (blame)
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
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 langs:Map<String, LangMap> = [];
	static var ids = ["en", "ru"];
	#if (js && !nodejs)
	static var lang = js.Browser.navigator.language.substr(0, 2).toLowerCase();
	#end

	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 {
		#if (js && !nodejs)
		// Filter unused languages
		ids = ids.filter(id -> id == lang || id == "en");
		#end
		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 ?? key;
	}
	#else
	public static function get(key:String):String {
		if (langs[lang] == null) lang = "en";
		final text = langs[lang][key];
		return text ?? key;
	}
	#end
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage