All files / src/lib/lang initElectronL10N.ts

85.11% Statements 40/47
80% Branches 12/15
80% Functions 4/5
86.36% Lines 38/44

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 755x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x   5x   100x   5x 2x 2x 2x     5x 2x 2x     5x   6x   6x 2x 2x 2x   2x                             2x     1x 1x     1x 1x         5x 1x 1x 1x   5x     5x  
import { app } from "electron";
import settings from "electron-settings";
import fs from "fs";
import glob from "glob";
import Path from "path";
import en from "lang/en.json";
import { LOCALE_SETTING_KEY, localesRoot } from "consts";
import { L10NLookup, setL10NData } from "shared/lib/lang/l10n";
import { getGlobalPluginsPath } from "lib/pluginManager/globalPlugins";
import mapValues from "lodash/mapValues";
 
const localesPath = `${localesRoot}/*.json`;
 
export const locales = glob
  .sync(localesPath)
  .map((path) => Path.basename(path, ".json"));
 
export const getAppLocale = () => {
  const settingsLocale = app && settings.get(LOCALE_SETTING_KEY);
  const systemLocale = app ? app.getLocale() : "en";
  return String(settingsLocale || systemLocale);
};
 
const initElectronL10N = () => {
  const appLocale = getAppLocale();
  loadLanguage(appLocale);
};
 
export const loadLanguage = (locale: string) => {
  // Reset back to en defaults before loading
  setL10NData(en);
 
  if (locale && locale !== "en") {
    try {
      const isPlugin = Path.basename(locale) === "lang.json";
      const globalPluginsPath = getGlobalPluginsPath();
 
      Iif (isPlugin) {
        const translation = JSON.parse(
          fs.readFileSync(`${globalPluginsPath}/${locale}`, "utf-8")
        ) as L10NLookup;
 
        // If localisation has debug flag set all missing values will
        // use translation keys rather than fallback to English
        Iif (translation.debug) {
          const debugLang = mapValues(en, (_value, key) => key);
          setL10NData(debugLang);
        }
 
        setL10NData(translation);
        return translation;
      } else {
        const translation = JSON.parse(
          fs.readFileSync(`${localesRoot}/${locale}.json`, "utf-8")
        ) as L10NLookup;
        setL10NData(translation);
        return translation;
      }
    } catch (e) {
      console.warn("No language pack for user setting, falling back to en");
      console.warn(
        `Add a language pack by making the file src/lang/${locale}.json`
      );
    }
  }
  if (typeof locale === "string" && locale.length === 0) {
    console.warn("Locale is set but doesn't have a value.");
    console.warn("Have you used l10n from electron before app is ready?");
    console.trace();
  }
  return {};
};
 
export default initElectronL10N;