(
language: TranslationLanguage,
id: TranslationKey,
...args: React.ReactNode[]
)
| 6 | * Translate a string. |
| 7 | */ |
| 8 | export function t( |
| 9 | language: TranslationLanguage, |
| 10 | id: TranslationKey, |
| 11 | ...args: React.ReactNode[] |
| 12 | ): React.ReactNode { |
| 13 | const string = language[id]; |
| 14 | if (!string) { |
| 15 | throw new Error(`Translation not found for "${id}"`); |
| 16 | } |
| 17 | |
| 18 | // Now we are going to replace the arguments |
| 19 | // but we want to return a string as long as it's possible |
| 20 | // (eg. if there isn't any argument that is a ReactNode) |
| 21 | const parts: React.ReactNode[] = []; |
| 22 | let currentStringToReplace: string = string; |
| 23 | |
| 24 | args.forEach((arg, i) => { |
| 25 | if (typeof arg === 'string') { |
| 26 | currentStringToReplace = currentStringToReplace.replace(`\${${i + 1}}`, arg); |
| 27 | } else { |
| 28 | const [partToPush, partToReplace] = currentStringToReplace.split(`\${${i + 1}}`); |
| 29 | parts.push(<React.Fragment key={`string-${i}`}>{partToPush}</React.Fragment>); |
| 30 | parts.push(<React.Fragment key={`arg-${i}`}>{arg}</React.Fragment>); |
| 31 | // @ts-expect-error |
| 32 | currentStringToReplace = partToReplace; |
| 33 | } |
| 34 | }); |
| 35 | |
| 36 | if (!parts.length) { |
| 37 | return currentStringToReplace; |
| 38 | } |
| 39 | |
| 40 | return ( |
| 41 | <> |
| 42 | {parts} |
| 43 | {currentStringToReplace} |
| 44 | </> |
| 45 | ); |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Version of `t` that returns a string. |
no outgoing calls
no test coverage detected