Browse Source

feat: tr.forLang() and tr.getTranslations()

Sv443 7 months ago
parent
commit
7e8e147
4 changed files with 131 additions and 11 deletions
  1. 6 0
      .changeset/heavy-needles-buy.md
  2. 2 0
      README-summary.md
  3. 66 0
      README.md
  4. 57 11
      lib/translation.ts

+ 6 - 0
.changeset/heavy-needles-buy.md

@@ -0,0 +1,6 @@
+---
+"@sv443-network/userutils": minor
+---
+
+- Added `tr.forLang()` to get the translation for a specified language code
+- Added `tr.getTranslations()` to return the translations object for the given or currently active language

+ 2 - 0
README-summary.md

@@ -61,9 +61,11 @@ or view the documentation of previous major releases:
     - [`randomizeArray()`](https://github.com/Sv443-Network/UserUtils#randomizearray) - returns a copy of the array with its items in a random order
 - **Translation:**
     - [`tr()`](https://github.com/Sv443-Network/UserUtils#tr) - simple translation of a string to another language
+        - [`tr.forLang()`](https://github.com/Sv443-Network/UserUtils#trforlang) - specify a language besides the currently set one for the translation
     - [`tr.addLanguage()`](https://github.com/Sv443-Network/UserUtils#traddlanguage) - add a language and its translations
     - [`tr.setLanguage()`](https://github.com/Sv443-Network/UserUtils#trsetlanguage) - set the currently active language for translations
     - [`tr.getLanguage()`](https://github.com/Sv443-Network/UserUtils#trgetlanguage) - returns the currently active language
+    - [`tr.getTranslations()`](https://github.com/Sv443-Network/UserUtils#trgettranslations) - returns the translations for the given language or the currently active one
 - **Colors:**
     - [`hexToRgb()`](https://github.com/Sv443-Network/UserUtils#hextorgb) - convert a hex color string to an RGB number tuple
     - [`rgbToHex()`](https://github.com/Sv443-Network/UserUtils#rgbtohex) - convert RGB numbers to a hex color string

+ 66 - 0
README.md

@@ -63,9 +63,11 @@ View the documentation of previous major releases:
     - [`randomizeArray()`](#randomizearray) - returns a copy of the array with its items in a random order
   - [**Translation:**](#translation)
     - [`tr()`](#tr) - simple translation of a string to another language
+    - [`tr.forLang()`](#trforlang) - specify a language besides the currently set one for the translation
     - [`tr.addLanguage()`](#traddlanguage) - add a language and its translations
     - [`tr.setLanguage()`](#trsetlanguage) - set the currently active language for translations
     - [`tr.getLanguage()`](#trgetlanguage) - returns the currently active language
+    - [`tr.getTranslations()`](#trgettranslations) - returns the translations for the given language or the currently active one
   - [**Colors:**](#colors)
     - [`hexToRgb()`](#hextorgb) - convert a hex color string to an RGB number tuple
     - [`rgbToHex()`](#rgbtohex) - convert RGB numbers to a hex color string
@@ -1960,6 +1962,39 @@ console.log(tr("welcome_name", "John")); // "Willkommen, John"
 
 <br>
 
+### tr.forLang()
+Usage:  
+```ts
+tr.forLang(language: string, key: string, ...values: Stringifiable[]): string
+```  
+  
+Returns the translation of the passed key in the specified language. Otherwise behaves exactly like [`tr()`](#tr)  
+This function does not change the currently active language set by [`tr.setLanguage()`](#trsetlanguage)  
+  
+<details><summary><b>Example - click to view</b></summary>
+
+```ts
+import { tr } from "@sv443-network/userutils";
+
+tr.addLanguage("en", {
+  "welcome_name": "Welcome, %1",
+});
+
+tr.addLanguage("de", {
+  "welcome_name": "Willkommen, %1",
+});
+
+// the language is set to "en"
+tr.setLanguage("en");
+
+console.log(tr("welcome_name", "John"));               // "Welcome"
+// the language doesn't need to be changed:
+console.log(tr.forLang("de", "welcome_name", "John")); // "Willkommen, John"
+```
+</details>
+
+<br>
+
 ### tr.addLanguage()
 Usage:  
 ```ts
@@ -2080,6 +2115,37 @@ tr.getLanguage(): string | undefined
 Returns the currently active language set by [`tr.setLanguage()`](#trsetlanguage)  
 If no language has been set yet, it will return undefined.
 
+<br>
+
+### tr.getTranslations()
+Usage:  
+```ts
+tr.getTranslations(language?: string): Record<string, string> | undefined
+```  
+  
+Returns the translations of the specified language.  
+If no language is specified, it will return the translations of the currently active language set by [`tr.setLanguage()`](#trsetlanguage)  
+If no translations are found, it will return undefined.  
+  
+<details><summary><b>Example - click to view</b></summary>
+
+```ts
+import { tr } from "@sv443-network/userutils";
+
+tr.addLanguage("en", {
+  "welcome": "Welcome",
+});
+
+console.log(tr.getTranslations());     // undefined
+tr.setLanguage("en");
+console.log(tr.getTranslations());     // { "welcome": "Welcome" }
+
+console.log(tr.getTranslations("en")); // { "welcome": "Welcome" }
+
+console.log(tr.getTranslations("de")); // undefined
+```
+</details>
+
 <br><br>
 
 ## Colors:

+ 57 - 11
lib/translation.ts

@@ -5,18 +5,10 @@ import type { Stringifiable } from "./types.js";
 const trans: Record<string, Record<string, string>> = {};
 let curLang: string;
 
-/**
- * Returns the translated text for the specified key in the current language set by {@linkcode tr.setLanguage()}  
- * If the key is not found in the previously registered translation, the key itself is returned.  
- *   
- * ⚠️ 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.
- * @param key Key of the translation to return
- * @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
- */
-function tr(key: string, ...args: Stringifiable[]): string {
-  if(!curLang)
+const trLang = (language: string, key: string, ...args: Stringifiable[]): string => {
+  if(!language)
     return key;
-  const trText = trans[curLang]?.[key];
+  const trText = trans[language]?.[key];
   if(!trText)
     return key;
 
@@ -24,18 +16,72 @@ function tr(key: string, ...args: Stringifiable[]): string {
     return insertValues(trText, ...args);
   }
   return trText;
+};
+
+/**
+ * Returns the translated text for the specified key in the current language set by {@linkcode tr.setLanguage()}  
+ * Use {@linkcode tr.forLang()} to get the translation for a specific language instead of the currently set one.  
+ * If the key is not found in the currently set language, the key itself is returned.  
+ *   
+ * ⚠️ 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.
+ * @param key Key of the translation to return
+ * @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
+ */
+function tr(key: string, ...args: Stringifiable[]): string {
+  return trLang(curLang, key, ...args);
 }
 
+/**
+ * Returns the translated text for the specified key in the specified language.  
+ * If the key is not found in the specified previously registered translation, the key itself is returned.  
+ *   
+ * ⚠️ Remember to register a language with {@linkcode tr.addLanguage()} before using this function, otherwise it will always return the key itself.
+ * @param language Language to use for the translation
+ * @param key Key of the translation to return
+ * @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
+ */
+tr.forLang = trLang;
+
+/**
+ * Registers a new language with its translations.  
+ * The translations are a key-value pair where the key is the translation key and the value is the translated text.  
+ *   
+ * The translations can contain placeholders in the format `%n`, where `n` is the 1-indexed argument number.  
+ * These placeholders will be replaced by the arguments passed to the translation functions.  
+ * @param language Language code to register
+ * @param translations Translations for the specified language
+ */
 tr.addLanguage = (language: string, translations: Record<string, string>): void => {
   trans[language] = translations;
 };
 
+/**
+ * Sets the active language for the translation functions.  
+ * This language will be used by the {@linkcode tr()} function to return the translated text.  
+ * If the language is not registered with {@linkcode tr.addLanguage()}, the translation functions will always return the key itself.  
+ * @param language Language code to set as active
+ */
 tr.setLanguage = (language: string): void => {
   curLang = language;
 };
 
+/**
+ * Returns the active language set by {@linkcode tr.setLanguage()}  
+ * If no language is set, this function will return `undefined`.  
+ * @returns Active language code
+ */
 tr.getLanguage = (): string => {
   return curLang;
 };
 
+/**
+ * Returns the translations for the specified language or currently active one.  
+ * If the language is not registered with {@linkcode tr.addLanguage()}, this function will return `undefined`.  
+ * @param language Language code to get translations for - defaults to the active language set by {@linkcode tr.setLanguage()}
+ * @returns Translations for the specified language
+ */
+tr.getTranslations = (language?: string): Record<string, string> | undefined => {
+  return trans[language ?? curLang];
+};
+
 export { tr };