translation.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { Stringifiable, insertValues } from "./misc";
  2. /** Trans rights! 🏳️‍⚧️ */
  3. const trans: Record<string, Record<string, string>> = {};
  4. let currentLanguage: string;
  5. /**
  6. * Returns the translated text for the specified key in the current language set by `setLanguage()`
  7. * If the key is not found in the previously registered translation, the key itself is returned.
  8. *
  9. * ⚠️ Remember to register a language with `tr.addLanguage()` and set it as active with `tr.setLanguage()` before using this function, otherwise it will always return the key itself.
  10. * @param key Key of the translation to return
  11. * @param args Optional arguments to be passed to the translated text. They will replace placeholders in the format `%n`, where `n` is the 1-indexed argument number
  12. */
  13. function tr(key: string, ...args: Stringifiable[]) {
  14. if(!currentLanguage)
  15. return key;
  16. const trText = trans[currentLanguage]?.[key];
  17. if(!trText)
  18. return key;
  19. if(args.length > 0 && trText.match(/%\d/)) {
  20. return insertValues(trText, ...args);
  21. }
  22. return trText;
  23. }
  24. tr.addLanguage = (language: string, translations: Record<string, string>) => {
  25. trans[language] = translations;
  26. };
  27. tr.setLanguage = (language: string) => {
  28. currentLanguage = language;
  29. };
  30. export { tr };