Files
ox_lib/package/shared/resource/locale/index.ts

91 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-11-07 18:51:51 +01:00
import { cache } from '../cache/index';
import { printf } from 'fast-printf';
2024-01-14 10:05:53 +11:00
const dict: Record<string, string> = {};
2023-11-07 18:51:51 +01:00
function flattenDict(source: Record<string, any>, target: Record<string, string>, prefix?: string) {
for (const key in source) {
const fullKey = prefix ? `${prefix}.${key}` : key;
const value = source[key];
if (typeof value === 'object') flattenDict(value, target, fullKey);
else target[fullKey] = String(value);
}
return target;
}
2024-01-14 10:05:53 +11:00
export const locale = (str: string, ...args: any[]) => {
2023-11-07 18:51:51 +01:00
const lstr = dict[str];
if (!lstr) return str;
if (lstr) {
if (typeof lstr !== 'string') return lstr;
if (args.length > 0) {
return printf(lstr, ...args);
}
return lstr;
}
return str;
2023-11-07 18:51:51 +01:00
};
export const getLocales = () => dict;
export function getLocale(resource: string, key: string) {
let locale = dict[key];
if (locale) console.warn(`overwritin existing locale '${key} (${locale})`);
locale = exports[resource].getLocale(key);
dict[key] = locale;
if (!locale) console.warn(`no locale exists with key '${key} in resource '${resource}`);
return locale;
}
function loadLocale(key: string): typeof dict {
const data = LoadResourceFile(cache.resource, `locales/${key}.json`);
2023-11-07 18:51:51 +01:00
if (!data) console.warn(`could not load 'locales/${key}.json'`);
2023-11-07 18:51:51 +01:00
return JSON.parse(data) || {};
}
2023-11-07 18:51:51 +01:00
export const initLocale = (key?: string) => {
const lang = key || exports.ox_lib.getLocaleKey();
let locales = loadLocale('en');
2023-11-07 18:51:51 +01:00
if (lang !== 'en') Object.assign(locales, loadLocale(lang));
2023-11-07 18:51:51 +01:00
const flattened = flattenDict(locales, {});
for (let [k, v] of Object.entries(flattened)) {
2023-11-07 18:51:51 +01:00
if (typeof v === 'string') {
const regExp = new RegExp(/\$\{([^}]+)\}/g);
const matches = v.match(regExp);
if (matches) {
for (const match of matches) {
if (!match) break;
const variable = match.substring(2, match.length - 1) as keyof typeof locales;
let locale: string = flattened[variable];
2023-11-07 18:51:51 +01:00
if (locale) {
v = v.replace(match, locale);
}
}
}
}
dict[k] = v;
}
};
initLocale();