i18n.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import fallbackLangData from "./locales/en.json";
  2. import percentages from "./locales/percentages.json";
  3. import { jotaiScope, jotaiStore } from "./jotai";
  4. import { atom, useAtomValue } from "jotai";
  5. import { NestedKeyOf } from "./utility-types";
  6. const COMPLETION_THRESHOLD = 85;
  7. export interface Language {
  8. code: string;
  9. label: string;
  10. rtl?: boolean;
  11. }
  12. export type TranslationKeys = NestedKeyOf<typeof fallbackLangData>;
  13. export const defaultLang = { code: "en", label: "English" };
  14. export const languages: Language[] = [
  15. defaultLang,
  16. ...[
  17. { code: "ar-SA", label: "العربية", rtl: true },
  18. { code: "bg-BG", label: "Български" },
  19. { code: "ca-ES", label: "Català" },
  20. { code: "cs-CZ", label: "Česky" },
  21. { code: "de-DE", label: "Deutsch" },
  22. { code: "el-GR", label: "Ελληνικά" },
  23. { code: "es-ES", label: "Español" },
  24. { code: "eu-ES", label: "Euskara" },
  25. { code: "fa-IR", label: "فارسی", rtl: true },
  26. { code: "fi-FI", label: "Suomi" },
  27. { code: "fr-FR", label: "Français" },
  28. { code: "gl-ES", label: "Galego" },
  29. { code: "he-IL", label: "עברית", rtl: true },
  30. { code: "hi-IN", label: "हिन्दी" },
  31. { code: "hu-HU", label: "Magyar" },
  32. { code: "id-ID", label: "Bahasa Indonesia" },
  33. { code: "it-IT", label: "Italiano" },
  34. { code: "ja-JP", label: "日本語" },
  35. { code: "kab-KAB", label: "Taqbaylit" },
  36. { code: "kk-KZ", label: "Қазақ тілі" },
  37. { code: "ko-KR", label: "한국어" },
  38. { code: "ku-TR", label: "Kurdî" },
  39. { code: "lt-LT", label: "Lietuvių" },
  40. { code: "lv-LV", label: "Latviešu" },
  41. { code: "my-MM", label: "Burmese" },
  42. { code: "nb-NO", label: "Norsk bokmål" },
  43. { code: "nl-NL", label: "Nederlands" },
  44. { code: "nn-NO", label: "Norsk nynorsk" },
  45. { code: "oc-FR", label: "Occitan" },
  46. { code: "pa-IN", label: "ਪੰਜਾਬੀ" },
  47. { code: "pl-PL", label: "Polski" },
  48. { code: "pt-BR", label: "Português Brasileiro" },
  49. { code: "pt-PT", label: "Português" },
  50. { code: "ro-RO", label: "Română" },
  51. { code: "ru-RU", label: "Русский" },
  52. { code: "sk-SK", label: "Slovenčina" },
  53. { code: "sv-SE", label: "Svenska" },
  54. { code: "sl-SI", label: "Slovenščina" },
  55. { code: "tr-TR", label: "Türkçe" },
  56. { code: "uk-UA", label: "Українська" },
  57. { code: "zh-CN", label: "简体中文" },
  58. { code: "zh-TW", label: "繁體中文" },
  59. { code: "vi-VN", label: "Tiếng Việt" },
  60. { code: "mr-IN", label: "मराठी" },
  61. ]
  62. .filter(
  63. (lang) =>
  64. (percentages as Record<string, number>)[lang.code] >=
  65. COMPLETION_THRESHOLD,
  66. )
  67. .sort((left, right) => (left.label > right.label ? 1 : -1)),
  68. ];
  69. const TEST_LANG_CODE = "__test__";
  70. if (import.meta.env.DEV) {
  71. languages.unshift(
  72. { code: TEST_LANG_CODE, label: "test language" },
  73. {
  74. code: `${TEST_LANG_CODE}.rtl`,
  75. label: "\u{202a}test language (rtl)\u{202c}",
  76. rtl: true,
  77. },
  78. );
  79. }
  80. let currentLang: Language = defaultLang;
  81. let currentLangData = {};
  82. export const setLanguage = async (lang: Language) => {
  83. currentLang = lang;
  84. document.documentElement.dir = currentLang.rtl ? "rtl" : "ltr";
  85. document.documentElement.lang = currentLang.code;
  86. if (lang.code.startsWith(TEST_LANG_CODE)) {
  87. currentLangData = {};
  88. } else {
  89. try {
  90. currentLangData = await import(`./locales/${currentLang.code}.json`);
  91. } catch (error: any) {
  92. console.error(`Failed to load language ${lang.code}:`, error.message);
  93. currentLangData = fallbackLangData;
  94. }
  95. }
  96. jotaiStore.set(editorLangCodeAtom, lang.code);
  97. };
  98. export const getLanguage = () => currentLang;
  99. const findPartsForData = (data: any, parts: string[]) => {
  100. for (let index = 0; index < parts.length; ++index) {
  101. const part = parts[index];
  102. if (data[part] === undefined) {
  103. return undefined;
  104. }
  105. data = data[part];
  106. }
  107. if (typeof data !== "string") {
  108. return undefined;
  109. }
  110. return data;
  111. };
  112. export const t = (
  113. path: NestedKeyOf<typeof fallbackLangData>,
  114. replacement?: { [key: string]: string | number } | null,
  115. fallback?: string,
  116. ) => {
  117. if (currentLang.code.startsWith(TEST_LANG_CODE)) {
  118. const name = replacement
  119. ? `${path}(${JSON.stringify(replacement).slice(1, -1)})`
  120. : path;
  121. return `\u{202a}[[${name}]]\u{202c}`;
  122. }
  123. const parts = path.split(".");
  124. let translation =
  125. findPartsForData(currentLangData, parts) ||
  126. findPartsForData(fallbackLangData, parts) ||
  127. fallback;
  128. if (translation === undefined) {
  129. const errorMessage = `Can't find translation for ${path}`;
  130. // in production, don't blow up the app on a missing translation key
  131. if (import.meta.env.PROD) {
  132. console.warn(errorMessage);
  133. return "";
  134. }
  135. throw new Error(errorMessage);
  136. }
  137. if (replacement) {
  138. for (const key in replacement) {
  139. translation = translation.replace(`{{${key}}}`, String(replacement[key]));
  140. }
  141. }
  142. return translation;
  143. };
  144. /** @private atom used solely to rerender components using `useI18n` hook */
  145. const editorLangCodeAtom = atom(defaultLang.code);
  146. // Should be used in components that fall under these cases:
  147. // - component is rendered as an <Excalidraw> child
  148. // - component is rendered internally by <Excalidraw>, but the component
  149. // is memoized w/o being updated on `langCode`, `AppState`, or `UIAppState`
  150. export const useI18n = () => {
  151. const langCode = useAtomValue(editorLangCodeAtom, jotaiScope);
  152. return { t, langCode };
  153. };