@jay-js/system
Version:
A powerful and flexible TypeScript library for UI, state management, lazy loading, routing and managing draggable elements in modern web applications.
64 lines • 2.16 kB
JavaScript
import { i18nOptions, i18nState } from "./configuration.js";
/**
* Function for accessing internationalized strings with type safety
*
* @template T - The type of the translation object (derived from translation files)
* @returns A translation function that accepts a key and optional data for variable substitution
*
* @example
* // With flat keys (default approach)
* type Translations = {
* 'Hello': string;
* 'Welcome, {{name}}!': string;
* 'You have {{count}} messages': string;
* };
*
* const t = getI18n<Translations>();
*
* // Get a translation
* const hello = t('Hello');
*
* // With variable substitution
* const welcome = t('Welcome, {{name}}!', { name: 'User' });
* const messages = t('You have {{count}} messages', { count: 5 });
*
* @example
* // With nested keys (requires nestedKeys: true in options)
* type NestedTranslations = {
* greetings: {
* hello: string;
* welcome: string;
* }
* };
*
* const t = getI18n<NestedTranslations>();
* const hello = t('greetings.hello');
*/
export function getI18n() {
return (path, data, options) => {
let result = i18nState.get().language.data;
if (!result) {
return (options === null || options === void 0 ? void 0 : options.default) || path;
}
if (!i18nOptions.nestedKeys) {
let translation = result[path] || (options === null || options === void 0 ? void 0 : options.default) || path;
if (data) {
translation = String(translation).replace(/{{(.*?)}}/g, (match, p1) => {
return data[p1.trim()] || match;
});
}
return translation;
}
const pathArray = path.split(".");
for (const key of pathArray) {
result = result[key] || (options === null || options === void 0 ? void 0 : options.default) || key;
if (data) {
result = String(result).replace(/{{(.*?)}}/g, (match, p1) => {
return data[p1.trim()] || match;
});
}
}
return result;
};
}
//# sourceMappingURL=get-i18n.js.map