UNPKG

kawkab-frontend

Version:

Kawkab frontend is a frontend library for the Kawkab framework

95 lines (94 loc) 3.23 kB
import { getI18nInstance, getCurrentLanguage as getI18nCurrentLanguage, translate as i18nTranslate } from './i18n'; /** * Translator class for use outside React components */ export class Translator { i18n; constructor() { this.i18n = getI18nInstance(); } /** * Translate a specific text - safe version with SSR support * @param key Translation key * @param fallback Fallback text if translation not found * @param options Additional translation options * @returns Translated text */ translate(key, fallback, options) { // Use the enhanced i18n translate function that supports SSR return i18nTranslate(key, fallback, options); } /** * Shortcut for the translate function * @param key Translation key * @param fallback Fallback text if translation not found * @param options Additional translation options * @returns Translated text */ t(key, fallback, options) { return this.translate(key, fallback, options); } /** * Change the language * @param lng Language code * @returns Promise */ changeLanguage(lng) { // SSR environment - just resolve if (typeof window === 'undefined') { return Promise.resolve(); } // Browser environment if (!this.i18n.isInitialized) { return Promise.resolve(); } try { return this.i18n.changeLanguage(lng); } catch (error) { return Promise.resolve(); } } /** * Get the current language * @returns Current language code */ getCurrentLanguage() { // Use the enhanced i18n getCurrentLanguage function that supports SSR return getI18nCurrentLanguage(); } /** * Check the language direction * @param language Language code * @returns Language direction */ getLanguageDirection(language) { const rtlLanguages = ['ar', 'arc', 'ckb', 'dv', 'fa', 'he', 'ps', 'ur', 'yi']; return rtlLanguages.includes(language.split('-')[0]) ? 'rtl' : 'ltr'; } /** * Check if the current language is RTL * @returns true if the language is RTL */ isRTL() { // Safe for SSR - uses getCurrentLanguage which handles SSR return this.getLanguageDirection(this.getCurrentLanguage()) === 'rtl'; } /** * Check if the current language is LTR * @returns true if the language is LTR */ isLTR() { // Safe for SSR - uses getCurrentLanguage which handles SSR return this.getLanguageDirection(this.getCurrentLanguage()) === 'ltr'; } } // Create a single instance for general use export const translator = new Translator(); // Export functions individually for direct use export const t = translator.t.bind(translator); export const changeLanguage = translator.changeLanguage.bind(translator); export const getCurrentLanguage = translator.getCurrentLanguage.bind(translator); export const getLanguageDirection = translator.getLanguageDirection.bind(translator); export const isRTL = translator.isRTL.bind(translator); export const isLTR = translator.isLTR.bind(translator);