(message, locale, interpolation = null)
| 6 | import I18n from 'locale'; |
| 7 | |
| 8 | export const t = (message, locale, interpolation = null) => { |
| 9 | let translation = I18n.t(message, locale, interpolation); |
| 10 | |
| 11 | if (translation === '') { |
| 12 | translation = message; |
| 13 | } |
| 14 | |
| 15 | const componentPlaceholdersReg = /({([^}]+)})/g; |
| 16 | |
| 17 | const retval = []; |
| 18 | |
| 19 | let ongoing = ''; |
| 20 | let lastIndex = 0; |
| 21 | let key = 0; |
| 22 | |
| 23 | translation.replace( |
| 24 | componentPlaceholdersReg, |
| 25 | (match, placeholder, name, index) => { |
| 26 | key += 1; |
| 27 | ongoing += translation.substring(lastIndex, index); |
| 28 | const value = interpolation[name]; |
| 29 | const type = typeof value; |
| 30 | |
| 31 | if (type === 'undefined') { |
| 32 | ongoing += '[unknown placeholder]'; |
| 33 | } else if (type === 'object') { |
| 34 | retval.push(ongoing); |
| 35 | retval.push(React.cloneElement(value, { key })); |
| 36 | ongoing = ''; |
| 37 | } else if (type === 'string' || type === 'number') { |
| 38 | ongoing += value; |
| 39 | } |
| 40 | lastIndex = index + match.length; |
| 41 | } |
| 42 | ); |
| 43 | |
| 44 | if (lastIndex < translation.length) { |
| 45 | ongoing += translation.substring(lastIndex); |
| 46 | } |
| 47 | |
| 48 | if (ongoing.length) { |
| 49 | retval.push(ongoing); |
| 50 | } |
| 51 | |
| 52 | if (retval.length === 1) { |
| 53 | return retval[0]; |
| 54 | } |
| 55 | |
| 56 | return retval; |
| 57 | }; |
| 58 | |
| 59 | export const getLocale = () => { |
| 60 | // If for some reason a locale cannot be determined, fall back to defaultLocale. |
no test coverage detected