translation.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { Stringifiable, insertValues } from "./misc";
  2. /** Trans rights! 🏳️‍⚧️ */
  3. const trans: Record<string, Record<string, string>> = {};
  4. let curLang: string;
  5. /**
  6. * Returns the translated text for the specified key in the current language set by {@linkcode tr.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 {@linkcode tr.addLanguage()} and set it as active with {@linkcode 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(!curLang)
  15. return key;
  16. const trText = trans[curLang]?.[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. curLang = language;
  29. };
  30. tr.getLanguage = () => {
  31. return curLang;
  32. };
  33. export { tr };