2023-07-27 07:31:52 +02:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: syuilo and other misskey contributors
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2021-02-06 10:55:53 +01:00
|
|
|
export class I18n<T extends Record<string, any>> {
|
2022-01-28 03:39:49 +01:00
|
|
|
public ts: T;
|
2021-02-06 10:55:53 +01:00
|
|
|
|
|
|
|
constructor(locale: T) {
|
2022-01-28 03:39:49 +01:00
|
|
|
this.ts = locale;
|
2021-02-06 10:55:53 +01:00
|
|
|
|
|
|
|
//#region BIND
|
|
|
|
this.t = this.t.bind(this);
|
|
|
|
//#endregion
|
|
|
|
}
|
|
|
|
|
|
|
|
// string にしているのは、ドット区切りでのパス指定を許可するため
|
|
|
|
// なるべくこのメソッド使うよりもlocale直接参照の方がvueのキャッシュ効いてパフォーマンスが良いかも
|
2022-06-21 10:55:38 +02:00
|
|
|
public t(key: string, args?: Record<string, string | number>): string {
|
2021-02-06 10:55:53 +01:00
|
|
|
try {
|
2022-01-28 03:39:49 +01:00
|
|
|
let str = key.split('.').reduce((o, i) => o[i], this.ts) as unknown as string;
|
2021-02-06 10:55:53 +01:00
|
|
|
|
|
|
|
if (args) {
|
|
|
|
for (const [k, v] of Object.entries(args)) {
|
2022-06-21 10:55:38 +02:00
|
|
|
str = str.replace(`{${k}}`, v.toString());
|
2021-02-06 10:55:53 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return str;
|
2022-01-28 03:39:49 +01:00
|
|
|
} catch (err) {
|
2021-02-13 04:28:26 +01:00
|
|
|
console.warn(`missing localization '${key}'`);
|
2021-02-06 10:55:53 +01:00
|
|
|
return key;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|