summaryrefslogtreecommitdiff
path: root/packages/sw/src/scripts/i18n.ts
blob: 77b955dbe837ef3c20ff332def463713702a115d (plain)
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
/*
 * SPDX-FileCopyrightText: syuilo and misskey-project
 * SPDX-License-Identifier: AGPL-3.0-only
 */

export type Locale = { [key: string]: string | Locale };

export class I18n<T extends Locale = Locale> {
	public ts: T;

	constructor(locale: T) {
		this.ts = locale;

		//#region BIND
		this.t = this.t.bind(this);
		//#endregion
	}

	// string にしているのは、ドット区切りでのパス指定を許可するため
	// なるべくこのメソッド使うよりもlocale直接参照の方がvueのキャッシュ効いてパフォーマンスが良いかも
	public t(key: string, args?: Record<string, string>): string {
		try {
			let str = key.split('.').reduce<Locale | Locale[keyof Locale]>((o, i) => o[i], this.ts);
			if (typeof str !== 'string') throw new Error();

			if (args) {
				for (const [k, v] of Object.entries(args)) {
					str = str.replace(`{${k}}`, v);
				}
			}
			return str;
		} catch (err) {
			console.warn(`missing localization '${key}'`);
			return key;
		}
	}
}