1
1
import log from 'loglevel' ;
2
2
3
+ export type CatI18nTranslationFn = ( key : string , params ?: unknown ) => string ;
4
+
3
5
export class CatI18nRegistry {
4
6
private static instance : CatI18nRegistry ;
5
7
6
8
private readonly id = ( Math . random ( ) + 1 ) . toString ( 36 ) . substring ( 2 ) ;
7
9
private readonly i18n : Map < string , string > = new Map ( ) ;
8
- private _locale ?: string ;
9
10
10
- _translator ?: ( key : string , params ?: unknown ) => string ;
11
+ private _locale ?: string ;
12
+ private _translator ?: CatI18nTranslationFn ;
11
13
12
14
private constructor ( ) {
13
15
// hide constructor
@@ -60,10 +62,15 @@ export class CatI18nRegistry {
60
62
}
61
63
}
62
64
63
- set ( i18n : { [ key : string ] : string } , silent = false ) : void {
64
- const i18nEntries = Object . entries ( i18n ) ;
65
- i18nEntries . forEach ( ( [ key , message ] ) => this . i18n . set ( key , message ) ) ;
66
- log . info ( `[CatI18nRegistry] Registered ${ i18nEntries . length !== 1 ? 'messages' : 'message' } ` ) ;
65
+ set ( i18n : { [ key : string ] : string } | CatI18nTranslationFn , silent = false ) : void {
66
+ if ( typeof i18n === 'function' ) {
67
+ this . _translator = i18n ;
68
+ log . info ( `[CatI18nRegistry] Registered translator` ) ;
69
+ } else {
70
+ const i18nEntries = Object . entries ( i18n ) ;
71
+ i18nEntries . forEach ( ( [ key , message ] ) => this . i18n . set ( key , message ) ) ;
72
+ log . info ( `[CatI18nRegistry] Registered ${ i18nEntries . length !== 1 ? 'messages' : 'message' } ` ) ;
73
+ }
67
74
! silent && window . dispatchEvent ( this . buildEvent ( 'cat-i18n-set' , { i18n, id : this . id } ) ) ;
68
75
}
69
76
@@ -74,12 +81,14 @@ export class CatI18nRegistry {
74
81
}
75
82
76
83
t ( key : string , params ?: { [ key : string ] : unknown } ) : string {
77
- const message = this . _translator ?.( key , params ) ?? this . i18n . get ( key ) ;
84
+ const message =
85
+ this . _translator ?.( key , params ) ??
86
+ this . i18n . get ( key ) ?. replace ( / { { \s * ( [ - a - z A - Z . _ ] + ) \s * } } / g, ( _match , key ) => `${ params ?. [ key ] ?? '' } ` ) ;
78
87
if ( message === undefined ) {
79
88
log . error ( `[CatI18nRegistry] Unknown message key: ${ key } ` ) ;
80
89
return key ;
81
90
}
82
- return message . replace ( / { { \s * ( [ - a - z A - Z . _ ] + ) \s * } } / g , ( _match , key ) => ` ${ params ?. [ key ] ?? '' } ` ) ;
91
+ return message ;
83
92
}
84
93
85
94
private buildEvent < T > ( name : string , detail ?: T ) {
0 commit comments