All files / i18n/src translator.js

74.68% Statements 59/79
68.65% Branches 46/67
65% Functions 13/20
75.64% Lines 59/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283                            33x                     33x 33x 33x                   111x 101x     111x 111x 111x             245x   245x 578x 134x   444x       245x                 10x 3x 3x   7x                   4x                       40x     40x     40x         40x 2x     2x       38x 12x       38x 38x                   42x 42x   42x 42x   42x 50x 47x   3x       39x               12x 4x       8x 8x 8x   8x 8x                                   38x 38x   38x 21x 21x     38x                     2x 2x                                     2x                 1x 1x   1x                                           33x                                                          
/**
 * Coherent.js Translator
 * 
 * Handles translation of strings with interpolation and pluralization
 * 
 * @module i18n/translator
 */
 
/**
 * Translator
 * Manages translations and locale switching
 */
export class Translator {
  constructor(options = {}) {
    this.options = {
      defaultLocale: 'en',
      fallbackLocale: 'en',
      missingKeyHandler: null,
      interpolation: {
        prefix: '{{',
        suffix: '}}'
      },
      ...options
    };
    
    this.translations = new Map();
    this.currentLocale = this.options.defaultLocale;
    this.loadedLocales = new Set();
  }
 
  /**
   * Add translations for a locale
   * 
   * @param {string} locale - Locale code (e.g., 'en', 'fr', 'es')
   * @param {Object} translations - Translation object
   */
  addTranslations(locale, translations) {
    if (!this.translations.has(locale)) {
      this.translations.set(locale, {});
    }
    
    const existing = this.translations.get(locale);
    this.translations.set(locale, this.deepMerge(existing, translations));
    this.loadedLocales.add(locale);
  }
 
  /**
   * Deep merge objects
   */
  deepMerge(target, source) {
    const result = { ...target };
    
    for (const [key, value] of Object.entries(source)) {
      if (value && typeof value === 'object' && !Array.isArray(value)) {
        result[key] = this.deepMerge(result[key] || {}, value);
      } else {
        result[key] = value;
      }
    }
    
    return result;
  }
 
  /**
   * Set current locale
   * 
   * @param {string} locale - Locale code
   */
  setLocale(locale) {
    if (!this.loadedLocales.has(locale)) {
      console.warn(`Locale ${locale} not loaded, using fallback`);
      this.currentLocale = this.options.fallbackLocale;
    } else {
      this.currentLocale = locale;
    }
  }
 
  /**
   * Get current locale
   * 
   * @returns {string} Current locale code
   */
  getLocale() {
    return this.currentLocale;
  }
 
  /**
   * Translate a key
   * 
   * @param {string} key - Translation key (supports dot notation)
   * @param {Object} [params] - Interpolation parameters
   * @param {string} [locale] - Override locale
   * @returns {string} Translated string
   */
  t(key, params = {}, locale = null) {
    const targetLocale = locale || this.currentLocale;
    
    // Get translation
    let translation = this.getTranslation(key, targetLocale);
    
    // Fallback to default locale
    Iif (translation === null && targetLocale !== this.options.fallbackLocale) {
      translation = this.getTranslation(key, this.options.fallbackLocale);
    }
    
    // Handle missing translation
    if (translation === null) {
      Iif (this.options.missingKeyHandler) {
        return this.options.missingKeyHandler(key, targetLocale);
      }
      return key;
    }
    
    // Handle pluralization
    if (typeof translation === 'object' && params.count !== undefined) {
      translation = this.selectPlural(translation, params.count, targetLocale);
    }
    
    // Interpolate parameters
    Eif (typeof translation === 'string') {
      return this.interpolate(translation, params);
    }
    
    return String(translation);
  }
 
  /**
   * Get translation from nested object
   */
  getTranslation(key, locale) {
    const translations = this.translations.get(locale);
    Iif (!translations) return null;
    
    const keys = key.split('.');
    let value = translations;
    
    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        return null;
      }
    }
    
    return value;
  }
 
  /**
   * Select plural form
   */
  selectPlural(pluralObject, count, locale) {
    // Check for explicit zero first (takes precedence over Intl rules)
    if (count === 0 && pluralObject.zero) {
      return pluralObject.zero;
    }
    
    // Use Intl.PluralRules for locale-specific pluralization
    Eif (typeof Intl !== 'undefined' && Intl.PluralRules) {
      const rules = new Intl.PluralRules(locale);
      const rule = rules.select(count);
      
      Eif (pluralObject[rule]) {
        return pluralObject[rule];
      }
    }
    
    // Fallback to simple rules
    if (count === 1 && pluralObject.one) {
      return pluralObject.one;
    } else if (pluralObject.other) {
      return pluralObject.other;
    }
    
    return pluralObject.one || pluralObject.other || '';
  }
 
  /**
   * Interpolate parameters into string
   */
  interpolate(str, params) {
    const { prefix, suffix } = this.options.interpolation;
    let result = str;
    
    for (const [key, value] of Object.entries(params)) {
      const placeholder = `${prefix}${key}${suffix}`;
      result = result.replace(new RegExp(placeholder, 'g'), String(value));
    }
    
    return result;
  }
 
  /**
   * Check if translation exists
   * 
   * @param {string} key - Translation key
   * @param {string} [locale] - Locale to check
   * @returns {boolean} True if translation exists
   */
  has(key, locale = null) {
    const targetLocale = locale || this.currentLocale;
    return this.getTranslation(key, targetLocale) !== null;
  }
 
  /**
   * Get all translations for current locale
   * 
   * @returns {Object} All translations
   */
  getTranslations(locale = null) {
    const targetLocale = locale || this.currentLocale;
    return this.translations.get(targetLocale) || {};
  }
 
  /**
   * Get all loaded locales
   * 
   * @returns {Array<string>} Array of locale codes
   */
  getLoadedLocales() {
    return Array.from(this.loadedLocales);
  }
 
  /**
   * Remove translations for a locale
   * 
   * @param {string} locale - Locale code
   */
  removeLocale(locale) {
    this.translations.delete(locale);
    this.loadedLocales.delete(locale);
    
    Iif (this.currentLocale === locale) {
      this.currentLocale = this.options.defaultLocale;
    }
  }
 
  /**
   * Clear all translations
   */
  clear() {
    this.translations.clear();
    this.loadedLocales.clear();
    this.currentLocale = this.options.defaultLocale;
  }
}
 
/**
 * Create a translator instance
 * 
 * @param {Object} [options] - Translator options
 * @returns {Translator} Translator instance
 */
export function createTranslator(options = {}) {
  return new Translator(options);
}
 
/**
 * Create a scoped translator
 * Automatically prefixes all keys with a namespace
 * 
 * @param {Translator} translator - Base translator
 * @param {string} namespace - Namespace prefix
 * @returns {Object} Scoped translator
 */
export function createScopedTranslator(translator, namespace) {
  return {
    t: (key, params, locale) => {
      return translator.t(`${namespace}.${key}`, params, locale);
    },
    has: (key, locale) => {
      return translator.has(`${namespace}.${key}`, locale);
    },
    getLocale: () => translator.getLocale(),
    setLocale: (locale) => translator.setLocale(locale)
  };
}
 
export default {
  Translator,
  createTranslator,
  createScopedTranslator
};