@@ -5,29 +5,41 @@ import { TxKeyPath } from "./i18n";
5
5
6
6
/**
7
7
* Translates text.
8
- * @param {TxKeyPath } key - The i18n key.
9
- * @param {i18n.TranslateOptions } options - The i18n options.
8
+ * @param {TxKeyPath | string } key - The i18n key or plain text .
9
+ * @param {Record<string, any> } options - The i18n options.
10
10
* @returns {string } - The translated text.
11
- * @example
12
- * Translations:
13
- *
14
- * ```en.ts
15
- * {
16
- * "hello": "Hello, {{name}}!"
17
- * }
18
- * ```
19
- *
20
- * Usage:
21
- * ```ts
22
- * import { translate } from "i18n-js"
23
- *
24
- * translate("common.ok", { name: "world" })
25
- * // => "Hello world!"
26
- * ```
27
11
*/
28
12
export function translate (
29
- key : TxKeyPath ,
30
- options ?: i18n . TranslateOptions
13
+ key : TxKeyPath | string ,
14
+ options ?: Record < string , any >
31
15
) : string {
32
- return i18n . t ( key , options ) ;
16
+ // Get the current language's translations
17
+ const translations = i18n . translations [ i18n . locale ] ;
18
+ const enTranslations = i18n . translations . en ;
19
+
20
+ // First try direct lookup, then fallback to path traversal
21
+ let result =
22
+ ( translations as Record < string , any > ) ?. [ key ] ??
23
+ key . split ( "." ) . reduce ( ( obj , k ) => obj ?. [ k ] , translations as any ) ;
24
+
25
+ // If no translation found in current locale, try English
26
+ if ( result === undefined ) {
27
+ result =
28
+ ( enTranslations as Record < string , any > ) ?. [ key ] ??
29
+ key . split ( "." ) . reduce ( ( obj , k ) => obj ?. [ k ] , enTranslations as any ) ;
30
+ }
31
+
32
+ // If still no translation found, return the key itself
33
+ if ( result === undefined ) {
34
+ result = key ;
35
+ }
36
+
37
+ // Handle interpolation if options are provided
38
+ if ( options ) {
39
+ Object . entries ( options ) . forEach ( ( [ k , v ] ) => {
40
+ result = result . replace ( new RegExp ( `{{${ k } }}` , "g" ) , String ( v ) ) ;
41
+ } ) ;
42
+ }
43
+
44
+ return result ;
33
45
}
0 commit comments