translation.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { insertValues } from "./misc.js";
  2. import type { Stringifiable } from "./types.js";
  3. /** Trans rights! 🏳️‍⚧️ */
  4. const trans: Record<string, Record<string, string>> = {};
  5. let curLang: string;
  6. /**
  7. * Returns the translated text for the specified key in the current language set by {@linkcode tr.setLanguage()}
  8. * If the key is not found in the previously registered translation, the key itself is returned.
  9. *
  10. * ⚠️ 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.
  11. * @param key Key of the translation to return
  12. * @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
  13. */
  14. function tr(key: string, ...args: Stringifiable[]): string {
  15. if(!curLang)
  16. return key;
  17. const trText = trans[curLang]?.[key];
  18. if(!trText)
  19. return key;
  20. if(args.length > 0 && trText.match(/%\d/)) {
  21. return insertValues(trText, ...args);
  22. }
  23. return trText;
  24. }
  25. tr.addLanguage = (language: string, translations: Record<string, string>): void => {
  26. trans[language] = translations;
  27. };
  28. tr.setLanguage = (language: string): void => {
  29. curLang = language;
  30. };
  31. tr.getLanguage = (): string => {
  32. return curLang;
  33. };
  34. export { tr };