2019-09-04 23:43:37 +02:00
|
|
|
// @flow
|
|
|
|
import React from 'react';
|
|
|
|
|
|
|
|
type Props = {
|
|
|
|
tokens: Object,
|
2019-09-25 20:06:50 +02:00
|
|
|
children: string, // e.g. "Read %faq_link% for more detail"
|
2019-09-04 23:43:37 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export default function I18nMessage(props: Props) {
|
2022-03-15 03:38:45 +01:00
|
|
|
const message = __(props.children), // whole message string
|
2019-09-04 23:43:37 +02:00
|
|
|
regexp = /%\w+%/g,
|
2022-03-15 03:38:45 +01:00
|
|
|
interpolatedVariables = message.match(regexp);
|
2019-09-04 23:43:37 +02:00
|
|
|
|
2022-03-15 03:38:45 +01:00
|
|
|
// if there's no variable to interpolate then just send message
|
|
|
|
// otherwise algo to build the element below
|
|
|
|
if (!interpolatedVariables) {
|
2019-09-25 20:06:50 +02:00
|
|
|
return message;
|
2019-09-04 23:43:37 +02:00
|
|
|
}
|
|
|
|
|
2022-03-15 03:38:45 +01:00
|
|
|
// split string from variables
|
2020-05-25 00:15:58 +02:00
|
|
|
const messageSubstrings = message.split(regexp),
|
2022-03-15 03:38:45 +01:00
|
|
|
// interpolated variables
|
2019-09-04 23:43:37 +02:00
|
|
|
tokens = props.tokens;
|
|
|
|
|
|
|
|
return (
|
|
|
|
<React.Fragment>
|
2022-03-15 03:38:45 +01:00
|
|
|
{/* loop through substrings, interpolate tokens in between them */}
|
2019-09-04 23:43:37 +02:00
|
|
|
{messageSubstrings.map((substring, index) => {
|
2022-03-15 03:38:45 +01:00
|
|
|
// the algorithm is such that, there will always be a variable in between a message substring
|
|
|
|
// so when you use the index you actually grab the proper token
|
|
|
|
const matchingToken = interpolatedVariables.length && interpolatedVariables[index];
|
|
|
|
|
|
|
|
// get token name without % on each side
|
|
|
|
const tokenVariableName = matchingToken && matchingToken.substring(1, matchingToken.length - 1);
|
|
|
|
|
|
|
|
// select token to use if it matches
|
|
|
|
const tokenToUse = tokenVariableName && tokens[tokenVariableName];
|
|
|
|
|
2019-09-04 23:43:37 +02:00
|
|
|
return (
|
|
|
|
<React.Fragment key={index}>
|
|
|
|
{substring}
|
2022-03-15 03:38:45 +01:00
|
|
|
{tokenToUse}
|
2019-09-04 23:43:37 +02:00
|
|
|
</React.Fragment>
|
|
|
|
);
|
|
|
|
})}
|
|
|
|
</React.Fragment>
|
|
|
|
);
|
|
|
|
}
|